text:
Q: What is the DRY way to restrict an entire controller with Pundit in Rails? I'm using Pundit with Rails, and I have a controller that I need to completely restrict from a specific user role. My roles are "Staff" and "Consumer." The staff should have full access to the controller, but the consumers should have no access.
Is there a way to do this that is more DRY than restricting each action one-by-one?
For instance, here is my policy:
class MaterialPolicy < ApplicationPolicy
  attr_reader :user, :material

  def initialize(user, material)
    @user     = user
    @material = material
  end

  def index?
    user.staff?
  end

  def show?
    index?
  end

  def new?
    index?
  end

  def edit?
    index?
  end

  def create?
    index?
  end

  def update?
    create?
  end

  def destroy?
    update?
  end
end

And my controller:
class MaterialsController < ApplicationController
  before_action :set_material, only: [:show, :edit, :update, :destroy]

  # GET /materials
  def index
    @materials = Material.all
    authorize @materials
  end

  # GET /materials/1
  def show
    authorize @material
  end

  # GET /materials/new
  def new
    @material = Material.new
    authorize @material
  end

  # GET /materials/1/edit
  def edit
    authorize @material
  end

  # POST /materials
  def create
    @material = Material.new(material_params)
    authorize @material

    respond_to do |format|
      if @material.save
        format.html { redirect_to @material, notice: 'Material was successfully created.' }
      else
        format.html { render :new }
      end
    end
  end

  # PATCH/PUT /materials/1
  def update
    authorize @material
    respond_to do |format|
      if @material.update(material_params)
        format.html { redirect_to @material, notice: 'Material was successfully updated.' }
      else
        format.html { render :edit }
      end
    end
  end

  # DELETE /materials/1
  def destroy
    authorize @material
    @material.destroy
    respond_to do |format|
      format.html { redirect_to materials_url, notice: 'Material was successfully destroyed.' }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_material
      @material = Material.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def material_params
      params.require(:material).permit(:name)
    end
end

Is there a way to do this that I'm not understanding, or is that how Pundit is designed, to require you to be explicit?

A: The first step is just to move the call to authorize to your callback:
def set_material
  @material = Material.find(params[:id])
  authorize @material
end

You can also write @material = authorize Material.find(params[:id]) if your Pundit version is up to date (previous versions returned true/false instead of the record).
Pundit has a huge amount of flexibility in how you choose to use it. You could for example create a separate headless policy:
class StaffPolicy < ApplicationPolicy
  # the second argument is just a symbol (:staff) and is not actually used
  def initialize(user, symbol)
    @user = user
  end
  def access?
    user.staff?
  end
end

And then use this in a callback to authorize the entire controller:
class MaterialsController < ApplicationController
  before_action :authorize_staff
  # ...

  def authorize_staff
    authorize :staff, :access?
  end
end

Or you can just use inheritance or mixins to dry your policy class:
class StaffPolicy < ApplicationPolicy
  %i[ show? index? new? create? edit? update? delete? ].each do |name|
    define_method name do
      user.staff?
    end
  end
end

class MaterialPolicy < StaffPolicy
  # this is how you would add additional restraints in a subclass
  def show?
    super && some_other_condition
  end
end

Pundit is after all just plain old Ruby OOP.

A: Pundit doesn't require you to be explicit, but it allows it. If the index? method in your policy wasn't duplicated, you'd want the ability to be explicit.
You can start by looking at moving some of the authorization checks into the set_material method, that cuts down over half of the checks.
The other half could be abstracted out into other private methods if you wanted, but I think they're fine as-is.
You could also look at adding a before_action callback to call the authorizer based on the action name, after you've memoized @material via your other callback, but readability is likely to suffer.

A: Use the second argument for the authorize method. Eg:
authorize @material, :index?

You can now remove all the other methods that just calls index?


text:
Q: internet connection: connected only when detach/attach the wire again I just started my adventure with Linux.
obviously had many issues already, but get to manage it.
one that bother me a little though I have found the temporary workoround
is my network connection.
my topology is: NAT->modem->router(NetGear 192.168.1.1)->TPLink(192.168.0.1)
TPLink gives me the wireless network at home. but I have also ubuntu 12.10
connected to TPLink through wire.
other machines (wireless) have IP addresses like 192.168.0.100,
ubuntu  (wire) has eth0 configured as address 192.168.0.101 netmask 255.255.255.0 gw 192.168.0.1
it works fine, but after restart or shutdown of system I get disconnected.
ping 192.168.0.1 gives "no network" error
I can get connected again if I get wire off, wait a while and plug it again.
sometimes it works instantaneously, but sometimes not, sometimes I get IP 192.168.1.5
as if the ubuntu was connected directly to the router (NetGear .1.1) but it is connected
to the TPLink(.0.1) -> how is this possible???
I have seen a post suggesting it might be dhcp, so installed dhcpcd. Here is
the result of running it while being disconected.
[sudo] password for user:
info, eth0: dhcpcd 3.2.3 starting
info, eth0: hardware address = d4:3d:7e:4b:47:dc
info, eth0: DUID = 00:01:00:01:18:ab:f5:fd:d4:3d:7e:4b:47:dc
info, eth0: broadcasting for a lease
debug, eth0: sending DHCP_DISCOVER with xid 0x105db75d
debug, eth0: waiting for 20 seconds
debug, eth0: sending DHCP_DISCOVER with xid 0x105db75d
debug, eth0: sending DHCP_DISCOVER with xid 0x105db75d
debug, eth0: sending DHCP_DISCOVER with xid 0x105db75d
debug, eth0: sending DHCP_DISCOVER with xid 0x105db75d
debug, eth0: sending DHCP_DISCOVER with xid 0x105db75d
debug, eth0: sending DHCP_DISCOVER with xid 0x105db75d
err, eth0: timed out
info, eth0: trying to use old lease in `/var/lib/dhcpcd/dhcpcd-eth0.info'
info, eth0: probing for an IPV4LL address
debug, eth0: sending ARP probe #1
debug, eth0: sending ARP probe #2
debug, eth0: sending ARP probe #3
debug, eth0: sending ARP claim #1
debug, eth0: sending ARP claim #2
warn, eth0: using IPV4LL address 169.254.146.212
info, eth0: adding IP address 169.254.146.212/16
debug, eth0: no dns information to write
debug, eth0: writing /var/lib/dhcpcd/dhcpcd-eth0.info
debug, eth0: exec "/etc/dhcpcd.sh" "/var/lib/dhcpcd/dhcpcd-eth0.info" "new"
debug, eth0: forking to background
info, eth0: exiting
user@cmp:~$ dhcpcd.sh: interface eth0 has been configured with new IP=169.254.146.212

it didn't work, I was given the IP 169.254.146.212 (ifconfig, below) but had no network connection. again, I connected again by taking wire off, wait a while and plug it again.
ifconfig
eth0      Link encap:Ethernet  HWaddr b4:1u:2b:4b:41:c7
          inet addr:169.254.146.212  Bcast:169.254.255.255  Mask:255.255.0.0
          inet6 addr: fe91::d62d:7eff:ft4b:54hc/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:138 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:35345 (35.3 KB)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:80 errors:0 dropped:0 overruns:0 frame:0
          TX packets:80 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:6432 (6.4 KB)  TX bytes:6432 (6.4 KB)

has anyone experienced such a thing?

A: I think thisis related to fact that my machine (Ubuntu 12.10) cannot find DHCP server which is my TP-LINK.

The foundation for UPnP networking is IP addressing. Each device must
  implement a DHCP client and search for a DHCP server when the device
  is first connected to the network. If no DHCP server is available, the
  device must assign itself an address. The process by which a UPnP
  device assigns itself an address is known within the UPnP Device
  Architecture as AutoIP. In UPnP Device Architecture Version 1.0,[6]
  AutoIP is defined within the specification itself; in UPnP Device
  Architecture Version 1.1,[7] AutoIP references IETF RFC 3927.[8] If
  during the DHCP transaction, the device obtains a domain name, for
  example, through a DNS server or via DNS forwarding, the device should
  use that name in subsequent network operations; otherwise, the device
  should use its IP address.

I've found at least temporary workoround:
kill dhcp process
root@ubuntu:/home/user# dhcpcd eth0
err, eth0: dhcpcd already running on pid 2186 (/var/run/dhcpcd-eth0.pid)
root@ubuntu:/home/user# kill -9 2186
root@ubuntu:/home/user# ifconfig
eth0      Link encap:Ethernet  HWaddr b4:1u:2b:4b:41:c7
          inet addr:192.168.0.100  Bcast:192.168.0.255  Mask:255.255.255.0
          inet6 addr: fe91::d62d:7eff:ft4b:54hc/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:8729693 errors:0 dropped:0 overruns:0 frame:0
          TX packets:7491675 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:4836487722 (4.8 GB)  TX bytes:720522105 (720.5 MB)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:51131 errors:0 dropped:0 overruns:0 frame:0
          TX packets:51131 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:5025732 (5.0 MB)  TX bytes:5025732 (5.0 MB)

put off the wire and plug it again, then dhcp service has to be turned on again:
root@ubuntu:/home/user# dhcpcd eth0
root@ubuntu:/home/user# dhcpcd.sh: interface eth0 has been configured with new IP=192.168.0.100

root@ubuntu:/home/user#

and should work ; )

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I make stereo wave sound in C? While I want to make stereo wave sound in C, I could found mono sound code, and here it is
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <iostream>

#pragma once
#define WAVE_FORMAT_UNKNOWN 0X0000;
#define WAVE_FORMAT_PCM 0X0001;
#define WAVE_FORMAT_MS_ADPCM 0X0002;
#define WAVE_FORMAT_IEEE_FLOAT 0X0003;
#define WAVE_FORMAT_ALAW 0X0006;
#define WAVE_FORMAT_MULAW 0X0007;
#define WAVE_FORMAT_IMA_ADPCM 0X0011;
#define WAVE_FORMAT_YAMAHA_ADPCM 0X0016;
#define WAVE_FORMAT_GSM 0X0031;
#define WAVE_FORMAT_ITU_ADPCM 0X0040;
#define WAVE_FORMAT_MPEG 0X0050;
#define WAVE_FORMAT_EXTENSIBLE 0XFFFE;

#define DURATION 8
#define SAMPLE_RATE 48000
#define CHANNEL 2
#define BIT_RATE 16

typedef struct {
    unsigned char ChunkID[4]; // Contains the letters "RIFF" in ASCII form
    unsigned int ChunkSize; // This is the size of the rest of the chunk following this number
    unsigned char Format[4]; // Contains the letters "WAVE" in ASCII form
} RIFF;

typedef struct {
    unsigned char ChunkID[4]; // Contains the letters "fmt " in ASCII form
    unsigned int ChunkSize; // 16 for PCM. This is the size of the rest of the Subchunk which follows this number.
    unsigned short AudioFormat; // PCM = 1
    unsigned short NumChannels; // Mono = 1, Stereo = 2, etc.
    unsigned int SampleRate; // 8000, 44100, etc.
    unsigned int AvgByteRate; // SampleRate * NumChannels * BitsPerSample/8
    unsigned short BlockAlign; // NumChannels * BitsPerSample/8
    unsigned short BitPerSample; // 8 bits = 8, 16 bits = 16, etc
} FMT;

typedef struct {
    char ChunkID[4]; // Contains the letters "data" in ASCII form
    unsigned int ChunkSize; // NumSamples * NumChannels * BitsPerSample/8
    } DATA;

    typedef struct {
        RIFF Riff;
        FMT Fmt;
        DATA Data;
    } WAVE_HEADER;

int main() {
        FILE * f_out;
    f_out = fopen("D:\\test.wav", "wb");

    WAVE_HEADER header;
    memcpy(header.Riff.ChunkID, "RIFF", 4);
    header.Riff.ChunkSize = DURATION * SAMPLE_RATE * CHANNEL * BIT_RATE / 8 + 36;
    memcpy(header.Riff.Format, "WAVE", 4);

    memcpy(header.Fmt.ChunkID, "fmt ", 4);
    header.Fmt.ChunkSize = 0x10;
    header.Fmt.AudioFormat = WAVE_FORMAT_PCM;
    header.Fmt.NumChannels = CHANNEL;
    header.Fmt.SampleRate = SAMPLE_RATE;
    header.Fmt.AvgByteRate = SAMPLE_RATE * CHANNEL * BIT_RATE / 8;
    header.Fmt.BlockAlign = CHANNEL * BIT_RATE / 8;
    header.Fmt.BitPerSample = BIT_RATE;

    memcpy(header.Data.ChunkID, "data", 4);
    header.Data.ChunkSize = DURATION * SAMPLE_RATE * CHANNEL * BIT_RATE / 8;

    fwrite(&header, sizeof(header), 1, f_out);

    short y[2]; double freq = 1000;
    for (int i = 0; i < SAMPLE_RATE * DURATION * CHANNEL * BIT_RATE / 8; i++) {
        y[0] = (short)30000 * sin(2 * 3.141592 * i * freq / SAMPLE_RATE);
        fwrite(&y[0], sizeof(short), 1, f_out);
        }

    fclose(f_out);
        return 0;
}

but I want to change this into stereo(Channel 2).
In detail, I wish I could make control of left sound function and right sound function (ex. Left_sound[0] = ~~; right_sound[0] = ~~)
and my final goal is making siren which is coming to me and go far away from me.
How can I add a function of left and right sound??

A: The point is the 16bit stereo data are packed as follows in the data chunk:
+-----------------+-----------------+-----------------+-----------------+
|    Left ch      |    Left ch      |    Right ch     |    Right ch     |
| low-order byte  | high-order byte | low-order byte  | high-order byte |
+-----------------+-----------------+-----------------+-----------------+

Then the difference from your code will be:
    short y[2]; double freq = 1000;
    for (int i = 0; i < SAMPLE_RATE * DURATION; i++) {
        double level_r = (double)i / (SAMPLE_RATE * DURATION);
        double level_l = 1.0 - level_r;

        y[0] = (short)(30000 * sin(2 * 3.141592 * i * freq / SAMPLE_RATE) * level_l);
        y[1] = (short)(30000 * sin(2 * 3.141592 * i * freq / SAMPLE_RATE) * level_r);
        fwrite(&y[0], sizeof(short), 1, f_out);
        fwrite(&y[1], sizeof(short), 1, f_out);
    }

The sound starts from the left side, comes close to the center, then passes
away to the right.
Please note the range of index i in your code is incorrect, because the unit of i is sample, not byte.


text:
Q: open folder with one click Is it possible to open folders with just one click in Mac OS 10.11? Renaming could be done using context menu with right click then.

A: It's not possible to open folder with one click in default "Icons" view in Finder. However switching to "Columns" view (cmd-3) will allow you to open folder with one click.
Also it could be faster to just use hotkeys instead of trackpad/mouse. Use arrows to navigate inside "Icons" view, cmd-down to open selected folder and enter to rename selected file or folder. When no file or folder is selected, you could just type in file/folder name and Finder will select closest match for you.


text:
Q: Spring is trying to parse the last part of the URL as a Long parameter When I try to do a call to my server through this URL in a web browser:
http://localhost:8080/server_platform/api/predios/count

The server works correctly and returns the expected result.
The REST controller is defined in this way:
@Controller
@RequestMapping(value = "api/predios")
public class PredioController {

    @RequestMapping(value = "/count", method = { RequestMethod.GET }, produces = { "text/plain" })
    @ResponseStatus(value = HttpStatus.OK)
    public @ResponseBody String count(
            HttpServletResponse response) throws Exception {
        // code removed to simplify
    }
}

But when I use the exchange method of Spring's RestTemplate like this:
restTemplate.exchange(
    url,
    HttpMethod.GET,
    entity,
    String.class);

The server does not enter into the method count() and prints this error:

org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long'; nested exception is java.lang.NumberFormatException: For input string: "count"

The variable url is exactly the same as the one used in the web browser previously. The variable entity also is correctly formed (in fact, if I change url removing the /count part the server responds correctly with the proper REST controller).
It looks like Spring is trying to parse the count part of the URL into a Long value and I can't find where nor why.
Do you have any idea of why could this be happening?
When I launch the server the log contains this line (for it may be a valuable info):

2015-05-21 15:26:47,637 INFO [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] - Mapped "{[/api/predios/count],methods=[GET],params=[],headers=[],consumes=[],produces=[text/plain],custom=[]}" onto public java.lang.String es.controllers.restful.PredioController.count(javax.servlet.http.HttpServletResponse) throws java.lang.Exception

A: You have to configure the REST template with the header "Accept text/plain". By default the template uses only "application/json", which doesn't get mapped to your controller.


text:
Q: get keys from the nested array of objects I am looking for a function that can mutate my data i.e array of object with a nested object. It will include keys that have object/array values (it should only include keys with immediate string/number/boolean values).
Example
[
{
  id: 1,
  person1: {
    firstname: "test1",
    lastname: 'singh',
    address: {
        state: "maharashtra",
    }
  }
},
{
  id: 2,
  person2: {
    firstname: "test2",
    lastname: 'rathod',
    address: {
        state: "kerala",
    }
  }
},
{
  id: 3,
  person3: {
    firstname: "test3",
    lastname: 'gokale',
    address: {
        state: "Tamilnadu",
    }
  }
}

]
Expected output
[
{
  title: 'person1',
  value: 'person.id'
},
{
    title: 'person1',
    value: 'person.firstname'
},
{
    title: 'person1',
    value: 'person.lastname'
},
{
    title: 'person1',
    value: 'person.address'
},
{
    title: 'person1',
    value: 'person.address.state'
},
...sameforOthers

]
Basically, I need a function that will get an array and will return an array of objects as a given above as expected output
Thanks in advance

A: I have come up with a solution. below is the link for code sandbox for the
https://codesandbox.io/s/heuristic-rubin-yy2cyy?file=/src/index.js:0-213same
 const suggestions = [
      {
        id: 1,
        person1: {
          id: "1",
          firstname: "test1",
          lastname: "singh",
          address: {
            state: "maharashtra"
          },
          attributeId: "fhgfgh"
        }
      }
    ];

const typeList = ["string", "number", "boolean"];

const getLabelValue = (itemList, initalArr, parentId) => {
  if (Array.isArray(itemList)) {
    itemList.forEach((currentItem, idx) => {
      const id = parentId ? `${parentId}.${idx}` : idx;
      if (typeList.includes(typeof currentItem)) {
        initalArr.push({
          title: id,
          value: id
        });
      } else {
        getLabelValue(currentItem, initalArr, id);
      }
    });
  } else {
    let keys = Object.keys(itemList);
    keys.forEach((currentKey) => {
      let currentItem = itemList[currentKey];
      const id = parentId ? `${parentId}.${currentKey}` : currentKey;
      if (typeList.includes(typeof currentItem)) {
        initalArr.push({
          title: id,
          value: id
        });
      } else {
        getLabelValue(currentItem, initalArr, id);
      }
    });
  }
  return initalArr;
};

console.log(">>>>>>>>>", getLabelValue(suggestions, [], ""));


text:
Q: Why are a lot of users' weekly reputation negative? I came across this page. Why does every user on this page have a negative weekly change?

A: First, in your specific case, the only reputation activity those users had so far this week was setting a 100 point bounty. You probably could also find many with -50 for the week (probably even more than the -100's) Of course, two 50 point bounties would also add up to -100.
There are other reasons users could have negative net changes, and it's possible these could total -100, or any other value. But the -100 is 'special' due to what I noted above.
Other possibilties (which could of course occur in combination)

*

*The user was down voted for more points than up voted.

*Another user who had up voted numerous posts of theirs was deleted, or the votes were invalidated.

*Posts the user edited for 2 points each were deleted.

*Posts the user had recently had up voted were deleted.

*Votes were reversed through the automatic serial vote detection tool.

*A user that had upvoted their posts was deleted, thus undoing their votes.


text:
Q: Send data in a specific packet format using php sockets I have to send some data in the format of TCP plain packets. I have read and understood how to use sockets to send data, but I can't find any help on how to create packets in a specific format. I will appreciate some help please.
Thanks

A: You need to look up pack for creating binary packets of a paticular format.


text:
Q: Remove espaços produzidos por quebras de linha Porque o código abaixo não remove os espaços, somente as quebras de linha?
$urlCorreios = "http://ws.correios.com.br/calculador/CalcPrecoPrazo.aspx?
   nCdEmpresa=&
   sDsSenha=&
   nCdFormato=1&
   nVlDiametro=0&
   sCdMaoPropria=n&
   sCdAvisoRecebimento=n&
   nCdServico=" . $cod_servico . "&
   sCepOrigem=" . $cep_origem . "&
   sCepDestino=" . $cep_destino . "&
   nVlPeso=" . $peso . "&
   nVlAltura=" . $altura . "&
   nVlLargura=" . $largura . "&
   nVlComprimento=" . $comprimento . "&
   nVlValorDeclarado=" . $valor_declarado . "&
   StrRetorno=xml";

echo preg_replace('/[\n\r\t]/', '', $urlCorreios);

A: E porque não simplesmente usar uma função nativa, como http_build_query()? Exemplo:
$urlCorreios = "http://ws.correios.com.br/calculador/CalcPrecoPrazo.aspx";

$data = array(
    "nCdEmpresa" => "",
    "sDsSenha" => "",
    "nCdFormato" => "1",
    "nVlDiametro" => "0",
    "sCdMaoPropria" => "n",
    "sCdAvisoRecebimento" => "n",
    "nCdServico=" => $cod_servico,
    "sCepOrigem=" => $cep_origem,
    "sCepDestino=" => $cep_destino,
    "nVlPeso=" => $peso,
    "nVlAltura=" => $altura,
    "nVlLargura=" => $largura,
    "nVlComprimento=" => $comprimento,
    "nVlValorDeclarado=" => $valor_declarado,
    "StrRetorno" => "xml"
);

$urlCorreios = $urlCorreios . '?' . http_build_query($data);

echo $urlCorreios . "\n";

Outra vantagem sobre isto é que não precisaria fazer urlencode() de valores e chaves, fora que vai ficar mais fácil do que ficar usando string e vai poder manipular o array a hora que desejar com funções nativas de array no PHP.
Outra coisa, usar \s, como está na outra resposta, sem tratar variável por variável com urlencode (acaso não use http_build_query) vai dar problema com certeza, se bem que só o não uso de urlencode já seria um problema.

A: Tente adicionar um \s no regex. Assim:
echo preg_replace('/[\s\n\r\t]/', '', $urlCorreios);


text:
Q: How to get the sending email address from outlook 2007 I am working on outlook add-in project using Visual studio 2008 for MS
Outlook 2007 in C#. Here I am explaining my problem...
I got multiple accounts (3 Accounts) with my outlook 2007. I need to get
accounts form Account box in New Mail Message window.
When we click New Mail Message, a new window will appear from which we can
send a new mail. Here (On this window) we can see Account Dropdown (Left
side) under the Send Button. If we have multiple accounts with outlook, we
can see all the accounts in Account Drop Down if we click on Account Box. If
we click on the particular email, a right mark will appear to that Email
Account and a message can bee seen on the top of the Send button is "This
message will be sent via xyz@gmail.com".
So, I want to get these email accounts into a string and that particular
email account (which has right mark) into another string.
I got these 3 email accounts into a string. But, I am not getting the
particular email account(which has the right mark when we send a new email).
I am using this code....
using Outlook = Microsoft.Office.Interop.Outlook;

using Office = Microsoft.Office.Core;

using Microsoft.Office.Interop.Outlook;

Outlook._Application myOutlookApp = new Outlook.Application();

Outlook.Accounts myAccounts = myOutlookApp.Session.Accounts;

foreach (Outlook.Account account in myAccounts)
                    {
                        string emailAddress = account.SmtpAddress;
                    }

I am able to get all the accounts from the above code..But, I just want to get the email address which we will use for sending an email at that particular moment..

A: Check out MailItem SendUsingAccount  property
Or you can grab it from the window name as you say.
Marcus

A: Solution is easy:
...
your code
...

    foreach (Outlook.Account account in myAccounts)
                        {
                            string emailAddress = account.CurrentUser.AddressEntry.Address;
                        }

Email is stored in AddressEntry propery, under CurretUser object. That object is under account - how simple :-)


text:
Q: How do you debug an Android app that crashes the device? I'm currently having an issue with certain Samsung devices where starting an activity with an intro animation sometimes causes the whole device to crash.
The app essentially transitions from an Activity with a VideoView to another activity with a VideoView. The video of the activity that just started stutters in a loop for about 10 seconds before the whole device crashes and restarts.
It's not crashing the device all the time, but is limited to a couple Samsung devices from what I've tested.
I've looked at crash logs of the device which currently seem to be inconclusive from what I can see.
Important but relevant note, I am finishing the activity once starting the next.

A: You could try to attach the debugger manually through Android Studio if your process is alive long enough after the boot sequence.
Source:
https://developer.android.com/studio/debug/index.html
One more thing you could try is to put the 'wait for debugger' instruction in your code, using the Debug.waitForDebugger() method.
Source: https://developer.android.com/reference/android/os/Debug.html#waitForDebugger()
Other than that, you could put a lot of logs in your code, then fetch them using adb logcat > crash-log.txt command from your CMD/Terminal.


text:
Q: Unobscured event gives NullReferenceException I am trying to add an Unobscured event to the root PhoneApplicationFrame like this:
PhoneApplicationFrame rootFrame = (PhoneApplicationFrame)App.Current.RootVisual;
rootFrame.Unobscured += new EventHandler((s, e) => { doSomething(); });

But when I run the Windows Phone 8 app like this it gives me a NullReferenceException in the second line of that code sample.
Is there any other way to do this?

A: You need to be careful when you access RootVisual as it may still be null. For example, it will be null in your main page constructor. The RootVisual is set in CompleteInitializePhoneApplication method in your App.cs file.


text:
Q: How to create button in Action bar in android I am working on android application where i need a button in action bar.
These are my activity and java files.
So, i need a button at right side of my tool bar.
Thanks in advance.
content_b2_bdeliveries.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.ideabiz.riderapplication.ui.B2BDeliveriesActivity"
tools:showIn="@layout/activity_b2_bdeliveries">
//remaining code;
</LinearLayout>

activity_b2_bdeliveries.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.ideabiz.riderapplication.ui.B2BDeliveriesActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_b2_bdeliveries" />

</android.support.design.widget.CoordinatorLayout>

B2BDeliveriesActivity.java:
public class B2BDeliveriesActivity extends AppCompatActivity {
private final String TAG_NAME="B2BActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_b2_bdeliveries);
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    ActionBar actionBar = getSupportActionBar();
    //Log.d(TAG_NAME,actionBar.toString());
    if (actionBar != null) {
        try {
            actionBar.setDisplayHomeAsUpEnabled(true);
            } catch (Exception e) {
                Crashlytics.logException(e);
                Log.d(TAG_NAME, "Null Pointer from setDisplayHomeAsUpEnabled" + e.getMessage());
                Utilities.issueTokenUpload("Null Pointer from setDisplayHomeAsUpEnabled" + e, sharedPreferences.getInt("tripId", 999999), sharedPreferences.getString("driverPhoneNo", "9999999999"), sharedPreferences.getString("driverName", "default"), getResources().getString(R.string.version));
            }
    }
}

A: In your activity class, override the following methods if they are not there by default:
// create an action bar button
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // R.menu.mymenu is a reference to an xml file named mymenu.xml which should be inside your res/menu directory.
    // If you don't have res/menu, just create a directory named "menu" inside res
    getMenuInflater().inflate(R.menu.mymenu, menu);
    return super.onCreateOptionsMenu(menu);
}

// handle button activities
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.mybutton) {
    // do something here
    }
    return super.onOptionsItemSelected(item);
}

mymenu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto">
<item
    android:id="@+id/mybutton"
    android:title=""
    app:showAsAction="always"
    android:icon="@drawable/mybuttonicon"
    />
</menu>

A: Here are the steps to get it done:

*

*Create a menu in res/menu (Name it my_menu.xml)
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:id="@+id/action_cart"
    android:icon="@drawable/cart"
    android:orderInCategory="100"
    android:showAsAction="always"/>
</menu>

*Override onCreateOptionsMenu and inflate the menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_menu, menu);
return true;
}

Visit: How to add button in ActionBar(Android)?

A: Make a xml file for your menu in res/menu directory ( menu_main.xml in this case):
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.rashish.myapplication.MainActivity">
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="Button title"
        android:icon="@drawable/buttonicon"
        app:showAsAction="never" />
</menu>

then add these methods in your activity class :
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here.
    int id = item.getItemId();

    if (id == R.id.action_settings) {
        //process your onClick here
        return true;
    }

    return super.onOptionsItemSelected(item);
}

A: If you want to customize UI of your ActionBar, then you can use Toolbar as ActionBar. Here are the steps to do the same :

*

*Add below code as a child of AppBarLayout in your activity layout xml.
<android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:weightSum="1">

            <TextView
                android:id="@+id/title"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="ActionBar Title"/>

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

        </LinearLayout>

    </android.support.v7.widget.Toolbar>

*Make your Toolbar as ActionBar by adding the below code in your Activity onCreate() method.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

*In AndroidManifest.xml, add following theme to your activity:
android:theme="@style/AppTheme.NoActionBar"

*In styles.xml add following code:
<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

A: its described properly at https://developer.android.com/guide/topics/ui/menus.html#xml . You can create a menu.xml file at "menu" directory, which is at the same level as "drawable" and "layout" directories


text:
Q: How to handle or ignore NAs when using ifelse to mutate a new column with multiple conditions (solved) I am a newcomer to dplyr and tried to create a new composite variable from three different age variables using dplyr and ifelse. I made a data frame to explain the situation as follows:
library(dplyr)

z <- data.frame("j6" = c(6, 19, NA, NA, NA, NA, NA, 8, 20, 20, NA),
                "j7" = c(27, 20, NA, 7, 19, NA, NA, 20, 30, 9, NA),
                "j8" = c(8, 22, NA, 20, NA, 8, 30, NA, NA, NA, 3))

z <- z %>%
        mutate(., age_event = NA) %>%
        mutate(., age_event = ifelse(j6 < 18 | j7 < 18 | j8 < 18, 1, 0))

My expectations:

*

*The three columns (j6, j7, and j8) indicate ages, and if at lease one of them is less than 18 year-old, the new column (age_event) should be "1", otherwise 0.

*And if the two of the three columns are both 18-year or older and the other is NA, the age_event variable should be 0 .

*Likewise if the one of the three columns is 18-year or older and the others are NAs, the age_event variable should be 0.

*Also it is NA if all of the three columns are NAs.

However, the result and problems are shown as follows:
> z
   j6 j7 j8 age_event
1   6 27  8         1
2  19 20 22         0
3  NA NA NA        NA
4  NA  7 20         1
5  NA 19 NA        NA  <-- should be 0, but NA
6  NA NA  8         1
7  NA NA 30        NA  <-- should be 0, but NA
8   8 20 NA         1
9  20 30 NA        NA  <-- should be 0, but NA
10 20  9 NA         1
11 NA NA  3         1

I'd like to know if there is a way to turn 5th, 7th, and 9th observations above to 0s using mutate and ifelse. Any suggestions would be greatly appreciated!

Update (2/27/2020): I found a solution with pmin when using mutate and ifelse:
z <- z %>%
        mutate(., age_event = ifelse(is.na(j6) & is.na(j7) & is.na(j8), NA,
                              ifelse(pmin(j6, j7, j8, na.rm = T) < 18, 1, 0)))

> z
   j6 j7 j8 age_event
1   6 27  8         1
2  19 20 22         0
3  NA NA NA        NA
4  NA  7 20         1
5  NA 19 NA         0
6  NA NA  8         1
7  NA NA 30         0
8   8 20 NA         1
9  20 30 NA         0
10 20  9 NA         1
11 NA NA  3         1

A: You can use rowMeans() in place of if_else() which will handle cases that are all NA.
z %>%
  mutate(age_event = +(rowMeans(. < 18, na.rm = TRUE) > 0))

   j6 j7 j8 age_event
1   6 27  8         1
2  19 20 22         0
3  NA NA NA        NA
4  NA  7 20         1
5  NA 19 NA         0
6  NA NA  8         1
7  NA NA 30         0
8   8 20 NA         1
9  20 30 NA         0
10 20  9 NA         1
11 NA NA  3         1

A: We can use rowSums to calculate number of NA values in a row and number of values that are less than 18. We can then use case_when to assign numbers based on different conditions.
library(dplyr)

z %>%
  mutate(calc = rowSums(!is.na(.), na.rm = TRUE),
         ls18 = rowSums(. < 18, na.rm = TRUE),
         age_event = case_when(calc == 0 & ls18 == 0 ~ NA_integer_,
                               ls18 > 0 ~ 1L,
                               TRUE ~ 0L)) %>%
   select(-calc, -ls18)

#   j6 j7 j8 age_event
#1   6 27  8         1
#2  19 20 22         0
#3  NA NA NA        NA
#4  NA  7 20         1
#5  NA 19 NA         0
#6  NA NA  8         1
#7  NA NA 30         0
#8   8 20 NA         1
#9  20 30 NA         0
#10 20  9 NA         1
#11 NA NA  3         1


text:
Q: "Unable to connect to server" error during the creation of development graph i receive this error:

but the server is started :  "server started at http://localhost:4000/graphql"
this is the code in index.ts :
(async () => {
  const app = express();

  const options = await getConnectionOptions(
    process.env.NODE_ENV || "development"
  );
  await createConnection({ ...options, name: "default" });

  const apolloServer = new ApolloServer({
    schema: await buildSchema({
      resolvers: [MovieResolver],
      validate: true
    }),
    context: ({ req, res }) => ({ req, res })
  });

  apolloServer.applyMiddleware({ app, cors: false });
  const port = 4000;
  app.listen(port, () => {
    console.log(`server started at http://localhost:${port}/graphql`);
  });
})();

A: Probably you need to add /graphql at the end,
http://localhost:4000/graphql


text:
Q: Combining two dataframes using same column names in R I have a dataframe named df_1 with following columns,

ID
Name
Age
City

1
Jaz
25
D

2
Sam
28
E

And another dataframe named df_2 with following columns,

ID
Name
City

4
Alex
F

5
Abi
E

I want a resultant df as follow,

ID
Name
Age
City

1
Jaz
25
D

2
Sam
28
E

4
Alex
NA
F

5
Abi
NA
E

How to get this using R?

A: You can use the following code:
library(dplyr)
bind_rows(df_1, df_2)

Output:
  ID Name Age City
1  1  Jaz  25    D
2  2  Sam  28    E
3  4 Alex  NA    F
4  5  Abi  NA    E

Data
df_1 <- data.frame(ID = c(1,2),
                   Name = c("Jaz", "Sam"),
                   Age = c(25,28),
                   City = c("D", "E"))

df_2 <- data.frame(ID = c(4,5),
                   Name = c("Alex", "Abi"),
                   City = c("F", "E"))


text:
Q: magento invalid transactional email code I did some research about this problem I'm having:
I deleted a transitional email template, and now I am getting this error over and over:
Invalid transactional email code: 4

Yeah, I know, the '4' is the ID of the template.
I made a dummy template, and changed the ID in the database to 4, but I don't want that dummy.
Is there anybody who is able to tell me how to fix this problem? Maybe a little reset for transactional emails?
Thanx in advance

A: References to the email templates are stored in the core_config_data table; these are id's that correspond to the template_id column of the core_email_template table. So when removing an entry from the core_email_template table, all references to it in the core_config_data tabel also need to be removed.
Assuming the order_new template is coupled to the core_config_data path Mage_Sales_Model_Order::XML_PATH_EMAIL_TEMPLATE (i.e. sales/email/order/template), the following line in an install script does the trick:
$installer->deleteConfigData(Mage_Sales_Model_Order::XML_PATH_EMAIL_TEMPLATE);

BTW It is also possible to reset the email template references via the admin system configuration by opening the corresponding tab and then saving that tab (without making any changes). For the order email templates, this is the Sales Emails tab.


text:
Q: Cannot invoke 'JSON' with an argument list of type '((Any))' - Using AlamoFire & SwiftyJSON In my previous project using older versions of Alamofire and SwiftyJSON, using JSON(response.result.value) worked just fine. I've tried to implement code in my new project but getting some errors I haven't seen before. I did see some questions asked about it here on SO, but none of the solutions seemed to resolve my issue (unless there's something I missed).
AF.request(self.apiEndpoint,
             method: .get,
             parameters: self.parameters,
             headers: self.headers,
             interceptor: nil).validate().responseJSON { (response) in

                switch response.result {
                case .success(let value):
                  let json = JSON(value)
                  print(json)
                case .failure(_):
                  print(response)
                }
}

This returns the following error:
Cannot invoke 'JSON' with an argument list of type '((Any))'

A: This is a strange situation. However, what I managed to identify was that if I call
JSON(value)

This fails with the error of not being able invoke the constructor with type (Any).
However, when I explicitly name the module as follows:
let json = SwiftyJSON.JSON(value)

Xcode no longer complains about that error.
Very strange indeed. I did go back and check that JSON() referred to SwiftyJSON when attempting to use it without specifically naming the module - just to verify there wasn't some sort of method naming clash with something else - and it did. So I'm not entirely sure why this works, but hopefully it helps someone else out. Or someone can give me a better answer if I've done something incorrectly.


text:
Q: Difficulty with 'any' in NumPy I am using Python 3 and am trying to check if the sqrt of elements in array2 are in a. I am returning the boolean response.
I am receiving the error:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

My code:
import numpy as np

def mems(a, b):
    a = np.array(a)
    b = np.array(b)
    return np.any(np.sqrt(b) in a)

A: I guess, return part is wrong. Try this:
import numpy as np

def mems(a, b):
    a = np.array(a)
    b = np.array(b)
    b_sqrt = np.sqrt(b)
    return any(sqrt in a for sqrt in b_sqrt)

print(mems([1, 2, 3, 4, 5], [20, 56]))
print(mems([1, 2, 3, 4, 5], [16, 25, 17, 18]))

Output:
False
True

A: You can use numpy function in1d for this
import numpy as np

def mems(a, b):
    return np.any(np.in1d(a, np.sqrt(b)))

But you will get wrong results if you do this with nonintegers.


text:
Q: Editing in Google Chrome Inspector and saving changes I use the Inspector (F12) in Google Chrome a lot. I was wondering if there was a way for it to actually save the changes that I make, as opposed to copying them into the CSS file manually for later use.
Does anybody know of a way?

A: You can save your CSS changes from Chrome Dev Tools. Look here Google I/O 2011: Chrome Dev Tools Reloaded. Also, check out this presentation from Ilya Grigorik Wait, Chrome Dev Tools could do THAT?. Chrome's Developer Tools has a lot of good stuff hidden away.

A: No.
I looked into this a while back and unfortunately the answer is no. The inspect element utility is only intended for developers to test minor tweaks to their code. You will need some other program to actually change your code.


text:
Q: Add x period to DateTime I have a problem to retrieve a good date after adding x period.
Period mean morning, evening or night. The incoming date can be have any hours and I do add x period to return date @ 7, 12 or 17.
Easy ? Just AddHours(8*period) ? Obviously no, period is not same range. Morning is 7 to 11:59, evening is 12 to 16:59 and night is 17 to 6:59.
I've found with modulo how retrieve the good period, but i'm stuck on calculate when the day is gone and it can create a gap of 1 day between date.
        int denominateur = 3; //denominateur
        int day = period/denominateur; //ecart jour

        int p = dt.GetPeriod(); //return 1 2 or 3 from the current hour of date
        int numerateur = period + p - 1; //numérateur

        switch ((numerateur  % denominateur))
        {
            case 0:
                dt = dt.Date.AddHours(7);
                break;
            case 1:
                dt = dt.Date.AddHours(12);
                break;
            case 2:
                dt = dt.Date.AddHours(17);
                break;
        }
        //if ((numerateur  % denominateur) == 0 && day == 0) day++; <== issue here

        dt = dt.AddDays(day);

Thanks for your helps
EDIT : with full console code
   static class Program
    {
        static void Main(string[] args)
        {
            //int a = 4;

            int b = 3;
            DateTime d = new DateTime(2014,01,02,8,00,00);
            Console.WriteLine("start ::::: " + d);
            int j = 0;

            for (int a = 1; a < 40; a++)
            {
                d = new DateTime(2014, 01, 02,8, 00, 00);
                Console.WriteLine("-------------------------");
                //Console.WriteLine(a / b);

                int period = d.GetPeriod();

            int c = a + period - 1;
                //Console.WriteLine(d);
               // Console.WriteLine(c % b);

                //if ((c%b) <= period && a < 6)
                //    d = d.AddDays(1);

                d = d.AddDays(a / b);

                switch ((c % b))
                {
                    case 0:
                        d = d.Date.AddHours(7);
                        break;
                    case 1:
                        d = d.Date.AddHours(12);
                        break;
                    case 2:
                        d = d.Date.AddHours(17);
                        break;
                }

                Console.WriteLine(d);

            }

            Console.Read();
        }

        public static int GetPeriod(this DateTime dt)
        {
            if (dt.Hour >= 7 && dt.Hour < 12)
                return 1;
            if (dt.Hour >= 12 && dt.Hour < 17)
                return 2;
            if (dt.Hour >= 17 || dt.Hour < 7)
                return 3;

            return 0;
        }
    }

And my goal is when a add period from 02/01/2014 8:00 :

*

*1+ : 02/01/14 12:00

*2+ : 02/01/14 17:00

*3+ : 03/01/14 07:00

That working with above code (just by AddDays(number of period / 3)
But when I try with 02/01/14 15:00 I have :

*

*1+ : 02/01/14 17:00 ==> OK

*2+ : 02/01/14 07:00 ==> KO

*3+ : 03/01/14 12:00 ==> OK

*5+ : 03/01/14 07:00 ==> KO

I try to find how to remove this gap.

A: Try this:
static class Program
{
    static void Main(string[] args)
    {
        var outputCount = 10;
        var hours = new[] { 8, 12, 17 };
        //var hours = new[] { 12, 17 };
        //var hours = new[] { 6, 8, 10, 12, 16, 18, 22};

        var d = new DateTime(2014, 01, 02, 15, 00, 00);
        var d1 = new DateTime(d.Year, d.Month, d.Day);

        var dates = Enumerable.Range(0, 2 + (outputCount / hours.Length))
            .Select(i => d1.AddDays(i))
            .Aggregate<DateTime, List<DateTime>>(new List<DateTime>(), (a, b) =>
            {
                for (int i = 0; i < hours.Length; i++)
                {
                    a.Add(b.AddHours(hours[i]));
                }
                return a;
            }
        ).Where(date => date > d).Take(outputCount).ToList();

        foreach (var date in dates)
        {
            Console.WriteLine(date);
            Console.WriteLine("-------------------------");
        }

        Console.Read();
    }
}

A more succint approach:
var dates = Enumerable.Range(0, 2 + (outputCount / hours.Length))
    .SelectMany(i => hours.Select(h => d1.AddDays(i).AddHours(h)))
    .Where(date => date > d)
    .Take(outputCount)
    .ToList();

A: I'm assuming the following: You have consecutively numbered periods. The first period (with index 0) begins on 2 Jan 2014 at 08:00h. You want return a DateTime that corresponds to perion n. Any three subsequent periods sum up to 24h, but the periods are of different length. The morning (0) and afternoon (1) periods are 5 hours long, the night period is 14 hours long.
But your nomenclature is confused: In GetPeriod, you number the periods 1, 2, 3 and then amend that by subtracting 1 when you calculate a. That's not wrong, but confusing.
Something that is wrong is that you add the period from GetPeriod to a at all - as yopu implement it, a already defines the period. Instead of just calculating a % 3, you're effectively calculating (a + a % 3) % 3, which is only correct in 1/3 of your cases.
Also, you probably shouldn't add 7, 12 and 17 to your base date, which already starts at 8:00h. Either make your base date start at midnight or add -1, 4 and 9. (Or should that really be 0, 5, 10? Why is your base not a starting point of a period?)
(Finally I have to say that I'm not familiar with C# and its dateTime implementation, so I might be wrong about the last paragraph. I tink your error is to add the day period to a. I'd also recommend to use a consistent nomenclature of the day period throughout or you're in a mess rather sooner than later.)


text:
Q: Regex class and test in C# .Net I've copied a RegEx that's working in Javascript. But when I run it in C# it returns false. I'm not sure if it's my code iteslf that's incorrect or if it is the RegEx. This is my code.
bool isValid = true;

string nameInput = "Andreas Johansson";
string emailInput = "email@gmail.com";
string passwordInput = "abcABC123";

string namePattern = @"^[A-z]+(-[A-z]+)*$";
string emailPattern = @"^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$";
string passwordPattern = @"^(?=.*\d+)(?=.*[a-zA-Z])[0-9a-zA-Z!@#$%]{6,50}$";
Regex nameRegEx = new Regex(namePattern);
Regex emailRegEx = new Regex(emailPattern);
Regex passwordRegEx = new Regex(passwordPattern);

if (model.CreateFullName.Length < 3 || !nameRegEx.IsMatch(nameInput))
                    isValid = false;

if (model.CreateEmail.Length < 3 || !emailRegEx.IsMatch(emailInput))
                    isValid = false;

if (model.CreatePassword.Length < 3 || !passwordRegEx.IsMatch(passwordInput))
                    isValid = false;

Thankful for inputs!

A: You should remove boundary slashes from pattern definitions. They are required for regex objects in javascript not .NET. e.g.:
string namePattern = @"^[A-z]+(-[A-z]+)*$";
string emailPattern = @"^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$";
string passwordPattern = @"^(?=.*\d+)(?=.*[a-zA-Z])[0-9a-zA-Z!@#$%]{6,50}$";

UPDATE: you fixed them in your edit.
The name pattern still does not account for spaces in the input. Try following instead:
^[A-z]+([-\s][A-z]+)*$

Also note that [A-z] is not a correct pattern for matching alphabet letters. Use [A-Za-z] for matching ASCII alphabet letters, or \p{L} for matching any unicode letter.
The problem for [A-z] is that it matches these character too that reside after Z and before a:
[\]^_`


text:
Q: Conservative vector fields on a Riemannian manifold
Given a vector field on a Riemannian manifold $M$, is there a condition that ensures the existence of a potential $\psi\in C^\infty(M)$ such that $\nabla \psi=X$?

Something like $\text{curl}(F)=0$ in $\mathbb{R}^n$. We can assume $M$ compact and connected.

A: Since the Riemannian metric $g$ is non-degenerate, it induces an isomorphism $X\in\mathfrak{X}(M) \mapsto X^\flat\in\Omega(M)$ given by
$$
X^\flat(Y) := g(X,Y).
$$
The potential condition can be written as $X^\flat = d\psi$. This is true locally if $dX^\flat = 0$. It's true globally if in addition $H^1(M) = \lbrace 0 \rbrace$.


text:
Q: empty result when parsing from xml into DataTable - c# .net i get an empty Datatable when parsing xml file with xmlReader and import it into one DataTable , its necessary for me to save it into Data table so i can import it later into sql server with sqlbulkcopy
easily (i have huge number of lines),
what i try
        using (XmlReader reader = XmlReader.Create(@"C:\Users\neyma\test/W.xml"))
        {
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add("EventID");
            dataTable.Columns.Add("Computer");
            dataTable.Columns.Add("TargetUserName");
            dataTable.Columns.Add("TargetDomainName");

            DataRow myDataRow;
            myDataRow = dataTable.NewRow();

            while (reader.Read())
            {
                if (reader.IsStartElement())
                {

                    switch (reader.Name.ToString())
                    {
                        case "EventID":

                            myDataRow["EventID"] = reader.ReadInnerXml();

                            break;
                        case "Computer":
                            myDataRow["Computer"] = reader.ReadInnerXml();
                            break;
                        case "Data":

                            if (reader.GetAttribute("Name") == "TargetUserName")
                                myDataRow["TargetUserName"] = reader.ReadInnerXml();
                            else if (reader.GetAttribute("Name") == "TargetDomainName")

                                myDataRow["TargetDomainName"] = reader.ReadInnerXml();
                            break;

sample from xml
<eventxml>
<Event <EventID>36</EventID><Computer>NH</Computer><EventData><Data Name="TargetUserName">TER.go</Data><Data Name="TargetDomainName">%4</Data></EventData></Event>
<Event <EventID>51</EventID><Computer>NQ-RS1-.ov</Computer><EventData><Data Name="TargetUserName">TERMSRiv</Data><Data Name="TargetDomainName">%%4</Data></EventData></Event>
<Event <EventID>536</EventID><Computer>CRS1.ov</Computer><EventData><Data Name="TargetUserName">TERRov</Data><Data Name="TargetDomainName">%%144</Data></EventData></Event>
</eventxml>

A: Seems like this is going to be much easier to do with XDocument and LINQ
var xDoc = XDocument.Load(path);

var table = new DataTable { Columns = {
    {"EventID", typeof(string)},
    {"Computer", typeof(string)},
    {"TargetUserName", typeof(string)},
    {"TargetDomainName", typeof(string)},
} };

foreach (var node in xDoc.Root.Elements("Event"))
{
    var data = node.Element("EventData");
    table.Rows.Add(
        node.Element("EventID").Value,
        node.Element("Computer").Value,
        data.Elements().FirstOrDefault(e => e.Attribute("Name").Value == "TargetUserName").Value,
        data.Elements().FirstOrDefault(e => e.Attribute("Name").Value == "TargetDomainName").Value
    );
}

dotnetfiddle
Another option is to pass the whole XML into SQL and parse it using XQuery.


text:
Q: Grails 3.0.15 running embedded war / jar vs running in a container Is running Grails in embedded mode (meaning the server is embedded  in the application) safe and ready for production?
Are there any known issues that shall prevent from using this mode?
Is embedded jar better than embedded war file?


text:
Q: add Object to array inside array with redux Hello my problem is i wont create, update or delete {note} in array [notes] finded by operationId in parent array id. but i dont now ho to do it. i have ADDNOTE but it not working.
i write i put here only ADDNOTE,  becouse with these i cant event start DELETE and UPDATE
my default
const initialState = {
    loading : false,
    isLoaded: false,
    person : {
        id:'',
        firstName: '',
        operations:[],
    },
    error : ''
};

my code :

 case ADDNOTE: return {
            ...state,
            person:
                {
                    ...state.person,
                    operations:[

                    ]
                        state.person.operations.find(item => item.id === action.payload.operationId).notes.push(action.payload)

                }

        };

action.payoload
{
              "id": "22",
              "operationId" : "123A",
              "note": "bla bla"
            }

what i wont :
 {
    "loading" : false,
    "person" : {
      "id": ""  ,
      "firstName": "",
      "operations":[
        {
          "id" : "123A",
          "notes": [
            {
              "id": "11",
              "operationId" : "123A",
              "note": "bla"
            },
            {
              "id": "22",
               "operationId" : "123A",
              "note": "bla bla"
            }
          ]
        },
        {
          "id" : "456B",
          "notes": [
            {
              "id": "99",
               "operationId" : "456B",
              "note": "bla xxx"
            }
          ]
        }
      ]
    },
    "error" : ""
  }

A: I think the following would work:
case ADDNOTE: return {
  ...state,
  person: {
    ...state.person,
    operations: state.person.operations.map((operation) =>
      operation.id !== action.payload.operationId
        ? operation //not this operation, just return original
        : { // add note
            ...operation,
            notes: [...operation.notes, action.payload],
          }
    ),
  },
};

More information on how to update can be found here


text:
Q: How to properly create pandas DataFrame from a list: all columns are merged in a single column "0" I have this code:
print("body['csvData']", body['csvData'])

print("===============================")

csvData = pd.DataFrame([x.split(';') for x in str(body['csvData']).split('\n')])

print("TYPE csvData", type(csvData))

print(csvData.head())

It receives the content of the POST body request from React.js and tries to convert csvData into pandas DataFrame.
I get this output:
body['csvData']
 NUM,AIRLINE_ARR_ICAO,WAKE,SIBT,SOBT,PLANNED_TURNAROUND,DISTANCE_FROM_ORIGIN,DISTANCE_TO_TARGET
1,AEA,H,2016-01-01 04:05:00,2016-01-01 14:10:00,605,9920.67,5776.89
2,AEA,H,2016-01-01 04:25:00,2016-01-01 06:30:00,125.0,10060.80,483.93
3,AVA,H,2016-01-01 05:05:00,2016-01-01 07:05:00,120.0,8033.86,8033.86
4,IBE,H,2016-01-01 05:20:00,2016-01-01 10:40:00,320.0,6000.00,8507.73
5,IBE,H,2016-01-01 05:25:00,2016-01-01 10:50:00,325.0,6698.42,6698.42

===============================
TYPE csvData <class 'pandas.core.frame.DataFrame'>
                                                0
0  NUM,AIRLINE_ARR_ICAO,WAKE,SIBT,SOBT,PLANNED_TU...
1,AEA,H,2016-01-01 04:05:00,2016-01-01 14:10:0...
2,AEA,H,2016-01-01 04:25:00,2016-01-01 06:30:0...
3,AVA,H,2016-01-01 05:05:00,2016-01-01 07:05:0...
4,IBE,H,2016-01-01 05:20:00,2016-01-01 10:40:0...

It looks like csvData is converted into pandas DataFrame, however all columns are merged into a single column called 0.
print(csvData.dtypes)

Output:
0    object
dtype: object

A: pd.read_csv() needs tte location of csv file. You should now add the codes given below.
csvData.columns = csvData.iloc[0]
csvData.reindex(csvData.index.drop(0))


text:
Q: ReferenceError: document is not defined - Firebase AppCheck with SvelteKit I'm trying to add AppCheck in my SvelteKit web app and it gives this error:
ReferenceError: document is not defined
at makeDiv (C:\Users...\ecomm\node_modules@firebase\app-check\dist\index.cjs.js:1149:24)
at initializeV3 (C:\Users...\ecomm\node_modules@firebase\app-check\dist\index.cjs.js:1094:17)
at ReCaptchaV3Provider.initialize (C:\Users...\ecomm\node_modules@firebase\app-check\dist\index.cjs.js:1294:9)
at _activate (C:\Users...\ecomm\node_modules@firebase\app-check\dist\index.cjs.js:1598:23)
at Proxy.initializeAppCheck (C:\Users...\ecomm\node_modules@firebase\app-check\dist\index.cjs.js:1554:5)
at C:/Users/.../ecomm/src/lib/firebase.ts:23:17
at async instantiateModule (file:///C:/Users/.../ecomm/node_modules/vite/dist/node/chunks/dep-1513d487.js:50330:9)
It's the same problem as this question, only it's not React but SvelteKit

My integration code is:
import { initializeApp } from "firebase/app";
import { initializeAppCheck, ReCaptchaV3Provider } from "firebase/app-check";

const firebaseConfig = { *the app config* };

const app = initializeApp(firebaseConfig);

const appCheck = initializeAppCheck( app, {
   provider: new ReCaptchaV3Provider('*my public key*'),
   isTokenAutoRefreshEnabled: true
});

Does anyone has an idea how to solve? Thanks


text:
Q: How do I uniquely identify tab control? I was planning to do something like this when certain condition is satisfied and the below code will run many times.
TabPage newtabcontrol = new TabPage();
tabControl1.Controls.Add(newtabcontrol);

But how do I know the tabIndex for the latest tabpage I just added?

A: You can assign TabPage a unique name
As for example
TabPage newtabcontrol = new TabPage();
newtabcontrol.Name = "ID-1";
tabControl1.Controls.Add(newtabcontrol);

And to find the tabPage, you can use
var tabPage = tabControl1.TabPages["ID-1"]
if (tabPage != null)
{
    // perform action
}

A: For last tabPage which added:
TabPage newtabcontrol = new TabPage();
tabControl1.Controls.Add(newtabcontrol);

TabPage temp = tabControl1.TabPages[tabControl1.TabCount - 1];


text:
Q: How do I start my grails dev server in single threaded mode? grails run-app will start my app in an embedded tomcat server.
I would like to configure this embedded server so that only a single request processor thread is available and that multiple threads are processed serially rather than concurrently (similar to default webrick behaviour in the rails world)
Is it possible? If so, how do I do it?

A: As far as I know, this is not directly supported by the Tomcat plugin. But you could easily modify the Tomcat plug-in and run your own version.
If you look at the class org.grails.tomcat.TomcatServer, you will see it starts a Tomcat instance.
Here is the doc for this class: http://tomcat.apache.org/tomcat-7.0-doc/api/org/apache/catalina/startup/Tomcat.html
There is a getConnector() method which will return the default HTTP connector. Once you have it, you can probably change the settings, like maxThreads.
But be careful the performance will be awful. But I guess you already know that.


text:
Q: Can a class extend the Collection object? I'm trying to extend functionality of the VBA Collection object in a new class and make this class an inheritant of Collection, but the Implements Collection statement gives me the following error:

Bad interface for Implements: method
  has underscore in its name.

What underscore?! Add, Item, Remove, and Count are the only methods listed in the documentation for Collection. All four are underscore-free.
EDIT: To clarify, I'm making a class called UniformCollection (that only accepts members that are all of the same type, inspired by this approach). I'd like it to implement Collection, so that a UniformCollection is a Collection and can be used in place of a Collection when calling other objects' methods, etc.
I know I have to write delegating methods/properties for Add, Item, etc., and a NewEnum property for For Each to work, and I've done so already.
My problem is that the Implements Collection statement gives me the error stated above.
Bonus question: is Count a method or a property of Collection? Help calls it a property, but the Object Browser in the VBA editor calls it a function i.e. method (flying yellow box).

A: You are running into one of the limitations of Implements in VBA.  You can't implement another class if the other class has any public methods or properties with an underscore in the name. Collection class of course has _NewEnum but any underscore will cause a problem.
For example, if you created a class AddressClass that had the following:
Public Address_City As String

Then created another class CustomerAddress:
Implements AddressClass

Private Property Get ClassInterface_Address_City() As String
End Property

Private Property Let ClassInterface_Address_City(ByVal RHS As String)
End Property

When you compile, you will get an error "Object module needs to implement 'Address_City' for interface 'AddressClass'." Changing the property to AddressCity makes the error go away.
Possible solution: If I understand correctly, you want to implement the collection class so you can pass your new class to methods that take in collections as parameters. Is it possible to alter those methods?  My suggestion would be to create your own collection class MyCollection and then implement it instead.  i.e. UniformMyCollection That way you can completely avoid problems with underscores.
As for Count, I would trust the Object Browser over the help text anytime.  On the other hand, if you are creating your own collection class, it doesn't matter which one you choose.

A: VBA has a lot of limitations on what classes you can implement.  The NewEnum is tripping up Collection, but even if it wasn't, there could very well be something else in that class to trip it up.  I think it reports the first problem it finds.
Because Collection has so few properties and methods, I just rewrite them.
Private mcolParts As Collection

Public Sub Add(clsPart As CPart)
    mcolParts.Add clsPart, CStr(clsPart.PartID)
End Sub

Public Property Get Count() As Long
    Count = mcolParts.Count
End Property

Public Property Get Item(vItm As Variant) As CPart
    Set Item = mcolParts.Item(vItm)
End Property

Public Sub Remove(vIndex As Variant)
    mcolParts.Remove vIndex
End Sub

In don't know why the OB shows methods (they look like green boxes to me).  For my money, methods either change multiple properties or interact with something outside of the class.  Everything else is a property.  I'd call both Count and Index properties.

A: Dick Kusleika has most of it, but if you want to use For Each on your custom class, you'll also need:
'--- required additional property that allow to enumerate the collection with For Each
Public Property Get NewEnum() As IUnknown
    Set NewEnum = m_ColParts.[_NewEnum]
End Property

This isn't discussed in either of the links I found in my Favorites (this one or this one), but they're both worth reading. If I find the site that talks about NewEnum I'll do an Edit to add it.
EDIT
Neither of these links are the one I was looking for, either, but both discuss the NewEnum property (including a little extra voodoo that neeeds to be added):
Here and
here.
Both of these talk about Excel, but the VBA is the same in other Office applications (including the need for the export->text edit->import process to get "Attributes").

A: Re RolandTumble's note on "NewEnum" :
My own experience in Access 2003 is that "For Each" works fine by importing code including the line
Attribute NewEnum.VB_UserMemId = -4

... but after I "/decompile" the file (command line switch), the line has been removed (verified on export) and the "For Each" does not function.
Unfortunately I need to use "/Decompile"  when "Compress and Repair" does not fix things for me.


text:
Q: Inferring the Lipschitz constant of a vector Laplacian, given Lipschitz constants of the second and third derivative I have a function $f: \mathbb{R}^d \to \mathbb{R}$, which is three times continuously differentiable. I know that the Lipschitz constants for the second and third derivative of this function are $\mu_2$ and $\mu_3$, i.e.
$$\| \nabla^2 f(x) - \nabla^2 f(y) \|_{\text{op}} \le \mu_2 \| x -y \|_2,$$
$$\| \nabla^3 f(x) - \nabla^3 f(y) \|_{\text{op}} \le \mu_3 \| x -y \|_2,$$
where the operator norms are defined to be
$$\| \nabla^2 f(x) \|_{\text{op}} = \sup_{ \|  u \|\le 1} \| \nabla^2 f(x)u \|_2, $$
$$\| \nabla^3 f(x) \|_{\text{op}} = \sup_{ \| u \|, \| v \| \le 1} \left\| \left(v^\top \nabla^2 \frac{\partial f}{\partial x_1} u, \dots, v^\top \nabla^2 \frac{\partial f}{\partial x_d} u \right) \right\|_2. $$
Now, I'm interested in the Lipschitz constant of the vector Laplacian of the gradient of $f$, i.e. $\vec{\Delta}(\nabla f)$, where each component is $\vec{\Delta}(\nabla f)_i = \Delta \left(\frac{\partial f}{\partial x_i}\right)$.
I'm guessing the constant is $d \mu_3$. Is there a way to formally show this?
It's trivial to show $d^{3/2} \mu_3$ is a valid Lipschitz constant. However, whether this is the best we can do seems non-trivial.


text:
Q: CDI @ConversationScoped with AJAX I've got a pretty typical CRUD situation that I'm struggling with so I assume I must be misunderstanding something. I've put together a little demo app to better explain my problem. The two files of interest are shown below:
PersonView - CDI Managed Bean backing the JSF page
package example

import java.io.Serializable;
import java.util.List;
import javax.enterprise.context.Conversation;
import javax.enterprise.context.ConversationScoped;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;
import javax.inject.Named;

@ConversationScoped @Named
public class PersonView implements Serializable {

private Person selectedPerson;
@Inject private PersonService personService;
@Inject private Conversation conversation;

public PersonView() {}

public List<Person> getPeople() { return personService.findAll(); }

public void beginConversation() { if( conversation.isTransient() ) {conversation.begin();} }

public void endConversation() { if( !conversation.isTransient() ) { conversation.end();} }

public void createPerson() {
    beginConversation();
    setSelectedPerson( new Person() );
}

public void addPerson() {
    personService.addPerson( getSelectedPerson() );
    endConversation();
}

public void updatePerson() { personService.updatePerson( getSelectedPerson() ); }

public Person getSelectedPerson() { return selectedPerson; }

public void setSelectedPerson(Person selectedPerson) { this.selectedPerson = selectedPerson; }
}

index.xhtml - JSF page for manipulating people
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<h:head>
    <title>CRUD Example</title>
</h:head>
<h:body>
    <h:form prependId="false">

<f:facet name="header">ID</f:facet>#{p.id}

<f:facet name="header">Name</f:facet>#{p.name}

            <f:facet name="footer">

            </f:facet>

    </h:form>

        <h:form prependId="false">

Name:

        </h:form>

</h:body>

On the index page the user is shown a data table containing all the people the system knows about. They then press the Create Person button at the bottom of the table. I have checked that this correctly calls the createPerson method and the conversation apparently starts. The create_dialog is then displayed where the user can enter a name. The problem comes when the user clicks the Add button. JSF attempts to store the persons name but the selectedPerson variable is now null so it fails with a NullPointerException.
I realize this isn't a common way of creating objects but in my current application is makes sense as I can guess some of the values of a new Person. It also fits quite well with how I'd like to do editing.
So my question(s): why doesn't the conversation propagate? The PersonView bean appears to be in request scope all the time. I've read about @ViewScoped in JSF2 but I'd rather stick with CDI if possible. From what I've read I think the problem is a failure to pass the CID name with the request but I'm at a loss to see how I could do that with AJAX.
The only solution that I've come up with is to move PersonView into the session but that feels like a huge kludge.
e

A: The only way that I got this to work is to use @ViewAccessScoped in MyFaces CODI.  CDI allows extensibility so all you have to do is include the CODI jar files in with your application.  This works even if you are using Mojarra and not MyFaces.
So if you want to use CDI annotations, that's my recommendation.  I tried using ConversationScoped annotation for a while but I just couldn't get it to work conveniently.  Once I started using CODI all my problems went away.

A: Seems like you are using PrimeFaces, Im not sure how to make an ajax call with Primefaces, so I will show you how its done with standard JSF 2.0
First of all when using AJAX, you MUST pass the cid with every AJAX request.
Try adding the following to your ConversationScope Managed Bean (You need to somehow pass the cid to the view - index.xhtml, then every subsequent AJAX call will pass the same cid back to the server):
@Named
@ConversationScoped
public class PersonView implements Serializable {

public List<Person> getPeople() {
 return personService.findAll();
}

 @Inject
 private Conversation conversation;

 //Start the conversation once the
 //bean is created and all injection is done on the bean
 //I typically use this in the case of AJAX
 @PostContruct
public void beginConversation() {
 if( conversation.isTransient() ) {
   conversation.begin();
 }
}

public void endConversation() {
  if( !conversation.isTransient() ) {
    conversation.end();
  }
}
// This will be used in the view (index.xhtml)
public String getConversationId() {
  return conversation.getId();
}

public void createPerson() {
 setSelectedPerson( new Person() );
}

public void addPerson() {
 personService.addPerson( getSelectedPerson() );
 endConversation();
 // beginConversation(); //might need to start a new conversation once old one is done
}
}

now in your view you will typically do the following:
<h:commandButton action="#{personView.createPerson}" value="Create Person">

   <f:param name="cid" value="#{personView.conversationId}" />
   <f:ajax execute="@form" />
</h:commandButton>

<h:commandButton action="#{personView.addPerson}" value="Add">

   <f:param name="cid" value="#{personView.conversationId}" />
   <f:ajax execute="@form" render=":person_table" />
</h:commandButton>

This works as long as all subsequent calls are AJAX. If you start mixing it with the normal calls the conversation gets lost. On the other hand, it this was a non-AJAX list of calls you are making, the cid would be passed in automatically for you

A: Working with @ConversationScoped in combination with <f:ajax> tags makes it necessary to pas the conversation id to commandButton and commandLink elements.
See this Example:
<h:commandLink value="update"
    actionListener="#{myController.updateSomething(myData)}">
    <f:ajax render="...."/>
    <f:param name="cid" value="#{myController.getCID()}" />
</h:commandLink>


text:
Q: How to edit SQL command in the pgadmin 4's create... > new column...? I cannot edit the SQL command in my pgadmin's UI
.
I was following a tutorial from 2016 that has this tutorial's pgadmin's UI. In the tutorial, there's a "read-only" checkbox that can be unchecked if we want to edit the SQL command (in this case I want to append PRIMARY KEY after ADD COLUMN id serial)
I'm using windows 10, pgadmin 4 in chrome browser.


text:
Q: creating executable program from multiple python py files using python3 probably using makefile and make so following is my code. I got code from here https://docs.python.org/3/tutorial/classes.html
Now creating executable by looking at this answer cause nonlocal error. the error only says
File "./scope.py", line 8
    nonlocal spam
                ^
SyntaxError: invalid syntax

because I ran it like from here https://stackoverflow.com/a/304896/4808760
#!/usr/bin/env python

i Placed above at top
give exe privileges
  chmod +x myfile.py

and ran like ./myfile.py
but this answer to create exe not working for me. what if I have multiple files. and I dont want to specify my python file names to run my program. I want to make program executable like in C C++ we use make to make programs and build.
If I have multiple python files then what command should I use in make file along with my makefile targets to create executable file named my_program. Can I do this in Linux from terminal
#!/usr/bin/env python

def scope_test():
    def do_local():
        spam = "local spam"

    def do_nonlocal():
        nonlocal spam
        spam = "nonlocal spam"

    def do_global():
        global spam
        spam = "global spam"

    spam = "test spam"
    do_local()
    print("After local assignment:", spam)
    do_nonlocal()
    print("After nonlocal assignment:", spam)
    do_global()
    print("After global assignment:", spam)

scope_test()
print("In global scope:", spam)


text:
Q: Android: Populating a listview from MySQL database? I have some data from mysql which I'm retrieving from my phone app. What is the best way to populate a listview with multiple data? I have something simple like this:
try {
        JSONArray jArray = new JSONArray(result);
        int jArrayLength = jArray.length();
        List<String> listContents = new ArrayList<String>(jArrayLength);

        for(int i =0; i<jArray.length(); i++){

            JSONObject json_data = jArray.getJSONObject(i);
            listContents.add(json_data.getString("full_name"));

        }

        ListView myListView = (ListView) findViewById(R.id.front_page_listview);
        myListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listContents));

    }catch(JSONException e){
        Log.e("log_tag","Error parsin data "+e.toString());
    }

I can add the names just fine, but what if I want more information within that same row? ie: email, birthday, etc...
listContents.add(json_data.getString("full_name"),json_data.getString("email"));

Gives me errors.
Thank you for your help!

A: I don't think listviews can have "columns" so you should concatenate the strints instead. Like:
listContents.add(json_data.getString("full_name")+ ' ' +json_data.getString("email"));

A: Define arrayadapter
           ArrayList<String> al = new ArrayList<String>();
            String fullName;

Then get value via http and set on array adapter(a1) :
try{
                    jArray = new JSONArray(result);
                    JSONObject json_data = null;
                    for (int i = 0; i < jArray.length(); i++) {
                        json_data = jArray.getJSONObject(i);
                        targetamount=json_data.getString("full_name");

                        al.add(fullName);

                    }
                }

Now excuted event:
 protected void onPostExecute(final Void unused) {
                 this.progressDialog.dismiss();
                try{
                         ListView listview = (ListView) findViewById(R.id.listView1);
                        this.progressDialog.dismiss();
                         listview.setAdapter(new DataAdapter(DemoActivity.this,al.toArray(new String[al.size()])));

                    }
                    catch(Exception e){

                        Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
                    }

            }

want more info about this problem related then goto belows link:
http://p-xr.com/android-tutorial-how-to-parse-read-json-data-into-a-android-listview/
http://fahmirahman.wordpress.com/2011/04/21/connection-between-php-server-and-android-client-using-http-and-json/
http://www.helloandroid.com/tutorials/connecting-mysql-database
and
http://www.androidhive.info/2012/03/android-listview-with-load-more-button/


text:
Q: FullCalendar: event source returning large amount of data causing UI blocking I am using the FullCalendar plug in to provide a calendar to the users of my web application. Within FullCalendar, I am allowing the user to pick between the following views:

right: 'agendaWeek,agendaDay,basicWeek,month'

My problem applies currently only when accessing the month view. On a busy month, the amount of JSON being return comes up to 5 MB 700KB.
eventSources: [
   {
      url: 'calendar.php',
      type: 'POST',
      data: {
         emp_id: emp_id
      },
    }
]

The fetching of this large chunk of data isn't an issue- it doesn't take longer than 1.5 seconds 1 second.
It is the rendering that is problematic- it can take upwards of 10 seconds during which the UI is blocked and the page appears unresponsive (for obvious reasons- the single threaded nature of JS).
I then looked in to Web Workers as a potential solution (I am okay with solutions that work only in newer browsers). However, that is not a simple fix either because any use of Web Workers is probably best done at the plugin (FullCalendar) level as opposed to when I create a calendar instance.
I have also looked at this answer. My evaluation of the suggested solutions:

*

*Break up the server response into multiple requests: probably doesn't apply here- this is the monthly view and users need to be able to see all the events in a given month.

*Break up the parsing into multiple pieces: probably best done at the FullCalendar level?

*Send the response off to a web worker and parse it in a web worker (doesn't work in older browsers).

I realize that parsing a large amount of JSON data and rendering it is time consuming.  However, what I'd like to be able to do at the very least is to have the rest of the page responsive while events are rendered.
What are some reasonable ways of remedying the situation?

Edit
I completely overlooked the fact that I wasn't filtering the events I needed at the SQL level. I am doing so now and the data coming in is about 700kb as opposed to 5mb. However, the page is still not as responsive at it should be.

A: Like André Catita said you should create a filter, probably you are returning the full year of events...guessing here...
If you send previously a date limit ( month wide ) like this:
eventSources: [
 {
    url: 'calendar.php',
    type: 'POST',
    data: {emp_id: emp_id, start: startdate, end: enddate},
  }
]

You would be able to set the time range in wich your events should be returned, ofc server-side you have to get startdate and enddate and fetch the events accordingly.
Check this link to give you a hint of what i'm talking about:
events (as a json feed), start end parameters unix timestamp, are different if I change my OS time zone


text:
Q: ffmpeg задать срок жизни видеофрагменту Дано:

*

*Приложение ASP .NET Core.

*Фронтенд на react

*Контроллер на c#.

*Есть rtsp поток с камеры и ffmpeg скрипт, который преобразует его в hls (создаёт плейлист .m3u8 и нарезает сегменты .ts). Другой скрипт на js чистит папку от сегментов старше 'n' секунд.

Пытаюсь переписать оба скрипта (заводились в окнах терминала) в виде методов контроллера.
Вопрос:
Можно ли совместить два скрипта в одном - задать в ffmpeg-скрипте срок жизни создаваемым сегментам?


text:
Q: Dynamic Nav-pills to show Tab-content in Bootstrap I have a function that dynamically creates navigation in a web page. The problem I have is that when I click on the top nav buttons it works. As I know you can only use ID's once. This is the problem. How can I use classes instead of ids to make sure that all the navigations work?
Thanks in advance. Any questions, just comment and i'll reply in a jiffy.
The code is :
function printComments($amb){
    foreach ($amb as $key => $a) {

                    {$a['amb_about']}

    HTML;
                $html .= outputComments($a['comments']);
    $html .= <<<HTML

    }
}

A: In all tab scripts I've used in 15+ years, the id of the tab matches an id of the tab-pane (or equiv), and it must otherwise how will it know which one to open? With Bootstrap you can use classes, but if the classes are not unique, then one will trigger the other and vice versa. See example: http://jsbin.com/viziju/1/edit. So might as well use ids.

Home

Profile

Messages

Settings

home

profile

messages

settings


text:
Q: using assembly code inside Objective c program (Xcode) Is there a way to use assembly code inside Objective C program. I am developing an application for OSX and wanted to use assembly code alongside the Objective C code. I searched the internet and found this But I am not able to implement any of these methods successfully. Any help will be greatly appreciated.

A: Yes, of course.
You can use GCC-style inline assembly in Objective-C just like you would in C.  You can also define functions in assembly source files and call them from Objective-C.  Here's a trivial example of inline assembly:
int foo(int x, int y) {
    __asm("add %1, %0" : "+r" (x) : "r" (y));
    return x;
}

And a similarly minimal example of how to use a standalone assembly file:
** myOperation.h **
int myOperation(int x, int y);

** myOperation.s **
.text
.globl _myOperation
_myOperation:
    add %esi, %edi  // add x and y
    mov %edi, %eax  // move result to correct register for return value
    ret

** foo.c **
#include "myOperation.h"   // include header for declaration of myOperation
...
int x = 1, y = 2;
int z = myOperation(x, y); // call function defined in myOperation.s


text:
Q: Оператор WHERE не убирает строки в SQL-запросе Имеется следующий SQL-запрос:
   SELECT
          SYS.Name0 'PC',
          VC.Name0 'Video',
          DDISK.Index0 + 1 '# HDD',
          DDISK.Caption0 'HDD'
    FROM v_R_System SYS
          outer apply (select max(cnt) as mx
                      from (select count(*) as cnt from v_GS_Disk
                            where v_GS_Disk.ResourceID = Sys.ResourceId
                            union all
                            select count(*) as cnt from v_GS_Video_Controller
                            where v_GS_Video_Controller.ResourceID = Sys.ResourceId
                            ) as cnts) as max_cnt
          cross apply dbo.GetNums(1, isnull(max_cnt.mx, 1)) as nums
           left join (select ResourceId, Index0, Caption0
                           , row_number() over (partition by resourceId
                                                order by Index0) as rn
                      from dbo.v_GS_Disk DDISK where DDISK.InterfaceType0 != 'USB') as DDISK
                  on Sys.ResourceId = DDISK.ResourceId
                  and nums.n = DDISK.rn
           left join (select ResourceId, Name0
                           , row_number() over (partition by resourceId
                                                order by Name0) as rn
                      from dbo.v_GS_Video_Controller VC where vc.name0 not like '%lan%') as VC
                  on Sys.ResourceId = VC.ResourceId
                  and nums.n = VC.rn

В запросе используется два условия выборки.
Вместо исключения из вывода строк, не попадающих под выборку, запрос их оставляет пустыми и они остаются при выводе.
Пример вывода без выборки:

Пример вывода с выборкой:

В данном случае должно выводиться 2 строки.
Как, в данном случае, исправить запрос?

A: Теперь понял, в чем проблема.
Вам нужно продублировать условия выбора в подзапросе, присоединяемом через outer apply, чтобы выбирать количество только нужных записей, вот так:
SELECT
          SYS.Name0 'PC',
          VC.Name0 'Video',
          DDISK.Index0 + 1 '# HDD',
          DDISK.Caption0 'HDD'
    FROM v_R_System SYS
          outer apply (select max(cnt) as mx
                      from (select count(*) as cnt from v_GS_Disk
                            where v_GS_Disk.ResourceID = Sys.ResourceId
                              and v_GS_Disk.InterfaceType0 != 'USB'
                            union all
                            select count(*) as cnt from v_GS_Video_Controller
                            where v_GS_Video_Controller.ResourceID = Sys.ResourceId
                              and v_GS_Video_Controller.name0 not like '%lan%'
                            ) as cnts) as max_cnt
          cross apply dbo.GetNums(1, isnull(max_cnt.mx, 1)) as nums
           left join (select ResourceId, Index0, Caption0
                           , row_number() over (partition by resourceId
                                                order by Index0) as rn
                      from dbo.v_GS_Disk DDISK
                      where DDISK.InterfaceType0 != 'USB') as DDISK
                  on Sys.ResourceId = DDISK.ResourceId
                  and nums.n = DDISK.rn
           left join (select ResourceId, Name0
                           , row_number() over (partition by resourceId
                                                order by Name0) as rn
                      from dbo.v_GS_Video_Controller VC
                      where vc.name0 not like '%lan%') as VC
                  on Sys.ResourceId = VC.ResourceId
                  and nums.n = VC.rn

A: Думаю вам нужно что то вроде этого:
SELECT SYS.Name0 'PC',
       MAX(X.Video) Video,
       MAX(X.Monitor) Monitor,
       MAX(X.Index0)+1 '# HDD'
       MAX(X.Caption0) 'HDD'
  FROM (
      SELECT ResourceID, Index0, Caption0, NULL as Video, NULL as Monitor,
             row_number() over(partition by resourceId order by NULL) as RN
        FROM dbo.v_GS_Disk
       WHERE InterfaceType0 != 'USB'
       UNION ALL
      SELECT ResourceID, NULL, NULL, Name0, NULL,
             row_number() over(partition by resourceId order by NULL)
        FROM dbo.v_GS_Video_Controller
       WHERE name0 not like '%lan%'
       UNION ALL
      SELECT ResourceID, NULL, NULL, NULL,UserFriendlyName0,
             row_number() over(partition by resourceId order by NULL)
        FROM dbo.v_GS_WMIMonitorID
  ) X
  JOIN v_R_System SYS on X.ResourceID=SYS.ResourceID
 GROUP BY X.ResourceID, X.RN, SYS.Name0


text:
Q: How to capture an image in xamarin android using the camera in fragment I am a beginner in xamarin android.I want to take photo using my device camera,I am using the following code to to capture the image but, I got an exception when running the code
Here is my Fragment.CS
  public class ScanFragments : Fragment
{
    ImageView imageView;

    public override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
    }

    public static ScanFragments NewInstance()
    {
        var scan = new ScanFragments { Arguments = new Bundle() };
        return scan;
    }

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        var ignored = base.OnCreateView(inflater, container, savedInstanceState);

        imageView =View.FindViewById<ImageView>(Resource.Id.Iv_ScanImg);
        var btnCamera =View. FindViewById<Button>(Resource.Id.btnCamera);

        btnCamera.Click += BtnCamera_Click;

        return inflater.Inflate(Resource.Layout.ScanLayout, null);
    }

    private void BtnCamera_Click(object sender, EventArgs e)
    {
        Intent intent = new Intent(MediaStore.ActionImageCapture);
        StartActivityForResult(intent, 0);
    }
}

A: Well now I see your mistake its actually very simple you get the null reference because of the following reasons
1.OnCreateView does not contain a definition of View basically what I mean here is View is a class which you are using as an object of that class.
2.The actual way I recommend using fragments is first you define it an XML or an AXML as its foreground view in on OnCreateView as follows :
 return inflater.Inflate(Resource.Layout.ScanLayout, null);

3.Override the OnViewCreated method and use its View to do all your work as follows :
 public override void OnViewCreated(View view, Bundle savedInstanceState)
{
    base.OnViewCreated(view, savedInstanceState);
    imageView =view.FindViewById<ImageView>(Resource.Id.Iv_ScanImg);
    var btnCamera =view. FindViewById<Button>(Resource.Id.btnCamera);

    btnCamera.Click += BtnCamera_Click;

}

4.For details related to the Android Activity and Fragment lifecycle check here
Goodluck!


text: Q: Phone gets really hot in certain spot when charging? My iPhone 4s keeps getting really really hot in the top right corner when i start charging it. Its mainly along the top, near the turn off button, all down the right side, and near the camera on the back. This causes my phone to charge really slowly and causes it to turn off multiple times due to overheating. Is this dangerous?


text:
Q: Messenger in Visual Studio After i restart laptop, visual studio don't turn off, then i open it again, It shows many lines on tabs.
"Feature 'Asset synchronization' is currently unavailable due to an internal error. Show Stack Trace"

A: Do these things:

*

*Press Alt + Ctrl + Del

*Select Task Manager.

*Click on "More details" on the left side below of the Task Manager.

*Then, click the Start button.

*Find Visual Studio in this list, then click on it.

*Click "Disable" after right-clicking on Visual Studio.

Then close the window, and your problem will be solved.


text:
Q: Meteor Helper not working with if statement I'll try to clarify this as much as possible because I believe the answer is going to be something very simple I'm overlooking.
My HTML:

Personal Info

Groups

Commitments

My Helper:
Template.Profile.helpers({
'personal':function(){
    if ($('.profile-info').hasClass('active')) {
        return true;
    } else {
        return false;
    }
}

});
I just want 'personal' to return TRUE. However it always returns false no matter what type of "IF" statement I give it.


text:
Q: What are the values of $k$ that males $x_1,x_2$ solutions to the linear system $AX=B$. Supose that $x_1$ and $x_2$ are solution to the linear system $ AX=B $ ,
 where $B$ is not equal zero then $3x_1-kx_2$ is a solution also if $k = ?$
How to find the value of $A$ ?

A: Hints: The fact that $x_1$ and $x_2$ are solutions to $AX = B$ means that $Ax_1 = B$ and $Ax_2 = B$.
In order for $3x_1-kx_2$ to be a solution to $AX=B$, we would need $A(3x_1-kx_2) = B$.
We can use linearity to simplify $A(3x_1-kx_2) = 3Ax_1-kAx_2 = \cdots$.
Can you figure out what value of $k$ makes $A(3x_1-kx_2) = B$?


text:
Q: laravel request validation issue Here is my view code:

<form class="form-horizontal" action="{{ isset($article) ? URL('console/articles/'.$article->id) : URL('console/articles') }}" method="POST">
  @if (isset($article))
    <input name="_method" type="hidden" value="PUT">
  @endif
  @unless (empty($errors->first()))

        <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>
        ...

  @endunless
  <input type="hidden" name="_token" value="{{ csrf_token() }}">

has('title') ? 'has-error' : '' }}">
    ...

      <input type="text" name="article[title]" id="article_title" class="form-control" placeholder="..." value="{{isset($article) ? $article->title : old('title')}}">
      {!! $errors->first('title', '
:message
') !!}

has('body') ? 'has-error' : '' }}">
    ...

      <textarea name="article[body]" id="article_body" cols="30" rows="10" class="form-control">{{isset($article) ? $article->body : old('body')}}</textarea>
      {!! $errors->first('body', '
:message
') !!}

      <button type="submit" class="btn btn-success">...</button>

</form>

and request validator:
// StoreArticleRequest.php
// ...
public function rules()
{
  switch ($this->method()) {
    case 'GET':
    case 'DELETE': {
      return [];
    }
    case 'POST': {
      return [
        'article.title' => 'required|unique:articles|max:255',
        'article.body' => 'required'
      ];
    }
    case 'PUT':
    case 'PATCH': {
      return [
        'article.title' => 'required|unique:articles,title,'.Route::input('articles').'|max:255',
        'article.body' => 'required'
      ];
    }
    default:
      break;
  }
  return [];
}
// ...

After send post request to create method, it raise

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'article.title'
  in 'where clause'
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'article.title'
  in 'where clause' (SQL: select count(*) as aggregate from articles
  where article.title = test)

Updated
Here`s my controller code:
// ArticlesController.php
// ...
public function store(StoreArticleRequest $request)
{
  $article = new Article($request->input('article'));
  if ($article->save()) {
    return redirect('console/articles')->with('success', '...');
  } else {
    return redirect()->back()->withInput();
  }
}

// ...
public function update(StoreArticleRequest $request, $id)
{
  $article = Article::find($id);
  if ($article->update($request->input('article'))) {
    return redirect('console/articles')->with('success', '...');
  } else {
    return redirect()->back()->withInput();
  }
}

// ...

A: Change your rules in  StoreArticleRequest.php file
case 'POST': {
  return [
    'article.title' => 'required|unique:articles,title|max:255',
    'article.body' => 'required'
  ];
}

if you not specify column name in unique validation it take consider key as column name.

A: instead of using article[title] as input name use title as input name and in rules use title instead of article.title


text:
Q: Bayesian posterior and prior distribution question Here is my question:
You want to find proportion x of phones from a given company is defective. You are sent a box of 10 samples, and you find that two are defective.

*

*Compute the posterior distribution for x using a uniform prior distribution.

2.Some time later, you are sent a second batch of 10 phones from the same company, but a different model. You find that three examples are defective in this new batch. Compute the updated posterior distribution. (One the includes the estimate obtained from the first batch).
I am not sure how to calculate the exact value of the first question since I got a beta(3,8) on question1. Also, for question2, how can I use the posterior distribution(beta(3,8))in question 1 to update the new posterior question? (I am also not sure whether using binomial distribution or beta distribution for this question)Thanks.

A: If you read through What is the intuition behind beta distribution? you'll find an explanation. (Or actually, several explanations from various viewpoints. The question itself is broader than yours, but several answers give examples.)
Several answers use a baseball analogy, and in case you're not familiar with baseball, the idea is that you are "at bat" a certain number of times in a game and some number of those times at bat you succeed and manage to get a "hit". You thus have two numbers representing your "at bat performance" in a baseball game, which correspond to your example problem: "at bat" corresponds to your number of samples, "hit" corresponds to your number of defects.