text:
Q: CDI injection doesn't inject on WebSphere 8.5 also CDI Facet causes Exception After failure getting a CDI @Inject to work  i.e, the following was not injected and got a null :
    private Standardizating standardizeService;

@Inject
public void setStandardizating(Standardizating standardizeService) {

    this.standardizeService = standardizeService;
}

Class to inject :
 @Default
 public class StandardizationService extends Service implements Standardizating {

(I have META-INF\beans.xml)
I noticed that CDI 1.0 is a facet in my Eclipse/Kepler for WAS 8.5. I turned the facet on and I got the following exception (at least now I can see that some sort of CDI is operative ... I didn't see anything in the logs earlier).
[09/01/15 15:06:14:097 EST] 00000091 StandaloneEJB I StandaloneEJBLifeCycle   startApplication OpenWebBeans Container is starting...
[09/01/15 15:06:14:136 EST] 00000091 Helpers       W   NMSV0606E: Object is not of any type which can be bound.
[09/01/15 15:06:14:140 EST] 00000091 BeansDeployer E BeansDeployer deploy
                             java.lang.RuntimeException:
com.ibm.ws.naming.util.CannotBindObjectException: Object is not of any type which can be bound.
    at com.sun.jersey.server.impl.cdi.CDIExtension.initialize(CDIExtension.java:196)
    at com.sun.jersey.server.impl.cdi.CDIExtension.beforeBeanDiscovery(CDIExtension.java:297)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
    at java.lang.reflect.Method.invoke(Method.java:611)
    at org.apache.webbeans.event.ObserverMethodImpl.notify(ObserverMethodImpl.java:285)
    at org.apache.webbeans.event.NotificationManager.fireEvent(NotificationManager.java:455)
    at org.apache.webbeans.container.BeanManagerImpl.fireEvent(BeanManagerImpl.java:415)
    at org.apache.webbeans.config.BeansDeployer.fireBeforeBeanDiscoveryEvent(BeansDeployer.java:260)
    at org.apache.webbeans.config.BeansDeployer.deploy(BeansDeployer.java:159)
    at org.apache.webbeans.lifecycle.AbstractLifeCycle.startApplication(AbstractLifeCycle.java:124)
    at com.ibm.ws.webbeans.common.CommonLifeCycle.startApplication(CommonLifeCycle.java:106)
    at com.ibm.ws.webbeans.services.JCDIComponentImpl.startEJBLifeCycle(JCDIComponentImpl.java:588)
    at com.ibm.ws.webbeans.services.JCDIComponentImpl.stateChanged(JCDIComponentImpl.java:562)
    at com.ibm.ws.runtime.component.ApplicationMgrImpl.stateChanged(ApplicationMgrImpl.java:1120)
    at com.ibm.ws.runtime.component.DeployedApplicationImpl.fireDeployedObjectEvent(DeployedApplicationImpl.java:1353)
    at com.ibm.ws.runtime.component.DeployedApplicationImpl.setState(DeployedApplicationImpl.java:294)
    at com.ibm.ws.runtime.component.DeployedApplicationImpl.setState(DeployedApplicationImpl.java:289)
    at com.ibm.ws.runtime.component.DeployedApplicationImpl.start(DeployedApplicationImpl.java:978)
    at com.ibm.ws.runtime.component.ApplicationMgrImpl.startApplication(ApplicationMgrImpl.java:774)
    at com.ibm.ws.runtime.component.ApplicationMgrImpl.startApplicationDynamically(ApplicationMgrImpl.java:1374)
    at com.ibm.ws.runtime.component.ApplicationMgrImpl.start(ApplicationMgrImpl.java:2179)
    at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.start(CompositionUnitMgrImpl.java:445)
    at com.ibm.ws.runtime.component.CompositionUnitImpl.start(CompositionUnitImpl.java:123)
    at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.start(CompositionUnitMgrImpl.java:388)
    at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.access$500(CompositionUnitMgrImpl.java:116)
    at com.ibm.ws.runtime.component.CompositionUnitMgrImpl$1.run(CompositionUnitMgrImpl.java:663)
    at com.ibm.ws.security.auth.ContextManagerImpl.runAs(ContextManagerImpl.java:5384)
    at com.ibm.ws.security.auth.ContextManagerImpl.runAsSystem(ContextManagerImpl.java:5600)
    at com.ibm.ws.security.core.SecurityContext.runAsSystem(SecurityContext.java:255)
    at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.startCompositionUnit(CompositionUnitMgrImpl.java:677)
    at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.startCompositionUnit(CompositionUnitMgrImpl.java:621)
    at com.ibm.ws.runtime.component.ApplicationMgrImpl.startApplication(ApplicationMgrImpl.java:1266)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
    at java.lang.reflect.Method.invoke(Method.java:611)
    at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:49)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
    at java.lang.reflect.Method.invoke(Method.java:611)
    at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:256)
    at javax.management.modelmbean.RequiredModelMBean$4.run(RequiredModelMBean.java:1148)
    at java.security.AccessController.doPrivileged(AccessController.java:252)
    at com.ibm.oti.security.CheckedAccessControlContext.securityCheck(CheckedAccessControlContext.java:30)
    at sun.misc.JavaSecurityAccessWrapper.doIntersectionPrivilege(JavaSecurityAccessWrapper.java:41)
    at javax.management.modelmbean.RequiredModelMBean.invokeMethod(RequiredModelMBean.java:1142)
    at javax.management.modelmbean.RequiredModelMBean.invoke(RequiredModelMBean.java:995)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:848)
    at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:774)
    at com.ibm.ws.management.AdminServiceImpl$1.run(AdminServiceImpl.java:1335)
    at com.ibm.ws.security.util.AccessController.doPrivileged(AccessController.java:118)
    at com.ibm.ws.management.AdminServiceImpl.invoke(AdminServiceImpl.java:1228)
    at com.ibm.ws.management.application.sync.StartDeploymentTask.startDeployment(StartDeploymentTask.java:247)
    at com.ibm.ws.management.application.sync.StartDeploymentTask.fullAppUpdate(StartDeploymentTask.java:119)
    at com.ibm.ws.management.application.sync.StartDeploymentTask.performTask(StartDeploymentTask.java:107)
    at com.ibm.ws.management.application.sync.AppBinaryProcessor$ExpandApp.expand(AppBinaryProcessor.java:1711)
    at com.ibm.ws.management.application.sync.AppBinaryProcessor.postProcessSynchronousExt(AppBinaryProcessor.java:751)
    at com.ibm.ws.management.bla.sync.BLABinaryProcessor.postProcess(BLABinaryProcessor.java:599)
    at com.ibm.ws.management.bla.sync.BLABinaryProcessor.onChangeCompletion(BLABinaryProcessor.java:476)
    at com.ibm.ws.management.bla.sync.BinaryProcessorWrapper.onChangeCompletion(BinaryProcessorWrapper.java:109)
    at com.ibm.ws.management.repository.FileRepository.postNotify(FileRepository.java:1924)
    at com.ibm.ws.management.repository.FileRepository.update(FileRepository.java:1433)
    at com.ibm.ws.management.repository.client.LocalConfigRepositoryClient.update(LocalConfigRepositoryClient.java:189)
    at com.ibm.ws.sm.workspace.impl.WorkSpaceMasterRepositoryAdapter.update(WorkSpaceMasterRepositoryAdapter.java:665)
    at com.ibm.ws.sm.workspace.impl.RepositoryContextImpl.update(RepositoryContextImpl.java:1998)
    at com.ibm.ws.sm.workspace.impl.RepositoryContextImpl.synch(RepositoryContextImpl.java:1946)
    at com.ibm.ws.sm.workspace.impl.WorkSpaceImpl.synch(WorkSpaceImpl.java:549)
    at com.ibm.ws.management.configservice.ConfigServiceImpl.save(ConfigServiceImpl.java:719)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
    at java.lang.reflect.Method.invoke(Method.java:611)
    at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:49)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
    at java.lang.reflect.Method.invoke(Method.java:611)
    at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:256)
    at javax.management.modelmbean.RequiredModelMBean$4.run(RequiredModelMBean.java:1148)
    at java.security.AccessController.doPrivileged(AccessController.java:252)
    at com.ibm.oti.security.CheckedAccessControlContext.securityCheck(CheckedAccessControlContext.java:30)
    at sun.misc.JavaSecurityAccessWrapper.doIntersectionPrivilege(JavaSecurityAccessWrapper.java:41)
    at javax.management.modelmbean.RequiredModelMBean.invokeMethod(RequiredModelMBean.java:1142)
    at javax.management.modelmbean.RequiredModelMBean.invoke(RequiredModelMBean.java:995)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:848)
    at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:774)
    at com.ibm.ws.management.AdminServiceImpl$1.run(AdminServiceImpl.java:1335)
    at com.ibm.ws.security.util.AccessController.doPrivileged(AccessController.java:118)
    at com.ibm.ws.management.AdminServiceImpl.invoke(AdminServiceImpl.java:1228)
    at com.ibm.ws.management.remote.AdminServiceForwarder.invoke(AdminServiceForwarder.java:346)
    at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1465)
    at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:85)
    at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1306)
    at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1398)
    at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:829)
    at javax.management.remote.rmi._RMIConnectionImpl_Tie.invoke(_RMIConnectionImpl_Tie.java:751)
    at javax.management.remote.rmi._RMIConnectionImpl_Tie._invoke(_RMIConnectionImpl_Tie.java:158)
    at com.ibm.CORBA.iiop.ServerDelegate.dispatchInvokeHandler(ServerDelegate.java:669)
    at com.ibm.CORBA.iiop.ServerDelegate.dispatch(ServerDelegate.java:523)
    at com.ibm.rmi.iiop.ORB.process(ORB.java:523)
    at com.ibm.CORBA.iiop.ORB.process(ORB.java:1575)
    at com.ibm.rmi.iiop.Connection.doRequestWork(Connection.java:3039)
    at com.ibm.rmi.iiop.Connection.doWork(Connection.java:2922)
    at com.ibm.rmi.iiop.WorkUnitImpl.doWork(WorkUnitImpl.java:64)
    at com.ibm.ejs.oa.pool.PooledThread.run(ThreadPool.java:118)
    at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1862)
Caused by: com.ibm.ws.naming.util.CannotBindObjectException: Object is not of any type which can be bound.
    at com.ibm.ws.naming.util.Helpers.processJavaObjectForBinding(Helpers.java:718)
    at com.ibm.ws.naming.jndicos.CNContextImpl.doRebind(CNContextImpl.java:2076)
    at com.ibm.ws.naming.jndicos.CNContextImpl.rebind(CNContextImpl.java:697)
    at com.ibm.ws.naming.jndicos.CNContextImpl.rebind(CNContextImpl.java:717)
    at com.sun.jersey.server.impl.cdi.CDIExtension.initialize(CDIExtension.java:193)
    ... 108 more

There are some Jersey libraries used in this Jar as well for Jersey JAX-RS but this exception seems to be referencing IBM libraries. NMSV0606E seems to be highlighing a problem with the object not being a CORBA object, EJB, serialized object etc. I'm just trying to inject a simple object which I think I should be able to do with CDI. It says in the facet CDI 1.0 Does that support simple object injection -- I'm haven't been able to determine this.
Any help would be appreciated Thanks

A: There might be two issues with your app:

*

*If you want to use Jersey instead of default WebSphere JAX-RS provider you have to correctly configure it as isolated shared library - check this - JAX-RS Jersey 2.10 support in Websphere 8

*If you replace the JAX-RS container, unfortunately CDI  will not work in these classess. See here.

When disabling the JAX-RS runtime environment, JAX-RS features are not
  available, including base JAX-RS runtime capabilities, Enterprise
  JavaBeans (EJB) runtime integration, Java Contexts and Dependency
  Injection (JCDI) runtime integration, and Servlet 3.0 web container
  integration.

So unless you really have to use Jersey, I'd recommend to switching to defalut WebSphere JAX-RS implementation, then your CDI will work.


text:
Q: The "grey market" of loans In Hebrew, the term "grey market" refers to a market of loans given by private lenders, with the following characteristics:

*

*Usury rates are much higher: even 1% per day is common.

*Collection is much stricter: a defaulting debtor is subject to mental and physical violence and may even be murdered.

*Lenders are usually related to and cooperate with underworld criminal organizations.

The term has a very strong negative connotation. Most people strongly hate or fear the "grey market" of loans.
In contrast, the term "grey market" in English refers to something entirely different - a legal but unofficial market of products. It doesn't have such a strong negative connotation.
What English term best describes the "grey market" of loans which I described above?

A: In AmE, this type of lender is a "Loan Shark," and the practice is thus some times called "loan sharking."

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the most efficient way to run a large number of simple queries without overloading the db? Let's say I have a method
public async Task SaveItemToDb(ItemEntity item) { ... }

which saves a single item the db and let's say I need to run it with 500,000 items and for business reasons I can't do bulk operations (e.g. I can't make a SaveItemsToDb(IEnumerable<ItemEntity> items)).
I'm wondering what the best way is to do this so that I don't overload the db with queries running simultaneously and yet each query can be considered independent of each other. Is this the case for Task.WhenAll(...)?

A: You could make sure you have at most numTasks running. The tricky bit at the end is to make sure you wait till all the tasks have finished. Unfortunately CountDownEvent does not have an async version so it is blocking but maybe that is not a big deal.
The code below doesn't handle the errors in any of the tasks correctly. You may want to improve it.
async Task ProcessTasks(IEnumerable<Task> tasks, int numTasks){
    var count = new CountDownEvent(0);
    SemaphoreSlim semaphore = new SemaphoreSlim(numTasks);
    foreach(var task in tasks){
        await semaphore.WaitAsync();
        task.ContinueWith(_=>{
            semaphore.Release();
            count.Signal();
            }
        );
    }
    count.Wait(); // Wait till the count reaches zero
}


text:
Q: BCM4360 on MacbookPro running QubesOS - Kernel does not bind modul Help!
I have installed on a Qubes Standalone Debian-11 VM which is running on a MacbookPro the Broadcom-sta-dkms package.
The installation does NOT indicate any errors.
lsmod shows the wl module:
user@sys-wifi:~$ sudo lsmod|grep wl
wl                   6471680  0
cfg80211              983040  1 wl
The wl.ko module is present:
user@sys-wifi:~$ sudo find / -name wl.ko -print
/var/lib/dkms/broadcom-sta/6.30.223.271/5.10.0-21-amd64/x86_64/module/wl.ko
find: '/run/user/1000/doc': Permission denied
/usr/lib/modules/5.10.0-21-amd64/updates/dkms/wl.ko
I have added the module to /etc/modules
user@sys-wifi:~$ cat /etc/modules
# /etc/modules: kernel modules to load at boot time.
#
# This file contains the names of kernel modules that should be loaded
# at boot time, one per line. Lines beginning with "#" are ignored.
wl
rfkill shows NOTHING!
user@sys-wifi:~$ sudo rfkill list all
inxi -n shows NO driver:
user@sys-wifi:~$ sudo inxi -n
Network:   Device-1: Intel 82371AB/EB/MB PIIX4 ACPI type: network bridge driver: N/A
Device-2: Broadcom BCM4360 802.11ac Wireless Network Adapter driver: N/A
IF-ID-1: eth0 state: up speed: N/A duplex: N/A mac: 00:16:3e:5e:6c:00
nmcli does NOT show any wireless interface:
user@sys-wifi:~$ sudo nmcli
eth0: connected to VM uplink eth0
"eth0"
ethernet (vif), 00:16:3E:5E:6C:00, hw, mtu 1500
ip4 default
inet4 10.137.0.21/32
route4 10.138.8.117/32
route4 0.0.0.0/0
inet6 fe80::216:3eff:fe5e:6c00/64
route6 fe80::/64
lo: unmanaged
"lo"
loopback (unknown), 00:00:00:00:00:00, sw, mtu 65536
DNS configuration:
servers: 10.139.1.1 10.139.1.2
interface: eth0
Use "nmcli device show" to get complete information about known devices and
"nmcli connection show" to get an overview on active connection profiles.
Consult nmcli(1) and nmcli-examples(7) manual pages for complete usage details.
dmesg shows no errors:
user@sys-wifi:~$ sudo dmesg|grep wl
The output of lshw
user@sys-wifi:~$ sudo lshw -C network
*-network UNCLAIMED
description: Network controller
product: BCM4360 802.11ac Wireless Network Adapter
vendor: Broadcom Inc. and subsidiaries
physical id: 6
bus info: pci@0000:00:06.0
version: 03
width: 64 bits
clock: 33MHz
capabilities: pm msi pciexpress bus_master cap_list
configuration: latency=0
resources: memory:f2210000-f2217fff memory:f2000000-f21fffff
*-network
description: Ethernet interface
physical id: 1
logical name: eth0
serial: 00:16:3e:5e:6c:00
capabilities: ethernet physical
configuration: broadcast=yes driver=vif driverversion=5.10.0-21-amd64 ip=10.137.0.21 link=yes multicast=yes
lspci shown the wifi adapter and the assigned module wl but NO kernel module is in use
user@sys-wifi:~$ sudo lspci -k
00:00.0 Host bridge: Intel Corporation 440FX - 82441FX PMC [Natoma] (rev 02)
Subsystem: Red Hat, Inc. Qemu virtual machine
00:01.0 ISA bridge: Intel Corporation 82371SB PIIX3 ISA [Natoma/Triton II]
Subsystem: Red Hat, Inc. Qemu virtual machine
00:01.1 IDE interface: Intel Corporation 82371SB PIIX3 IDE [Natoma/Triton II]
Subsystem: Red Hat, Inc. Qemu virtual machine
Kernel driver in use: ata_piix
Kernel modules: ata_piix, ata_generic
00:01.3 Bridge: Intel Corporation 82371AB/EB/MB PIIX4 ACPI (rev 03)
Subsystem: Red Hat, Inc. Qemu virtual machine
Kernel modules: i2c_piix4
00:02.0 Unassigned class [ff80]: XenSource, Inc. Xen Platform Device (rev 01)
Subsystem: XenSource, Inc. Xen Platform Device
Kernel driver in use: xen-platform-pci
00:03.0 VGA compatible controller: Device 1234:1111 (rev 02)
Subsystem: Red Hat, Inc. Device 1100
Kernel driver in use: bochs-drm
Kernel modules: bochs_drm
00:04.0 USB controller: Intel Corporation 82801DB/DBM (ICH4/ICH4-M) USB2 EHCI Controller (rev 10)
Subsystem: Red Hat, Inc. QEMU Virtual Machine
Kernel driver in use: ehci-pci
Kernel modules: ehci_pci
00:06.0 Network controller: Broadcom Inc. and subsidiaries BCM4360 802.11ac Wireless Network Adapter (rev 03)
Subsystem: Apple Inc. BCM4360 802.11ac Wireless Network Adapter
Kernel modules: bcma, wl
user@sys-wifi:~$
Can anyone say anything about this puzzle?
Please help!
Thanks!

A: I finally came up with this solution.
Namely:

Assumption:
Some internet connection, either wired or wireless using a dongle (sys-usb)
Steps:

*

*Create a new qube based on the fedora-36 template

*

*Open Qube Manager → New qube

[Basic] Name and label: sys-wl
[Basic] Type: StandaloneVM (fully persistent)
[Basic] Template: fedora-36 (default)
[Basic] Networking: sys-net (you need somebody to connect you)
[Basic] Enable "Launch settings after creation"
[Advanced] Enable "Provides network access to other qubes"
[Advanced] Leave everything else as it is preconfigured

*

*After Creation the [Dom0] Settings window for sys-wl pops up

[Basic] Leave everything else as it is preconfigured
[Advanced] Disable "Include in memory balancing"
[Advanced] Kernel->Kernel: (provided by qube) → alternatively: (dom0): qvm-prefs sys-wl kernel ''
[Advanced] Virtualization->Mode: HVM

*Install broadcom-wl

Open a terminal
sys-wl: Terminal
Based on the information by balko here
[user@sys-wl ~]$ sudo dnf config-manager --set-enabled rpmfusion-free
[user@sys-wl ~]$ sudo dnf config-manager --set-enabled rpmfusion-free-updates
[user@sys-wl ~]$ sudo dnf config-manager --set-enabled rpmfusion-nonfree
[user@sys-wl ~]$ sudo dnf config-manager --set-enabled rpmfusion-nonfree-updates
[user@sys-wl ~]$ sudo dnf upgrade --refresh
[user@sys-wl ~]$ sudo dnf install broadcom-wl

*Blacklist unwanted modules

[user@sys-wl ~]$ sudo vi /etc/modprobe.d/blacklist.conf
blacklist b43
blacklist bcma

*Prepare settings for sys-wl prior to restart

Open Qube Manager
sys-wl->Settings
[Basic] Net qube: (none)(current)
[Basic] Leave everything else as it is already configured

*Detach BCM4350 in case that it is attached to any VM (in my case it was attached per default to sys-net)

*

*Shutdown the VM (my case: sys-net) to which the bcm4360 card has been assigned.

*Open Qube Manager → sys-net → Settings → Devices → click in the right window frame on "Broadcom Inc. and subsidiaries BCM4360 802.11ac Wireless Network Adapter", and move ( < ) it to the left one → OK

*Attach BCM4360 to the newly created sys-wl with the "magic" options

*

*Shutdown the newly created sys-wl

*Find out the BDF of your device
(dom0) qvm-pci
BACKEND:DEVID DESCRIPTION USED BY
…
dom0:02_00.0 Network controller: Broadcom Inc. and subsidiaries BCM4360 802.11ac Wireless Network Adapter
…

*

*Now: The magic one step. BEING WELL AWARE OF side channel attacks based on this description (How to use PCI devices | Qubes OS) attach the device to sys-wl:

(dom0) sudo qvm-pci a sys-bcm4360 dom0:02_00.0 --persistent -o no-strict-reset=true -o permissive=true

Show the changes:
(dom0) qvm-pci
BACKEND:DEVID DESCRIPTION USED BY
…
dom0:02_00.0 Network controller: Broadcom Inc. and subsidiaries BCM4360 802.11ac Wireless Network Adapter sys-bcm4360 (no-strict-reset=true, permissive=true)
…

*Reboot the whole system

*

*After you got your system up and running again, the Network Manager icon will be shown on the right part of the taskbar, and available networks will be shown, and you will be able to establish a wireless connection.


text:
Q: how to add innerhtml to the specific ul of whose parent li is clicked? i want to add some content to ul class="overl" of whose parent li has been clicked and remove innerhtml of any previous li that was clicked?

    <link rel="stylesheet" type="text/css" href="testtab.css"/>

abcy1 new*

avvva

gttd

trte

kkkf

once it's known then how to do that whichever li is clicked it's innerhtml gets something and the previous li that was clicked has innerthtml as null?

A: You're mixing up DOM methods and jQuery selectors:
$(this).innerHTML=""

Must be
 $(this).html("") // or $(this).empty()

Then, since you want to clear up your li, you'd want to do this :
$(this).parent().html("") // or $(this).parent().empty()

A: Try binding click on $(document).ready();
Like
$(document).ready(
   function(){
     $('.overl').html("");
     $('#chat ul li a').on('click', function (e) {
       $(this).parent().children('.chattng').children('.overl').html("Your message");
   });
  });


text:
Q: Small World clustering coefficients and characteristic path lengths I want to compute and compare the clustering coefficients and characteristic path lengths of 50 WS graphs for different values of    between  0  and  1 with n and d fixed.
Here is what I have so far:
n, d = 1000, 5
for p in range(0,1,50):
G1 = nx.watts_strogatz_graph(n, 2*d, p)

A: Something like this? Change the while loop to a for loop if you prefer with your range(0,1,50) or np.linspace(0,1,50)
i = 0
results={}
while i < 1:
   current_I = []
   current_C = []
   for _ in range(20):
      G = nx.watts_strogatz_graph(n = 1000,k = 4,p = i)
      current_I.append(nx.average_shortest_path_length(G))
      current_C.append(nx.average_clustering(G))
   results[i] = (np.mean(current_I), np.mean(current_C))
   i += .052631


text:
Q: Calculation over each row from a CSV - file with Python I want to do a calculation over each row from  csv-file in Python.
This is the loaddataa File:
import os
import pandas as pd

def loadData(relativPath):
    files = os.listdir(relativPath)
    path = os.path.abspath(relativPath)
    datas = list()
    for file in files:
        absPath = path + "/" + file
        print(absPath)
        data = pd.read_csv(absPath)
        datas.append(data)
    return datas

These were my first steps:
import math as m
import loaddataa as ld

dataListStride = ld.loadData("../Data/Fabienne")
    indexStrideData = 1
    strideData = dataListStride[indexStrideData]

def horizontal(yAngle, yAcceleration, xAcceleration):
    a = (m.cos(yAngle)*yAcceleration)-(m.sin(yAngle)*xAcceleration)
    return a

resultsHorizontal = list()

for i in range (len(strideData)):
    strideData_yAngle = strideData.to_numpy()[i, 2]
    strideData_xAcceleration = strideData.to_numpy()[i, 4]
    strideData_yAcceleration = strideData.to_numpy()[i, 5]
    ......
    ......

In the for - loop I don't know how to go on. The csv - file consists of 9 columns and 150 row. For the calculation I just need column 2, 4 and 5. The calculation with the formula in def horizontal shall be executed over each row, so that in the end I have 150 values. I hope it's clear what I want to do.
Thanks for helping me.

A: Call the horizontal() function in each cycle and add the result to your list using resultsHorizontal.append().

Code:
resultsHorizontal = list()

for i in range (len(strideData)):
    strideData_yAngle = strideData.to_numpy()[i, 2]
    strideData_xAcceleration = strideData.to_numpy()[i, 4]
    strideData_yAcceleration = strideData.to_numpy()[i, 5]
    resultsHorizontal.append(horizontal(strideData_yAngle, strideData_yAcceleration, strideData_xAcceleration))


text:
Q: React rendering an unexpected element EDIT: I imported something wrong :facepalm:
Let me first run down what code ive written to get this output then I will tell you the expected output and what im confused about
App.jsx
import React from "react";
import Home from "./components/pages/HomePage";
import store from "./ducks/store";
import { Provider } from "react-redux";
import { BrowserRouter, Route, Switch } from "react-router-dom";

const App = () => {
  return (
    <BrowserRouter>
      <Provider store={store}>
        <Switch>
          <Route exact path="/" component={Home} />
        </Switch>
      </Provider>
    </BrowserRouter>
  );
};

export default App;

Home.jsx
import React, { useEffect } from "react";
import FlexBox from "../../shared/FlexBox";
import BlogPostList from "./SortSettings";
import { useSelector, useDispatch } from "react-redux";
import { fetchAllBlogs } from "../../../ducks/blogs";
import {
  getBlogData,
  getBlogPosts,
  getBlogTags,
} from "../../../ducks/selectors";
import SpinLoader from "../../shared/SpinLoader";

const Home = () => {
  const blogData = useSelector((state) => getBlogData(state));
  const blogPosts = useSelector((state) => getBlogPosts(state));
  const blogTags = useSelector((state) => getBlogTags(state));
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(fetchAllBlogs());
  }, [dispatch]);

  // TODO: handle if blogData.requestError comes back as true

  if (blogData.isLoading || !blogPosts || !blogTags) {
    return (
      <FlexBox
        alignItems="center"
        justifyItems="center"
        width="100vw"
        height="100vh"
      >
        <SpinLoader />
      </FlexBox>
    );
  }

  return (
    <FlexBox height="100vh" width="100vw">
      <BlogPostList blogPosts={blogPosts} />
    </FlexBox>
  );
};

export default Home;

BlogPostList.jsx
import React from "react";
import BlogPost from "./BlogPost";
import FlexBox from "../../shared/FlexBox";

const BlogPostList = ({ blogPosts }) => {
  return (
    <FlexBox flexDirection="column">
      Why in the world is this rendering a SortSettings component AHHHHHH!
    </FlexBox>
  );
};

export default BlogPostList;

Now my question is this why is it that the Home component is rendering a  component as showed here https://gyazo.com/8cac1b28bdf72de9010b0b16185943bb what I would  expect the Home component to be rendering is a BlogPostList if anyone has an idea help would be appreciated ive been stuck on this for awhile now (im pretty new so this might just be a noob mistake so sorry if its something obvious)


text:
Q: Can a different (older) version of a similar directory tree be imported into SVN? Is it possible to import a directory tree into subversion if a large number of the files already exist in the repository? Many of the files that will be imported will match those in the repository, both in path and content, but some will be older, and some will be newer, and some files will be in either the repo or the imported tree but not the other. Is it possible to do this in such a way that the files getting imported are treated as the head of the repo so that changed, deleted files still maintain their history?

A: Here are the steps to get this work easily.

*

*Copy the directory over the svn directory with the option to no overwrite files.

*Do a recursive add on all the files in the directory (that will cause the new files to be added to svn.)

*Do another copy, the time allow overwrite.

*Commit

If you do it like this what will happen, is you will add all your files that didn't exist before in that directory to SVN, then you will overwrite the ones that did exist, which svn will see as a change.  You can then check those in.  I would do it in these steps to make sure that you separate those two actions, so you can validate they happen correctly independently.


text:
Q: Getting Intermittent 404 Not Found error in google Bigquery API Using Python 2.X to insert into Bigquery table from file
The method that i am using is load_table_from_file()
From today i started to recieve  404 with not much details
Here is the error
google.api_core.exceptions.NotFound: 404 PUT
https://www.googleapis.com/upload/bigquery/v2/projects/my_project/jobs?uploadType=resumable&upload_id=AEnB2UodF7My9IjTefRjWHDSIKZeBxDdjRhSmO9-DJH5l7md4Nt-4ZnpJ5n0u9H0MgEUWYATVfVORWywlgErRhWCuWvgB9PBFg:
Not Found`

Could someone guide ?

A: Looks like this was an issue with the google bigquery service itself!


text:
Q: How to properly handle mixed RF/digital design in HFSS 3Dlayout I have a big design imported from Altium into HFSS 3DLayout with several RFIC that I want to simulate. RF and Digital (SPI) nets are included in this design.
I'm interested mainly in the RF side of things so when  I cut out of the main design to analyze a specific area the shape of this cut-out is usually driven by the RF nets I want to include in my design. This means that sometimes I can have digital nets floating or partially floating in my sub-design.
I do not want  to remove completely the digital part as I would like to evaluate any possible effect on my RF design, and I'm not sure either that terminating this floating/partially floating nets to ground is the right solution.
How do I handle this situation?


text:
Q: Openlayers source tileWMS? TypeError: a.addEventListener is not a function I want to add features to my tile map, the problem ocurred when I try to use
ol.source.TileWMS

The error message is:

TypeError: a.addEventListener is not a function

However it works with
ol.source.OSM

My code:
var projection = new ol.proj.Projection({
    code: 'EPSG:32719',
    extent: [441867.78, 1116915.04, 833978.56, 10000000.00]
});

var extent = [576631.5686027373,8119272.722829757,655823.9357532839,8286730.359291008];

var wmsSource = new  ol.source.TileWMS({
    url: 'http://192.168.5.94:8080/geoserver/wms',
    params: {'LAYERS': 'layer'},
    ratio: 1,
    serverType: 'geoserver'
});

var wmsLayers = [
    new ol.layer.Tile({
        extent: extent,
        source: wmsSource
    })
];

var raster = new ol.layer.Tile({
    source: new ol.source.OSM()
});

var source = new ol.source.Vector({wrapX: false});

var vector = new ol.layer.Vector({
    source: source
});

var view = new ol.View({
    projection: projection,
    center: [593169.72792, 8174979.55243],
    //center: ol.proj.fromLonLat([-16.5088, -68.1388], projection),
    extent: extent,
    zoom: 12
});

var map = new ol.Map({
    controls: ol.control.defaults().extend([
        new ol.control.ScaleLine()
    ]),
    layers: [wmsLayers, vector],
    target: 'map',
    view: view
});

var draw; // global so we can remove it later

function addInteraction(){
    draw = new ol.interaction.Draw({
        source: source,
        type: 'Point'
    });
    map.addInteraction(draw);
}

map.on('singleclick', function(evt) {
    var coordinate = map.getEventCoordinate(evt.originalEvent);
    console.log(coordinate);
    document.getElementById('latitud').value = coordinate[0];
    document.getElementById('longitud').value = coordinate[1];
    addInteraction();
});

addInteraction();

Just change this line to change my layer, when I use  OSM, everything is ok... But when I use TileWMS the error appear

layers: [wmsLayers, vector],

Is there a conflict with TileWMS and Vector source?

A: ol.Map.layers expects an array of layers - your first object in the array is an array.
Try this:
var wmsLayer = new ol.layer.Tile({
   extent: extent,
   source: wmsSource
});

var map = new ol.Map({
   layers: [wmsLayer, vector],
   target: 'map',
   view: view
});


text:
Q: PHP, converted data into a Unix timestamp format I have a form that looks like this:
  Starts

    <select name="mm" id="mm">
      <option value="">---</option>
      <option value="01">Jan</option>
      <option value="02">Feb</option>
    </select>

    <select name="dd" id="dd">
   <option value="">--</option>
       <option value="1">01</option>
       <option value="2">02</option>
    </select>

      <input type="text" name="year" id="year" />

It is for people to choose the month | day | year. But the field in the database is Unix timestamp format.
Any ideas how can I take this data and converted into a Unix timestamp format for my database?

A: Another alternative, in mysql:
INSERT ... UNIX_TIMESTAMP('$year-$month-$day') ...

once appropriate data sanitization and sql injection prevention's been taken care of.

A: This'll help you, very easy to follow.
php strotime();

A: <?php
if ($_POST) {
    // convert POST to MySQL date format
    $date_string = sprintf('%04d-%02d-%02d', $_POST['year'], $_POST['mm'], $_POST['dd']);
    // if you need it in a UNIX timestamp, do the following
    $unix_timestamp = strtotime($date_string);
}

A: <?php

$time = new mktime($hour, $minute, $second, $month, $day, $year);

Or ..
<?php

$time = new DateTime();
$time->setDate($year, $month, $day);
// set both to 0, otherwise you will get the current time at the given day/month
$time->setTime($hour, $minute);

There's a ton of ways to do this in php, spend some time looking over the date/time functions

A: If the form fields are captured variables $mm, $dd, $yy, then
$timestemp = strtotime($yy . '-' . $mm . '-' . $dd);

will indeed give you an integer $timestamp (in epoch seconds), as Grigor correctly points out. But in general that may be only half the battle. In your case the Unix timestamp format makes things simple. But depending on your DB (and your associated drivers and DB abstraction layer) you may in some cases need to convert this into a date string of some form. For example, Oracle takes date strings of the form YYYY-MM-DD HH:MM:SS, which would be generated by
$oracle_date_string = gmdate("Y-m-d H:i:s", $timestamp);

A: After you have posted the form back to php, you will end up with your form data in
the special global $_POST.  If your user has selected a date completely, the code snippet
set $unix_ts to the unix timestamp of the date.
<?php

  $unix_ts = null;

  // validate date
  if (is_numeric($_POST['dd']) || is_numeric($_POST['mm']) || is_numeric($_POST['year'])) {
    if (($tmp = strtotime($_POST['mm']."/".$_POST['dd']."/".$_POST['year'])) !== false) {
       $unix_ts = $tmp;
    }
  } else {
    // display error message however you choose
    echo "Date not set
";
  }

  if ($unix_ts != null) {
     // do query
  }

?>


text:
Q: Estimating timeline or estimated timeline? What is the correct phrase to say in proper english:
Estimating timeline or estimated timeline?
Timeline is a noun so I conjecture that in front of it you should put an adjective. Thus my correct answer is Estimating Timeline. Am I correct?

A: Estimating is a conjugated version of the verb Estimate
Bill was estimating the distance he'd need to throw the rock.

Estimated is also a past tense verb, but is used like an adjective to provide more information about the history of the Timeline
This is an estimated timeline

Therefore, the timeline is estimated
Edit: More information

A: "Estimating (a/the) timeline" describes the process of guessing or roughly calculating the timeline.
"An/The estimated timeline" describes the result: not the process but the timeline itself.
The problem there seems to have been that "Estimating" is not adjective but a verb.


text:
Q: installing PHP 5.5.15 on Windows Server 2008 r2 64bit THe last time I installed PHP there was a great install program. Now I guess I have to do this version manually, So
I am trying to install PHP 5.5.15 on a Windows Server 2008 r2 64 bit and I am getting no where. I have followed the instruction multiple times and no dice.
If I try to check PHP by typing ...testphp.php into IE I get the following error:
HTTP Error 500.0 - Internal Server Error
C:\PHP\php-cgi.exe - The FastCGI process exited unexpectedly
Detailed Error Information
Module
FastCgiModule
Notification
ExecuteRequestHandler
Handler
PHPFast_CGI
Error Code
0xc0000135
IF I try to check using the Command Line I get error that says MSVCR110.dll is missing. I have installed MS Visual C++ 2010 x64 red... and also tried installing MS Visual C++ 2012 x64 red... and that did not fix the problem.
What am I doing wrong?
Steps used
Set up IIS
Download PHP (non thread safe), unzip to php folder
added Module Map...(FastCGIModule)
try to test php
also tried to modify the php.ini file before testing and no dice

A: Install the 32 bit version of VC11 or 9 from Microsoft. PHP is most likely 32 bit unless you selected the experimental version of PHP from their site - regardless of your OS type. I think that might solve your problem.
BUT...
I can't get php 5.5 to work on IIS 7.5 and Windows. I've tried for several days and I get 404.3 module handler or MIME type missing. No matter what the hell I do.


text:
Q: SSDT Doesn't import table indexes I am importing a database using SSDT, but the indexes are not loaded into my sqlproj.
I tried to update the script in my project and publish it, but it is ignored on publishing. All the options for indexes are selected on schema compare options.


text:
Q: Update display in Android This is what I am doing
ProgressBar myProgressBar = (ProgressBar) findViewById(R.id.progressBar);
myProgressBar.setVisibility(View.VISIBLE);
fetchData();
mainView();
myProgressBar.setVisibility(View.INVISIBLE);

But the progressbar does not show.
fetchData takes around 5 seconds and while it is running, the progressbar should be shown.
I guess the display is not updated while the App is busy. Is there a way to update the display before I call fetchData?

A: You should try using an AsyncTask. This will allow you to run fetchData() using the doInBackground(...) method and post progress using onProgressUpdate(...).

A: In the layout file give android:visibility="visible" for the ProgressBar. And when the content is loaded u set visibity to invisible.


text:
Q: UIView: Rounded Corners Without Performance Issues I am using an AQGridView to display my data in a grid on iPad. Every cell is a UIView subclass and typically, there are 18 cells displayed simultaneously.
I would like to add a round corner to these cells, so I set the cornerRadius property of the relevant layers (i.e. the layer of the main UIView and of one subview). However, this results in performance issues and the scrolling is not smooth any more. When using other CALayer properties, such as shadowOpacity, this does not happen.
Are there any other ways to add a rounded corner (apart from using an image)? Or am I doing something wrong?

A: I also saw a major performance hit when using cornerRadius on the layer of a view that contained a UIImageView subview.  Rasterization solved that problem:  view.layer.shouldRasterize = YES;

A: It could be where you're placing the setCornerRadius call. Make sure it's somewhere that only gets called once, not, for example, in a drawRect method.


text:
Q: How to solve the irrational inequality? Solve the inequality
$$\dfrac{2x^4+2x^2}{\sqrt{x+1}}+(x+2)\sqrt{x+1}>x ^3 + 2x^2 + 5x.$$
I tried. By putting $t = \sqrt{x+1}$, we have
$$2t^8-t^7-8t^6+t^5+15t^4-4t^3-11t^2+4t+4>0.$$
Using Maple, I got
$$(2t^2-t-2)(t^2-t-1)(t^4+t^3-t^2-t+2)>0.$$
How to solve the given inequality with another way?

A:
Try to make sure the coefficient of the largest degree of $t$ is positive.
Then, solve all the roots of the polynomial $P(t)=0$.
Then draw a picture as above.
Draw a axis.
Then draw a thread goes through the line from the roots. If there is multiple root, goes through the line and goes back. Right to left. Rightmost must be above the axis.
The positive intervals are above the axis.

A: Hint: You also want the condition that $ t \geq 0$.
Hint: The quartic polynomial $t^4 + t^3 - t^2 - t + 2 = (t^2 + 0.5 t -1)^2 + 0.75t^2 + 1$ is always positive for all real $t$.
You can continue from what you have (assuming your calculations are correct).

I'm not sure if this helps, but your inequality can be simplified to
$$ (x^2-x+2)(2x^2+2x+1) > x(x^2+2x+5) \sqrt{x+1}$$


text:
Q: Where does user click on progress bar? I have an audio player and a progress bar. I'm letting users click on the progress bar. When they click on the bar, it advances the audio player. The position where the user clicked on the progress bar is where the audio player should start. Here's my code.
So if the user clicks on the 80% position in the progress bar, the audio player should be 20% of the way from finishing playing the song.
  var aud = $('audio')[0];
  $('.progress-bar-wrapper').on('click', (e) => {
     var posX = e.pageX - $(this).offset().left;
     var percentage = parseInt((posX / $(this).width()) * 100);
     aud.currentTime = percentage/100 * aud.duration;
     $('.progress:eq(' + index + ')').css('width', percentage + '%');
  });

Unfortunately, this is not precise. When I click on the 80% position in the progress bar, it does not move the audio player to the 80% duration. What should I do?

A: I just ran your code with out changing too much, made a few little tweeks but your math seems to work good in my demo.
I change your percentage to parseFloat instead of parseInt which makes it more accurate.
See comments in code below and fiddle...
https://jsfiddle.net/joshmoto/v20ndcue/

// window on load
$(window).on('load', function(e) {

  // once audio loaded get the audio object
  let aud = $('audio')[0];

  // on prorgess bar wrapper click
  $(document).on('click', '.progress-bar', function(e) {

    // get x position in progress bar
    let posX = e.pageX - $(this).offset().left;
    let progressWidth = $(this).outerWidth();

    // create percentage from position etc
    let percentage = parseFloat((posX / progressWidth) * 100);

    // set the audio current time to progress position
    aud.currentTime = percentage / 100 * aud.duration;

    // update the progress bar width
    $('.progress',this).css('width', percentage + '%');

  });

});
HTML {
  height: 100%;
  min-height: 100%;
}

BODY {
  background: #20262E;
  padding: 10px;
  font-family: Helvetica;
  height: 100%;
}

AUDIO {
  width: 100%;
  padding: 0;
  margin: 0 0 15px 0;
}

.progress-bar {
  position: relative;
  height: 15px;
  overflow: hidden;
  border-radius: .5rem;
  background: #fff;
}

.progress-bar .progress {
  display: block;
  height: 100%;
  width: 0;
  background: #2e71ff;
}
<audio controls>
  <source src="https://dev.joshmoto.wtf/mp3/crane-flock-aproaching.mp3" type="audio/mpeg">
</audio>

https://jsfiddle.net/joshmoto/0qydrf3t/

Added a few more tweeks, but a little rough, to handle multiple audio clips, with a function to handle/return audio item data (globally)...
https://jsfiddle.net/joshmoto/0qydrf3t/


text:
Q: Attribute category not allowed on element li at this point I came across this Grid/List layout demo from this page, which is pretty neat, but the validator gives this error for the category filter:
Attribute category not allowed on element li at this point.

Here's the filter markup:

All

Category 1

Category 2

Category 3

Is it possible to fix this or use another attribute? Thank you.

A: Typically custom attributes (those not defined by the W3C) are prefixed with data-
so try: data-category=""

A: Follow @El Guapo's answer and change this line in the jQuery
var CategoryID = $(this).attr('category');

change to:
var CategoryID = $(this).data('category');

or:
var CategoryID = $(this).attr('data-category');


text:
Q: Git Inconsistent behavior of "checkout"? Consider these commands:
# create file myfile.txt
git add myfile.txt
git commit myfile.txt               # sha = SHA1
# modify myfile.txt
git status  # shows myfile.txt modified

git branch branch2
git checkout branch2                # myfile is not replaced
git status                          # shows myfile.txt modified
git add myfile.txt
git commit myfile.txt

git checkout master                 # myfile is replaced
git status                          # nothing to commit, working directory clean
# myfile.txt is back to original state SHA1

When branch2 is checked out, the working directory copy of myfile.txt is not modified.
However when master is checked out, the working directory copy of myfile.txt is modified, it is
replaced with that from the repo.
Is this inconsistent behavior? If not, what is the "mental model" to use that explains it?

A: The general mental model is that unstaged changes are left alone, and everything else in the working copy is updated when checking out a different commit.  Or as the docs put it:

git checkout <branch>
To prepare for working on <branch>, switch to it by updating the index and the files in the working tree, and by pointing HEAD at the branch. Local modifications to the files in the working tree are kept, so that they can be committed to the <branch>.

This is consistent with both cases that you've observed.


text:
Q: Suppress Application not responding message I am having Delphi windows application running in Windows Server 2008 R2, which will initiate request to windows service to populate data. While performing this task, application will become busy with the not responding message on the application title bar. At this time if we close the application, application will terminate with out displaying any message "the application is not responding. The program may respond again if you wait "
But the application running in Windows server 2016 is showing "the application is not responding. The program may respond again if you wait" while closing the application.

Can anyone suggest how to suppress this message with no code change and allow user to close the application if he wants to close?
disableProcessWindowsGhosting; code is not supposed to include in the application.

A: You have two main options:

*

*Call DisableProcessWindowsGhosting. This is not a great option in the sense that it suppresses the problem rather than solves it.

*Move the long running task into a worker thread and thereby allow your main thread to service the UI. This is the best practice solution.


text:
Q: Understanding Difference in results between two code solutions I am newbie here in more way than one, so please go easy on me :)
Here is a problem I was tasked with solving using javascript:
Print out the numbers from 1 - 20.
The rules:
For numbers divisible by 3, print out "Fizz".
For numbers divisible by 5, print out "Buzz".
For numbers divisible by both 3 and 5, print out "FizzBuzz" in the console.
Otherwise, just print out the number.
Here was my first attempt at approaching it:
 var numberArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];

for(var i = 0; i < numberArray.length; i++){
    if(i % 3 === 0 && i % 5 === 0){
       console.log("FizzBuzz");
    }
    else if(i % 3 === 0 && i % 5 !== 0){
        console.log("Fizz");
    }
    else if(i % 3 !== 0 && i % 5 === 0){
        console.log("Buzz");
    }
    else {
        console.log(numberArray[i]);
    }
}

This returned the following incorrect values:
FizzBuzz
2
3
Fizz
5
Buzz
Fizz
8
9
Fizz
Buzz
12
Fizz
14
15
FizzBuzz
17
18
Fizz
20
I then took a different approach which DID result in the correct answer:
    var fizBuzz = function() {
        for (i = 1; i < 21; i++) {
        if (i % 3 === 0 && i%5 === 0) {
        console.log ("FizzBuzz");
        } else if (i % 3 === 0) {
        console.log ("Fizz");
        } else if (i % 5 === 0) {
        console.log ("Buzz");
        } else {
        console.log (i);
        }
        }
};

fizBuzz();

Would someone be willing to help me understand what was wrong about the first approach? This is really bothering me :)

A: The problem is you were checking the divisibility of i (which starts at 0) rather than of numberArray[i] (which starts at 1).


text:
Q: PHP email with attached file always 41B and not working: Whenever i send an email with attachment the file is 41B and it is not working. How to fix it? I've tried with jpeg and zip and all was the same. The file is with its name and extension but it is 41B and cannot open it.
This is my code:
if($_POST){
    $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
    if(!empty($_POST['author']) && preg_match($email_exp,($_POST['email']))){
        $mail_to = "example@example.com";
        $from_mail = $_POST['email'];
        $from_name = $_POST['author'];
        $reply_to = "reply@example.com";
        $subject = "Subject";
        $boundary = md5(uniqid(time()));
        $message = "Author: ".$_POST['author']."
E-mail: ".$_POST['email']."";

        //Set e-mail headers
        $headers = "From: ".$from_name."<".$from_mail.">\r\n";
        $headers .= "Reply-To: ".$reply_to."\r\n";
        $headers .= "MIME-Version: 1.0\r\n";

        $headers .= "Content-Type: multipart/mixed;\r\nboundary=\"".$boundary."\"\r\n";
        $headers .= "This is a multi-part message in MIME format.\r\n";
        $headers .= "--".$boundary."\r\n";

        $headers .= "Content-type:text/html; charset=UTF-8\r\n";
        $headers .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
        $headers .= "$message\r\n";
        $headers .= "--".$boundary."\r\n";

        if(!empty($_FILES['picture1']['name']) || !empty($_FILES['picture2']['name']) || !empty($_FILES['picture3']['name']) || !empty($_FILES['picture4']['name']) || !empty($_FILES['picture5']['name'])){
            $file = array($_FILES['picture1']['tmp_name'], $_FILES['picture1']['name'], $_FILES['picture1']['size'],$_FILES['picture2']['tmp_name'],
            $_FILES['picture2']['name'],$_FILES['picture2']['size'], $_FILES['picture3']['tmp_name'], $_FILES['picture3']['name'], $_FILES['picture3']['size'],
            $_FILES['picture4']['tmp_name'], $_FILES['picture4']['name'], $_FILES['picture4']['size'], $_FILES['picture5']['tmp_name'],
            $_FILES['picture5']['name'], $_FILES['picture5']['size']);
            for($i=0;$i<15;$i+=3){
                if(!empty($file[$i])){
                    $headers .= "Content-Type: application/xml;\r\n name=\"".$file[$i+1]."\"\r\n";
                    $headers .= "Content-Transfer-Encoding: base64\r\n";
                    $headers .= "Content-Disposition: attachment;\r\n filename=\"".$file[$i+1]."\"\r\n";
                    $cnt = $file[$i].$file[$i+2];
                    $content = chunk_split(base64_encode($cnt));
                    $headers .= "\r\n".$content."\r\n";
                    $headers .= "--".$boundary."--\r\n";
                    echo $i;
                }
            }
        }
        if(mail($mail_to, $subject, "", $headers)){
            echo 'MAIL SENT';
        }else {
            echo 'MAIL FAILED';
        }

    }else{
        echo "The fields!";
    }
}

A: The solution was to replace
$cnt = $file[$i].$file[$i+2];

with:
$cnt = file_get_contents($file[$i]);

A: There are a number of problems with your code:

$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';

This regexp excludes a lot of valid email addresses, for example anything from the .museum domain, or the local-part in addresses such as ^_^@domain.example or "^stack\ exchange$"@domain.example.

$from_mail = $_POST['email'];
$from_name = $_POST['author'];
/* ... */
$headers = "From: ".$from_name."<".$from_mail.">\r\n";

You should ensure that there are no control characters (such as \r\n) in those variables. As it is, a malicious user can comfortably inject their own email headers (Bcc: or similar).

$message = "Author: ".$_POST['author']."
E-mail: ".$_POST['email']."";

You should run those $_POST variables through htmlspecialchars() to prevent malicious users from injecting arbitrary scripts or other elements of their choice.

$headers .= "Content-Type: multipart/mixed;\r\nboundary=\"".$boundary."\"\r\n";

This is wrong. You cannot put the boundary part on its own line. If you want to break a long header line, you have to use Folding White Space, i.e. a CR LF SP or CR LF HTAB sequence ("\r\n " or "\r\n\t").

$headers .= "Content-Type: multipart/mixed;\r\nboundary=\"".$boundary."\"\r\n";
$headers .= "This is a multi-part message in MIME format.\r\n";

The first line above is the end of the headers. The second line is the start of the message body. There must be a double "\r\n" between them. Semantically, everything from the second line should be passed through the third ($message) argument to mail(). The mail() funcion will do some trimming of the headers which may or may not interfere with your message bodies.

$headers .= "Content-Type: application/xml;\r\n name=\"".$file[$i+1]."\"\r\n";
$headers .= "Content-Transfer-Encoding: base64\r\n";
$headers .= "Content-Disposition: attachment;\r\n filename=\"".$file[$i+1]."\"\r\n";

You may want to ensure that there are no double quotes or control characters in the file names.

$cnt = $file[$i].$file[$i+2];
$content = chunk_split(base64_encode($cnt));

As you have noted yourself, you should use $cnt = file_get_contents($file[$i]). I mention it here for the sake of completeness.

$headers .= "\r\n".$content."\r\n";
$headers .= "--".$boundary."--\r\n";

This is wrong. The "\r\n--" ... "--" is a close-delimiter. You should use a dash-boundary between each file part, and the close-delimiter after the last part. See the syntax section below. Eg.
$headers .= "$message\r\n";
/*$headers .= "--".$boundary."\r\n";*/  /* <--- */

if (!empty /* ... */) {
    $file = /* ... */;

    for($i=0;$i<15;$i+=3){
        if(!empty($file[$i])){
/* ---> */  $headers .= "\r\n--$boundary\r\n";
            $headers .= "Content-Type: application/xml;\r\n name=\"".$file[$i+1]."\"\r\n";
            $headers .= "Content-Transfer-Encoding: base64\r\n";
            $headers .= "Content-Disposition: attachment;\r\n filename=\"".$file[$i+1]."\"\r\n";
            $cnt = file_get_contents ($file[$i]);
            $content = chunk_split(base64_encode($cnt));
            $headers .= "\r\n".$content;
            echo $i;
        }
    }
}
$headers .= "\r\n--$boundary--\r\n";  /* <--- */

MIME Syntax
This is an excerpt of what the structure of a multi-part message body looks like according to RFC 2046. (BNF syntax, somewhat simplified.)

multipart-body := [preamble CRLF]
                  dash-boundary CRLF
                  body-part *encapsulation
                  close-delimiter
                  [CRLF epilogue]

dash-boundary := "--" boundary

body-part := MIME-part-headers [CRLF *OCTET]

encapsulation := delimiter
                 CRLF body-part

delimiter := CRLF dash-boundary

close-delimiter := delimiter "--"

References

*

*RFC 5322 Internet Message Format

*RFC 2045 (MIME) Part One: Format of Internet Message Bodies

*RFC 2046 (MIME) Part Two: Media Types


text:
Q: Multiple weighted matrices in a SLX model in R Is there any packages or commands allow multiple weighted matrices in a spatial lagged X  (SLX) model?
I want to include two different weighted matrices with one dependent variable, but I cannot find any packages for it?
Theoretically, in spatial analysis, including multiple W matrices are not appropriate? If it is possible, how can I conduct analysis with W1 and W2? Do I have to do it by hand?(I meant, once create the lagged variable by multiplying W matrix and the key DV, and and run a OLS regression with the variables. Is it the right way applying multiple weighted matrices?
Thanks!
Dongjin


text:
Q: How to set 2 y-axis title (and/or label) on chartjs? I know that setting a title or a label on chartjs' charts takes only a few properties on chart options.
...
yAxes: [{
    scaleLabel: {
        display: true,
        labelString: "My Chart"
    }
}]
...

but, is there anyway to set 2 title/label on chartjs ? I'd like to add some sort of a sub-title.

A: There is no option for yAxes subtitles but you can use a secondary yAxis properly configured:
scales : {
    yAxes : [{
            scaleLabel : {
                display : true,
                labelString : "subtitle",
                fontStyle : 'italic'
            }
        }, {
            display : true,
            gridLines : {
                display : false,
                color : 'transparent'
            },
            ticks : {
                display : false
            },
            scaleLabel : {
                display : true,
                labelString : "My Chart title",
                fontStyle : 'bold',
                fontSize : 14
            }
        }
    ]
}

Check this fiddle: https://jsfiddle.net/beaver71/jg7Lgc43/


text:
Q: AS3 Make function listen to different kinds of events I have a login function that activates after the user enters his Username and Password and clicks the Login button. It works perfectly, but some people want to do things faster; instead of clicking the button after entering the password, they want to press Enter to Login... But at the same time, I want the Login button to work too. How do I make a function listen to 2 different kinds of events (a MouseEvent and a KeyboardEvent)?
I've tried things like checkLogin(e:MouseEvent || e:KeyboardEvent) But they just threw me errors.
Here's my code...
function checkLogin(e:MouseEvent):void
{
    trace("Submition Going Down!!");
    if (username.text == "" || password.text == "")
    {
        //Lots and lots of checks...
    else
    {
        //if the user and pass fields are valid
        logErrorT.text = "\n\nRequesting Login...";
        processLogin();
    }
}
loginButton.addEventListener(MouseEvent.CLICK, checkLogin);
//All this listens for clicks only.

A: It's quite simple actually. First, you have to un-limit the kind of event checkLogin listens for, like this:
function checkLogin(e:Event):void
{
    //code
}

Then you just need it to listen for the keyboard event...
function runCheck(e:KeyboardEvent):void
    {
        if (e.charCode == 13) //charCode 13 is Enter
        {
            checkLogin(e);
            //e is the KeyboardEvent.
        }
    }
password.addEventListener(KeyboardEvent.KEY_DOWN, runCheck);

Hope I helped, I didn't have this problem for too long, but I wasn't able to find an answer for it online either. So I thought I'd give any confused beginners the answer. Good Luck! ^^


text:
Q: Selenium driver throws error on Ubuntu 18.04 I am porting my code over from Windows to Ubuntu, I went ahead and installed java, and all the drivers, and built my jar file. While executing it, I am getting this error. I downloaded the Linux 64bit Chrome Driver for this.
Feb 01, 2021 12:20:51 PM org.openqa.selenium.remote.DesiredCapabilities chrome
INFO: Using `new ChromeOptions()` is preferred to `DesiredCapabilities.chrome()`
Starting ChromeDriver 89.0.4389.23 (61b08ee2c50024bab004e48d2b1b083cdbdac579-refs/branch-heads/4389@{#294}) on port 21398
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error: Chrome failed to start: exited abnormally.
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
Build info: version: 'unknown', revision: 'unknown', time: 'unknown'
System info: host: 'xxxx', ip: 'xxxxxx', os.name: 'Linux', os.arch: 'amd64', os.version: '4.15.0', java.version: '11.0.9.1'
Driver info: driver.version: ChromeDriver
remote stacktrace: #0 0x5567a65a12b9 <unknown>

        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
        at org.openqa.selenium.remote.W3CHandshakeResponse.lambda$errorHandler$0(W3CHandshakeResponse.java:62)
        at org.openqa.selenium.remote.HandshakeResponse.lambda$getResponseFunction$0(HandshakeResponse.java:30)
        at org.openqa.selenium.remote.ProtocolHandshake.lambda$createSession$0(ProtocolHandshake.java:126)
        at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
        at java.base/java.util.Spliterators$ArraySpliterator.tryAdvance(Spliterators.java:958)
        at java.base/java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:127)
        at java.base/java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:502)
        at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:488)
        at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
        at java.base/java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:150)
        at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
        at java.base/java.util.stream.ReferencePipeline.findFirst(ReferencePipeline.java:543)
        at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:128)
        at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:74)
        at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:136)
        at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
        at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:213)
        at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:131)
        at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:181)
        at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:147)
        at Main.main(Main.java:17)

The error seems to be starting from my jars main class line 17, which is this line.
driver = new ChromeDriver(desiredCapabilities);

Here is my entire code, that I am trying to execute.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
public class Main {
    public static WebDriver driver;

    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "chromedriver");
        DesiredCapabilities desiredCapabilities = DesiredCapabilities.chrome();
        ChromeOptions options = new ChromeOptions();
        options.addArguments("user-data-dir=Profile 1");
        desiredCapabilities.setCapability(ChromeOptions.CAPABILITY, options);
        driver = new ChromeDriver(desiredCapabilities);
        driver.get("https://google.com");
    }
}

A: Adding --disable-dev-shm-usage as an argument seems to solve the issue.
options.addArguments("--disable-dev-shm-usage");


text:
Q: PHP e Javascript - Desabilitar um botão submit se textarea estiver vazio No formulário do meu site, possuo um campo textarea e um botão submit. Segue o código dos dois:
<textarea name='texto1' id="txtBriefing" rows="5" style="font-family: Trebuchet MS; font-size: 16px; width: 394px; height: 100px" onkeyup="doSomething(this.value)" ></textarea>
<input name="btnEnvia" type="submit" value="Enviar" style="font-family: Trebuchet MS; font-size: 20px" />

Contudo, eu gostaria que esse botão só estivesse habilitado apenas se a textarea txtBriefing não estiver vazia. Já tentei alguns códigos em javascript com as funções onkeyup e onchange procurando na internet, mas nenhum funcionou até o momento.
O que pode ser feito pra esse caso?

A: Com JavaScript
Basta adicionar o ID no seu botão, e mudar o seu onkeyup do textarea para onkeyup="javascript: doSomething(this)"
function doSomething(input) {
    document.getElementById('btnEnvia').disabled = (input.value.length == 0);
}

Exemplo: http://jsfiddle.net/5kdy8L63/2/

Com jQuery
$(function(){
   $('#txtBriefing').on('keyup', function(){
      $('#btnEnvia').prop('disabled', ($(this).val().length == 0));
   });
});

Exemplo: http://jsfiddle.net/b9kzwjmt/

A: Acredito que o evento oninput seja o ideal para este tipo de situação, digo isto pq ele é disparado apenas quando o valor do input é alterado.
Em todo caso, te aconselho a evitar setar eventos JS e styles no arquivo HTML.

var txtBriefing = document.getElementById("txtBriefing");
var btnEnvia = document.getElementById("btnEnvia");

var onBriefingInput = function (event) {
  btnEnvia.disabled = !event.target.value;
}

txtBriefing.addEventListener("input", onBriefingInput);
txtBriefing.dispatchEvent(new Event('input'));
#txtBriefing {
  font-family: Trebuchet MS;
  font-size: 16px;
  width: 394px;
  height: 100px
}

#btnEnvia {
  font-family: Trebuchet MS;
  font-size: 20px
}
<textarea id="txtBriefing" name="texto1" rows="5"  ></textarea>
<input id="btnEnvia" name="btnEnvia" type="submit" value="Enviar" />

uma outra opção, é usar uma validação HTML5 textarea[required], desta forma o formulário não será enviado se a textarea estiver vazia.

#txtBriefing {
  font-family: Trebuchet MS;
  font-size: 16px;
  width: 394px;
  height: 100px
}

#btnEnvia {
  font-family: Trebuchet MS;
  font-size: 20px
}

/* O Estilo abaixo é valido apenas no FireFox. */
#form1:invalid #btnEnvia {
  color: grey;
}
<form id="form1">
  <textarea id="txtBriefing" name="texto1" rows="5" required ></textarea>
  <input id="btnEnvia" name="btnEnvia" type="submit" value="Enviar" />
</form>


text:
Q: What is the best datastructure to use in Java for a "multidimensional" list? I need a dictionary-like data structure that stores information as follows:
key [value 1] [value 2] ...

I need to be able to look up a given value by supplying the key and the value I desire (the number of values is constant).  A hash table is the first thing that came to my mind but I don't think it can be used for multiple values.  Is there any way to do this with a single datastrucuture rather than splitting each key-value pair into a separate list (or hash table)? Also I'd rather not use a multi-dimensional array as the number of entries is not known in advance.  Thanks

A: I'm not sure what you mean about your list of values, and looking up a given value.  Is this basically a keyed list of name-value pairs?  Or do you want to specify the values by index?
If the latter, you could use a HashMap which contains ArrayLists - I'm assuming these values are String, and if the key was also a String, it would look something like this:

    HashMap<String, ArrayList<String>> hkansDictionary = new HashMap<String, ArrayList<String>>();

    public String getValue (String key, int valueIdx) {
        ArrayList<String> valueSet = hkansDictionary.get(key);
        return valueSet.get(valueIdx);
    }

If the former, you could use a HashMap which contains HashMaps.  That would look more like this:

    HashMap<String, HashMap<String, String>> hkansDictionary
              = new HashMap<String, HashMap<String, String>>();
    ----
    public String getValue (String key, String name) {
        HashMap<String, String> valueSet = hkansDictionary.get(key);
            return valueSet.get(name);
    }

A: You could make a class that holds the two key values you want to look up, implement equals() and hashcode() to check/combine calls to the underlying values, and use this new class as the key to your Map.

A: I would use
Map<Key,ArrayList<String>> map = new HashMap<Key,ArrayList<String>>

where you define Key as
public class Key{
    private String key;
    private String value;
    //getters,setters,constructor

    //implement equals and hashcode and tostring
}

then you can do
Key myKey = new Key("value","key");
map.get(myKey);

which would return a list of N items

A: You can create a multidimensional array by first declaring it, then creating a method to ensure that new value keys are initialized before the put.  This example uses a Map with an embedded List, but you can have Maps of Maps, or whatever your heart desires.
I.e., you must define your own put method that handles new value initialization like so:
private static Map<String, List<USHCommandMap>> uSHCommandMaps = new HashMap<String, List<USHCommandMap>>();

public void putMemory() {

        if (!uSHCommandMaps.containsKey(getuAtom().getUAtomTypeName()))
            uSHCommandMaps.put(getuAtom().getUAtomTypeName(), new ArrayList<USHCommandMap>());

        uSHCommandMaps.get(getuAtom().getUAtomTypeName()).add(this);

    }


text:
Q: How I can move to the next page in react JavaScript by clicking Google Sign in Page along with loading Google data? I have been trying to move to the next page by clicking on Google sign in button. Before it, I want to load data from Google API, then it should automatically load the other page.
I have tried logging with Google using Google API I want to load the other page by clicking the Google sign in button and it should load the other page in a time span that it loads the data as well.
This is my code:
import React, { useEffect, useState } from "react";
import GoogleLogin from "react-google-login";

import { Link } from "react-router-dom";

const Registeration = (props) => {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [url, setUrl] = useState("");

  const responseGoogle = async (response) => {
    setName(response.profileObj.name);
    setEmail(response.profileObj.email);
    setUrl(response.profileObj.imageUrl);

    props.setDataFromGoogle(response.profileObj.givenName);
    props.setDataFromGoogle1(response.profileObj.familyName);

    console.log(response);
  };

  return (
    <>

            <BiPlusMedical className="plusIcon" />

            <Link to="/RegisterationSecondS">
              <GoogleLogin
                className="btnGoogle"
                clientId="677360402906-
                                dm66f7qv5dkfaoqt0kleshkeoma85fjn.apps.googleusercontent.com"
                buttonText="Continue with Google"
                onSuccess={responseGoogle}
                onFailure={responseGoogle}
                cookiePolicy={"single_host_origin"}
              />
            </Link>

            Help me login

    </>
  );
};

export default Registeration;


text:
Q: ExtJS 4.2.0 Nested modal windows issue I have a tree in a modal window, when I select tree node I want to show another modal window to confirm action, but due to bug in ExtJS 4.2.0 (it seems to be fixed in ExtJS 4.2.1) second modal window displayed under first modal window (z-index-wise).
Check this simple fiddle.
Any idea how I can fix this issue for 4.2.0?


text:
Q: "Cannot read property of undefined" NodeJS This is my NodeJS/Express/Mongoose application.
https://gist.github.com/nosille/e114ed3cb52ed88650c1
This is my template register.jade file that's supposed to receive the firstName property from the user object from the main application. I suspect there might be something wrong with the header order, so that the properties of the user object aren't sent before the template is rendered.


text:
Q: gridview model binding and sorting I have the below GridView on a page which I'm using Model Binding to get the data into.
                <asp:GridView ID="grdvAppType" DataKeyNames="ApplicationTypeSeqid" runat="server" ItemType="MyType.ApplicationType"
                AutoGenerateColumns="false" SelectMethod="GetAppliationTypes" AllowPaging="true" PageSize="10" AllowSorting="true">
                <EmptyDataTemplate>
                    No records
                </EmptyDataTemplate>
                <Columns>
                    <asp:TemplateField HeaderText="Type Name" SortExpression="TypeName">
                        <ItemTemplate>
                            <%# Item.TypeName %>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>

There are other columns, but i've removed them here.  The code behind has the SelectMethod set as:
        public List<MyType.ApplicationType> GetAppliationTypes(int startRowIndex, int maximumRows, out int totalRowCount)
    {
        List<MyType.ApplicationType> lstAppType = null;
        using (ApplicationTypeRepository appTypeRepos = new ApplicationTypeRepository(new UnitOfWork()))
        {
            totalRowCount = appTypeRepos.All.Where(x => x.isActive).Count();
            var data = appTypeRepos.All.Where(x => x.isActive).OrderBy(x => x.TypeName).Skip(startRowIndex).Take(maximumRows);
            lstAppType = data.ToList();
        }

        return lstAppType;
    }

This works fine, as i'm retrieving just the records I want per page, rather than getting all the data every time I move from page to page.  But I'm not sure how to get this to work with sorting, for example, if I wanted the TypeName column to be sortable.  What do I need to look for in the SelectMethod to see what option was selected to sort by, if nothing is chosen it should default to the TypeName?

A: In WPF I'm using the DataGrid for auto-sorting and it works fine for me but I don't know if it's available for ASP.NET too . I also found this article, check it out , I think that it's what you're searching for . Hope it helps!
 http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.allowsorting(v=vs.110).aspx

A: there is another argument to the SelectMethod call called "sortExpression".  It will give you the field being sorted.
public List<MyType.ApplicationType> GetAppliationTypes(string sortExpression,
                   int startRowIndex, int maximumRows, out int totalRowCount)


text:
Q: Drupal json output bad format Need some help please,
Actually, I am using Drupal 8 as a content manager for my mobile application.
For that, I need to output my contents as JSON structures, meanwhile, I am using address and office hours modules in my data.
The problem is that when I try to output my data, I get some "\n" and spaces in the response like show the images :

I need a result like that :
address:{ "address": "", "city" : "" ,"zip_code": "", "country":{}}

"openingHours":[{"day":"Saturday","opening":"07:00", "closing":"18:00"},{"day":"Sunday","opening":"10:00", "closing":"18:00"}]

Any Idea to how to rewrite the response to get a proper data?
for information, the problem appears only when I use fields.
thank you

A: If you want to show the address on mobile you need to replace \n with space or the character which mobile developer use for the linebreak.


text:
Q: How to make a registration and login system using django? I want to create a registration and login system I have made the registration form but I'm not able to carry out the authentication part of it.
Models.py
from __future__ import unicode_literals
from django.db import models

class profile(models.Model):
    WORK = (
            ('School', 'School'),
            ('Collage', 'Collage'),
            ('Job', 'Job')
        )
    name = models.CharField(max_length=150)
    email = models.EmailField(max_length=254)
    username = models.CharField(max_length=100, unique=True)
    password = models.CharField(max_length=80)
    age = models.IntegerField()
    work = models.CharField(max_length=10, choices=WORK)

    def __unicode__(self):
        return self.username

Forms.py For the registration of user
from django import forms
from .models import profile

class registration_form(forms.ModelForm):
    class Meta:
        model = Post
        fields={
        "name",
        "email",
        "username",
        "password",
        "work",
        "age"
        }

I want to use the above database to authenticate the user how can i do that ?(also I dont want to use any third party library like django-registration)

A: @Alasdair is right, you don't need the django.contrib.admin in order to use the django.contrib.auth.
Next a solution, that make use of django generic class based views.
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser

class Profile(AbstractUser):
    WORK = (
        ('School', 'School'),
        ('Collage', 'Collage'),
        ('Job', 'Job')
    )
                                                        )
    age = models.IntegerField()
    work = models.CharField(max_length=10, choices=WORK)

settings.py
AUTH_USER_MODEL = 'my_users_app.Profile'
LOGIN_URL = '/login/'  # Where our login page is

views.py
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.views import login as django_login_view
from django.views.generic import FormView

class LoginView(FormView):
    form_class = AuthenticationForm
    template_name = 'my_users_app/login.html'

    def form_valid(self, form):
        usuario = form.get_user()

        django_login_view(self.request, usuario)
        return super(LoginView, self).form_valid(form)

urls.py
from my_users_app.views import LoginView
urlpatterns = [
    url(r'^login/$', LoginView.as_view(), name='login'),
]

login.html
<form method="post" autocomplete="off">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Login</button>
</form>

Note:

*

*In order to make your own User model, you need to configure the AUTH_USER_MODEL, and inherit from AbstractUser.

*The AuthenticationForm will validate the username/password and will trigger the form_valid.

*I'm using from django.contrib.auth.views import login to import the django login view who is responsible to make the login action once the form has been validated.


text:
Q: Refusing connection from a host I'm writing a simple tcp server application using sockets. As far as I know I can obtain the client's ip address and port after calling accept().
Now lets assume I have a banlist and I want to ban some ip addresses from my server. Is there a better way than accepting the connection and then dropping it?
Is there a way to get the client's ip and port before accepting the connection? If we have accept() why don't we have something like refuse()? Is there a way to refuse the connection or simply ignore connection attempt from a host?

A: On windows: look at WSAAccept, may be it is what you need:
SOCKET WSAAccept(
  __in     SOCKET s,
  __out    struct sockaddr *addr,
  __inout  LPINT addrlen,
  __in     LPCONDITIONPROC lpfnCondition,
  __in     DWORD dwCallbackData
);

lpfnCondition -- the address of an optional, application-specified condition function that will make an accept/reject decision based on the caller information passed in as parameters, and optionally create or join a socket group by assigning an appropriate value to the result parameter g of this function. If this parameter is NULL, then no condition function is called.
For linux solution look at: GNU Common C++ -- TCPSocket class, it has onAccept(), and reject() methods.
virtual bool TCPSocket::onAccept    (       const InetHostAddress &      ia,
        tpport_t    port
    )   [inline, protected, virtual]

A method to call in a derived TCPSocket class that is acting as a server when a connection request is being accepted.
The server can implement protocol specific rules to exclude the remote socket from being accepted by returning false. The Peek method can also be used for this purpose.

However, you can just close socket after accept if pre-condition is false :)

A: The TCP implementation normally completes the TCP 3-way handshake before the user process even has access to the connection, and the accept() function merely gets the next connection off the queue.  So it is too late to pretend that the server is down.  This works the same way for regular TCP data; the TCP implementation does not wait for the application to actually recv() the data before a TCP ACK is sent.  This keeps the other side from needlessly retransmitting packets that were received correctly, and allows the throughput to remain high, even when the application is bogged down with other things.  In the case of new connections (SYN packets), this also allows the kernel to protect itself (and the application) from SYN flood attacks.
Although not portable, many platforms provide some sort of firewall capability that will allow filtering incoming connections based on IP address/port.  However that is usually configured system-wide and not by an individual application.

A: TCP Wrapper has become very widespread on UNIX-like platforms.  Yes, the connection is only checked after accept; however, if you're doing this anyways, you might as well use the same configuration that everybody else uses.
In essence, your program is either run with tcpd or modified to use libwrap directly, like so:
#include <tcpd.h>
connfd = accept(listenfd, (struct sockaddr *)&addr, &addrlen);
if (!hosts_ctl("my_program", STRING_UNKNOWN, inet_ntoa(addr.sin_addr), STRING_UNKNOWN)) {
    fprintf(stderr, "Client %s connection disallowed\n", inet_ntoa(addr.sin_addr));
    close(connfd);
}

Then you configure /etc/hosts.allow and /etc/hosts.deny according to your desires, e.g.

# /etc/hosts.allow
my_program: 127.0.0.1 10. 192.168.

# /etc/hosts.deny
my_program: ALL

This will cause my_program to reject all connection attempts from non-local addresses, but can be changed without touching my_program at all.

A: the concept of not accepting connection based on IP address will not work if you are behing NAT.


text:
Q: forEach not a function error in NodeJS when using FakerJS I was taking a Udemy course, here is my code for an exercise that I was doing.
Faker is a package downloaded from the NPM library
var faker = require("faker");

console.log("+++++++++++++++++++");
console.log("Welcome to my shop!");
console.log("+++++++++++++++++++");
var data = faker.commerce.productName();

data.forEach(function(print){
    console.log(data);
});

I was expecting the code to iterate over every item in the variable "data" and print the result, however this is the result I get
+++++++++++++++++++
Welcome to my shop!
+++++++++++++++++++
/home/ubuntu/workspace/node_practice/demo_app/app.js:8
data.forEach(function(print){
     ^

TypeError: data.forEach is not a function
    at Object.<anonymous> (/home/ubuntu/workspace/node_practice/demo_app/app.js:8:6)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:389:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:504:3

I am using Cloud9 ide, why am I getting this error?

A: You should read the faker documentation.
https://cdn.rawgit.com/Marak/faker.js/master/examples/browser/index.html#commerce
faker.commerce.productName() is a string. Those don't have a prototype.forEach()
If you'd like to generate a set of names you can use Array.from() with faker like so:
let products = Array
  .from({length: 100})
  .map(faker.commerce.productName)

You now have an Array of 100 product name


text:
Q: Convert from .ppm to .png file How do I convert from .ppm to .png? I am using C++ in Visual Studio 2017.
I have heard about Magick++, but I don't know how to download or use it. Can someone provide a download link for Windows 32bit? (Got 64bit processor, but don't want to mess other bits up).
Are there any other libraries which might be suitable for this?
Thanks!
EDIT
I no longer need to convert this, I just used an online converter instead.

A: You can use Freeimage , an open source software to convert to/from ppm to png. Use vcpkg to automatically install the freeimage libraries ( static or dynamic in x86 or x64) to your visual studio 2015 (or later). For example in powershell command you can type:
.\vcpkg install freeimage:x64-windows-static


text:
Q: Passing raw params to angular I am building a small mobile app blog with ionic and angular but when i try to make a resource query with manually injected params i have a bad url string. meaning angular is not passing my syntax correctly or i am making a bad mistake.
Here is my code
angular.module('starter.posts', ['ionic','ngResource'])

    .factory('Post', function ($resource) {
        return $resource('http://example.org/wp-json/:params');
    });

app.controller('HomeCtrl', function ($scope, $state, $ionicSideMenuDelegate, Post) {
    "use strict";
    /* Items for left side menu. */
    $scope.posts = Post.query({params: "posts?filter[posts_per_page]=3"})

})

and the error log show the bellow error
http://example.org/wp-json/posts%3Ffilter%5Bposts_per_page%5D=3 Failed to load resource: the server responded with a status of 404 (Not Found)

which simply means that it did not translate the url correctly. How can i fix this so the url can be in the bellow format
http://example.org/wp-json/posts?filter[posts_per_page]=3

I am new to angular trying to simulate an entire wordpress blog with angular.

A: I usually do something like this, passing a js object in:
usersFactory.get = function (request) {
                var operation= $http({url: urlBase, method:'get', params:request });

perhaps you should add posts to your resource url
$resource('http://example.org/wp-json/posts:params');

and pass an object like this
var filter={};
filer.posts_per_page=3

in as your params

A: I was able to figure the right syntax by using the code below,
 Post.query({'filter[posts_per_page]': 20, 'page' : $scope.pageNum}, function (data, responseHeaders)


text:
Q: Would this headset work with Ubuntu? This one, by Rosewill. It doesn't mention Ubuntu/Linux compatibility, only Windows. Does anyone know if it works?

A: Even if it produces sound under Linux, many of the features listed such as "5.1 surround" and "vibration" are not going to work if the company has not released Linux drivers.
Most USB speakers and headphones will work under Ubuntu using generic speaker drivers to produce stereo sound.  I was unable to unable to find any reports of users getting these particular headphones to work, or any headphones made by Rosewill for that matter.
After reading a bunch of reviews I recently purchased Plantronics Gamecom headset.  The surround sound doesn't work, but the stereo audio, volume up and down, mute button, and microphone all do.
With Ubuntu, the functionality of USB headphones leaves a bit to be desired.  Especially for plugging and unplugging them.  When you plug in headphones, Ubuntu does not automatically shut off analog speakers and turn on the headphones.  Each time you plug or unplug, you need to go into the sound setting and specifically choose your input and output sources.


text:
Q: PyTorch: Sharing a model between threads, do I need to lock it myself? I'm sharing a PyTorch neural network model between a main thread which trains the model and a number of worker threads which eval the model to generate training samples (à la AlphaGo).
My question is, do I need to create a separate mutex to lock and unlock when accessing the model in different threads?

I did not see any mutex in the PyTorch Hogwild example, however the difference there is that all threads are in train mode.
Apart from the official tutorial, I'm unable to find even basic information (like this question) online.
I'm using the torch.multiprocessing module for this and I'm using model.share_memory() and torch.multiprocessing.set_start_method('spawn', force=True).

A: You need to .join() all worker threads if you wish to continue using main thread.


text:
Q: What good is a VHD backup if you can't boot the Machine in Virtual PC? I've read that you cannot boot from the VHD backups that Vista Ultimate / Server 2008 creates.  However you can mount them with vhdmount.
So if you can't boot it then what good is the VHD backup over a regular compressed file backup and system restore?

A: Microsoft uses a technology called Volume Shadow Copy to make these backups. It's a very clever approach because it allows full volume sector-by-sector backups (like a Ghost image) that can be stored incrementally. If you backup every day, each additional copy only consumes the space required to store the changes, yet still looks like a full stand-alone image.
The combination of VHD (a convenient pre-existing disk image format) and Volume Shadow Copy makes it trivial to restore to any point in time (that you have a backup of).
Why are these image (or sector-based) backups useful?
1) Sector-based backups are orders of magnitude faster than file-based ones. In a sector-based backup the disk heads are moving sequentially whereas in a file-based backup the heads are moving randomly. In many cases this means the difference between backups being able to complete overnight or not.
2) You can do a complete system restore simply by booting from the Vista/Windows 7 DVD and going through the option of recovering your system. This covers scenarios like failed hardware or malware damaging your OS.
3) They are very space-efficient. Think of a 100 MB database file. If you do incremental file-based backups, every new backup will consume 100 MB. On the other hand, a sector-based incremental backup will only consume the space necessary to store the changes to the 100 MB file, which could be as small as a single sector.
Microsoft's use of the VHD format was a logical choice that saved them creating a new format -- a laudable approach in my opinion (the less "standards" the better). Think about it; with VHDMount I can now mount full-disk backups AND Virtual PC/Hyper-V virtual disks -- what's not to like? Nowhere in all that is the implication that an image of a computer will boot on completely different hardware (which is what Virtual PC/Hyper-V are equivalent to).

A: I think the idea behind it is that if using Hyper-V, you can quickly move it to another Hyper-V server and mount it to another Virtual server.


text:
Q: Python 3.4 - failing to connect to http with urllib I'm trying to run a simple Python script which connects to a website and reads a document on the website, but it fails. Any help, would be most welcome, thank you!
The code is as follows:
import urllib.request

fhand = urllib.request.urlopen('http://www.py4inf.com/code/romeo.txt')

for line in fhand:
    print (line.strip())

And I'm getting the following two error messages:

TimeoutError: [WinError 10060] A connection attempt failed because the
connected party did not properly respond after a period of time, or
established connection failed because connected host has failed to
respond
urllib.error.URLError: {urlopen error [WinError 10060] A connection
attempt failed because the connected party did not properly respond
after a period of time, or established connection failed because
connected host has failed to respond}

A: This is the windows error, not urllib's one. The latter has a handy default timeout value of never, but the former depends on settings of your proxy (with default being 60 seconds for initial connection and 120 for any further GET requests.
I can't help much with windows, but at least now you know where to look.

A: I had this same issue, and tried specifying a timeout in the urllib.request.urlopen, but no dice.
What did work was including a header, as described here. The first answer worked, and so did the second, so I used the simpler, second solution.


text:
Q: include errno if not accessed directly Do i need to include errno.h even if i don't access errno directly? Eg.
void *mem = malloc(16384);
if (mem == NULL) {
    perror("malloc");
    exit(EXIT_FAILURE);
}

I tried a simple piece of code like this without including errno.h and it worked, but i'm not sure if it's OK to do this. Maybe errho.h is also included in other libraries like stdlib.h and so i don't need to explicitly include it myself?

A: You don't need <errno.h> if you use only perror().
From the Linux Programmer's Manual:
NAME
       perror - print a system error message

SYNOPSIS
       #include <stdio.h>

       void perror(const char *s);

       #include <errno.h>

       const char *sys_errlist[];
       int sys_nerr;
       int errno;

This means that you need <errno.h> only if you use sys_errlist, sys_nerr or errno. Note that sys_errlist and sys_nerr are BSD extensions.
Similar entries can also be found on the C99 standard.

7.19.10.4 The perror function
Synopsis
#include <stdio.h>
void perror(const char *s);

And you need <errno.h> only if you use the following:

7.5 Errors
1 The header <errno.h> defines several macros, all relating to the reporting of error conditions.
2 The macros are
EDOM
EILSEQ
ERANGE

which expand to integer constant expressions with
  type int, distinct positive values, and which are suitable for use in
  #if preprocessing directives; and
errno

which expands to a modifiable lvalue 175) that has type int, the value of which is set to a positive
  error number by several library functions.
[...]
4
  Additional macro definitions, beginning with E and a digit or E and an
  uppercase letter, 177) may also be specified by the implementation.

A: *

*malloc() requires stdlib.h

*perror() requires stdio.h

*exit() requires stdlib.h

So nothing here requires errno.h


text:
Q: Backpropagation between pooling and convolutional layers I've been working on understanding how convolutional neural networks by building my own implementation and trying to run a small network. So far I think I've gotten a good handle on the feed-forward through the network. I also think I have a good grasp on how to backpropagate from the fully-connected layers to the pooling layers.
Unfortunately I've been having some issues working out the backpropagation from a convolutional layer up to a pooling layer. Since the output of the pooling layer is of a different dimension than the output of the convolution layer, I'm guessing that the backprop is a full convolution of the convolutional layer's weights with the errors. Is this the correct calculation to do?

A: Although asked quite a while ago, I bumped into this question and saw it had no answers. Then found this from data science stack exchange:
https://datascience.stackexchange.com/questions/11699/backprop-through-max-pooling-layers
Quoting user104493:
"There is no gradient with respect to non maximum values, since changing them slightly does not affect the output. Further the max is locally linear with slope 1, with respect to the input that actually achieves the max. Thus, the gradient from the next layer is passed back to only that neuron which achieved the max. All other neurons get zero gradient."


text:
Q: What does char c[2] = { [1] = 7 }; do? I am reading Bruce Dawson's article on porting Chromium to VC 2015, and he encountered some C code that I don't understand.
The code is:
char c[2] = { [1] = 7 };

Bruce's only comment on it is: "I am not familiar with the array initialization syntax used - I assume it is some C-only construct."  So what does this syntax actually mean?

A: Its meaning would be
char c[2]={ 0, 7 }

OR you can say
char c[2];
c[0]=0;
c[1]=7;

A: C99 allows you to specify the elements of the array in any order (this appears to be called "Designated Initializers" if you're searching for it). So this construct is assigning 7 to the second element of c.
This expression is equivalent to char c[2] = {0, 7}; which does not save space for such a short initializer but is very helpful for larger sparse arrays.
See this page for more information:
https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html