text:
Q: Java IO Copying File I've been trying to get a file in java from a internal to a external location. The file is copying but its not transferring the bytes. The file is originally 98 bytes and when transferred then set to 0. If you could tell me what im doing wrong or help me in any sort of way that would be great.
    private static void copyFile(String internal, File external) {
    InputStream stream = FileManager.class.getResourceAsStream(internal);
    if(stream == null) {
        System.err.println("Error: File not found when trying to copy at location " + internal);
    }
    OutputStream resStreamOut = null;
    int readBytes;
    byte[] buffer = new byte[4096];
    try {
        resStreamOut = new FileOutputStream(external);
        while((readBytes = stream.read(buffer)) > 0) {
            resStreamOut.write(buffer, 0 , readBytes);
        }

    } catch(IOException e1) {
        e1.printStackTrace();
        System.exit(1);
    } finally {
        try {
        stream.close();
        resStreamOut.close();
        } catch(IOException e2) {
            e2.printStackTrace();
            System.exit(1);
        }

    }

}

Edit:
Getting null pointer:
4.4.0 Error: File not found when trying to copy at location /res/shaders/basicFragment.fs
Exception in thread "main" java.lang.NullPointerException at
com.thinmatrix.konilax.handlers.FileManager.copyFile(FileManager.java:80) at
com.thinmatrix.konilax.handlers.FileManager.update(FileManager.java:56) at
com.thinmatrix.konilax.MainComponent.<init>(MainComponent.java:22) at
com.thinmatrix.konilax.MainComponent.main(MainComponent.java:115)

A: Only read the file if your code manages to open it (note the else statement when testing if your stream is null):
private static void copyFile(String internal, File external) {
    InputStream stream = FileManager.class.getResourceAsStream(internal);
    if(stream == null) {
        System.err.println("Error: File not found when trying to copy at location " + internal);
    } else {
        OutputStream resStreamOut = null;
        int readBytes;
        byte[] buffer = new byte[4096];
        try {
            resStreamOut = new FileOutputStream(external);
            while((readBytes = stream.read(buffer)) > 0) {
                resStreamOut.write(buffer, 0 , readBytes);
            }
        } catch(IOException e1) {
            e1.printStackTrace();
            System.exit(1);
        } finally {
            try {
                stream.close();
                resStreamOut.close();
            } catch(IOException e2) {
                e2.printStackTrace();
                System.exit(1);
            }
        }
    }
}


text:
Q: When a  in a table has some text in it, auto check(tick) a check box which is outside of the table I want check box to auto-check when there's text in  of table:

A: You just want to check the innerHTML of the td and if that is empty "" then you can change the checked attribute of checkbox to true
Example:

   Put some content here and try and try without any content

<input type="checkbox" id="chk">

http://jsfiddle.net/tintucraju/3p6ucfnm/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Are there any common Design patterns or common idioms that are important for C++ win32 multithreading programming? One example could be: RAII - Resource Acquisition is Initialization used with critical sections
Any others that are important, popular and you often use?

A: This link mentions quite a few.  The Command pattern comes in handy for dispatching requests to threads.  Leader/Followers seems to be an interesting pattern as well.

A: You can try this also: patterns and idioms

A: I use message passing, share nothing concurrency both for my current product and for high performance desktop applications I have written in the past. In my experience, its better to avoid shared data synchronization. You can use NamedPipes, window messages or sockets to communicate between threads.
If you do decide to try and syncronize access to shared data, take a look at this topic.


text:
Q: How FAT (File Allocation Table) works? I got the following description of FAT from a powerpoint slide:
Partition boot record(1 sector)
-------------------------------
Main FAT (size is up to 2 clusters)
-------------------------------
Backup FAT (sam size as main FAT)
-------------------------------
Root directory
-------------------------------
Data area(size varies)

By searching on the Internet, mainly I can  get the main point of FAT features. But getting into details like the above, I dont understand the functionality of each part as shown.
Can anyone explain features of each section in the above FAT structure?

A: Wikipedia has a good explanation:

A FAT file system is composed of four different sections:
The Reserved sectors, located at the very beginning. The first
  reserved sector (sector 0) is the Boot Sector (aka Volume Boot Record
  (VBR)). It includes an area called the BIOS Parameter Block (with some
  basic file system information, in particular its type, and pointers to
  the location of the other sections) and usually contains the operating
  system's boot loader code. Important information from the Boot Sector
  is accessible through an operating system structure called the Drive
  Parameter Block (DPB) in DOS and OS/2. The total count of reserved
  sectors is indicated by a field inside the Boot Sector. For FAT32 file
  systems, the reserved sectors include a File System Information Sector
  at sector 1 and a Backup Boot Sector at sector 6.
The FAT Region.
This typically contains two copies (may vary) of the File Allocation
  Table for the sake of redundancy checking, although rarely used, even
  by disk repair utilities. These are maps of the Data Region,
  indicating which clusters are used by files and directories. In FAT12
  and FAT16 they immediately follow the reserved sectors. Typically the
  extra copies are kept in tight synchronization on writes, and on reads
  they are only used when errors occur in the first FAT. In FAT32, it is
  possible to switch from the default behaviour and select a single FAT
  out of the available ones to be used for diagnosis purposes.
The Root Directory Region.
This is a Directory Table that stores information about the files and
  directories located in the root directory. It is only used with FAT12
  and FAT16, and imposes on the root directory a fixed maximum size
  which is pre-allocated at creation of this volume. FAT32 stores the
  root directory in the Data Region, along with files and other
  directories, allowing it to grow without such a constraint. Thus, for
  FAT32, the Data Region starts here.
The Data Region.
This is where the actual file and directory data is stored and takes
  up most of the partition. Traditionally, the unused parts of the data
  region are initialized with a filler value of 0xF6 during format on
  IBM compatible machines, but also used on the Atari Portfolio. 8-inch
  CP/M floppies typically came pre-formatted with a value of 0xE5;[9] by
  way of Digital Research this value was also used on Atari ST formatted
  floppies.[nb 3] Some modern formatters wipe hard disks with a value of
  0x00, whereas a value of 0xFF is used on flash disks to reduce wear.
  The latter value is typically also used on ROM disks. (Some advanced
  formating tools allow to configure the format filler byte.[nb 4])
The size of files and subdirectories can be increased arbitrarily (as
  long as there are free clusters) by simply adding more links to the
  file's chain in the FAT. Note however, that files are allocated in
  units of clusters, so if a 1 KB file resides in a 32 KB cluster, 31 KB
  are wasted.
FAT32 typically commences the Root Directory Table in cluster number
  2: the first cluster of the Data Region.


text:
Q: Unable to surf internet with VPN on OpenBSD I am using OpenBSD 5.7-amd64 with the latest patches applied.
I downloaded and installed OpenVPN (package version: openvpn-2.3.6.tgz) available for OpenBSD 5.7 using the following command:
sudo pkg_add -vi openvpn

I change to the directory where my .ovpn files are located:
cd openvpn-configs

I choose one ovpn file, say uk.ovpn and type the following command:
sudo openvpn uk.ovpn

Lines flash across my terminal and finally the message:
Initialization Sequence Completed

indicate that I am connected to the UK server.
I launch Firefox and type in a URL.
Nothing appears in the browser.
I open up another terminal and type:
ping microsoft.com

No pings are recorded.
What is happening?

In response to mjturner's request for more information, below are additional details.
Please note that the basic pf firewall supplied by OpenBSD during installation of the OS is enabled by default. Moreover during installation of the OS, when asked whether to configure/turn-on IPv6, I answered "No".
Details of the log of the VPN connection:
Tue Jul 14 00:00:17 2015 OpenVPN 2.3.6 x86_64-unknown-openbsd5.7 [SSL (OpenSSL)] [LZO] [MH] [IPv6] built on Mar  7 2015
Tue Jul 14 00:00:17 2015 library versions: LibreSSL 2.1, LZO 2.08
Tue Jul 14 00:00:17 2015 WARNING: file 'auth.txt' is group or others accessible
Tue Jul 14 00:00:17 2015 Socket Buffers: R=[41600->65536] S=[9216->65536]
Tue Jul 14 00:00:17 2015 UDPv4 link local: [undef]
Tue Jul 14 00:00:17 2015 UDPv4 link remote: [AF_INET]111.222.333.444:443
Tue Jul 14 00:00:19 2015 TLS: Initial packet from [AF_INET]111.222.333.444:443, sid=16-alphanumeric-string
Tue Jul 14 00:00:19 2015 WARNING: this configuration may cache passwords in memory -- use the auth-nocache option to prevent this
Tue Jul 14 00:00:20 2015 VERIFY OK: depth=1, [particulars of commercial VPN service provider]
Tue Jul 14 00:00:20 2015 Validating certificate key usage
Tue Jul 14 00:00:20 2015 ++ Certificate has key usage  00a0, expects 00a0
Tue Jul 14 00:00:20 2015 VERIFY KU OK
Tue Jul 14 00:00:20 2015 Validating certificate extended key usage
Tue Jul 14 00:00:20 2015 ++ Certificate has EKU (str) TLS Web Server Authentication, expects TLS Web Server Authentication
Tue Jul 14 00:00:20 2015 VERIFY EKU OK
Tue Jul 14 00:00:20 2015 VERIFY OK: depth=0, [particulars of commercial VPN service provider]
Tue Jul 14 00:00:21 2015 Data Channel Encrypt: Cipher 'BF-CBC' initialized with 128 bit key
Tue Jul 14 00:00:21 2015 Data Channel Encrypt: Using 160 bit message hash 'SHA1' for HMAC authentication
Tue Jul 14 00:00:21 2015 Data Channel Decrypt: Cipher 'BF-CBC' initialized with 128 bit key
Tue Jul 14 00:00:21 2015 Data Channel Decrypt: Using 160 bit message hash 'SHA1' for HMAC authentication
Tue Jul 14 00:00:21 2015 Control Channel: TLSv1, cipher TLSv1/SSLv3 DHE-RSA-AES256-SHA, 2048 bit RSA
Tue Jul 14 00:00:21 2015 [VPN-UK] Peer Connection Initiated with [AF_INET]111.222.333.444:443
Tue Jul 14 00:00:23 2015 SENT CONTROL [VPN-UK]: 'PUSH_REQUEST' (status=1)
Tue Jul 14 00:00:24 2015 PUSH: Received control message: 'PUSH_REPLY,redirect-gateway def1,dhcp-option DNS 208.67.222.222,dhcp-option DNS 208.67.220.220,route 10.9.0.1,topology net30,ping 5,ping-restart 30,ifconfig 10.9.0.6 10.9.0.5'
Tue Jul 14 00:00:24 2015 OPTIONS IMPORT: timers and/or timeouts modified
Tue Jul 14 00:00:24 2015 OPTIONS IMPORT: --ifconfig/up options modified
Tue Jul 14 00:00:24 2015 OPTIONS IMPORT: route options modified
Tue Jul 14 00:00:24 2015 OPTIONS IMPORT: --ip-win32 and/or --dhcp-option options modified
Tue Jul 14 00:00:24 2015 ROUTE_GATEWAY 192.168.220.1
Tue Jul 14 00:00:24 2015 TUN/TAP device /dev/tun0 opened
Tue Jul 14 00:00:24 2015 do_ifconfig, tt->ipv6=0, tt->did_ifconfig_ipv6_setup=0
Tue Jul 14 00:00:24 2015 /sbin/ifconfig tun0 10.9.0.6 10.9.0.5 mtu 1500 netmask 255.255.255.255 up -link0
Tue Jul 14 00:00:26 2015 /sbin/route add -net 111.222.333.444 192.168.220.1 -netmask 255.255.255.255
add net 111.222.333.444: gateway 192.168.220.1
Tue Jul 14 00:00:26 2015 /sbin/route add -net 0.0.0.0 10.9.0.5 -netmask 128.0.0.0
add net 0.0.0.0: gateway 10.9.0.5
Tue Jul 14 00:00:26 2015 /sbin/route add -net 128.0.0.0 10.9.0.5 -netmask 128.0.0.0
add net 128.0.0.0: gateway 10.9.0.5
Tue Jul 14 00:00:26 2015 /sbin/route add -net 10.9.0.1 10.9.0.5 -netmask 255.255.255.255
add net 10.9.0.1: gateway 10.9.0.5
Tue Jul 14 00:00:26 2015 Initialization Sequence Completed

Details of ifconfig -a when the VPN connection is ON:
$ ifconfig -a
lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 32768
    priority: 0
    groups: lo
    inet6 xx11::1%lo0 prefixlen 64 scopeid 0x3
    inet6 ::1 prefixlen 128
    inet 127.0.0.1 netmask 0xff000000
re0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 1500
    lladdr [MAC address of network card]
    priority: 0
    groups: egress
    media: Ethernet autoselect (100baseTX full-duplex,rxpause,txpause)
    status: active
    inet 192.168.220.176 netmask 0xffffff00 broadcast 192.168.220.255
enc0: flags=0<>
    priority: 0
    groups: enc
    status: active
pflog0: flags=141<UP,RUNNING,PROMISC> mtu 33144
    priority: 0
    groups: pflog
tun0: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 1500
    priority: 0
    groups: tun
    status: active
    inet 10.9.0.6 --> 10.9.0.5 netmask 0xffffffff

Details of netstat -nr -f inet when the VPN connection is ON:
$ netstat -nr -f inet
Routing tables

Internet:
Destination        Gateway            Flags   Refs      Use   Mtu  Prio Iface
0/1                10.9.0.5           UGS        0        0     -     8 tun0
default            192.168.220.1      UGS        1      137     -     8 re0
10.9.0.1/32        10.9.0.5           UGS        0        0     -     8 tun0
10.9.0.5           10.9.0.6           UH         3        0     -     4 tun0
10.9.0.6           10.9.0.6           UHl        0        0     -     1 lo0
111.222.333.444/32 192.168.220.1      UGS        0        0     -     8 re0
127/8              127.0.0.1          UGRS       0        0 32768     8 lo0
127.0.0.1          127.0.0.1          UHl        1        4 32768     1 lo0
128/1              10.9.0.5           UGS        0        0     -     8 tun0
192.168.220/24     link#1             UC         1        0     -     4 re0
192.168.220.1      [MAC-router]       UHLc       2        0     -     4 re0
192.168.220.176    [MAC-network card] UHLl       0        0     -     1 lo0
192.168.220.255    link#1             UHLb       0        0     -     1 re0
224/4              link#1             UCS        0        0     -     8 re0

Details of dig when the VPN connection is ON:
$ dig +short microsoft.com
;; connection timed out; no servers could be reached
$


text:
Q: Different `geom_hline()` for each facet of ggplot
library(tidyverse)
ggplot(mpg, aes(cty, hwy)) +
  geom_point() +
  facet_grid(year ~ fl) +
  geom_hline(yintercept = mean(mpg$hwy))

I want each geom_hline() in the facet shown above to be the mean of the points that are only contained within that facet. I would think that I could do it with something like (below). But that doesn't work. I'm close, right?
library(tidyverse)
ggplot(mpg, aes(cty, hwy)) +
  geom_point() +
  facet_grid(year ~ fl) +
  geom_hline(yintercept = mean(mpg %>% group_by(year, fl)$hwy))

A: If you have the value you wish to use for each facet as a column in the data frame, and that value is unique within each facet, then you can use geom_hline(aes(yintercept=column)), which will then plot a horizontal line for each of the facets


text:
Q: Why put images into Next.js public folder? Is there an advantage? I could put my images anywhere it seems, and it just works fine. However, Next.JS seems to recommend to put the images into the public folder. What's the advantage here?

A: If you have your static files in the public folder, it would be easier to import them elsewhere. Files inside public can be referenced by your code starting from the base URL (/).
For example, if you add an image to public/me.png, the following code will access the image:
import Image from 'next/image'

function Avatar() {
  return <Image src="/me.png" alt="me" width="64" height="64" />
}

export default Avatar

More info about that can be found here: https://nextjs.org/docs/basic-features/static-file-serving


text:
Q: Send data from php to JS for google motion chart I'm trying to draw a MotionChart with data coming from a XMLHttpRequest. If data for MotionChart is hardcoded like the following example it is properly displayed.
function drawMotChart(dataObject) {

    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Fruit');
    data.addColumn('date', 'Date');
    data.addColumn('number', 'Sales');
    data.addColumn('number', 'Expenses');
    data.addColumn('string', 'Location');
    data.addRows([
      ['Apples',  new Date (1988,0,1), 1000, 300, 'East'],
      ['Oranges', new Date (1988,0,1), 1150, 200, 'West'],
      ['Bananas', new Date (1988,0,1), 300,  250, 'West'],
      ['Apples',  new Date (1989,6,1), 1200, 400, 'East'],
      ['Oranges', new Date (1989,6,1), 750,  150, 'West'],
      ['Bananas', new Date (1989,6,1), 788,  617, 'West']
    ]);

    var chart = new google.visualization.MotionChart(document.getElementById('chart_div'));
    chart.draw(data, {width: 600, height:300});
}

But I want to get data from a php. So I tried the following. In the webpage header I have:
function SendParameters() {
    document.getElementById("chart_div").innerHTML ="";

        if (window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
        } else {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status==200) {
                document.getElementById("ShowAjax").innerHTML = "Just to see the incomming data:<br>"+xmlhttp.responseText;
                DataFromAjax = xmlhttp.responseText;
                drawMotChart(DataFromAjax);
            }
        }
        xmlhttp.open("GET", "L_GetDataAjax.php?Group=Main", true);
        xmlhttp.send();
}

function drawMotChart(dataObject) {

    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Fruit');
    data.addColumn('date', 'Date');
    data.addColumn('number', 'Sales');
    data.addColumn('number', 'Expenses');
    data.addColumn('string', 'Location');
    data.addRows([dataObject]);

    var chart = new google.visualization.MotionChart(document.getElementById('chart_div'));
    chart.draw(data, {width: 600, height:300});
}

And the L_GetDataAjax.php file is like this:
PHP
$DataToSend="['Apples',  new Date (1988,0,1), 1000, 300, 'East'],
             ['Oranges', new Date (1988,0,1), 1150, 200, 'West'],
             ['Bananas', new Date (1988,0,1), 300,  250, 'West'],
             ['Apples',  new Date (1989,6,1), 1200, 400, 'East'],
             ['Oranges', new Date (1989,6,1), 750,  150, 'West'],
             ['Bananas', new Date (1989,6,1), 788,  617, 'West']";
echo $DataToSend;

But in this case there is no Chart.
So my question is: How can I add the data from a XMLHttpRequest to the chart?


text:
Q: Azure AD B2C Single Logout implementation I have 2 web aplications using AAD B2C single sign-on, the Mainsite.mydomain.com and support.provider.com (note that they are in different domains). My B2C has only local users, so no external IdP (e.g. Google, Facebooks, etc).
Single sign-on works as expected and the individual logout from each website works as expected.
Now I want Single Logout, i.e. when the users logout from the Mainsite I want them to be automatically logged out from the Support website, too. At logout from each app I do call the OIDC /logout endpoint to kill the B2C session as per the documentation, but that isn't enough to logout from the other application.
Reading the OIDC specs it seems there are 3 ways to have single-logoff, as described here, but none of them seem to be available for B2C:

*

*Front-end channel (it would require registering a Logout URL for each
app, but B2C apps don't have this attribute)

*Back-end channel (it would require registering a Logout URL for each
app, but B2C apps don't have this attribute)

*Session Management (this requires a check_session_iframe URL, which
is not provided by the B2C /.well-known endpoint)

So it seems that none of the standard methods are supported by B2C, did anybody manage to figure out  how to do it?
Note: There's another similar SO question here but the single response doesn't actually answer the question and the comments to it show that others couldn't do single logoff either. Even more, my case is even simpler as I don't have any external IdP.

A: According to Microsoft Support, this is currently not possible. They even pointed me to a feature request for this exact thing, but it's not on their near-term roadmap.


text:
Q: I can't fetch any images or show any URL image in my website Whenever I try to fetch an image URL from the database to the client, I get this error:
Refused to load the image 'https://nuclear-photos.s3-ap-southeast-1.amazonaws.com/…22:33:44%20GMT+0400%20(GST)TEST.png'
 because it violates the following Content Security Policy directive: "img-src data: 'self' http://*.s3.amazonaws.com https://*.s3.amazonaws.com".

What is causing this problem?!

A: This is probably because you have the browser-policy package installed.  Fix it by adding this line of code on your server:
BrowserPolicy.content.allowOriginForAll("nuclear-photos.s3-ap-southeast-1.amazonaws.com");

This tells your browser policy to allow anything from this domain (presumably your own S3 bucket).


text:
Q: Profiling a benchmark compiled for the SPARC v8 on an x86 I'm trying to make a (small) improvement to the leon3 processor (instruction set is SPARC v8) for an academic exercise. Before I decide what to improve, I want to profile a couple of benchmark programs that I want to tailor the improvements to.
I don't have access to a SPARC v8 machine.
Currently, I'm using an evaluation version of 'tsim' (a leon3 simulator) which does profiling at the functional level. Which is not really all that useful.
I have tried weird stuff like compiling with loop unrolling enabled and then counting the interesting instructions in the assembly code, but gcc refuses to unroll the loops, probably because some of them go too deep (e.g. 4 nested 'for' loops).
Ideally, what I'm looking for is a SPARC v8 simulator that runs the benchmark and profiles it at the instruction level (stuff like: 'smul' was executed x times) so that I can decide where to start trying with the improvement. Of course if there are other ways I can do this if not a profiler, I won't mind.
Any ideas?

A: If you really want to dig that deep into the hardware, you'll find a simulator useful that helps you with that.
Simics comes into mind. They used to have free academic licenses, but since they were bought by Intel, you now need to apply for one, which from my experience takes a couple of weeks. If you are willing to invest this time, you'll certainly get a tool that suits your needs, although they support LEON2, not LEON3, as a model, but for profiling this should be fine.
Qemu also has LEON support but as they're heavily recompiling, it will probably be hard to to instruction-level profiling with it.

A: Simulating the processor in Modelsim could be an option. With Modelsim you can do a functional simulation of the complete LEON3 processor. Although the simulation will be quite slow and probably complete overkill for your purposes but Aeroflex Gaisler provides excellent scripts to work with Modelsim.
A student edition of modelsim can be found here:
http://www.mentor.com/company/higher_ed/modelsim-student-edition


text:
Q: Globaly fetch python class variable Class Information:
   def __init__(self):
      self.name = 200

   def ajust(self):
      self.name = 250

Class Jesus:
   def __init__(self):
      self.age = 10

   def ajust(self):
      self.age = 20

Printdata = Information()
print(Printdata.name)

________________________
Result: >>> 200

This print is printing out the first name value. how can i get it to print the value after calling ajust? i want it to print 250, not 200. i have looked all over stackoverflow to find a solution. Keep in mind this is not my actual code, just a simple example to showcase my issue.

A: You need to call ajust() first
Printdata = Information()
Printdata.ajust()
print(Printdata.name)

However once you call it name will always be 250, I suggest you use property instead to allow more changes
class Information:

    def __init__(self):
        self.__name = 200

    @property
    def name(self):
        return self.__name

    @name.setter
    def name(self, value):
        self.__name = value

information = Information()
print(information.name) # 200
information.name = 250
print(information.name) # 250

A: Let's take a look at what's going on here behind the scenes.
Your class information has a constructor(in python these are defined by the method __init__(self).
When you call Information(), in reality you are calling the constructor, which returns an instance of your object, in this case an Information object, it also sets name to 200.
So when you print name on a newly built Information, name will be 200.
You have an ajust method. But you'll need to call it in order to update the name variable inside the class.
So your order of events should be: Build the class, call ajust, print name


text:
Q: list control font in wxPython I have following code to set the font in list control:
item = wx.ListItem()
font = wx.Font(pointSize=48, family=wx.ROMAN, style=wx.NORMAL, weight=wx.FONTWEIGHT_BOLD,
               underline=False, face="", encoding=wx.FONTENCODING_DEFAULT
item.SetFont(font)
item.SetText("hello")
self.list.InsertItem(item)

When I run the above code, the item will display after a blank item. If I remove the font = ... and item.SetFont(font) line, the item will display correctly.
Is there anybody can help me?
Thanks a lot.

A: Are you wanting to change the font on all the rows or individually? If you want to do all the rows, then just use the wx.ListCtrl instance's SetFont() method. Otherwise, your method should work. A small runnable example would help us figure this out if you're wanting the latter.


text:
Q: SSD1306-based OLED display E/RD# and R/W# pins This is the OLED display in question and this is the datasheet of the display. I am going to connect to it using I2C.
The datasheet provides mostly understandable explanations for the pins as far as their usage in different communication modes (I2C,SPI,8 bit parallel etc.) goes.
These are a couple that I have trouble with:

Both of these pins have mentions of their function when driving them using using "68XX-series and 80XX-series microcontroller". From the datasheet it seems they mean 8-bit parallel com:

The question is, should leave them floating when using I2C? Or is data read still dependent on the state of those pins. I assume not, but I'd like to hear from someone who has had actual experience with them.

A:
The question is, should leave them floating when using I2C?

Use this "ER-OLED0.96-1 Series Interfacing Document" from the display manufacturer's page which you linked.
It includes the following I2C interface schematic, which shows those two signals E/RD# and R/W# are both grounded when using I2C, as I've marked in red on this extract from that document:


text:
Q: How to use Multiple WhereIn queries in Firebase Android? I'm working on an app where I'm using Cloud Firestore, at times I need to use multiple whereIn() queries but it's not working. Is there any way I can use multiple wherein queries or I can compare multiple list values?

A:
is there any way I can use multiple wherein queries or I can compare multiple list values

No, there is not.  Please read the documentation on query limitations:

Note the following limitations for in, not-in, and array-contains-any:

*

*You can use at most one in, not-in, or array-contains-any clause per query. You can't combine these operators in the same query.

Instead, you can use a single whereIn filter, then filter the remaining results on the client app.


text:
Q: Adding a new node to a list Hey so i am wondering how i would go about adding a new node to a list. So have a container that holds the list, which i need to add too. Which is defined as follows.
This is the container for the list
struct vm
{
    struct vm_list * item_list;
    struct coin * coins;
    char * foodfile;
    char * coinsfile;
};

this is the list that holds node.
struct vm_list
{
    struct vm_node * head;
    unsigned length;
};

this is the definition of the node
struct vm_node
{
    struct stock_item * data;
    struct vm_node * next;
};

this is how i am attempting to add an item to the list.
BOOLEAN add_item(struct vm* vm)
{
    struct stock_item *newItem;
    newItem = malloc(sizeof(struct stock_item));
    struct vm_node *newNode; //setup a new item to store the data in.
    newNode = malloc(sizeof(struct vm_node));
    struct vm_node *VMP; //setup the new Node to hold the newItem
    VMP = malloc(sizeof(struct vm_node));
    struct vm_node *VMF; //too keep track of the first element in the list. So i can print out the list from the start.
    VMF = malloc(sizeof(struct vm_node));
    VMF->next = vm->item_list->head;
/* the following loops through until it finds the last element in the list. Which it stores in the VMP structure. So we can increment the ID counter by 1.*/
    while(vm->item_list->head){
        VMP->data = vm->item_list->head->data; //stores the last element of the linked list. Allowing us to add information to the nth bottom of the list.
        vm->item_list->head = vm->item_list->head->next;
    }
/* defining the items to be stored in the newItem struct. */
    char *newName;
    char *newDesc;
    char * onHand;
    char *price;
    newName = malloc(sizeof(char));
    newDesc = malloc(sizeof(char));
    price = malloc(sizeof(char));
    onHand = malloc(sizeof(char));
    char *dem = VMP->data->id; //returns the ID of the last item in the list.
    int change = atoi(&dem[4]); //changes the item to a int.
    change++; //increments by 1.
    char str;
    sprintf(&str, "%d", change); // converts back to char.
    dem[4]=str; // stores back in the char array.
    read_rest_of_line(); //buffer handler.
    printf("Enter the item name: ");
    newName = getlines();
    printf("\n");
    printf("Enter the item description: ");
    newDesc = getlines();
    printf("\n");
    printf("Enter how many will be stocked: ");
    onHand = getlines();
    printf("\n");
    printf("How much will the item cost: ");
    price = getlines();
    printf("\n");
//adding a new item to the list.
    newNode->next = NULL;
    newItem  = add_tobottomoflist(dem,newName,newDesc,onHand,price); //add_tobottom is setups the newItem.
    newNode->data = newItem; // sets the data for newNode = to newItem
    vm->item_list->head = newNode; //sets up the new Node.
    vm->item_list->head->next = VMF; //points to the first element in the list for linking.
    display_items(vm); // displays all the elements in the list.

    /* The UNUSED() function is designed to prevent warnings while your
     * code is only partially complete. Delete this function call once
     * you are using vm in your own code */
    UNUSED(vm);
    return FALSE;
}

The output when the code is ran is as follows.
IO        NAME                Description                                                           On Hand        price
I0006     Nam
                desc
                                                                 12             $3.04
p�                                                                                -2108446504    $-2108446504.32615
I0001     Coke                375 ml Can of coke                                                    50             $3.50
I0002     Pepsi               375 ml Can of pepsi                                                   20             $3.00
I0003     Lemon Cheesecake    A delicious, 1/8 size slice of cheesecake                             10             $4.00
I0004     Mars Bar            A delicious 50 g Mars Bar chilled just the way you like it.           20             $3.00
I0006     Lemon Tart          A delicious lemon butter tart with a pastry based                     12             $3.75

The lemon tart id should be equal to I0005 not I0006, i have no idea where it has incremented, and the new item has been added to the beginning of the list not at the end. There also appears to be a null object at the start of the list also.
Any thoughts on what could be happening here?

A: I see a couple things that are problematic.
One, the null thing you have at the beginning is VMF. your comments say that this variable is to keep track of the beginning of the list. You already have head for that. Why are you mallocing more memory for this VMF?
You seem to be trying to modify existing code that adds to the beginning of the list, instead of the end. To add to the end, you have to change your while loop. In your while loop, iterate through the list, and keep track of the last node that isn't null. Then point last_node->next to your new node


text:
Q: Restoring System after crash fails (Ubuntu Budgie 20.04) My ubuntu  20.04 crashed and now the computer only boots into grub rescue mode. As usual, i wanted to repair Ubuntu with fsck. But the df output doesnt list my hard drives /dev/sda and /dev/sdb. The output looks like in the attached screenshot. And sorry for adding it as a picture, copy+paste destroyed the formatting of the table.
Do you have an idea how to restore the OS?

Here is the output of cat and fdisk (shortened to the important hard drive).

Thank you in advance!

A: If the OS cannot mount the partition, it won't be visible with df.
You can see which are the available partitions with
cat /proc/partitions

or (as root)
fdisk -l

Keep in mind you don't have to pass whole disks (i.e. sda or sdb) to fsck, but the specific partition (i.e.: sda1 or sdb1)


text:
Q: Meilisearch API Key not accepted in Test (Jest) works fine in nestjs I tried to test my function and only with the test I get:
{
"code": "invalid_api_key",
"httpStatus": 403,
"link": "https://docs.meilisearch.com/errors#invalid_api_key",
"name": "MeiliSearchApiError",
"type": "auth"
}
same settings in the nestjs backend works fine.
beforeEach(async () => {
  const module: TestingModule = await Test.createTestingModule({
    imports: [
      MeiliSearchModule.forRoot({
        host: 'http://127.0.0.1:7700',
        apiKey: 'masterKey',
    })],
    providers: [
      UsersService,
      {
        provide: getModelToken(User),
        useValue: {
          findAll: jest.fn(() => usersArray),
          findOne: jest.fn(),
          create: jest.fn(() => oneUser),
          remove: jest.fn(),
          destroy: jest.fn(() => oneUser),
        },
      },
    ],
  }).compile();

  service = module.get<UsersService>(UsersService);
  model = module.get<typeof User>(getModelToken(User));
});

env file (working)
MEILI_HOST: 'http://127.0.0.1:7700'
MEILI_APIKEY: 'masterKey'

Any idea in which direction I should look?
Set new key
tried reset the docker


text:
Q: Trouble checking a string for numbers in C I've checked similar questions posted here on the forum, but none of those answers my question.
I have a string (char s []) and I want to 'copy' the numbers in that string to another one (char n []).
Here's my attempt at this:
   char s[] = "oa323shsh123383.33hbabsa3€"
   int len = strlen(s);
   char n[];
   int k;

   for (k = 0; k <= len; k++){
       if( s[k] >= '0' || s[k] <= '9') {
           n[k] = s[k] - 48;
       }
   }

However this is wrong, because it doesn't print out anything. Can anybody help me ?

A: Use && in your IF.
Allocate your array n. Easy way is to declare n as
char n[] = char[len+1];

Use another variable to count the number being added to n, otherwise you will have n being:
"..323....123383" etc

Should end up with something like
char s[] = "oa323shsh123383.33hbabsa3€"
int len = strlen(s);
char n[] = char[len+1];
int k, j=0;

for (k = 0; k <= len; k++){

    if( s[k] >= '0' && s[k] <= '9') {
        n[j] = s[k] - 48;
        n[j+1] = '\0';
        j++;
    }
}

A: char s[] = "oa323shsh123383.33hbabsa3€";
int len = strlen(s);
char* n = (char*) malloc(len+1);
int i,j=0;

for (i = 0; i < len; ++i)
{
    if( s[i] >= '0' && s[i] <= '9')
        n[j++] = s[i];
}
n[j]=0;

n is now a printable string
dont forget to free it when you are done.


text:
Q: Function composition, tuples and unpacking (disclaimed: not a Python kid, so please be gentle)
I am trying to compose functions using the following:
def compose(*functions):
  return functools.reduce(lambda acc, f: lambda x: acc(f(x)), functions, lambda x: x)

which works as expected for scalar functions. I'd like to work with functions returning tuples and others taking multiple arguments, eg.
def dummy(name):
  return (name, len(name), name.upper())

def transform(name, size, upper):
  return (upper, -size, name)

# What I want to achieve using composition,
# ie. f = compose(transform, dummy)
transform(*dummy('Australia'))
=> ('AUSTRALIA', -9, 'Australia')

Since dummy returns a tuple and transform takes three arguments, I need to unpack the value.
How can I achieve this using my compose function above? If I try like this, I get:
f = compose(transform, dummy)
f('Australia')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in <lambda>
  File "<stdin>", line 2, in <lambda>
TypeError: transform() takes exactly 3 arguments (1 given)

Is there a way to change compose such that it will unpack where needed?

A: This one works for your example but it wont handle just any arbitrary function - it will only works with positional arguments and (of course) the signature of any function must match the return value of the previous (wrt/ application order) one.
def compose(*functions):
    return functools.reduce(
        lambda f, g: lambda *args: f(*g(*args)),
        functions,
        lambda *args: args
        )

Note that using reduce here, while certainly idiomatic in functional programming, is rather unpythonic. The "obvious" pythonic implementation would use iteration instead:
def itercompose(*functions):
    def composed(*args):
        for func in reversed(functions):
            args = func(*args)
        return args
    return composed

Edit:
You ask "Is there a way to make have a compose function which will work in both cases" - "both cases" here meaning wether the functions returns an iterable or not (what you call "scalar functions", a concept that has no meaning in Python).
Using the iteration-based implementation, you could just test if the return value is iterable and wrap it in a tuple ie:
import collections

def itercompose(*functions):
    def composed(*args):
        for func in reversed(functions):
            if not isinstance(args, collections.Iterable):
                args = (args,)
            args = func(*args)
        return args
    return composed

but this is not garanteed to work as expected - actually this is even garanteed to NOT work as expected for most use cases. There are a lot of builtin iterable types in Python (and even more user-defined ones) and just knowing an object is iterable doesn't say much about it's semantic.
For example a dict or str are iterable but in this case should obviously be considered a "scalar". A list is iterable too, and how it should be interpreted in this case is actually just undecidable without knowing exactly what it contains and what the "next" function in composition order expects - in some cases you will want to treat it as a single argument, in other cases ase a list of args.
IOW only the caller of the compose() function can really tell how each function result should be considered - actually you might even have cases where you want a tuple to be considered as a "scalar" value by the next function. So to make a long story short: no, there's no one-size-fits-all generic solution in Python. The best I could think of requires a combination of result inspection and manual wrapping of composed functions so the result is properly interpreted by the "composed" function but at this point manually composing the functions will be both way simpler and much more robust.
FWIW remember that Python is first and mostly a dynamically typed object oriented language so while it does have a decent support for functional programming idioms it's obviously not the best tool for real functional programming.

A: The compose function in the answer contributed by Bruno did do the job for functions with multiple arguments but didn't work any more for scalar ones unfortunately.
Using the fact that Python `unpacks' tuples into positional arguments, this is how I solved it:
import functools

def compose(*functions):
  def pack(x): return x if type(x) is tuple else (x,)

  return functools.reduce(
    lambda acc, f: lambda *y: f(*pack(acc(*pack(y)))), reversed(functions), lambda *x: x)

which now works just as expected, eg.
#########################
# scalar-valued functions
#########################

def a(x): return x + 1
def b(x): return -x

# explicit
> a(b(b(a(15))))
# => 17

# compose
> compose(a, b, b, a)(15)
=> 17

########################
# tuple-valued functions
########################

def dummy(x):
  return (x.upper(), len(x), x)
def trans(a, b, c):
  return (b, c, a)

# explicit
> trans(*dummy('Australia'))
# => ('AUSTRALIA', 9, 'Australia')

# compose
> compose(trans, dummy)('Australia')
# => ('AUSTRALIA', 9, 'Australia')

And this also works with multiple arguments:
def add(x, y): return x + y

# explicit
> b(a(add(5, 3)))
=> -9

# compose
> compose(b, a, add)(5, 3)
=> -9

A: You might consider inserting a "function" (really, a class constructor) in your compose chain to signal the unpacking of the prior/inner function's results.  You would then adjust your composer function to check for that class to determine if the prior result should be unpacked.  (You actually end up doing the reverse:  tuple-wrap all function results except those signaled to be unpacked -- and then have the composer unpack everything.)  It adds overhead, it's not at all Pythonic, it's written in a terse lambda style, but it does accomplish the goal of being able to properly signal in a function chain when the composer should unpack a result.  Consider the following generic code, which you can then adapt to your specific composition chain:
from functools import reduce
from operator import add

class upk:  #class constructor signals composer to unpack prior result
  def __init__(s,r):  s.r = r  #hold function's return for wrapper function

idt = lambda x: x  #identity
wrp = lambda x: x.r if isinstance(x, upk) else (x,)  #wrap all but unpackables
com = lambda *fs: (  #unpackable compose, unpacking whenever upk is encountered
  reduce(lambda a,f: lambda *x: a(*wrp(f(*x))), fs, idt) )

foo = com(add, upk, divmod)  #upk signals divmod's results should be unpacked
print(foo(6,4))

This circumvents the problem, as called out by prior answers/comments, of requiring your composer to guess which types of iterables should be unpacked.  Of course, the cost is that you must explicitly insert upk into the callable chain whenever unpacking is required.  In that sense, it is by no means "automatic", but it is still a fairly simple/terse way of achieving the intended result while avoiding unintended wraps/unwraps in many corner cases.


text:
Q: how can listen to http and https requests with julia I want to set up a telegram webhook and I need to receive https requests.
How can I make my ip an accessible url?
I was doing this in Python with aiohttp.

A: You should configure Apache web server or Nginx as a web proxy and run it with Genie.jl as a backend.
According to the Telegram webhook documentation https://core.telegram.org/bots/webhooks you need to provide an SSL server (so you will need certificate etc.). While HTTP.jl provides some SSL listen capability, almost in any integration scenario I can think of you will end up needing some options that only robust servers such as Apache or Nginx can support.
Similarly, you want to have Genie.jl as a backend of the Apache/nginx proxy (rather than HTTP.jl) - as this is a standard integration scenario for webservices in Julia and this is a higher level interface than HTTP.jl with error handling for production systems etc. You can find a detailed tutorial for Nginx setup with Genie.jl here: https://genieframework.github.io/Genie.jl/dev/tutorials/92--Deploying_Genie_Server_Apps_with_Nginx.html   if you are experienced with Apache you will not have problems applying the same approach to Apache web server

A: Try HTTP.jl, you can start from these examples.


text:
Q: Closer to bypassing Flex print dialogue? I know this is a pretty heavy topic and see requests for it all the time (I believe the stance for blocking it is security related).
While messing around trying to get ZPL printing working in AIR, I ran into something interesting.
Looking at other programming languages and their attempts to print to ZPL, most of them handle it through a File Stream and treat the printer as a file (see here for a .NET example .NET code to send ZPL to Zebra printers).
I took this approach with Flex and got some interesting results.
I tested this talking directly to a network shared printer on my own PC.  It's a simple piece of code:
var file:File = new File('\\\\PC-Name\\Printer-Name');
var stream:FileStream = new FileStream();
stream.open(file, FileMode.WRITE);

Obviously you will need to fill in your own info for PC-Name (network name) and Printer-Name (printer's shared name).
If you watch your printer, you'll notice that it does initiate spooling with this request.
Unfortunately, this is about as far as I'm able to get with it.  Initiating any sort of actually writing over that stream doesn't seem to work (although I'm far from an expert on the matter, I could be missing something).
Stepping through something like:
var file:File = new File('\\\\PC-Name\\Printer-Name');
var stream:FileStream = new FileStream();
stream.open(file, FileMode.WRITE);
stream.close();

You can watch it hit the spooler with the open and then successfully close without any ill effects.
Once you add an actual write though such as:
var byteArray:ByteArray = new ByteArray();
byteArray.writeUTFBytes("Hello World");
byteArray.position = 0;

var file:File = new File('\\\\PC-Name\\Printer-Name');
var stream:FileStream = new FileStream();
stream.open(file, FileMode.WRITE);
stream.writeBytes(byteArray, 0, byteArray.length);
stream.close();

It all goes to hell unfortunately.
Some things to note about the variables and what happens:
After declaring your file (var file:File = new File('\\PC-Name\Printer-Name');), when you inspect the file variable you'll notice a few issues.  creationDate, modificationDate, and size all have "exception thrown by getter" errors.  More specifically "Error: Error #3003: File or directory does not exist.".  I'm not overly concerned with these as it isn't a file, it's a printer.
After opening the stream (stream.open(file, FileMode.WRITE);) and inspecting the stream variable the "bytesAvailable" has an "exception thrown by getter" (Error: Error #2029: This URLStream object does not have a stream opened).  Once again, it isn't a file so the bytesAvailable like this might be okay (or it may be the reason everything after this seems to fail).  At this point, you will also have a print document with a status of "Spooling" in your print queue.
Calling stream.writeBytes(byteArray, 0, byteArray.length); causes the stream variable position to move from 0 to 167 (the length of my byteArray).  So it seems to think it attempts to write.  Nothing "bad" seems to happen here.....
Calling stream.close(); however, brings the whole thing crashing down with a "Error #2038: File I/O Error. at flash.filesystem::FileStream/close()
Posting this here to see if anyone has any ideas (am I missing something?  Is it completely not possible?  Close but no cigar?)
******** UPDATE *********
I did find a way to accomplish this with a network printer (unfortunately not with a windows shared printer).  It is using sockets instead of filestreams.  I can almost guarantee you this will throw some sandbox violations upon an actual release so that will need to be handled (socket policy files I would assume).
public var socket:Socket = new Socket();
socket.addEventListener( Event.CONNECT, onConnect);
socket.addEventListener( ProgressEvent.SOCKET_DATA, onSocketData);
socket.connect(ip_address, 9100);

private function onConnect(event : Event) : void {
  var byteArray:ByteArray = new ByteArray();
  byteArray.writeUTFBytes("Hello World");
  byteArray.position = 0;

  socket.writeBytes(byteArray, 0, byteArray.length);
  socket.removeEventListener(Event.CONNECT, onConnect);
  socket.removeEventListener(ProgressEvent.SOCKET_DATA, onSocketData);
  socket.flush();
  socket.close();
}

public function onSocketData(event:Event):void {
  trace("onSocketData Fired");
}

Not sure if one can even connect over a socket to a windows shared printer (ie a printer connected to someone's PC and shared).  So far I haven't had any luck.  But, if you are strictly dealing with networked printers this might work for you to skip/bypass the flex print dialogue.

A: I'm making a few assumptions: If you're using AIR and you have a working .Net solution and you are targeting Windows only... why not just use the .Net solution and call it using NativeProcess class?
Basically you compile the ZPL .NET printer as an EXE and call it using NativeProcess, passing in the printer string.
That way you can still have a nice Flexy interface but get native printing controls.


text:
Q: Threading Problems (I don't understand it) There's lots and lots of pages on the internet regarding threading but I can't seem to get my head around it.
I have a Form, which on the click of a button, loops through a file and reads it line by line. Each line is the login details for different FTP sites.
When it reads a line, it Dim's a variable as a new instance of a class named CallFTP using the login details.
It then Dim's a variable as a new Thread using a function in CallFTP named PerformFTP.
PerformFTP returns a string with the results of the FTP and I want to add this to a ListBox on the form that began it all.
The code for the button goes like this...
Private Sub cmdRun_Click(sender As Object, e As EventArgs) Handles cmdRun.Click
    For Each _FTPLine As String In Split(_FTPDetails, vbNewLine)
        Dim _Active As Boolean = CBool(Split(_FTPLine, "|")(7))

        If _Active Then
            _CurNum += 1
            _ID = Format(Now.Year, "0000") & Format(Now.Month, "00") & Format(Now.Day, "00") & Format(Now.Hour, "00") & Format(Now.Minute, "00") & Format(Now.Second, "00") & Format(Now.Millisecond, "000") & Format(_CurNum, "00000")

            Dim _FTP As New CallFTP(_ID, Split(_FTPLine, "|")(0), Split(_FTPLine, "|")(1), Split(_FTPLine, "|")(2), Split(_FTPLine, "|")(3), Split(_FTPLine, "|")(4), Split(_FTPLine, "|")(5), Split(_FTPLine, "|")(6))
            Dim _Thread = New Thread(New ThreadStart(AddressOf _FTP.PerformFTP))

            With _Thread
                .IsBackground = True
                .Start()
            End With
        End If
    Next _FTPLine
End Sub

The class is as below (not quite but you don't need the rest of the code lol)
Public Class CallFTP
    Private _ID As String = ""
    Private _Response As String = ""
    Private _IPAddress As String = ""
    Private _Port As String = ""
    Private _User As String = ""
    Private _Pass As String = ""
    Private _Remote As String = ""
    Private _Local As String = ""
    Private _InOut As String = ""

    Public Sub New(ID As String, Server As String, PortNum As String, Username As String, Password As String, RemoteDir As String, LocalDir As String, InOrOut As String)
        _ID = ID
        _IPAddress = Server
        _Port = PortNum
        _User = Username
        _Pass = Password
        _Remote = RemoteDir
        _Local = LocalDir
        _InOut = InOrOut
    End Sub

    Public Function PerformFTP() As String
        Return "This is a test"
    End Function
End Class

Could anyone explain how I would call a sub named LogMessage on a module named modMisc (which adds a string to a ListBox on the main form)?
I've read that you need to invoke it but everything I read seems to give me a headache and make me need to lie down in a dark room for a few hours.
Is anyone capable of explaining as though you're speaking to a 2 year old? :)
Any help would be much appreciated.

A: You need to invoke a delegate to update your GUI if you're going to update it from another thread that from where it was created.
1º Your delegate must match (have the same signature) than the method you'll use:
    Delegate Sub LogMessageExampleDelegate(ByVal x As Integer, ...)

Signature means that the delegate must return and receive the same types than your function/method.
2º Call your function to update GUI using delegate. This for example inside your update GUI function:
If yourListBox.InvokeRequired Then
    yourListBox.Invoke(New LogMessageExampleDelegate(AddressOf THE_FUNCTION_WHICH_UPDATES_THE_GUI_NAME), parameter_value)
Else
    'Just call your function
End If

With, as example:
sub addToListBox(byval text as string)
    myListBox.Items.add(text)
end sub

So your invoke would be:
If yourListBox.InvokeRequired Then
    yourListBox.Invoke(New LogMessageExampleDelegate(AddressOf addToListBox), "Item 1")
Else
    'Just call your function
    addToListBox("Item 1")
End If

PS: I wrote it two times so hope I didn't mess up with something without noticing it.


text:
Q: Read a stdclassObject to get the key and values Below is the resultset of a Query.  How can I print out the column names User,UserID and place?
print_r($report_results);

$report_results is the object shown below
Array (
        [0] => stdClass Object ( [User] => Helton, Joshua [UserID] => 31 [place] => Dallas)
        [1] => stdClass Object ( [User] => Miller, Jona [UserID] => 95 [place] => Cupertino)
        [2] => stdClass Object ( [User] => Sarah, Thomson [UserID] => 32 [place] => Las Vegas)
    )

A: Use object access notation, -> as in
var_dump($stdObj->User, $stdObj->UserID, $stdObj->place);

What you have dumped is an array, though, so you'll have to access elements within the array:
var_dump($array[0]->User);

You probably just want to iterate over the array.
foreach ($user as $array) {
    var_dump($user->User, $user->UserID, $user->place);
}


text:
Q: Django - dictionary passed in redirect is not showing in template I'm trying to redirect my signup form to the same form after saving the values also I wanted to return a dictionary in the redirect response.
But the following code is not working.
urls.py
url(r'^signupform/$', views.render_signup, name='render_signup'),
url(r'^signup/$', views.sign_up_account_admin, name='sign_up_account_admin'),

views.py
def render_signup(request):
    """
    """
    data_dict = {"some_keys":"some_values"}
    return render(request, "admin.html", data_dict)

def sign_up_account_admin(request):
    """
    """
    user = None
    user, msg = save_form_data(request)
    req_dict = {"msg": msg}
    if user:
        ret = redirect('homepage') #-- This works pretty fine
    else:
        ret = redirect('/signupform/', resp = req_dict) #-- This redirects but I don't get the `resp` Objects in the template
    return ret

Html Temlpate

      =={{resp}}
      ===>>>>>>>{{resp.msg}}

And the Output HTML

      ==
      ===>>>>>>>

A: You can't pass random kwargs to the redirect function.
The arguments passed to redirect are the same positional or keyword arguments which you would have passed had you used reverse() to generate the url. These arguments are used to reverse resolve the url.
As mentioned in the Django docs about using redirect() function.

By passing the name of a view and optionally some positional or
  keyword arguments; the URL will be reverse resolved using the
  reverse() method.

Now, as you are passing a hardcoded url, then the argument passed along with it will get discarded.
The recommended way to use redirect() with a hardcoded url as mentioned in Django docs is:
def my_view(request):
    ...
    return redirect('/some/url/')

So, what you can do now is use to Django sessions or maybe pass a parameter in the url to access the value of resp in the render_signup view.
Solution-1 Using Django Sessions
One way is to use Django sessions to get the msg.
def sign_up_account_admin(request):
    """
    """
    user = None
    user, msg = save_form_data(request)
    req_dict = {"msg": msg}
    if user:
        ret = redirect('homepage') #-- This works pretty fine
    else:
        request.session['resp'] = msg # set in session
        ret = redirect('/signupform/')

    return ret

Then in your render_signup view, you can do:
def render_signup(request):
    """
    """
    resp = request.session.get('resp') # get the value from session
    data_dict = {'resp': resp, ..}
    return render(request, "admin.html", data_dict)

Solution-2 Pass it as url parameters
Another solution is to pass it in url as query parameters.
ret = redirect('/signupform/?resp=%s'%msg) # pass as query parameter

Then in the render_signup view, get this value from request.GET.
resp = request.GET.get('resp') # get the value of 'resp' from request.GET
data_dict = {'resp':resp, ..}

EDIT:
If you have multiple parameters to send which are in a dictionary, then you can use urllib.urlencode() to encode the dictionary and send it with the url.
encoded_string = urllib.urlencode(my_dict)
redirect('/signupform/?%s'%encoded_string) # attach the encoded string in the url

Then in your view, you can retrieve the keys of the dictionary from request.GET.
value1 = request.GET.get('key1')
value2 = request.GET.get('key2')


text:
Q: How to remove "?" from python data frame field I have a python dataframe,named data. In this data frame one field is price with data type object.
The data frame contains missing value in different fields & missing values are "?". I want to replace that missing value. I thought to replace "?" by "NaN" & then apply fillna(). So I wrote this code
data.replace('?','NaN')

But after executing this code,I'm still getting "?" while I'm writing below line
data['price'].max()

Can you suggest me what is the correct way? i'm using python 3.6 on Windows 10

A: Try using np.nan
Ex:
import pandas as pd
import numpy as np
data = pd.DataFrame({"price": ["?", "Hello", "?", "World"]})
data["price"].replace('?',np.nan, inplace=True)
print(data.fillna(0))

Output:
   price
0      0
1  Hello
2      0
3  World

A: Try using inplace=True to keep changes in your original dataframe.
data.replace('?','NaN', inplace=True)


text:
Q: MongoDB not working (v6.0) on macOS error 3584 I have tried multiple fixes, including uninstalling and reinstalling mongodb following the mongodb official documentation, but nothing seems to fix my issue. Here is the error message I get when I run brew services start:
mongodb-community error  3584 <username> ~/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist

When I try to connect with the mongosh command, I get this error:
Connecting to:      mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.1

MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017

It seems that is because mongod has not been started? I don't have anything essential saved to the /data folder so any method including wiping all files associated with mongodb would be fine by me. Here are the logs:
{"t":{"$date":"2022-12-19T17:51:14.407-05:00"},"s":"I",  "c":"NETWORK",  "id":4915701, "ctx":"-","msg":"Initialized wire specification","attr":{"spec":{"incomingExternalClient":{"minWireVersion":0,"maxWireVersion":17},"incomingInternalClient":{"minWireVersion":0,"maxWireVersion":17},"outgoing":{"minWireVersion":6,"maxWireVersion":17},"isInternalClient":true}}}
{"t":{"$date":"2022-12-19T17:51:14.408-05:00"},"s":"I",  "c":"CONTROL",  "id":23285,   "ctx":"thread1","msg":"Automatically disabling TLS 1.0, to force-enable TLS 1.0 specify --sslDisabledProtocols 'none'"}
{"t":{"$date":"2022-12-19T17:51:14.408-05:00"},"s":"I",  "c":"NETWORK",  "id":4648602, "ctx":"thread1","msg":"Implicit TCP FastOpen in use."}
{"t":{"$date":"2022-12-19T17:51:14.408-05:00"},"s":"I",  "c":"REPL",     "id":5123008, "ctx":"thread1","msg":"Successfully registered PrimaryOnlyService","attr":{"service":"TenantMigrationDonorService","namespace":"config.tenantMigrationDonors"}}
{"t":{"$date":"2022-12-19T17:51:14.408-05:00"},"s":"I",  "c":"REPL",     "id":5123008, "ctx":"thread1","msg":"Successfully registered PrimaryOnlyService","attr":{"service":"TenantMigrationRecipientService","namespace":"config.tenantMigrationRecipients"}}
{"t":{"$date":"2022-12-19T17:51:14.408-05:00"},"s":"I",  "c":"REPL",     "id":5123008, "ctx":"thread1","msg":"Successfully registered PrimaryOnlyService","attr":{"service":"ShardSplitDonorService","namespace":"config.tenantSplitDonors"}}
{"t":{"$date":"2022-12-19T17:51:14.409-05:00"},"s":"I",  "c":"CONTROL",  "id":5945603, "ctx":"thread1","msg":"Multi threading initialized"}
{"t":{"$date":"2022-12-19T17:51:14.409-05:00"},"s":"I",  "c":"CONTROL",  "id":4615611, "ctx":"initandlisten","msg":"MongoDB starting","attr":{"pid":5662,"port":27017,"dbPath":"/data/db","architecture":"64-bit","host":"Angelas-MBP"}}
{"t":{"$date":"2022-12-19T17:51:14.409-05:00"},"s":"I",  "c":"CONTROL",  "id":23352,   "ctx":"initandlisten","msg":"Unable to resolve sysctl {sysctlName} (number) ","attr":{"sysctlName":"hw.cpufrequency"}}
{"t":{"$date":"2022-12-19T17:51:14.409-05:00"},"s":"I",  "c":"CONTROL",  "id":23351,   "ctx":"initandlisten","msg":"{sysctlName} unavailable","attr":{"sysctlName":"machdep.cpu.features"}}
{"t":{"$date":"2022-12-19T17:51:14.409-05:00"},"s":"I",  "c":"CONTROL",  "id":23403,   "ctx":"initandlisten","msg":"Build Info","attr":{"buildInfo":{"version":"6.0.3","gitVersion":"f803681c3ae19817d31958965850193de067c516","modules":[],"allocator":"system","environment":{"distarch":"aarch64","target_arch":"aarch64"}}}}
{"t":{"$date":"2022-12-19T17:51:14.409-05:00"},"s":"I",  "c":"CONTROL",  "id":51765,   "ctx":"initandlisten","msg":"Operating System","attr":{"os":{"name":"Mac OS X","version":"21.6.0"}}}
{"t":{"$date":"2022-12-19T17:51:14.409-05:00"},"s":"I",  "c":"CONTROL",  "id":21951,   "ctx":"initandlisten","msg":"Options set by command line","attr":{"options":{}}}
{"t":{"$date":"2022-12-19T17:51:14.409-05:00"},"s":"I",  "c":"NETWORK",  "id":5693100, "ctx":"initandlisten","msg":"Asio socket.set_option failed with std::system_error","attr":{"note":"acceptor TCP fast open","option":{"level":6,"name":261,"data":"00 04 00 00"},"error":{"what":"set_option: Invalid argument","message":"Invalid argument","category":"asio.system","value":22}}}
{"t":{"$date":"2022-12-19T17:51:14.409-05:00"},"s":"E",  "c":"CONTROL",  "id":20557,   "ctx":"initandlisten","msg":"DBException in initAndListen, terminating","attr":{"error":"NonExistentPath: Data directory /data/db not found. Create the missing directory or specify another path using (1) the --dbpath command line option, or (2) by adding the 'storage.dbPath' option in the configuration file."}}
{"t":{"$date":"2022-12-19T17:51:14.409-05:00"},"s":"I",  "c":"REPL",     "id":4784900, "ctx":"initandlisten","msg":"Stepping down the ReplicationCoordinator for shutdown","attr":{"waitTimeMillis":15000}}
{"t":{"$date":"2022-12-19T17:51:14.409-05:00"},"s":"I",  "c":"REPL",     "id":4794602, "ctx":"initandlisten","msg":"Attempting to enter quiesce mode"}
{"t":{"$date":"2022-12-19T17:51:14.409-05:00"},"s":"I",  "c":"-",        "id":6371601, "ctx":"initandlisten","msg":"Shutting down the FLE Crud thread pool"}
{"t":{"$date":"2022-12-19T17:51:14.409-05:00"},"s":"I",  "c":"COMMAND",  "id":4784901, "ctx":"initandlisten","msg":"Shutting down the MirrorMaestro"}
{"t":{"$date":"2022-12-19T17:51:14.409-05:00"},"s":"I",  "c":"SHARDING", "id":4784902, "ctx":"initandlisten","msg":"Shutting down the WaitForMajorityService"}
{"t":{"$date":"2022-12-19T17:51:14.409-05:00"},"s":"I",  "c":"NETWORK",  "id":20562,   "ctx":"initandlisten","msg":"Shutdown: going to close listening sockets"}
{"t":{"$date":"2022-12-19T17:51:14.409-05:00"},"s":"I",  "c":"NETWORK",  "id":4784905, "ctx":"initandlisten","msg":"Shutting down the global connection pool"}
{"t":{"$date":"2022-12-19T17:51:14.409-05:00"},"s":"I",  "c":"CONTROL",  "id":4784906, "ctx":"initandlisten","msg":"Shutting down the FlowControlTicketholder"}
{"t":{"$date":"2022-12-19T17:51:14.409-05:00"},"s":"I",  "c":"-",        "id":20520,   "ctx":"initandlisten","msg":"Stopping further Flow Control ticket acquisitions."}
{"t":{"$date":"2022-12-19T17:51:14.409-05:00"},"s":"I",  "c":"NETWORK",  "id":4784918, "ctx":"initandlisten","msg":"Shutting down the ReplicaSetMonitor"}
{"t":{"$date":"2022-12-19T17:51:14.409-05:00"},"s":"I",  "c":"SHARDING", "id":4784921, "ctx":"initandlisten","msg":"Shutting down the MigrationUtilExecutor"}
{"t":{"$date":"2022-12-19T17:51:14.409-05:00"},"s":"I",  "c":"ASIO",     "id":22582,   "ctx":"MigrationUtil-TaskExecutor","msg":"Killing all outstanding egress activity."}
{"t":{"$date":"2022-12-19T17:51:14.409-05:00"},"s":"I",  "c":"COMMAND",  "id":4784923, "ctx":"initandlisten","msg":"Shutting down the ServiceEntryPoint"}
{"t":{"$date":"2022-12-19T17:51:14.409-05:00"},"s":"I",  "c":"CONTROL",  "id":4784925, "ctx":"initandlisten","msg":"Shutting down free monitoring"}
{"t":{"$date":"2022-12-19T17:51:14.409-05:00"},"s":"I",  "c":"CONTROL",  "id":4784927, "ctx":"initandlisten","msg":"Shutting down the HealthLog"}
{"t":{"$date":"2022-12-19T17:51:14.409-05:00"},"s":"I",  "c":"CONTROL",  "id":4784928, "ctx":"initandlisten","msg":"Shutting down the TTL monitor"}
{"t":{"$date":"2022-12-19T17:51:14.409-05:00"},"s":"I",  "c":"CONTROL",  "id":6278511, "ctx":"initandlisten","msg":"Shutting down the Change Stream Expired Pre-images Remover"}
{"t":{"$date":"2022-12-19T17:51:14.409-05:00"},"s":"I",  "c":"CONTROL",  "id":4784929, "ctx":"initandlisten","msg":"Acquiring the global lock for shutdown"}
{"t":{"$date":"2022-12-19T17:51:14.409-05:00"},"s":"I",  "c":"-",        "id":4784931, "ctx":"initandlisten","msg":"Dropping the scope cache for shutdown"}
{"t":{"$date":"2022-12-19T17:51:14.409-05:00"},"s":"I",  "c":"CONTROL",  "id":20565,   "ctx":"initandlisten","msg":"Now exiting"}
{"t":{"$date":"2022-12-19T17:51:14.409-05:00"},"s":"I",  "c":"CONTROL",  "id":23138,   "ctx":"initandlisten","msg":"Shutting down","attr":{"exitCode":100}}


text:
Q: instagram_business_account ID missing on Facebook graph api When i test my app on the Graph Explorer the instagram_business_account id doesn't appear in my list...
We manage several facebook pages, and some others work fine with same parameters.
I have all the permissions needed, manage_pages business_management and instagram_basic.
I already tried to to go back to personal instagram account and then business again but it doesn't change anything...
Any new solution for this known issue?
ref : https://developers.facebook.com/support/bugs/177912116363088/?disable_redirect=0

A: Try to add pages_read_engagement permission to your auth request. You don't need manage_pages just to get Instagram ID, its overkill.


text:
Q: JavaScript Array to HTML - function to show specific elements What I would like to do:

*

*When the user types, show similar or matching results from array (Maximum 5 results).

*Each element has to be unique

*When the user uses 'backspace', remove also the last result(s)

When you run the code, you'll see the problem.

var allUsers = document.getElementById('searchUsers');
var value; // User input
let currentCount = 0;
let newValues = [];
var names = ["James", "Liam", "Olivia", "Mia", "Sophia", "Sophie", "Oli",
  "Olivia", "Ana", "Bianca", "James"
];

$("#searchUsers").on("keyup", function() {
  value = $(this).val();
})

$("#searchUsers").on("keyup", function() {
  let result = names.filter(item => item.toLowerCase().indexOf(value) > -1);

  // If user presses the backspace
  allUsers.addEventListener('keyup', function(event) {
    const key = event.key; // const {key} = event;
    if (key === "Backspace" && currentCount > 1) {

      //alert(key);
    }
  });

  for (let i = 0; i < result.length; i++) {

    newValues.push(result[i]);

    // If there's not input, empty the list
    if (value === '') {
      newValues = [];

    }

  }

  // Gets 5 last elements of array
  var filterResult = (newValues.slice((newValues.length - result.length), newValues.length));

  // Removes all duplicatess
  let uniqueElement = [...new Set(filterResult)];

  for (const user of uniqueElement) {
    var element = document.getElementById("searchUsers2");
    element.innerHTML += `<li><a href="/profile/${user}">${user}</a></li>`;

  }

})

  <input id="searchUsers" type="text" placeholder="Search">

A: Maybe you don't need much scripting when using a datalist.

$(`.searchArticle`).append(
  `<datalist id="users">
   ${["James", "Liam", "Olivia",
      "Mia", "Sophia", "Sophie", "Oli",
      "Olivia", "Ana", "Bianca"]
      .map(v => `<option value="${v}">`)
      .join(``)}</datalist>`);

  <input type="text" id="searchUsers"
    placeholder="🔍 search users" list="users">

A: You can try below one

*

*Create a seperate function instead of calling $("#searchUsers").on("keyup", function()  each time

*No need for keeping extra variables like value and currentCount

*Keep global variables at top

const allUsers = document.getElementById('searchUsers');
    const element = document.getElementById("searchUsers2");

    const names = ["James", "Liam", "Olivia", "Mia", "Sophia", "Sophie", "Oli",
      "Olivia", "Ana", "Bianca", "James"
    ];

    $("#searchUsers").on("keyup", function() {
      // call this function by passing user input
      filterResults($(this).val())
    })

  function filterResults(value){
     element.innerHTML = "";
     let newValues = [];
     const result = names.filter(item => item.toLowerCase().indexOf(value) > -1);

     if (value === '' || !result.length) {
          newValues = [];
      }

      for (let i = 0; i < result.length; i++) {
        newValues.push(result[i]);
      }

      if(value === '' || !newValues.length) {
          return;
       }

      // Gets 5 last elements of array
      var filterResult = (newValues.slice((newValues.length - result.length), newValues.length));

      // Removes all duplicatess
      let uniqueElement = [...new Set(filterResult)];

      for (const user of uniqueElement) {
        element.innerHTML += `<li><a href="/profile/${user}">${user}</a></li>`;

      }
  }

      <input id="searchUsers" type="text" placeholder="Search">


text:
Q: Can I help the Galaxy S III browser recognize a street address? I'm always surprised and delighted when the web browser on my Android phone recognizes a phone number or a street address, and offers to call the number or map the address.
On a new web site I'm building, the address of the business is recognized on my Droid 4, but not on my wife's Samsung GS3.
Is there any way I can apply some mark up to the business address to help the browser recognize it?


text:
Q: How do I select a row with max count doing a group by I have a table posts with columns (id, user_name, thread_id).
A user can submit multiple posts for a thread. thread to post is one to many.
I need to find out who submitted max posts per thread. So the result would be
Max(Count), user_name, thread_id WHERE there will be only one row per thread_id.
The table is too huge so I wanted to get the query optimized as much as I could.

A: You can try with the group by and having clauses:
select t.user_name, t.thread_id , count(*) as max_count
from tbl t
group by t.user_name, t.thread_id
having count(*) = ( select count(*) as ttl
                    from tbl
                    where thread_id = t.thread_id
                    group by user_name
                    order by ttl desc
                    limit 1 )

A: select user_name, thread_id, count(*) as max
from tbl t
group by user_name, thread_id
having count(*) = (
    select count(*) as cnt /* most posts per user per thread */
    from tbl
    group by user_name, thread_id
    order by cnt desc
    limit 1
)

Easy workaround for system that don't have limit is:
select user_name, thread_id, count(*) as max
from tbl t
group by user_name, thread_id
having count(*) = (
    select max(cnt) from (
        select count(*) as cnt /* most posts per user per thread */
        from tbl
        group by user_name, thread_id
    ) m
)

A: Suppose you have a table posts with fields id, user_name & thread_id.
If you want to query which user has posted the most posts on a specific thread and the total number of his posts from a table, you can achieve that with this MySQL query:
SELECT user_name, thread_id, count(thread_id)
FROM posts WHERE thread_id=1 GROUP BY user_name
ORDER BY count(thread_id) DESC LIMIT 1;

It will return only one row...


text:
Q: How to get Facebook friend list with gender using Graph API in Android? I want to get Facebook friend list with gender in my Android project.
My Code;
 new GraphRequest(
                AccessToken.getCurrentAccessToken(),
                "/"+ AccessToken.getCurrentAccessToken().getUserId()+"/taggable_friends",
                null,
                HttpMethod.GET,
                new GraphRequest.Callback() {
                    public void onCompleted(GraphResponse response) {
                        try {
                            JSONObject jsonObjectData = response.getJSONObject();
                            JSONArray jsonArrayData = jsonObjectData.getJSONArray("data");
                            personList = new ArrayList<Person>();
                            for (int i = 0; i < jsonArrayData.length(); i++) {
                                JSONObject jsonObjectPerson = jsonArrayData.getJSONObject(i);
                                Person person = new Person();
                                person.setId(jsonObjectPerson.optString("id"));
                                person.setName(jsonObjectPerson.optString("name"));

                                personList.add(person);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
        ).executeAsync();

This method return to me 3 parameters; ID, NAME and PICTURE. I try to change endPoint with "/friends" but this time data was null. When I try to use FQL, I get this message:

"fql is deprecated for versions v2.1 and higher".

How can I get Facebook friend list with gender?

A: I'm afraid it's not possible via Graph Api at the moment.
You could try Graph API Explorer to check its possibility.


text:
Q: Home Page Wordpress on Free MAMP does not work I have installed MAMP (free version) on my Mac and I see the Start Page but I have a problem:
I deployed wordpress but browser say unable to connect (basically I cannot see wordpress page in browser).
In Document Root if I put a static html file I am able to see it in the browser. I am also able to see wordpress administrative pages and all other pages but home page. I have 8888 and 8889 for php and mysql ports. I do not know how to debug the issues. php, apache and mysql do not report any particular problems.
I configured virtual hosts following this guide:
http://foundationphp.com/tutorials/vhosts_mamp.php
The strange thing when I put http://localhost:8888/mywebsite in the browser it is redirected to localhost/mywebsite.
In /etc/hosts I have:
127.0.0.1 localhost

In httpd.conf I activated:
Include /Applications/MAMP/conf/apache/extra/httpd-vhosts.conf

and in this file I have:
NameVirtualHost *:8888

<VirtualHost *:8888>
    ServerAdmin myuser@gmail.com
    DocumentRoot "/Applications/MAMP/htdocs"
    ServerName localhost
    ErrorLog "logs/mywebsite-error_log"
    CustomLog "logs/mywebsite-access_log" common
</VirtualHost>

Hope someone could help.

A: I found the solution. After several debugging I found that this guide is correct: http://foundationphp.com/tutorials/vhosts_mamp.php
You need: 1. In /etc/hosts add your virtual hosts like:
127.0.0.1 localhost
127.0.0.1 mywebsite

before I only used localhost because I hoped to use this host in browser but I found it's required to define a new host like mywebsite.

*In httpd.conf I activated:
Include /Applications/MAMP/conf/apache/extra/httpd-vhosts.conf

*In this file I have:

    ServerAdmin myuser@gmail.com
    DocumentRoot "/Applications/MAMP/htdocs"
    ServerName mywebsite
    ErrorLog "logs/mywebsite-error_log"
    CustomLog "logs/mywebsite-access_log" common


text:
Q: How to define within scope for (hidden) div with id-tag (capybara testing)? Does somebody know how i use the visible option in a within to define a scope within a tagged div like <div id="contact-persons" class="row"> so that my testing scope for within will look like within("#contact-persons", visible: false) do ... end?
I just tried it exactly that way, but still cannot find the div.


text:
Q: virtual-machine (vm image) of java development environment with an app server and database I am looking for a free downloadable vmware image with java development environment; an app server and database is installed/set up. I will be using it for personal educational purpose. It would be nice, if I get some running hello world examples in different latest java technologies (Spring, hibernate, JSF). I prefer guest OS as windows.
Greatly appreciate if someone can send a link to download this. Thanks

A: Oracle website gives similar to what I was looking. Not sure, if I can expect a windows image.
http://www.oracle.com/technetwork/middleware/weblogic/downloads/weblogic-developer-vm-303434.html


text:
Q: Folder monitoring and event triggering according to folder status in php There is a folder in which xml files are beeing copied at no particular time, when an event is happening. I want a php way to inspect the folder's status and when an xml file arrives, an event will be triggered.(ex.call to the xml parser). So which is the best way (in php) to monitor a folder and trigger events according to it's status? Thanx!

A: Haven't tried it, but maybe Inotify can help you:

inotify is a Linux kernel subsystem that acts to extend filesystems to notice changes to the filesystem, and report those changes to applications.

There's a PHP extension for inotify, see InotifyDocs and inotifyPECL.
Another alternative if you're running on linux is to use a PHP-independent daemon to monitor  a directory for changes. You can use dnotify for it (obsoleted by inotify), something like:
dnotify -a -r -b -s /path/ -e <command>;

It will execute the command each time one of the files in other folder are modified (-a -r -b -s = any access/recursive directory lookup/run in background/no output).
Related:

*

*Read file change in php (linux equivalent of tail -f )

*How to efficiently monitor a directory for changes on linux?

A: You should take a look at FAM (File Alteration Monitor). PHP 4 based binary extension (beta status); documentation.

A: I think the most simple way to do this is to use cron job to examine the folder every minute. The other option is to trigger your php script from another script/program that copies new xml file to the directory.
Cron enables you to run your script every minute. If you want instant response you should write a shell script(http://aplawrence.com/Unixart/watchdir.html) that constanlty runs in the background or maybe pearl daemon to you detect new file and trigger your php script to examine changes.

A: Use cron to regularly scandir() the directory.


text:
Q: Transform a string of an object to an object I am trying to take an object from the server-side and bring it to an ejs file to use it in javascript.
The object inside the javascript looks like this:
   var span = document.createElement("SPAN");
   span.innerHTML = "<%= JSON.stringify(positions) %>";
   var positions = span.innerText;
   span.remove()
   console.log(positions)

and it returns a string like this one:
"
    {
        '0': { foo: foo },
        '1': { foo: boo },
        '2': { foo: doo }
    }
    "

Is there a way for me to do that?
Thanks!

A: You can just assign a variable to the stringified positions (no quotes) and it becomes a javascript object.  Then to display it stringify that object again.
(This "renders it as JS from the outset").
const myJSObj = <%= JSON.stringify(positions) %>;
console.log(JSON.stringify(myJSObj));


text:
Q: compatible wireless adapter for ad hoc/Access Point on Ubuntu I would like to find a wireless adapter for enabling ad hoc or AP mode on Ubuntu that works "out of box".  I have tried edimax 7811Un without success and would like to find another adapter that will work without giving me any trouble.  Can someone recommend an adapter that they have had success with?

A: To create an ad-hoc or hotspot using your wireless adapter, DON'T use the Create New Wi-fi Network from the network icon in the top panel. One reason is because you'll only be able to do WEP security.
Rather, go to Edit Connections... in the network icon menu, and ADD a new Wi-Fi profile. In the Wi-fi tab, change the mode to ad-hoc or hotspot, and in the security tab, choose WPA2. As seen below...


text:
Q: Splash screen does not transition to my main menu screen I am currently working on an application that is supposed to have a transition from the splash screen to a main menu screen. I have done the coding but it doesnt seem to do that. Can anyone please spot out what is wrong with the code below?
Splash screen Activity:
public class MainActivity extends Activity {

public static final String GAME_PREFERENCES = "GamePrefs";
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splash);

    // fade in animation
    TextView logo1 = (TextView)findViewById(R.id.TextViewTopTitle);
    Animation fade1 = AnimationUtils.loadAnimation(this, R.anim.fade_in);
    logo1.startAnimation(fade1);

    // custom animation
    Animation spining = AnimationUtils.loadAnimation(this, R.anim.custom_anim);
    LayoutAnimationController controller = new LayoutAnimationController(spining);
    TableLayout table = (TableLayout)findViewById(R.id.TableLayout01);
    for(int i=0; i < table.getChildCount(); i++)
    {
        TableRow row = (TableRow) table.getChildAt(i);
        row.setLayoutAnimation(controller);
    }

    startAnimations();

    // saving game preferences
    SharedPreferences settings = getSharedPreferences(GAME_PREFERENCES, MODE_PRIVATE);
    SharedPreferences.Editor prefEditor = settings.edit();
    prefEditor.putString("UserName", "JaneDoe");
    prefEditor.putInt("UserAge", 22);
    prefEditor.commit();
}

private void startAnimations() {
    // Transition from Splash screen to Main Menu screen
    Animation fade2 = AnimationUtils.loadAnimation(this, R.anim.fade_in2);
    fade2.setAnimationListener(new AnimationListener() {
        public void onAnimationEnd(Animation animation)
        {
            startActivity(new Intent(MainActivity.this,QuizMenuActivity.class));
            MainActivity.this.finish();
        }
        public void onAnimationStart(Animation animation)
        {
            //Nothing
        }
        public void onAnimationRepeat(Animation animation)
        {
            //Nothing
        }
    });
}

Main Menu Activity:
public class QuizMenuActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.menu);
    }
}

My layouts are done already. Any suggestions on what is wrong here?

A: Maybe the AnimationListener is never triggered? If you just want the Splash screen to display then leave.. how about just trying adding the following to your Splash activity's onCreate:
Thread timer = new Thread() {
    public void run() {
        try {
            sleep(5000); // Sets delay before splash appears
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            Intent main = new Intent(Splash.this, MainMenu.class);
            startActivity(main);
            finish();
        }
   };
   timer.start();

It sleeps for 5 seconds then goes to the MainMenu.
Edit
I think your AnimationListener is never being invoked, so try adding fade2.startNow() here:
private void startAnimations() {
    // Transition from Splash screen to Main Menu screen
    Animation fade2 = AnimationUtils.loadAnimation(this, R.anim.fade_in2);
    fade2.setAnimationListener(new AnimationListener() {
    public void onAnimationEnd(Animation animation)
    {
        startActivity(new Intent(MainActivity.this,QuizMenuActivity.class));
        MainActivity.this.finish();
    }
    public void onAnimationStart(Animation animation)
    {
        //Nothing
    }
    public void onAnimationRepeat(Animation animation)
    {
        //Nothing
    }
});
fade2.startNow();
}

For more information on how to use Animation.startNow() or Animation.start():
animation.start() or animation.startNow() does not start the animation immediately


text:
Q: How to return specified text if true in pandas column I am creating a dataframe that looks at the column 'Study Title' and returns a text category in a new column 'Categories' if the 'Study Title' column contains specific text in the string. For example, if the study title contains the text 'Child Care' or 'Head Start' then it will return a value if true in the new 'Categories' column with 'Child Care' for 'Child Care' and 'School Readiness' for 'Head Start', etc. How can I add multiple conditions with more values if true so that I have a list of strings to look for that returns a value I assign?
This is an example of what I would like the output to look like where the column 'Categories' returns the value 'Child Care' if the title contains the words 'Child Care'.

I have more conditions I want to include for other title considerations like 'School Readiness' for 'Head Start'. So far what I have only returns a true/false value based on the one condition for 'Child Care'.

This is the code I have so far:
df['Categories'] = df['Study Title'].str.contains(r'Child Care', na=True)
df

Copy-Paste CSV Sample

Study Title,URL,Funding Agency,Category
"American Indian and Alaska Native Head Start Family and Child Experiences Survey, 2015",https://www.icpsr.umich.edu/web/ICPSR/studies/36804,United States Department of Health and Human Services. Administration for Children and Families. Office of Planning Research and Evaluation,
American Indian and Alaska Native Head Start Family and Child Experiences Survey 2019 (AIAN FACES 2019),https://www.icpsr.umich.edu/web/ICPSR/studies/38028,United States Department of Health and Human Services. Administration for Children and Families. Office of Planning Research and Evaluation,
"Carolina Abecedarian Project (ABC) and the Carolina Approach to Responsive Education (CARE), Age 21 Follow Up Study, 1993 - 2003",https://www.icpsr.umich.edu/web/ICPSR/studies/32262,United States Department of Health and Human Services. Administration for Children and Families. Office of Planning Research and Evaluation,
"Child Care and Development Fund (CCDF) Policies Database, 2009",https://www.icpsr.umich.edu/web/ICPSR/studies/32261,United States Department of Health and Human Services. Administration for Children and Families. Office of Planning Research and Evaluation,
"Child Care and Development Fund (CCDF) Policies Database, 2011",https://www.icpsr.umich.edu/web/ICPSR/studies/34390,United States Department of Health and Human Services. Administration for Children and Families. Office of Planning Research and Evaluation,
"Child Care and Development Fund (CCDF) Policies Database, 2012",https://www.icpsr.umich.edu/web/ICPSR/studies/34902,United States Department of Health and Human Services. Administration for Children and Families. Office of Planning Research and Evaluation,
"Child Care and Development Fund (CCDF) Policies Database, 2013",https://www.icpsr.umich.edu/web/ICPSR/studies/35482,United States Department of Health and Human Services. Administration for Children and Families. Office of Planning Research and Evaluation,
"Child Care and Development Fund (CCDF) Policies Database, 2014",https://www.icpsr.umich.edu/web/ICPSR/studies/36276,United States Department of Health and Human Services. Administration for Children and Families. Office of Planning Research and Evaluation,
"Child Care and Development Fund (CCDF) Policies Database, 2015",https://www.icpsr.umich.edu/web/ICPSR/studies/36581,United States Department of Health and Human Services. Administration for Children and Families. Office of Planning Research and Evaluation,

A: What you're trying to do is essentially a mapping, which a basic membership test is not suitable for. You need to define a mapping function:
In [8]: def determine_category(title):
   ...:     if "Child Care" in title:
   ...:         return "Child"
   ...:     elif "Head Start" in title:
   ...:         return "School Readiness"
   ...:     return "no matching category"
   ...:

In [9]: df["Study Title"].apply(determine_category)
Out[9]:
0        School Readiness
1        School Readiness
2    no matching category
3                   Child
4                   Child
5                   Child
6                   Child
7                   Child
8                   Child
Name: Study Title, dtype: object


text:
Q: Getting data from a Google Drive Spreadsheet Cell I am attempting to display some data in a HTML document coming from a Google Drive Spreadsheet cell by using the following javascript code:
var URL = "https://docs.google.com/spreadsheet/pub?key=0AhQNAOBkQ63ldFl6N0tDeTFDYWVXeF8yQ0kwdWtoZnc&gid=0&single=true&gid=0&output=txt&range=";
$.ajax(URL + "D2").done(function(result){ document.getElementById("demo").innerHTML=result; });

This works fine when I have an HTML tag with a "demo" id, but I need the value as a variable so I can display it anywhere in the page and not in a specific HTML element.

A: You'll need to specify async:false because otherwise the variable probably won't end up getting set until after you've tried to use it.  Also, for some scope reasons it's easiest to reference a variable in the context of the window (ie window.variable).
var URL = "https://docs.google.com/spreadsheet/pub?key=0AhQNAOBkQ63ldFl6N0tDeTFDYWVXeF8yQ0kwdWtoZnc&gid=0&single=true&gid=0&output=txt&range=";

window.variable = "test";

$.ajax({url:URL + "D2",async:false}).done(function(result){ window.variable = result; });

document.getElementById("demo").innerHTML = window.variable;

http://jsfiddle.net/8Dk4Y/1/


text:
Q: How to disallow user to select time form extjs timefield not more than maxDate set in datepicker How to disallow user to select time form extjs timefield not more than maxDate set in datepicker?
   Ext.create('Ext.panel.Panel', {
        title: 'Choose a future date:',
        width: 330,
        bodyPadding: 10,
        renderTo: Ext.getBody(),
        items: [{
            xtype: 'datepicker',
            minDate: new Date(),
            maxDate: Ext.Date.add(new Date(), Ext.Date.HOUR, + 14)
        },
        {
            xtype: 'timefield',
            minValue: '12:00 AM',
            maxValue: '11:00 PM',
            increment: 60,
            value: '12:00 AM',
        }]
    });


text:
Q: explicit 'this' binding precedence vs implicit 'this' binding precedence I'm reading "this & object prototype" by Kylie Simpson. The author says that explicit binding have a higher precedence than implicit.
I understand that "obj1.foo()" is the implicit binding and that "obj1.foo(obj2) is the explicit binding.
However, if implicit is higher, I do not understand how the last 2 lines result in that?
function foo()  console.log( this.a );
var obj1 = { a: 2, foo: foo };
var obj2 = { a: 3, foo: foo };

obj1.foo(); // 2
obj2.foo(); // 3
obj1.foo.call( obj2 ); // 3
obj2.foo.call( obj1 ); // 2

Ok, reading of such an expression : obj1.foo.call(obj2) , i think, according to that book, that there is two way to resolve the "this".
First : explicit binding. obj2 is forced to be the context of foo.
Second : implicit binding, obj1 is the context of the function following the dot in "obj1 dot xxxxxx", and the "this" of that function is obj1.
I mean, i was thinking that there is no logical way to determine if we choose "explicit first" or "implicit first". It is a "convention".
I hope it is more clear.

A: The this keyword is overridden in the last 2 statements via the native call method for foo of the respective objects. The first parameter specified for call is the reference that this will be in the scope of foo. The other arguments for call that aren't there are just passed as parameters to foo. Thus, with call, the bound reference is not really prioritized, but rather replaced entirely for that function call only. Respectively, those last 2 statements are just the same as:
obj2.foo();
obj1.foo();


text:
Q: How can I access each thread's stack using THREAD type in QNX? What is the THREAD datatype in QNX neutrino?
How can I access to content of a thread's stack using its THREAD* value just like when you debug stack frames using gdb command tool?

A: You can retrieve the register values of a particular thread in your own or (if you are root) in another process via the /proc filesystem.
First you use the DCMD_PROC_CURTHREAD devctl() to select the thread you want to retrieve the registers of:
http://www.qnx.com/developers/docs/6.5.0_sp1/index.jsp?topic=%2Fcom.qnx.doc.neutrino_prog%2Fprocess.html&cp=13_7_3_4_7&anchor=DCMD_PROC_CURTHREAD
After that you use DCMD_PROC_GETREG to retrieve the value of registers, including the stack pointer.
If you are doing this from another thread of the same process then you can use the value of SP as it is because you are in the same address space.
If you are doing this from another process then you need to read() the address space via /proc/PID/as as described at:
http://www.qnx.com/developers/docs/6.5.0_sp1/index.jsp?topic=%2Fcom.qnx.doc.neutrino_prog%2Fprocess.html&cp=13_7_3_4_1&anchor=Address_space