text:
Q: Using datepicker in MVC 4.0 to persist a date value in db, throwing "object doesn't support this property or method" Working around with MVC 4.0/Razor as the view engine.
Scenario: Binding a calendar to a text box, clicking in the txtBox should let a calendar flow down,using jqueryUI's datepicker and submitting it to a sql db.
What I did:
Model class:
    public class UserModels
    {

        [Required(ErrorMessage = "Mandatory Field")]
        public virtual string Name { get; set; }
        public virtual int Id { get; set; }
        [DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
        public virtual DateTime Dob { get; set; }
        [Display(Name = "CountrY")]
        public virtual string Country { get; set; }
        public virtual string Gender { get; set; }

    }

Razor View:
@model EMSapp.Models.UserModels

@{
    ViewBag.Title = "AddUser";
}

AddUser

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>UserModels</legend>

            @Html.LabelFor(model => model.Dob)

            @**Html.TextBoxFor(model => model.Dob, new { id = "date" })**

Error: When is the view is loading, "object doesn't support this property or method" is thrown.

A: Html.TextBoxFor(model => model.Dob, new { id = "date" }) should be setting the name and id attributes of your textbox to "Dob".
Try calling Html.TextBoxFor(model => model.Dob) and using $('#Dob').datepicker(); instead.


text:
Q: How do I copy a part of bytearray to c_void_p-referenced memory and vice versa? In the Python application, I have a bytearray with some data. My python code is called by some external native library (DLL/so/dylib) (using ctypes and its callback functions). One of the callback functions includes a pointer to the unmanaged buffer, allocated in that external library.
I need to copy a part of the bytearray into this unmanaged buffer or copy contents of the unmanaged buffer into the bytearray at specific location.
To put it simply, I have
def copy_from_python_callback(c_void_p_parameter : c_void_p, offset : int, size : int):
  managed_buf = bytearray(some_size) # suppose we have data in this buffer already
  unmanaged_buf = c_void_p_parameter
  # what do I need to do here?
  # src_buf = pointer_to_specific_byte_in_managed_buf
  memmove(unmanaged_buf, src_buf, size)

def copy_to_python_callback(c_void_p_parameter : c_void_p, offset : int, size : int):
  managed_buf = bytearray(some_size) #some_size is assumed to be larger than offset + size
  unmanaged_buf = c_void_p_parameter
  # what do I need to do here?
  # dst_buf = pointer_to_specific_byte_in_managed_buf
  memmove(dst_buf, unmanaged_buf, size)

In other languages, the answer would be simple - I'd either call the dedicated method (e.g. in .NET Framework's Marshal class), or get the pointer to the specific byte in the bytearray (in native languages like C++ or Pascal) and be done. Unfortunately, I don't see how to do either of these operations in Python without an intermediate bytes() or similar buffer.
I have some methods which use the intermediate bytes() instance, but copying the data just because there's no way to get a pointer seems to be weird to me.
I am looking for version-independent solution, if possible, but can live with python3-only one as well. Thank you in advance.

A: Listing [Python.Docs]: ctypes - A foreign function library for Python.
What you're looking for is possible. Arrays (CTypes) come in handy. Below it's a "small" example. For demo purposes, the buffers only contain "human friendly" chars.
dll00.c:
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

#if defined(_WIN32)
#  define DLL00_EXPORT_API __declspec(dllexport)
#else
#  define DLL00_EXPORT_API
#endif

#define C_TAG "From C - "

typedef int (*ReadFunc)(void *ptr, uint32_t offset, uint32_t size);
typedef int (*WriteFunc)(void *ptr, uint32_t offset, uint32_t size);

#if defined(__cplusplus)
extern "C" {
#endif

DLL00_EXPORT_API int testBufferCallbacks(uint32_t bufSize,
                                         ReadFunc read, uint32_t readOffset, uint32_t readSize,
                                         WriteFunc write, uint32_t writeOffset, uint32_t writeSize);

#if defined(__cplusplus)
}
#endif

void prinBuffer(const uint8_t *buf, uint32_t size) {
    printf("%sBuffer (size %d) 0x%016llX\n  Contents: ", C_TAG, size, (uint64_t)buf);
    for (uint32_t i = 0; i < size; i++) {
        printf("%c", ((uint8_t*)buf)[i]);
    }
    printf("\n");
}

int testBufferCallbacks(uint32_t bufSize,
                        ReadFunc read, uint32_t readOffset, uint32_t readSize,
                        WriteFunc write, uint32_t writeOffset, uint32_t writeSize) {
    const uint8_t charOffset = 0x41;
    void *buf = malloc(bufSize);
    uint8_t *cBuf = (uint8_t*)buf;
    for (uint32_t i = 0; i < bufSize; i++) {
        cBuf[i] = (uint8_t)((i + charOffset) % 0x100);
    }
    prinBuffer(cBuf, bufSize);
    if ((read != NULL) && (readSize > 0)) {
        printf("\n%sCalling read(0x%016llX, %u, %u)...\n", C_TAG, (uint64_t)buf, readOffset, readSize);
        read(buf, readOffset, readSize);
    }
    if ((write != NULL) && (writeSize > 0)) {
        printf("\n%sCalling write(0x%016llX, %u, %u)...\n", C_TAG, (uint64_t)buf, writeOffset, writeSize);
        write(buf, writeOffset, writeSize);
        prinBuffer(cBuf, bufSize);
    }
    if ((read != NULL) && (readSize > 0)) {
        printf("\n%sCalling read(0x%016llX, %u, %u)...\n", C_TAG, (uint64_t)buf, readOffset, readSize);
        read(buf, readOffset, readSize);
    }
    prinBuffer(cBuf, bufSize);
    free(buf);
    printf("\n%sDone.\n", C_TAG);
    return 0;
}

code00.py:
#!/usr/bin/env python3

import sys
import ctypes as ct

DLL_NAME = "./dll00.dll"

ReadFunc = ct.CFUNCTYPE(ct.c_int, ct.c_void_p, ct.c_uint32, ct.c_uint32)
WriteFunc = ct.CFUNCTYPE(ct.c_int, ct.c_void_p, ct.c_uint32, ct.c_uint32)

def create_bytearray(size, offset_char=0x61):
    contents = "".join(chr(i) for i in range(offset_char, offset_char + size))
    return bytearray(contents.encode())

def read_c_buf(buf : ct.c_void_p, offset : ct.c_uint32, size : ct.c_uint32):
    print("C buf: 0x{0:016X}".format(buf))
    ba = create_bytearray(0x1A)
    print("Python initial buffer: {0:}".format(ba))
    UCharArr = ct.c_uint8 * size
    uchar_arr = UCharArr.from_buffer(ba, offset)  # Shared memory
    ct.memmove(uchar_arr, buf, size)
    print("Python final buffer: {0:}\n".format(ba))
    return 0

def write_c_buf(buf : ct.c_void_p, offset : ct.c_uint32, size : ct.c_uint32):
    print("C buf: 0x{0:016X}".format(buf))
    ba = create_bytearray(size + offset, offset_char=0x30 - offset)
    print("Python buffer: {0:}\n".format(ba))
    UCharArr = ct.c_uint8 * size
    uchar_arr = UCharArr.from_buffer(ba, offset)  # Shared memory
    ct.memmove(buf, uchar_arr, size)
    return 0

def main(*argv):
    dll00 = ct.CDLL(DLL_NAME)
    testBufferCallbacks = dll00.testBufferCallbacks
    testBufferCallbacks.argtypes = (ct.c_uint32, ReadFunc, ct.c_uint32, ct.c_uint32, WriteFunc, ct.c_uint32, ct.c_uint32)
    testBufferCallbacks.restype = ct.c_int

    read_callback = ReadFunc(read_c_buf)
    buf_size = 0x1A
    read_offset = 10
    read_size = 16
    write_callback = WriteFunc(write_c_buf)
    write_offset = 5
    write_size = 10
    res = testBufferCallbacks(buf_size, read_callback, read_offset, read_size, write_callback, write_offset, write_size)
    print("\n{0:s} returned: {1:d}".format(testBufferCallbacks.__name__, res))

if __name__ == "__main__":
    print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")),
                                                   64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    rc = main(*sys.argv[1:])
    print("\nDone.")
    sys.exit(rc)

Output:

[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q059255471]> sopr.bat
### Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ###

[prompt]> "c:\Install\x86\Microsoft\Visual Studio Community\2017\VC\Auxiliary\Build\vcvarsall.bat" x64
**********************************************************************
** Visual Studio 2017 Developer Command Prompt v15.9.17
** Copyright (c) 2017 Microsoft Corporation
**********************************************************************
[vcvarsall.bat] Environment initialized for: 'x64'

[prompt]> dir /b
code00.py
code01.py
dll00.c

[prompt]> cl /nologo /MD /DDLL dll00.c  /link /NOLOGO /DLL /OUT:dll00.dll
dll00.c
   Creating library dll00.lib and object dll00.exp

[prompt]> dir /b
code00.py
code01.py
dll00.c
dll00.dll
dll00.exp
dll00.lib
dll00.obj

[prompt]> "e:\Work\Dev\VEnvs\py_064_03.07.03_test0\Scripts\python.exe" code00.py
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] 064bit on win32

From C - Buffer (size 26) 0x0000016BFE546EB0
  Contents: ABCDEFGHIJKLMNOPQRSTUVWXYZ

From C - Calling read(0x0000016BFE546EB0, 10, 16)...
C buf: 0x0000016BFE546EB0
Python initial buffer: bytearray(b'abcdefghijklmnopqrstuvwxyz')
Python final buffer: bytearray(b'abcdefghijABCDEFGHIJKLMNOP')

From C - Calling write(0x0000016BFE546EB0, 5, 10)...
C buf: 0x0000016BFE546EB0
Python buffer: bytearray(b'+,-./0123456789')

From C - Buffer (size 26) 0x0000016BFE546EB0
  Contents: 0123456789KLMNOPQRSTUVWXYZ

From C - Calling read(0x0000016BFE546EB0, 10, 16)...
C buf: 0x0000016BFE546EB0
Python initial buffer: bytearray(b'abcdefghijklmnopqrstuvwxyz')
Python final buffer: bytearray(b'abcdefghij0123456789KLMNOP')

From C - Buffer (size 26) 0x0000016BFE546EB0
  Contents: 0123456789KLMNOPQRSTUVWXYZ

From C - Done.

testBufferCallbacks returned: 0

Done.

Needless to say that going outside (C) buffer's bounds, would yield Undefined Behavior (and my code doesn't perform that kind of checks).

redpajama_set_name: RedPajamaStackExchange


text:
Q: TypeError: __array__() takes 1 positional argument but 2 were given I've been doing the pytorch tutorial (https://pytorch.org/tutorials/intermediate/torchvision_tutorial.html) and have been getting this error that I don't know how to fix. The full error is below:
Traceback (most recent call last):
  File "main.py", line 146, in <module>
    main()
  File "main.py", line 138, in main
    train_one_epoch(model, optimizer, data_loader, device, epoch, print_freq=10)
  File "/engine.py", line 26, in train_one_epoch
    for images, targets in metric_logger.log_every(data_loader, print_freq, header):
  File "/utils.py", line 180, in log_every
    for obj in iterable:
  File "/usr/local/lib/python3.6/dist-packages/torch/utils/data/dataloader.py", line 521, in __next__
    data = self._next_data()
  File "/usr/local/lib/python3.6/dist-packages/torch/utils/data/dataloader.py", line 1203, in _next_data
    return self._process_data(data)
  File "/usr/local/lib/python3.6/dist-packages/torch/utils/data/dataloader.py", line 1229, in _process_data
    data.reraise()
  File "/usr/local/lib/python3.6/dist-packages/torch/_utils.py", line 425, in reraise
    raise self.exc_type(msg)
TypeError: Caught TypeError in DataLoader worker process 0.
Original Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/torch/utils/data/_utils/worker.py", line 287, in _worker_loop
    data = fetcher.fetch(index)
  File "/usr/local/lib/python3.6/dist-packages/torch/utils/data/_utils/fetch.py", line 44, in fetch
    data = [self.dataset[idx] for idx in possibly_batched_index]
  File "/usr/local/lib/python3.6/dist-packages/torch/utils/data/_utils/fetch.py", line 44, in <listcomp>
    data = [self.dataset[idx] for idx in possibly_batched_index]
  File "/usr/local/lib/python3.6/dist-packages/torch/utils/data/dataset.py", line 311, in __getitem__
    return self.dataset[self.indices[idx]]
  File "main.py", line 64, in __getitem__
    img, target = self.transforms(img, target)
  File "/transforms.py", line 26, in __call__
    image, target = t(image, target)
  File "/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py", line 1051, in _call_impl
    return forward_call(*input, **kwargs)
  File "/transforms.py", line 50, in forward
    image = F.to_tensor(image)
  File "/usr/local/lib/python3.6/dist-packages/torchvision/transforms/functional.py", line 129, in to_tensor
    np.array(pic, mode_to_nptype.get(pic.mode, np.uint8), copy=True)
TypeError: __array__() takes 1 positional argument but 2 were given

I believe it means somewhere I'm using an array with 2 arguments which isn't allowed, but I don't really know where abouts that is happening - perhaps in one of their pre written libraries?
I can share the code in full if desired, but thought its a bit unwieldy. Does anyone know what might be causing this error?

A: PyTorch has already considered this issue. It does not seem to be a PyTorch problem.
As xwang233 mentioned in the issue, we can fix it by downgrading pillow:
pip install pillow==8.2.0

A: This issue could be fixed as well by upgrading Pillow from version 8.3.0 to 8.3.1. I had the same issue with
torch==1.9.0+cu111
torchvision==0.10.0+cu111
Pillow==8.3.0

After Pillow was upgraded to 8.3.1 (with no change to torch and torchvision) as below, the issue is gone:
pip install --upgrade pillow

Thanks to DRTorresRuiz for providing the clue about Pillow.

A: I had the same error when using:
torch==1.9.0
torchvision==0.10.0

In my requirements.txt file I downgraded the torch library, which forced me to downgrade torchvision, and that fixed the error for me.  The library versions I ended up using that did not raise the error were:
torch==1.8.1
torchvision==0.9.1

A: change your code:

np.array(pic ,np.float32)

to:

np.array(pic).astype('float32')


text:
Q: Why is "render 'new' " changing my URL? (Ruby On Rails) I have a view called new.html.erb for clients at localhost:3000/clients/new. I validate it for errors. If there's an error I render the new view again to show all the errors. The problem is that it is showing as localhost:3000/clients in my browser instead of localhost:3000/clients/new. Why is that? Isn't "render" supposed to not change anything from the URL? This gives problems when I refresh the page because I have no "index" view and it's triggering an error instead of showing the "new" view as it's supposed to.
new.html.erb
<% if @client.errors.any? %>

Error

            <% @client.errors.full_messages.each do |msg| %>

<%= msg %>

            <% end %>

<% end %>

<%= form_for @client, url: clients_path, remote: false do |f| %>

*Name

            <%= f.text_field :name, class:"form-control" %>
                <% if @client.errors[:name].any? %>

                <% end %>

    <%= f.submit "Submit", id:"submit", class: 'btn btn-primary btn-sm'%>
    <%= link_to "Cancel", controller:"mainpages", action:"index", :html=>{:class=> "btn btn-primary btn-sm"}%>

<% end %>

clients_controller.rb
def new
    @client = Client.new
  end

  def create
    @client = Client.new(client_params)

      if @client.save
        return redirect_to :root
      end
      render 'new'
  end

routes.rb
  root to: "mainpages#index"

  get '/mainpages', controller: 'mainpages', action: 'index'
  get '/planes', controller: 'planes', action: 'planes'

  resources :clients
  resources :planes

client.rb
class Client < ApplicationRecord
    validates :name, presence: true
end

A: The reason the URL shows /clients after submitting invalid data is because the /clients/new form submits the request to clients#create which is registered under POST /clients if you use the Rails defaults.
If your data was valid, Rails will redirect the user to the root path GET /. If your data was invalid it will render :new as response to POST /clients which shows up as /clients in your browser.
If you try to refresh the page after submitting invalid data, the browser should ask something like "do you want to resubmit the form?". If you click yes the page is refreshed and and it shouldn't hit GET /clients (which normally routes to clients#index). If you manually click in the URL bar of your web-browser and hit Enter a GET /clients request is send instead, thus landing you on the wrong page.
You can see all routes, including request types, by running the rails routes command.

A: Your expectation is completely wrong but quite common among Rails beginners.
In Rails flavor REST GET /clients/new is just a page that contains the form for creating a new resource. Since its a GET request it is idempotent - that means its stateless and looks the same for all visitors.
When you submit the form your browser is sending a POST request to /clients. Again in Rails flavored REST this is how you create a resource.
If the validation fails rails simply renders a response containing the form. This SHOULD NOT redirect the user as what you are seeing is the result of the non-idempotent POST request. This is not the same resource as GET /clients/new.
In fact render 'new' is just a shortcut to render 'app/views/clients/new.html.erb'. The two endpoints share a view - nothing else.

Why is that? Isn't "render" supposed to not change anything from the URL?

You are completely mistaken. render does not change the URL. Submitting the form earlier changed the URL in the browser. Render just renders the view and returns it as the body of the response. Look at the logs of your Rails app if you want to get an idea of how the interchange between client and server actually works.
You can contrast this with redirect_to which sends a location header back and the correct response code (302) which will redirect the browser to the new location.

This gives problems when I refresh the page because I have no "index"
  view and it's triggering an error instead of showing the "new" view as
  it's supposed to.

To resolve this you need to add an index action which can be a simple redirect to /clients/new. When you reload the page you are sending a GET request to /clients which should render the index.
I would really recommend that you try just creating a scaffolded rails app so that you get an idea of how the rails conventions do simple CRUD operations before you start imposing your own ideas.

A: When you submit this form, it goes to /client URL with the post method. And when you call render method in case of error,
let's understand how 'render' works and what it does (and how it is different from 'redirect'):
render: Renders the content that will be returned to the browser as the response body.
Render tells Rails which view or asset to show a user, without losing access to any variables defined in the controller action.
Redirect is different. The redirect_to method tells your browser to send a request to another URL. Since the request is completely different, the view to which you redirect will NOT have access to any variables defined in the controller.
So in this case, if you redirect, you will lose your submitted data as this will be a completely fresh and independent request.
There are some ways (described in below URL) by which you can also change the URL with render (but these are not the Rails and Rest way.)
Render template and change url string in browser?

A: Sharing this because I was confused for a while: If you use turbo-rails, which is baked into Rails 7, the URL actually doesn't change


text:
Q: How to get data back from Mysql for days that have no statistics I want to get the number of Registrations back from a time period (say a week), which isn't that hard to do, but I was wondering if it is in anyway possible to in MySQL to return a zero for days that have no registrations.
An example:
DATA:

ID_Profile    datCreate
1   2009-02-25 16:45:58
2   2009-02-25 16:45:58
3   2009-02-25 16:45:58
4   2009-02-26 10:23:39
5   2009-02-27 15:07:56
6   2009-03-05 11:57:30

SQL:

    SELECT
        DAY(datCreate) as RegistrationDate,
    COUNT(ID_Profile) as NumberOfRegistrations
    FROM tbl_profile
    WHERE DATE(datCreate) > DATE_SUB(CURDATE(),INTERVAL 9 DAY)
    GROUP BY RegistrationDate
    ORDER BY datCreate ASC;

In this case the result would be:

RegistrationDate    NumberOfRegistrations
25  3
26  1
27  1
5   1

Obviously I'm missing a couple of days in between. Currently I'm solving this in my php code, but I was wondering if MySQL has any way to automatically return 0 for the missing days/rows. This would be the desired result:

RegistrationDate    NumberOfRegistrations
25  3
26  1
27  1
28      0
1       0
2       0
3       0
4       0
5   1

This way we can use MySQL to solve any problems concerning the number of days in a month instead of relying on php code to calculate for each month how many days there are, since MySQL has this functionality build in.
Thanks in advance

A: No, but one workaround would be to create a single-column table with a date primary key, preloaded with dates for each day. You'd have dates from your earliest starting point right through to some far off future.
Now, you can LEFT JOIN your statistical data against it - then you'll get nulls for those days with no data. If you really want a zero rather than null, use IFNULL(colname, 0)

A: Thanks to Paul Dixon I found the solution. Anyone interested in how I solved this read on:
First create a stored procedure I found somewhere to populate a table with all dates from this year.

CREATE Table calendar(dt date not null);

CREATE PROCEDURE sp_calendar(IN start_date DATE, IN end_date DATE, OUT result_text TEXT)
  BEGIN
    SET @begin = 'INSERT INTO calendar(dt) VALUES ';
    SET @date = start_date;
    SET @max = SUBDATE(end_date, INTERVAL 1 DAY);
    SET @temp = '';
    REPEAT
      SET @temp = concat(@temp, '(''', @date, '''), ');
      SET @date = ADDDATE(@date, INTERVAL 1 DAY);
      UNTIL @date > @max
    END REPEAT;
    SET @temp = concat(@temp, '(''', @date, ''')');
    SET result_text = concat(@begin, @temp);
  END

   call sp_calendar('2009-01-01', '2010-01-01', @z);

   select @z;

Then change the query to add the left join:

SELECT
    DAY(dt) as RegistrationDate,
    COUNT(ID_Profile) as NumberOfRegistrations
FROM calendar
LEFT JOIN
    tbl_profile ON calendar.dt = tbl_profile.datCreate
WHERE dt  BETWEEN DATE_SUB(CURDATE(),INTERVAL 6 DAY)  AND CURDATE()
GROUP BY RegistrationDate
ORDER BY dt ASC

And we're done.
Thanks all for the quick replies and solution.


text:
Q: Ruby: Encapsulate an operation with Enumerable's inject method I have such an operation to be done for a bunch of array of arrays:
obj = MyObject.new
[[
  #data
 ],
 [
  #data
 ],
 # ...
].inject(obj) do |memo, i|
    memo.foo_method AnotherObject.new(i[0],i[1])
  end

The thing that never changes is an inject's operation itself. What if it could be hidden inside a helper method in a proper way? Something like follows:
def my_helper_method(obj,arr)
  # obj is MyObject's instance,
  # arr - an array from the external array
  inject(obj) do |memo, i|
    memo.foo_method AnotherObject.new(i[0],i[1])
  end
end

[[
  #data
 ],
 [
  #data
 ],
 # ...
].each(&:my_helper_method)

How do I pass both to the helper method: MyObject's instance and an item? Is it ever possible to do when a method is turned to a block?

A: Based on your function definition shared in the question, you should be using something like below.  And, your function should use arr.inject instead of just inject
arr = [[
  #data
 ],
 [
  #data
 ],
 # ...
]

obj = MyObject.new

my_helper_method(obj, arr)

However, if you want to make the code inside the inject block re-usable, you could make use of a Proc as shown below:
block = Proc.new { |memo, i| p "Put your code here...#{memo} #{i}" }

[[
  "s"
 ],
 [
  "p"
 ],
 # ...
].inject(MyObject.new, &block)

If you don't like Proc and want to use the function, you could do something like below:
def f memo, i
    p "put your code here... #{memo} #{i}"
end

[[
  "s"
 ],
 [
  "p"
 ],
 # ...
].inject(MyObject.new, &method(:f))


text:
Q: How to downcast in Unity C# when you need to access specific subclass information on hover? EDIT 2
This is what is being shown in the unity debugger when I look at the list of Items. It is seeing the baseball bat as an Item type, not WeaponItem type.

EDIT 1
This is currently all I have in my ItemsContainer ( my old file has the bloated xml file)
<?xml version="1.0" encoding="utf-8" ?>
<ItemsContainer>
  <Items>
    <!--Weapon Items-->
       <WeaponItem Name = "Baseball Bat" ID="501">
          <!--General Info-->
          <Description>A wooden bat that may have belonged to somone famous</Description>
          <!--Weapon Item-->
          <Damage>4</Damage>
          <Targets>1</Targets>
       </WeaponItem>
   </Items>
</ItemsContainer>

ORIGINAL POST
I'm working on a complex inventory system for a 2D game in Unity.
I read game data with XML serialization and have set up a drag/drop system that works using an Item class. I've also gotten pretty far with a dialogue system that can tell what items are in certain characters inventories.

Issue:
Want to be able to downcast to an item subclass in order to access
  specific data about it on a UI hover (At least that's what I think I
  need to do), or find another solution on how to setup my item database

For eg:

*

*When you hover over a WeaponItem - it shows you damage information + desc

*When you hover over a general Item - it only shows you desc

History:
What I have right now is a very bloated Items.xml file that has all tags necessary, regardless of item category. This is really painful to maintain as I come up with new Items and categories - so I wanted to try inheritance.
At first, my initial approach was:
<ItemsContainer>
   <Items>
      <Item>
          <!-- Generic tags or attributes: ID, Name, Description etc -->
          <!-- Other tags that define the item, is there in every item!-->
      </Item>
   </Items>
</ItemsContainer>

and now it's this:
<ItemsContainer>
   <Items>
      <WeaponItem>
          <!-- Generic tags or attributes: ID, Name, Description etc -->
          <!-- WeaponItem specific tags: Damage, Targets Etc -->
      </WeaponItem>
      <ClothingItem>
          <!-- Generic tags or attributes: ID, Name, Description etc -->
          <!-- ClothingItem specific tags: Exposure, ArmorRating Etc -->
      </ClothingItem>
      .
      .
      .
   </Items>
</ItemsContainer>

My Item class looks like this:
public class Item
{
   [XmlAttribute("Name")]
   public string Name;
   [XmlAttribute("ID")]
   public int ID;
   // General Info
   public string Description;
   public virtual string GetDetails()
   {
      return
        "\nName: " + Name +
        "\nID: " + ID +
        "\nDescription: " + Description;
   }
}

While my subclass WeaponItem looks like this:
class WeaponItem : Item
{
   public int Damage;
   public int Targets;
   public override string GetDetails()
   {
       return
           base.ToString() +
        "\nDamage: " + Damage +
        "\nTargets: " + Targets;
   }
}

Here's what my ItemsContainer looks like:
[XmlRoot("ItemsContainer")]
public class ItemsContainer
{
    [XmlArray("Items"),XmlArrayItem("WeaponItem"), XmlArrayItem("ClothingItem"),...]
    public List<Item> Items = new List<Item>();

    public static ItemsContainer Load(string path)
    {
       TextAsset _xml = Resources.Load<TextAsset>(path);
       XmlSerializer Serializer = new XmlSerializer(typeof(ItemsContainer));
       StringReader reader = new StringReader(_xml.text);
       ItemsContainer items = Serializer.Deserialize(reader) as ItemsContainer;
       reader.Close();
       return items;
    }
}

My ItemUI class contains:

*

*Item variable

*Several public game objects (I have a prefab of the game object this
class is attached to)

*OnDrag, EndDrag, BeginDrag methods

What I want to do in ItemUI - is sort of something like this:
public void HoverOn()
{
    if(Item.Class == "Weapon")
    {
        WeaponItem WeaponItem = (WeaponItem) Item; // Downcast Fail
        Damage.txt = WeaponItem.GetDamage() + "";
        Damage.gameObject.SetVisible(true);
    }
    else if(Item.Class = "Clothing")
    {
        ClothingItem ClothingItem = (ClothingItem) Item; // Downcast Fail
        Exposure.txt = ClothingItem.GetExposure() + "";
        Exposure.gameObject.SetVisible(true);
    }
    ItemInfo.gameObject.SetVisible(true);
}

Question:
With the fact that I want my items in separate categories in XML, how would I accomplish showing Item information based on the subclass of the Item, if all I have at the time of access is a higher level Item class type?

A: You can check the type of the item with the is operator and do the rest as you planned.
if (Item is WeaponItem)
...

Another way of course would be to create a method or property for UI description and override it in to classes. This way you don't need to recode anything in the UI if you add new types.

A: The problem isn't the cast - it's the XML deserialization. The serializer is only creating Item instances, which is why the cast is failing.
You need to change your attributes to tell the serializer which types you want to create:
[XmlArray("Items")]
[XmlArrayItem("WeaponItem", Type = typeof(WeaponItem))]
[XmlArrayItem("ClothingItem", Type = typeof(ClothingItem))]
[...]
public List<Item> Items = new List<Item>();

Note that rather than a series of if statements, you might also want to just switch on Item.Class. (And in C# 7, you'll be able to use pattern matching to switch on the type instead...)


text:
Q: saga fetch data after component rendered hi sorry for my bad english.i am using react and redux.i dispatch getTags action in  layout component.problem is after getData action called,getDataSuccess action called after my components rendered.so my data is null.
how i can be sure that data is fetched and render my components?
layout:
function DashboardLayout({
  children,
  showSideBar,
  backgroundColor,
  getTagsFromServer,
  getCategoriesFromServer,
}) {
  getTagsFromServer();
  getCategoriesFromServer();

  return (
    <StyledDashbordLayout>
      <NavBar />
      <SideBarDrawer />
      <Grid container className="container">
        {showSideBar && (
          <Grid item className="sidebar-section">
            <SideBar />
          </Grid>
        )}
        <Grid item className="content">
          {children}
        </Grid>
      </Grid>
    </StyledDashbordLayout>
  );
}

DashboardLayout.propTypes = {
  children: PropTypes.node.isRequired,
  showSideBar: PropTypes.bool.isRequired,
  backgroundColor: PropTypes.string,
  getTagsFromServer: PropTypes.func,
  getCategoriesFromServer: PropTypes.func,
};

function mapDispatchToProps(dispatch) {
  return {
    dispatch,
    getTagsFromServer: () => dispatch(getTags()),
    getCategoriesFromServer: () => dispatch(getCategories()),
  };
}

const withConnect = connect(
  null,
  mapDispatchToProps,
);

export default compose(withConnect)(DashboardLayout);

saga:
import { call, put, takeLatest } from 'redux-saga/effects';

function* uploadVideo({ file }) {
  try {
    const { data } = yield call(uploadVideoApi, { file });
    yield put(uploadFileSuccess(data));
  } catch (err) {
    yield put(uploadFileFail(err));
  }
}
function* getTags() {
  const { data } = yield call(getTagsApi);
  console.log(data, 'app saga');
  yield put(getTagsSuccess(data));
}
function* getCategories() {
  const { data } = yield call(getTCategoriesApi);
  yield put(getCategoriesSuccess(data));
}
// Individual exports for testing
export default function* appSaga() {
  yield takeLatest(UPLOAD_VIDEO, uploadVideo);
  yield takeLatest(GET_TAGS, getTags);
  yield takeLatest(GET_CATEGORIES, getCategories);
}

this is my select box component which gets null data from store:
import React, { useState } from 'react';
function UploadFileInfo({ tags, categories }) {
  return (
    <Paper square className={classes.paper}>
      <Tabs
        onChange={handleChange}
        aria-label="disabled tabs example"
        classes={{ indicator: classes.indicator, root: classes.root }}
        value={tab}
      >
        <Tab
          label="مشخصات ویدیو"
          classes={{
            selected: classes.selected,
          }}
        />
        <Tab
          label="تنظیمات پیشرفته"
          classes={{
            selected: classes.selected,
          }}
        />
      </Tabs>
      {tab === 0 && (
        <Grid container className={classes.info}>
          <Grid item xs={12} sm={6} className={classes.formControl}>
            <label htmlFor="title" className={classes.label}>
              عنوان ویدیو
            </label>
            <input
              id="title"
              type="text"
              className={classes.input}
              onChange={e => setValue('title', e.target.value)}
              defaultValue={data.title}
            />
          </Grid>
          <Grid item xs={12} sm={6} className={classes.formControl}>
            <SelectBox
              onChange={e => setValue('category', e.target.value)}
              value={data.category}
              label="دسته بندی"
              options={converItems(categories)}
            />
          </Grid>
          <Grid item xs={12} className={classes.textAreaWrapper}>
            <label htmlFor="info" className={classes.label}>
              توضیحات
            </label>
            <TextField
              id="info"
              multiline
              rows={4}
              defaultValue={data.info}
              variant="outlined"
              classes={{ root: classes.textArea }}
              onChange={e => setValue('info', e.target.value)}
            />
          </Grid>
          <Grid item xs={12} sm={6} className={classes.formControl}>
            <SelectBox
              onChange={e => {
                if (e.target.value.length > 5) {
                  console.log('hi');
                  setError(
                    'tags',
                    'تعداد تگ ها نمی تواند بیشتر از پنج عدد باشد',
                  );
                  return;
                }
                setValue('tags', e.target.value);
              }}
              value={data.tags}
              label="تگ ها"
              options={converItems(tags)}
              multiple
              onDelete={id => deleteTagHandler(id)}
              error={errors.tags}
            />
          </Grid>
        </Grid>
      )}
      {tab === 1 && 'دومی'}
      <Dump data={data} />
    </Paper>
  );
}

const mapStateToProps = createStructuredSelector({
  tags: makeSelectTags(),
  categories: makeSelectCategories(),
});

const withConnect = connect(
  mapStateToProps,
  null,
);

export default compose(withConnect)(UploadFileInfo);

A: Use your functions to call the API inside React.useEffect.
All your API calls should be inside the useEffect hook.
For more on useEffect, read this
function DashboardLayout({
  children,
  showSideBar,
  backgroundColor,
  getTagsFromServer,
  getCategoriesFromServer,
}) {

  React.useEffect(() => {
     getTagsFromServer();
     getCategoriesFromServer();
  }, []);

  return (
    <StyledDashbordLayout>
      <NavBar />
      <SideBarDrawer />
      <Grid container className="container">
        {showSideBar && (
          <Grid item className="sidebar-section">
            <SideBar />
          </Grid>
        )}
        <Grid item className="content">
          {children}
        </Grid>
      </Grid>
    </StyledDashbordLayout>
  );
}

A: Question Summary
If I understand your question correctly, you are asking how to guard the passing of options, options={converItems(tags)}, in the SelectBox in UploadFileInfo against null or undefined values when the data hasn't been fetch yet.
Solutions
There are a few options for either guarding against null or undefined values.
Easiest is to provide a default fallback value for tags. Here I am making an assumption the tags are an array, but they can be anything, so please adjust to match your needs.

*

*Inline when passed options={converItems(tags || []) or options={converItems(tags ?? [])

*In the function signature function UploadFileInfo({ tags = [], categories })

*As part of a fallback return value in makeSelectTags
Another common pattern is conditional rendering where null may be the initial redux state value, so you simply wait until it is not null to render your UI.

*

*Early return null if no tags
function UploadFileInfo({ tags, categories }) {
  if (!tags) return null;

  return (
    <Paper square className={classes.paper}>
      ...

*Conditional render SelectBox
{tags ? (
    <SelectBox
      ...
    />
  ) : null
}

Side Note about fetching data calls in DashboardLayout
When you place function invocations directly in the function body they will be invoked any time react decides to "render" the component to do any DOM diffing, etc..., pretty much any time DashboardLayout renders the data fetches are made, which could have unintended effects. For this reason, react functional component bodies are supposed to be pure functions without side effects. Place any data fetching calls in an effect hook that is called only once when the component mounts (or appropriate dependency if it needs to be called under other specific conditions).
useEffect(() => {
  getTagsFromServer();
  getCategoriesFromServer();
}, []);


text:
Q: Pass a promise to a component React Native I'm filling my data array with an API call like so
 const getData = async () => {
    const response = await fetch(
      "URL"
    );
    var data = await response.json();
    let arr = [];
    for (let i = 0; i < data.length; i++) {
      arr.push(data[i]);
    }
    return arr;
  };

How do i pass it to a react Native component, with it being a promise?
return(
 <View style={styles.container}>
      <Swiper
        cards={  getData } //Here
        renderCard={(card) => {
          return (
            <View style={styles.card}>
              <Text style={styles.text}>{card}</Text>
            </View>
          );
        }}

      </Swiper>
);

A: Put the fetch function in a useEffect in the parent component and make arr a state variable
const [arr, setArr] = useState([])
useEffect(()=>{
  const getData = async () => {
      const response = await fetch(
        "URL"
      );
      var data = await response.json();
      setArr(data)
  }
  getData();
},[])
return (
 <View style={styles.container}>
      <Swiper
        cards={arr} //Here
        renderCard={(card) => {
          return (
            <View style={styles.card}>
              <Text style={styles.text}>{card}</Text>
            </View>
          );
        }}
      </Swiper>
  </View>)


text:
Q: IPhone Development - Custom Cel I'm trying to create my own custom cell, but for some reason, it isn't appearing. I read a lot of example, the code looks like (at least for me) equal to others. I used the interface builder to recreate it (I deleted the Default View, add a TableViewCell, put Identifier = CustomCell,  and wire up the Label with valueLabel).
Can comeone help me?
Thanks in advance.
//CustomCell.h
#import <UIKit/UIKit.h>

@interface CustomCell : UITableViewCell {
    IBOutlet UILabel *valueLabel;
}
@property(nonatomic, retain) IBOutlet UILabel *valueLabel;

@end

//CustomCell.C
#import "CustomCell.h"
@implementation CustomCell

@synthesize valueLabel;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) {
        // Initialization code
    }
    return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {

    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)dealloc {
    [super dealloc];
}

@end

//Where I'm trying to use this cell. Here I imported the .h file (#import "CustomCell.h"):

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"CustomCell";

    CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];

        cell = [[[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

    }

    cell.valueLabel.text = @"Any text";

    return cell;
}

A: Your cellForRowAtIndexPath method belongs in the table view controller? Is that where it is located?


text:
Q: Adjust diacritic position in emph mode I use the the additionnal letters ḧ, ĥ, and ḋ. With the CMU font in emph mode.
So, with the following MWE:
\documentclass{article}
\usepackage{fontspec}

\setmainfont{CMU Serif}

\begin{document}

\emph{ḧ ĥ ḋ}

\end{document}

I get this rendering:

But the diacritics seems a little bit   unbalanced, especially when it is followed by other characters with the same diacritic, as you can see bellow:

So, the goal is to horizontally move the diacritics to adjust it according to the following table:

Is it possible to do that?

A: The position of the diacritics can be adjusted using stackinset from the stackengine package. The idea is to define a separate macro for every combination of letter and diacritic. This defeats the purpose of using unicode, but the result is as required.
The arguments of \stackinset are horizontal align of the inserted symbol relative to the base symbol (left, center, right), horizontal offset (positive or negative), vertical align, vertical offset, inserted symbol (called inset), base symbol (called anchor).
MWE:
\documentclass{article}
\usepackage{fontspec}
\usepackage{stackengine}

\setmainfont{CMU Serif}

\begin{document}
\emph{ḧ ĥ ḋ} (default)

\def\huml{\stackinset{c}{-1pt}{t}{-2pt}{\"{}}{h}}
\def\hcar{\stackinset{c}{-1pt}{t}{-2.5pt}{\^{}}{h}}
\def\ddot{\stackinset{c}{2.5pt}{t}{-3.5pt}{$\cdot$}{d}}

\vspace{2mm}

\emph{\huml\ \hcar\ \ddot} (with \texttt{\textbackslash stackinset})

\end{document}

Result:


text:
Q: OutOfMemoryException when creating large ZIP file using System.IO.Packaging I am trying to debug an OutOfMemoryException that occurs when creating a fairly large ZIP file using System.IO.Packaging.ZipPackage.
The code is iterating through a large list of objects, doing the following for each object.

*

*Serializing the object data to a temporary file.

*Creating a PackagePart for the file.

*Copy from a source System.IO.Stream to another:

*

*Source stream: FileStream

*Target stream: PackagePart::GetStream() => MS.Internal.IO.Zip.ZipIOModeEnforcingStream
Finally it calls Package::Close() which saves the file.
The problem I am having is that for a particularly large list of objects, I am seeing an OutOfMemoryException (the x86 process size is getting to about 1.2GB in size).
I was thinking about partitioning the object data into chunks so I only process a smaller amount per loop (i.e. steps 1-3 above).  The idea is that I would create n ZIP files in a temporary directory, and then find a way to combine them into a single archive.
Is this possible using System.IO.Packaging?  What would I use to combine the parts?
Or is there a better way to fix this?

A: Calling the Flush method on the Package object in between creating a new package should probably solve the problem as that would cause the memory buffer to be flushed to disk.

A: I would use the DotNetZip library (http://dotnetzip.codeplex.com/). I've tried several zip libraries (System.IO like you are currently using and also SharpZibLib) and by far the easiest to use is the DotNetZip library.
You'll almost certainly end up with fewer lines of code and I found the memory usage to be very good (had a problem in a virtual machine environment which I reported and a new release fixed it).


text:
Q: Replace XML values in bash in linux I have the following XML data:
<info>
    <data>
        <name>my_image</name>
        <value>site.com/image1.img</value>
    </data>
    <data>
        <name>my_link</name>
        <value>site.com/p_info</value>
    </data>
</info>

I want to replace all the site.com to siteimag.com of every my_image value (just for the my_image attributes).
So the result will be:
<info>
    <data>
        <name>my_image</name>
        <value>siteimag.com/image1.img</value>
    </data>
    <data>
        <name>my_link</name>
        <value>site.com/p_info</value>
    </data>
</info>

How can it be done with sed command?
Thanks.

A: sed '/my_image/{n;s/site.com/siteimag.com/}' file

Brief explanation,

*

*/my_image/: search the line contained "my_image"

*Once the string searched,

*

*read the next line by using the command n.

*s/site.com/siteimag.com/: do the substitution

A: The right way is using xml parsers like xmlstarlet:
xmlstarlet ed -u "//data/name[text()='my_image']/following-sibling::value" \
-v "$(sed 's/site/&imag/' <(xmlstarlet sel -t -v "//data/name[text()='my_image']/following-sibling::value" file.xml))" file.xml

The output:
<?xml version="1.0"?>
<info>
  <data>
    <name>my_image</name>
    <value>siteimag.com/image1.img</value>
  </data>
  <data>
    <name>my_link</name>
    <value>site.com/p_info</value>
  </data>
</info>

A: The same XML document can be written and formatted in many different ways,
so using a simple text tool like sed to update it, would be very fragile and easy to break.
E.g. just adding an empty line between name and value, will break the naïve sed script above:
<data>
    <name>my_image</name>

    <value>site.com/image1.img</value>
</data>

It also can not really follow the XML structure, and will simply replace any site.com reference, if there is a my_image pattern in the line above it, even if it is in a comment:
<data>
    <name>my_link</name> <!-- Used to be "my_image" -->
    <value>site.com/p_info</value>
</data>

There are literally hundreds of other ways, the source XML can be modified, without changing it's meaning, to make it break or result in a false replacements.
To avoid that, you should use an XML-aware tool, to do the replacement, e.g. xmlstarlet:
xmlstarlet ed \
-u "//data/name[text()='my_image']/../value" \
-x "concat(substring-before(.,'site.com'),'sitemag.com',substring-after(.,'site.com'))"|
data.xml


text:
Q: Java - can't change int value inside for-each loop This question looks hilariously obvious, however I can't see my fault...
I'm declaring an int variable inside for-each loop and it looks like I can't modify it.
for(String tmp : list) {
        int i = 0;
        System.out.println("i = " + i);
        i++;
}

List is a LinkedList that is not empty and exists somewhere in the code. The output is:
i = 0
i = 0
i = 0

Is it even possible to modify a value of int inside such loop? Thanks.

A: With each loop, you create a new i variable, one completely unrelated to the previous ones from previous iterations of the loop. Solution: declare it above the loop.
int i = 0;
for(String tmp : list) {
        System.out.println("i = " + i);
        i++;
}

A: You need to move the declaration of int i = 0 outside the for loop. Currently you are just initializing an int i to 0 every iteration.

A: You can edit it, but the variable is discarded after the closing bracket.

A: It should be outside the for loop
int i = 0;
for(String tmp : list) {
    System.out.println("i = " + i);
    i++;
}


text:
Q: Several UIAlertViews for a delegate Currently I've got a class popping up UIAlertViews here and there. Currently, the same class is the delegate for these (it's very logical that it would be). Unfortunately, these UIAlertViews will call the same delegate methods of the class. Now, the question is - how do you know from which alert view a delegate method is invoked? I was thinking of just checking the title of the alert view, but that isn't so elegant. What's the most elegant way to handle several UIAlertViews?

A: FYI, if you want to target just iOS 4 users (which is reasonable now that ~98.5% of clients have at least iOS 4 installed), you should be able to use Blocks to do really nice inline handling of UIAlertViews.
Here's a Stackoverflow question explaining it:
Block for UIAlertViewDelegate
I tried using Zachary Waldowski's BlocksKit framework for this.  His UIAlertView(BlocksKit) API reference looked really good.  However, I tried to follow his instructions to import the BlocksKit framework into my project, but unfortunately I couldn't get it to work.
So, as Can Berk Güder suggests, I've used UIAlertView tags for now.  But at some point in future I'm going to try to move to using Blocks (preferably one which supports ARC out of the box)!

A: easier & newer
UIAlertView *alert = [[UIAlertView alloc] init...
alert.tag = 1;

UIAlertView *alert = [[UIAlertView alloc] init...
alert.tag = 2;

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if(alertView.tag == 1) {
        // first alert...
    } else  {
        // sec alert...
    }
}

all done!

A: Tag the UIAlertViews like this:
#define kAlertViewOne 1
#define kAlertViewTwo 2

UIAlertView *alertView1 = [[UIAlertView alloc] init...
alertView1.tag = kAlertViewOne;

UIAlertView *alertView2 = [[UIAlertView alloc] init...
alertView2.tag = kAlertViewTwo;

and then differentiate between them in the delegate methods using these tags:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if(alertView.tag == kAlertViewOne) {
        // ...
    } else if(alertView.tag == kAlertViewTwo) {
        // ...
    }
}

A: You can overcome this whole ordeal and prevent yourself from using tags by enhancing UIAlertView to use block callbacks. Check out this blog post I wrote on the subject.

A: I've always thought using tags is a bit of a hack. If you do use them, at least set some defined constants for the tag numbers.
Instead, I use properties like this:
In the interface section:
@property (nonatomic, weak) UIAlertView *overDueAlertView;
@property (nonatomic, weak) UIAlertView *retryPromptAlertView;

Creating the alert view:
UIAlertView *alert = [[UIAlertView alloc] init...
self.overDueAlertView = alert;
[alert show];

Delegate method:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
  if (alertView == self.overDueAlertView) {
    // Overdue alert
  } else if (alertView == self.retryPromptAlertView) {
    // Retry alert
  }


text:
Q: About script execution permissions on Linux shell I've just created a script, let's say, "helloworld.sh".
The script doesn't yet have execution permissons: -rw-rw-r--
If I try to execute that script with: "./helloword.sh", I'll get an error message, as expected. But, if I try to execute that same script as: . helloword, it will execute with no problems.
How? Why does that happen?

A: This happens because on Linux the "." (dot) alone is a built-in command that execute the script within your current session with your current shell. This is the same as calling the script with source command (the BSD default method). It's almost the same than execute with bash helloworld.sh.
When you call the script with ./helloworld.sh or /root/helloworld.sh the shell will try to figure out how to execute it, if the file is a binary, it will simply run, if it is a script, the shell will read the first line looking for the interpreter. To do this, you'll need execution permission.
To simplify:

*

*One is a command;

*The other one is a path.

You can even run:
. --help

About . against bash:
This is why we use . or source to load variables from a file in our session, for example, when we change ~/.bashrc and reload it without login again.
You can see this happens when you execute:
. /etc/os-release

All variables defined inside this file will be loaded and available in your current shell session.
The same will not happen if you execute:
bash /etc/os-release

Because you opened a "new session" inside that bash that you called, the new bash executes and close, cleaning the session.
The same process happen if you give execute permission +x to the script, because when you call the script with ./ or something like that, a new session will be created too.


text:
Q: Typegoose - pass arbitrary JSON objects to array I have a Typegoose model (simplified)
export class SurveyClass extends BaseClass {
  @prop({ required: true, default: '' })
  public description!: string;

  @prop({ required: true, default: [] })
  public questions!: Array<any>;
}

The "questions" array is intended to receive chunks of JSON, for example:
{
  id: "1869050556234435",
  type: "feedback",
  data: "the feedback data"
  i18n: {
    fr: {
      data: "le feedback data"
    }
  }
}

...because the kind and number of these chunks are arbitrary, and many are more deeply nested, I've tried to use Array<any>
This works, but if I pass in data like this:
{
  id: "1869050556234435",
  type: "feedback",
  data: "the feedback data"
  i18n: {}
  }
}

... then the "i18n" key and value is never set in the database. Those fields are "ignored" (though the others are saved.)
I have a few questions associated with this:

*

*Could this be a bug with Typegoose? (ie: should this work?)

*If I'm "doing this wrong", is somehow possible to configure this array field to receive arbitrarily nested objects the way I have described? Or would I need to save it as a string (ie: JSON.stringify) to save truly arbitrary object data?

*If this can't be done, and the right approach is to build types to save such nested objects into an array, how should this be done? (Hoping for examples both of the type definition and the use of it in the model.)

A: By default mongoose removes properties that it considers "empty" before insertion.
If the default "empty" behavior is not wanted:

*

*for objects it can be disabled with the schema option minimize.

*for arrays, the default is by default [] and will also store it this way.

*for other types like a String, set required: true to disallow empty strings.

Also the the class in the question is not properly formed and requires option type to be set.
See Quick-Start-Guide Caution Note:

type has to be defined when working with Arrays, because Reflection only returns basic information. Look here for why
Like public: string[] is in reflection only Array.

Note: i am not sure if the schema option minimize will apply to nested schemas (all nested classes in typegoose are nested Schemas)


text:
Q: Todo-list using useReducer and MongoDB - updating DB after Action of Reducer? I tried connecting my Todolist with MongoDB to store my data.
Since it is not recommended to fetch and update data within the reducer I'm a little confused on where to update the DB.
My thoughts are whenever I change the List with an Action, I would need to Replace the whole list on the DB, which doesnt seem efficient to me.
But when i only update only the changed element in the DB i dont see a reason to use useReducer.
Can someone help me how i should continue? :/
(This Todolist was using useStates and MongoDB before I tried exercising on useReducer, that's why the Routes and APIhelper include other functions)
App.js:
import React, { useState, useEffect, useReducer } from "react";
import APIHelper from "./APIHelper.js";
import Todo from "./components/Todo";
import "./index.css";

export const ACTIONS = {
  ADD_TODO: "add-todo",
  TOGGLE_TODO: "toggle-todo",
  DELETE_TODO: "delete-todo",
  SET_TODO: "set-todos",
};

const reducer = (state, action) => {
  switch (action.type) {
    case ACTIONS.SET_TODOS: {
      return Object.assign({}, state.todos, {
        todos: action.payload.todos,
      });
    }

    case ACTIONS.ADD_TODO:
      return [...state.todos, newTodo(action.payload.task)];

    case ACTIONS.TOGGLE_TODO:
      return state.todos.map((todo) => {
        if (todo._id === action.payload.id) {
          return { ...todo, completed: !todo.completed };
        }
        return todo;
      });

    case ACTIONS.DELETE_TODO:
      return state.todos.filter((todo) => todo._id !== action.payload.id);
    default:
      return state.todos;
  }
};

const newTodo = (task) => {
  return { _id: Date.now(), task: task, completed: false };
};

export const setTodos = (todos) => {
  return {
    type: ACTIONS.SET_TODOS,
    payload: {
      todos,
    },
  };
};

const App = () => {
  const initialState = {
    todos: [],
  };

  const [state, dispatch] = useReducer(reducer, initialState);
  const [task, setTask] = useState("");

  useEffect(async () => {
    const fetchTodoAndSetTodo = async () => {
      const todos = await APIHelper.getAllTodos();
      return todos;
    };
    const todos = await fetchTodoAndSetTodo();
    //console.log(todos);
    dispatch(setTodos(todos));
  }, []);

  const handleSubmit = (e) => {
    e.preventDefault();
    dispatch({ type: ACTIONS.ADD_TODO, payload: { task: task } });
    setTask("");
  };

  return (

      {console.log(state.todos)}
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          value={task}
          onChange={(e) => setTask(e.target.value)}
        />
      </form>
      {state.todos &&
        state.todos.map((todos) => {
          return <Todo key={todos._id} todo={todos} dispatch={dispatch} />;
        })}
        {//APIHelper.updateTodo(state.todos)}

  );
};

export default App;

Todo.js:
import React from "react";
import { ACTIONS } from "../App";

const Todo = ({ todo, dispatch }) => {
  return (

        {todo.task}

      <button
        onClick={() =>
          dispatch({ type: ACTIONS.TOGGLE_TODO, payload: { id: todo.id } })
        }
      >
        Toggle
      </button>
      <button
        onClick={() =>
          dispatch({ type: ACTIONS.DELETE_TODO, payload: { id: todo.id } })
        }
      >
        Delete
      </button>

  );
};

export default Todo;

APIHelper.js:
import axios from "axios";

const API_URL = "http://localhost:8080/todos/";

const createTodo = async (task) => {
  const { data: newTodo } = await axios.post(API_URL, {
    task,
  });
  return newTodo;
};

const deleteTodo = async (id) => {
  const message = await axios.delete(`${API_URL}${id}`);
  return message;
};

const updateTodo = async (payload) => {
  const { data: newTodo } = await axios.put(`${API_URL}`, payload);
  return newTodo;
};

const getAllTodos = async () => {
  const { data: todos } = await axios.get(API_URL);
  return todos;
};

export default { createTodo, deleteTodo, updateTodo, getAllTodos };

routes.js:
const db = require("./db.js");

const routes = express.Router();

const success = (res, payload) => {
  return res.status(200).json(payload);
};

routes.get("/", async (req, res, next) => {
  try {
    const todos = await db.Todo.find({}, "_id task completed");
    return success(res, todos);
  } catch (err) {
    next({ status: 400, message: "failed to get todos" });
  }
});

routes.post("/", async (req, res, next) => {
  try {
    const todo = await db.Todo.create(req.body);
    return success(res, todo);
  } catch (err) {
    next({ status: 400, message: "failes to create todo" });
  }
});

routes.put("/", async (req, res, next) => {
  try {
    const todo = await db.Todo.findByIdAndUpdate(req.params.id, req.body, {
      new: true,
    });
    return success(res, todo);
  } catch (err) {
    next({ status: 400, message: "failed to update todo" });
  }
});

routes.delete("/:id", async (req, res, next) => {
  try {
    await db.Todo.findByIdAndRemove(req.params.id);
    return success(res, "todo deleted");
  } catch (err) {
    next({ status: 400, message: "failed to delete todo" });
  }
});

routes.use((err, req, res, next) => {
  return res.status(err.status || 400).json({
    status: err.status || 400,
    message: err.message || "there was an error processing request",
  });
});

module.exports = routes;
```


text:
Q: Harmonic Differential forms with respect to different metrics For a closed Riemannian Manifold with two metrics $g$ and $h$, the harmonic k-forms decompose into
$$\Omega^k=\mathcal{H_g}+d^*_g(\Omega^{k+1})+d(\Omega^{k-1})$$
And
$$\Omega^k=\mathcal{H_h}+d^*_h(\Omega^{k+1})+d(\Omega^{k-1})$$
My question is, wether (it should certainly be true) there is, and how to explicitly find an isomorphism between these subspaces. There is a related question wether the projection would do – But I would need explicit dependence on the metric for my purposes. My attempt doesn't go futher then the observation that: $$\omega\in\mathcal{H}_g\implies d^*_h(*_h*_g\omega)=0$$ But I cannot prove and am not sure wether also $d(*_h*_g\omega)=0$, which would imply that $\omega\in\mathcal{H}$.


text:
Q: is there a algorithmic problem that can cause code in python don't give us specific outpu? I am writing a program that takes n number of input in any kind of integer or float. I wanted to make  this program a calculator with n number of input in any kind (int/float)
but I think for some algorithmic reason in writing code,
I can't give integer to the program after it find out it's int.
print("start")
b=int(input("The number of numbers in operations: "))
for a in range (b):
  c=input("choose format of numbers integer or float?")
if c=="integer":
  int(input("integer number:"))
elif c=="float":
  float(input("float number :"))

A: I think your problem is with indentation your code should be indented like this:
print("start")
b=int(input("The number of numbers in operations: "))
for a in range (b):
  c=input("choose format of numbers integer or float?")
  if c=="integer":
     int(input("integer number:"))
  elif c=="float":
     float(input("float number :"))

the if - elif statement should be at the same indentation level as the for loop


text:
Q: How to use formula field in Javascript button Can we use formula field in javascript button? im getting an error "Incorrect parameter type for function 'or()'. Expected Boolean, received Text".
Account_Inactive__c is formula field on contact object which returns "Active" or "Inactive" if the checkbox on account field is checked and viceversa
if( {!or(Account.Inactive_del__c, false)} ) {
    alert('You cannot create a new opp for an Inactive account.');
}
else if( {!or(Contact.Inactive__c,false)} ) {
    alert('You cannot create a new opp for an Inactive contact.');
}
else if( {!or(Contact.Account_Inactive__c,active)} ) {
    alert('You cannot create a new opp for an Inactive contact.');
}
else
{
    window.top.location.href = "{!URLFOR($Action.Opportunity.New, null, ["retURL"="/"&NULLVALUE(Contact.Id, Account.Id), "00N40000002Gafd"=Account.Location__c, "opp3"=Account.Name&" "&"-","opp4_lkid"=Account.Id,"conid"=Contact.Id], true)}";
}

A: The word "active" should be "false", just the same as the previous two entries. OR always takes Boolean values, true or false, or fields that are checkboxes, or comparisons (<, >, !=, =, <>, etc) that compare to true or false.


text:
Q: React Router 4 Warning: "tried to redirect to the same route you're currently on" I can't seem to find a way of making this warning go away.
When the application first loads, the URL only receives the "#/" from hash router, so I've added the conditional <Redirect /> so that the user gets redirected to the first tab, but this throws the warning message tried to redirect to the same route you're currently on.
Does anyone know how to fix this warning?
<HashRouter>

      { tabs }

  { routes }
  {
      (location.hash == '' || location.hash == '#/') &&
      <Redirect to={'/' + tabs[0].name} />
  }

</HashRouter>

Having the <Redirect /> before or after { routes } seems to have no effect.

A: Just needed to wrap the Routes with a  <Switch /> component that comes with React Router. No more warning.
<HashRouter>

      { tabs }

  <Switch>
    { routes }
    <Redirect to={'/' + tabs[0].name} />
  </Switch>

</HashRouter>


text:
Q: Want to alert on html from code of .gs file I have a Google Sheet, wep app - form and want to check the duplicate of input data.
If it's duplication, pop up alert on html page before sending data to Google Sheet.
But, alert() from [.gs file of Google Apps Script] seems doesn't work.
I want to alert when [if (position >-1) ] is true.
What am I missing? help me...
function addItem(userInfo) {
  var ss = SpreadsheetApp.openByUrl(url);
  var ws = ss.getSheetByName('Sheet1');

  var data = ws.getRange(2, 4, ws.getLastRow(), 1).getValues();
  var codeList = data.map(function(r) {
    return r[0].toString();
  });
  var position = codeList.indexOf(userInfo.studentname); //the code that user input is a number

  if (position > -1) {
    var m1 = userInfo.studentname;

    sendTelegram('"' + m1 + 'no' + '"');

    return true;
  } else {
    ws.appendRow([
      userInfo.bzpatteacher,
      userInfo.bzperiod,
      userInfo.seatnum,
      userInfo.studentname,
      userInfo.reginm,
      new Date(),
    ]);
    return false;
  }
}

A: codeList.indexOf(userInfo.studentname); //the code that user input is a number

If userInfo.studentname is of Number type, then strict checking by indexOf will fail as codeList is a array of String types.
Try
var position = codeList.indexOf(userInfo.studentname.toString());


text:
Q: Escaping backslash when adding file path to local storage ? I want to save a file path in local storage of chrome, but the js API escape the "\" character then I can't retrieve the file again. any suggestion to prevent escaping backslash when adding a file path to local storage?

A: It doesn't escape the backslash, here's a snippet from chrome's JS console session:
>>> localStorage["test"] = "C:\\test";
"C:\test"
>>> localStorage["test"]
"C:\test"

Try posting a testcase (for example using http://jsfiddle.net/) that demonstrates the problem -- a testcase is worth a thousand words.


text:
Q: Is there a VB 6 to VB.net conversion guide? While I used to VB 6 like the back of my hand, it has been a very long time I have never attempted to convert a large project. Are their any guides to help me along the process?

A: There is Dan Appleman's Moving to VB .NET
Also:

*

*10 Things to Avoid When Moving From VB6 to VB.NET

*Microsoft Visual Basic 6.0 Migration Resource Center (an excellent resource)

*Moving from VB6 to VB.NET (Windows Forms)
These 2 tools can be useful in conversions:

*

*Code Advisor for Visual Basic 6.0

*Visual Basic 6.0 to Visual Basic .NET Upgrade Assessment Tool

A: At this http://migrationguide.artinsoft.com/ you will find a good guide, as a matter of fact is a whole book addressing a lot of issues of VB6 migration.
You can also look at the blogs in artinsoft which provide good information and also there is a tool by this company that you can download from MSDN.


text:
Q: How do I choose which parts of the json file to include in the dataframe I have this json right here, I want to create a DF using id as one column, and the fields as the other columns, but not the whole fields, I want a column for message, a column for result, how do I achieve this?
[{'id': 'rec6cGAtjL8lmoBgT', 'createdTime': '2022-10-11T22:54:23.000Z', 'fields': {'result': 3, 'message': "Today was meh, but I got a good bit of work done, so it's fine", 'isitweird': True}}, {'id': 'recG1bde9NYyWs9Gm', 'createdTime': '2022-10-12T08:30:20.000Z', 'fields': {'message': "Today was meh, but I got a good bit of work done, so it's fine", 'result': 3, 'isitweird': True}}, {'id': 'rectKvuz20jYYQ7OC', 'createdTime': '2022-10-11T16:39:26.000Z', 'fields': {'result': 5, 'message': 'I am very happy today, it was awesome', 'isitweird': True}}, {'id': 'rectQfHPJZbdDtIpW', 'createdTime': '2022-10-11T22:54:34.000Z', 'fields': {'result': 3, 'message': "Today was meh, but I got a good bit of work done, so it's fine", 'isitweird': True}}, {'id': 'recxbt94M70AjBQS7', 'createdTime': '2022-10-11T22:52:42.000Z', 'fields': {'result': 3, 'message': "Today was meh, but I got a good bit of work done, so it's fine", 'isitweird': True}}, {'id': 'recy1DjwMNOIfuWa6', 'createdTime': '2022-10-11T22:53:56.000Z', 'fields': {'result': 3, 'message': "Today was meh, but I got a good bit of work done, so it's fine", 'isitweird': True}}]

A: You can create a new list of dicts using flatter function and map function:
Input:
json_input = [{'id': 'rec6cGAtjL8lmoBgT', 'createdTime': '2022-10-11T22:54:23.000Z', 'fields': {'result': 3, 'message': "Today was meh, but I got a good bit of work done, so it's fine", 'isitweird': True}}, {'id': 'recG1bde9NYyWs9Gm', 'createdTime': '2022-10-12T08:30:20.000Z', 'fields': {'message': "Today was meh, but I got a good bit of work done, so it's fine", 'result': 3, 'isitweird': True}}, {'id': 'rectKvuz20jYYQ7OC', 'createdTime': '2022-10-11T16:39:26.000Z', 'fields': {'result': 5, 'message': 'I am very happy today, it was awesome', 'isitweird': True}}, {'id': 'rectQfHPJZbdDtIpW', 'createdTime': '2022-10-11T22:54:34.000Z', 'fields': {'result': 3, 'message': "Today was meh, but I got a good bit of work done, so it's fine", 'isitweird': True}}, {'id': 'recxbt94M70AjBQS7', 'createdTime': '2022-10-11T22:52:42.000Z', 'fields': {'result': 3, 'message': "Today was meh, but I got a good bit of work done, so it's fine", 'isitweird': True}}, {'id': 'recy1DjwMNOIfuWa6', 'createdTime': '2022-10-11T22:53:56.000Z', 'fields': {'result': 3, 'message': "Today was meh, but I got a good bit of work done, so it's fine", 'isitweird': True}}]

Script:
def flatter(data_row):
    return {'id': data_row['id'], 'result': data_row['fields']['result'], 'message': data_row['fields']['message']}

pd.DataFrame(map(flatter, json_input))

Output:
    id  result  message
0   rec6cGAtjL8lmoBgT   3   Today was meh, but I got a good bit of work do...
1   recG1bde9NYyWs9Gm   3   Today was meh, but I got a good bit of work do...
2   rectKvuz20jYYQ7OC   5   I am very happy today, it was awesome
3   rectQfHPJZbdDtIpW   3   Today was meh, but I got a good bit of work do...
4   recxbt94M70AjBQS7   3   Today was meh, but I got a good bit of work do...
5   recy1DjwMNOIfuWa6   3   Today was meh, but I got a good bit of work do...

Another option is to create a DataFrame and then to apply some functions:
df = pd.DataFrame(json_input)
df['message'] = df['fields'].str['message']
df['result'] = df['fields'].str['result']
df = df.drop(columns=['createdTime', 'fields'])
df

Output:
id  message result
0   rec6cGAtjL8lmoBgT   Today was meh, but I got a good bit of work do...   3
1   recG1bde9NYyWs9Gm   Today was meh, but I got a good bit of work do...   3
2   rectKvuz20jYYQ7OC   I am very happy today, it was awesome   5
3   rectQfHPJZbdDtIpW   Today was meh, but I got a good bit of work do...   3
4   recxbt94M70AjBQS7   Today was meh, but I got a good bit of work do...   3
5   recy1DjwMNOIfuWa6   Today was meh, but I got a good bit of work do...   3


text:
Q: Top category missing from ordinal classifier I am trying to implement an ordinal classifier based on the sources below:

*

*original source: Simple Trick to Train an Ordinal Regression with any Classifier

*updated coding: How to use ordinal classifier?
In my training dataset, I have 5 categories (usefulness level 1 - level 5). However, I only end up with level 1- level 4 usefulness in the prediction for the test dataset using the code above (the answer in How to use ordinal classifier?). I have enough samples in both training (n=1,000) and test (n=15,000) datasets.
from sklearn.base import clone
import numpy as np

# Source:
# 1. https://stackoverflow.com/questions/66486947/how-to-use-ordinal-classifier
# 2. https://towardsdatascience.com/simple-trick-to-train-an-ordinal-regression-with-any-classifier-6911183d2a3c

class OrdinalClassifier():

    def __init__(self, clf):
    self.clf = clf
    self.clfs = {}

def fit(self, X, y):
    self.unique_class = np.sort(np.unique(y))
    if self.unique_class.shape[0] > 2:
        for i in range(self.unique_class.shape[0] - 1):
            # for each k - 1 ordinal value we fit a binary classification problem
            binary_y = (y > self.unique_class[i]).astype(np.uint8)
            clf = clone(self.clf)
            clf.fit(X, binary_y)
            self.clfs[i] = clf

def predict_proba(self, X):
    clfs_predict = {k: v.predict_proba(X) for k, v in self.clfs.items()}
    predicted = []
    for i, y in enumerate(self.unique_class):
        if i == 0:
            # V1 = 1 - Pr(y > V1)
            predicted.append(1 - clfs_predict[i][:, 1])
        elif y in clfs_predict:
            # Vi = Pr(y > Vi-1) - Pr(y > Vi)
            predicted.append(clfs_predict[i - 1][:, 1] - clfs_predict[i][:, 1])
        else:
            # Vk = Pr(y > Vk-1)
            predicted.append(clfs_predict[i - 1][:, 1])
    return np.vstack(predicted).T

def predict(self, X):
    return self.unique_class[np.argmax(self.predict_proba(X), axis=1)]

knn = KNeighborsClassifier()
oc = OrdinalClassifier(knn)
oc.fit(X_train, y_train)
oc.predict(X_test)

Stats for each class in the training dataset and the three prediction models


text:
Q: iOS user registration/authentication without signup (using Parse / Swift) I'd like to create a user in Parse without asking the user to sign up. It is for a chat app built for iOS in Swift. I've heard that UDID is deprecated so cannot use that to uniquely identify user. I want to identify the user even if he/she reinstalls the app / changes device. I don't necessarily want to know any info on the user (email/mobile/etc), just to authenticate them and identify them with an account.

A: What about using Login in Anonymously? and then after login, save the objectId of PFUser in Keychain. Before logging in check first for keychain if it has an objectId and use it to get the PFUser. Saving data in keychain will remain even if you uninstalled the app
PFAnonymousUtils.logInWithBlock {
(user: PFUser?, error: NSError?) -> Void in
 if error != nil || user == nil {
  println("Anonymous login failed.")
 } else {
   println("Anonymous user logged in.")
 }
}


text:
Q: Loading properties and injecting to final variables - Java I want to load property values to a constants class.I can do that by injecting the value in class constructor or static initialization like the following.
public class MyConstants {
    public final String CONSTANT;

    Myconstants() {
        //read property and set to this.CONSTANT
    }
}

Above initialization works fine. But problem arises when I have to use the CONSTANT in a switch case statement. It will give me error because CONSTANT at that point is not constant but blank final field.
Is there any way I can read properties file and put value to CONSTANT so that no compilation error exist? [Like loading properties and setting at compile time itself]. I am using spring and is there any Spring or java workaround for this use case. My intention is to not build for each time a constant change. Also How would you approach to this use case?
Thanks

A: the strings in switch statements are 'hardcoded'. It is literally impossible to make a switch/case statement in java whose 'case' elements are not locked in at compile time. If you want to load those string 'constants' in during app initialization from a properties file, they aren't constant.
Or at least, as far as the needs of java's string-based switch/case is concerned, not constant
Instead, use a java.util.Map of some sort (that maps string values onto runnables or whatnot representing what you're now putting in case blocks), or a bunch of if/else-if statements.
EDIT: How to use a Map to do this.
@FunctionalInterface
public interface CommandProcessor {
    String apply(String cmd);
}

public class CommandHandler {
    private Map<String, CommandProcessor> processors = Map.of(
        "hello", cmd -> "Hello, " + cmd,
        "time", cmd -> "It is " + System.currentTimeMillis() + " past 1970.",
        "capitalize", String::toUpperCase);

    public static void main(String[] args) throws Exception {
        Scanner s = new Scanner(System.in);
        s.useDelimiter("\r?\n");
        CommandProcessor unknownCommand =
            cmd -> "Known commands: " + processors.keySet();

        while (true) {
            String line = s.next();
            String[] parts = line.split("\\s+", 2);
            var processor = processors.getOrDefault(parts[0], unknownCommand);
            String answer = processor.apply(parts.length > 1 ? parts[1] : "");
            System.out.println(answer);
        }
    }
}

A: Usually a property file consists of 'key=value' pairs which can be loaded at runtime. Environment variables may be used similarly. In general, the constant is the key and the value is used to impact application logic. As long as the key is unchanged, the property value can be changed as needed without any need to recompile and the range of possible values can be used in a switch statement. Ex:
    public static void main(String[] args)
    {
        AppConfigParam<Type1> type1   = new AppConfigParam<>("Param1", Type1::valueOf);
        AppConfigParam<Integer> type2 = new AppConfigParam<>("Param2", Integer::parseInt);
        switch(type1.value().orElseThrow(() -> new IllegalStateException("Missing type"))) { case A: break; }
        switch(type2.value().orElseThrow(() -> new IllegalStateException("Missing type"))) { case 1: break; }
    }

    public enum Type1{ A, B, C }

    private static final class AppConfigParam<T>
    {
        private final String constant;
        private final Function<? super String, T> resolver;
        AppConfigParam(String constant, Function<? super String, T> resolver){ this.constant = constant; this.resolver = resolver; }
        public Optional<T> value(){ return Optional.ofNullable(PARAMS.get(constant)).map(resolver); }
        private static final Map<String, String> PARAMS = System.getenv();
    }

While it will not be possible to dynamically set constants, it may be possible to use dynamic constants in switch statements by having a 2 phase build process.

*

*Read properties and generate constant classes.

*Compile rest of project.


text:
Q: Spark dataframe filter both nulls and spaces I have a spark dataframe for which I need to filter nulls and spaces for a particular column.
Lets say dataframe has two columns. col2 has both nulls and also blanks.
col1   col2
1      abc
2      null
3      null
4
5      def

I want to apply a filter out the records which have col2 as nulls or blanks.
Can any one please help on this.
Version:
Spark1.6.2
Scala 2.10

A: The standard logical operators are defined on Spark Columns:
scala> val myDF = Seq((1, "abc"),(2,null),(3,null),(4, ""),(5,"def")).toDF("col1", "col2")
myDF: org.apache.spark.sql.DataFrame = [col1: int, col2: string]

scala> myDF.show
+----+----+
|col1|col2|
+----+----+
|   1| abc|
|   2|null|
|   3|null|
|   4|    |
|   5| def|
+----+----+

scala> myDF.filter(($"col2" =!= "") && ($"col2".isNotNull)).show
+----+----+
|col1|col2|
+----+----+
|   1| abc|
|   5| def|
+----+----+

Note: depending on your Spark version you will need !== or =!= (the latter is the more current option).
If you had n conditions to be met I would probably use a list to reduce the boolean columns together:
val conds = List(myDF("a").contains("x"), myDF("b") =!= "y", myDF("c") > 2)

val filtered = myDF.filter(conds.reduce(_&&_))


text:
Q: Created Docker Container process not getting listed Created Docker container process is not showing using command docker ps --all
I have created only one Dockerfile in a directory, and which is a single available file inside the directory.
the Dockerfile contains following lines:
# Use an existing docker image as a base
FROM alpine

# Download and install a dependency
RUN apk add --update redis

# Tell the image what to do when it starts
# as a container
CMD ["redis-server"]

and after saving the file with name "Dockerfile" and without any extension, I am simply executing the command to build using docker build .
and the logs are as follows:
Sending build context to Docker daemon  2.048kB
Step 1/3 : FROM alpine
 ---> a24bb4013296
Step 2/3 : RUN apk add --update redis
 ---> Using cache
 ---> 218559ae3e9b
Step 3/3 : CMD ["redis-server"]
 ---> Using cache
 ---> fc607b62e266
Successfully built fc607b62e266
SECURITY WARNING: You are building a Docker image from Windows against a non-Windows Docker host. All files and directories added to build context will have '-rwxr-xr-x' permissions. It is recommended to double check and reset permissions for sensitive files and directories.

so, as above you can see the container image process is getting built successfully, but still the container not getting displayed using docker ps --all command.
Well I am using Windows 10 x64 OS & with assurance that no antivirus or firewall is blocker this docker. Am I missing something or making any mistake here?

A: docker ps works like the unix command ps.  It doesn't show all the docker images that could be run.  It only shows the docker containers that are running (or with -a, have been run).
You've built a docker image but you haven't yet run it with docker run.
Try docker run --rm -it fc607b62e266 and if you have everything et up right, it should start up your redis server.  (--rm removes the container when it stops running, generally a good practice unless you want it to persist).
You'll see your new image - not container because it hasn't been instantiated yet - in the output of docker images.  Add a -t flag to give a tag to your docker build  command and you'll see it under that name, otherwise, you can always use the image ref.
A container will only run while it's underlying "root process" is running.     When running a service like redis-server, this means the container will run until signaled (docker service restart, system restrart, or docker kill).
While it is running, more processes can be executed within the container with docker exec.  Each of these is a separate process, but all will be terminated when the "root process" ends.  The converse, of course, is not true - ending the execed process doesn't affect the "root process".


text:
Q: Add dynamic number of columns in grid according to query in BIRT i have a query which designs dynamic number of columns from a table having data.
now i need to add grid with dynamic number of columns according to query.
select fruit,count(*) from mytable group by fruit;
i am getting how to add it manually but at runtime i may be having  different number of columns. so what procedure i need to do for adding columns to grid dynamically in BIRT report

A: You can extend or modify your report template at runtime in, for instance, a custom EventHandler for the Report.beforeFactory() event. The handler can be implemented either in Java or in JavaScript. BIRT has Design Engine API. There is a plug-in, that could be helpful. Even if you cannot use it as it is, it provides examples of how to use BIRT Design Engine API. Using Design Enigine API you can also create new template from scratch at runtime.

A: Alternatively you can use Crosstab and have fruits as a Dimension and COUNT(*) as a Measure. It will add a column for each fruit, but it might be an overkill for your example.


text:
Q: Add namespace prefix to only root elements? I have a XSD from which I generate my Java classes using xjc.
XSD:
<xs:schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://example.com/xml/protocols"
    xmlns:abc="http://example.com/xml/protocols" elementFormDefault="unqualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">

    <xs:element name="student">
        <xs:complexType>
            <xs:complexContent>
                <!-- Inherit common attributes from Regular Type -->
                <xs:extension base="abc:regular">
                    <xs:sequence>
                        <!-- Resource Specific Attributes -->
                        <xs:element name="name" type="abc:name" minOccurs="0" />
                        <xs:element name="URI" type="abc:listOfURIs" />

                        <xs:element name="content" type="abc:content" />

            </xs:complexContent>
        </xs:complexType>
    </xs:element>

Student.java:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "eventNotificationCriteria",
    "notificationURI",
    "notificationContentType"
})
@XmlRootElement(name = "student")
public class Student
    extends Regular
{

    protected Name name;
    @XmlList
    @XmlElement(required = true)
    protected List<String> URI;

    @XmlElement(required = true)
    protected BigInteger content;
.........
}

package-info.java
@XmlSchema(
    elementFormDefault=XmlNsForm.QUALIFIED,
    xmlns={@XmlNs(prefix="abc",
                  namespaceURI="http://example.com/xml/protocols")}
)
package package.com;
import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;

I marshall this object to get:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<abc:student xmlns:abc="http://www.example.com/xml/protocols">
    <name>
        <firstname>Jack</firstname>
    </name
    <URI>http://192.168.100.213:8090/S0</URI>
    <content>1</content>
</abc:student>

Here I want only my root elements to have abc prefix (abc:student).
I marshal like:
  marshaller.marshal(new JAXBElement<Student>(new QName("http://example.com/xml/protocols", "student", "abc"), Student.class, (Student)object), outputStream);

So I add abc prefix to my element.
However when I unmarshall I get exception:
javax.xml.bind.UnmarshalException: unexpected element (uri:"http://www.example.com/xml/protocols", local:"student"). Expected elements are <{}student>
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:647)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:243)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:238)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportUnexpectedChildElement(Loader.java:105)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext$DefaultRootLoader.childElement(UnmarshallingContext.java:1048)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext._startElement(UnmarshallingContext.java:483)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.startElement(UnmarshallingContext.java:465)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.SAXConnector.startElement(SAXConnector.java:135)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:506)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:376)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(XMLNSDocumentScannerImpl.java:602)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3116)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:880)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:606)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:116)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:846)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:775)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:123)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1210)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:628)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:203)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:175)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:157)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:214)

I know this exception is getting thrown as it's expecting an element without abc prefix (abc:student).
So if I add namespace inside @XmlRootElement like:
    @XmlRootElement(name = "student", namespace="http://example.com/xml/protocols")
    public class Student
        extends Regular{

}

This exception is not thrown. Now I have many such model classes all in same package. I want to add namespace in @XmlRootElement in all these.
I don't want to edit my so many classes manually.
Is there a way to add namespace to all @XmlRootElements in a package ??
Or am I doing something wrong ??
How to add a prefix to only root elements ??
If I add namespace in package-info, all elements get prefix abc which I don't want.
@XmlSchema(
        elementFormDefault=XmlNsForm.QUALIFIED,
        namespace="http://example.com/xml/protocols"
        xmlns={@XmlNs(prefix="abc",
                      namespaceURI="http://example.com/xml/protocols")}
    )

A: I think you are unclear about the XML namespace. The element <student> is defined in default namespace as per your xsd, where as the child elements in abc:namespace. But if you add namespace in the @XMLRootElement then it means you are overwriting the xsd and the corresponding JAXB class is no more valid against the xsd.
So if you want to add namespace abc only to <student>, you can add it in xsd as follows
 <xs:element name="abc:student">

and rest of them in defaultnamespace.
   <xs:element name="abc:student">
        <xs:complexType>
            <xs:complexContent>
                <!-- Inherit common attributes from Regular Type -->
                <xs:extension base="regular">
                    <xs:sequence>
                        <!-- Resource Specific Attributes -->
                        <xs:element name="name" type="name" minOccurs="0" />
                        <xs:element name="URI" type="listOfURIs" />

                        <xs:element name="content" type="content" />

            </xs:complexContent>
        </xs:complexType>
    </xs:element>


text:
Q: Using Many Arguments Without Duplicating Code Is there a way to use each of the arguments in this function in sequence without duplicating code?  For example, the first time through the loop I'd like to use R, the next time I'd like to use L, etc.  valuestruct is set up in the same order as the arguments, so the button method will return the equivalent bool I need for currentbutton according to int i.  If there's a better method to accomplish the same thing that's ok too.
int valuex=0;

void SetValue(bool &R,bool &L,bool &D,bool &U,bool &T,bool &S,bool &B,bool &A,bool &Y,bool &X,bool &W,bool &E,bool &G, bool &F) {

        bool value[4] = {true, false, true, false};
        bool currentbutton;

        for (int i=0; i < 12; i++) {
            currentbutton=valuestruct.button(i);

            if(currentbutton) {
                "I want to grab each argument in sequence here"=value[valuex];
                valuex++;
                if(valuex>ARRAYSIZE(value))
                    valuex=0;
            }
        }
    }

A: If you really do insist on this function prototype (and not following the other suggestions here of passing an array or a list - which are better), you can use something like that -
void SetValue(bool &R,bool &L,bool &D,bool &U,bool &T,bool &S,bool &B,bool &A,bool &Y,bool &X,bool &W,bool &E,bool &G, bool &F)
{
   bool* Bools[] = { &R, &L, &D, &U, &T, &S, &B, &A, &Y, &X, &W, &E, &G, &F };

   // *Bools[i] can be used to access the ith element.

   // Print the 4th element.
   std::cout << *Bools[3];

   // Change the value of the 5th.
   *Bools[4] = true;
}

By the way, if you don't really need to change the passed values, you should not pass them by reference. Passing a bool by reference only wastes time and space. It would also make the code here a bit less cluttered.

A: Have you considered using a bool array? :) A collection is definitely the way to go. If you need to retain metadata for filtering or grabbing certain values, consider using a Map.

A: Or a bit field? Quick&dirty version:
int field = FLAG_R | FLAG_L

void SetValue(int fields) {
    for (int i = 0; i < FLAG_COUNT; i++) {
        if (fields & (1 << i)) {
            // Flag #i is set
        }
    }
}

EDIT
Btw, passing bools as reference is useless if you're not changing the value. The pointer used for the reference is possibly longer than the type holding the bool itself.

A: You could use the variable argument support, since you have a fixed number of arguments you know how much to loop for.  IIRC it does not actually require that the function have variable arguments.
va_list args;
va_start(args,R);
// your code here...
va_end();

Forgive me if this is off base... it's been some years since I actively coded C.

A: I'd add this to hexagon's answer but I can't edit posts yet.
int valuex=0;

void SetValue(bool &R,bool &L,bool &D,bool &U,bool &T,bool &S,bool &B,bool &A
             ,bool &Y,bool &X,bool &W,bool &E,bool &G, bool &F)
{
    bool* bools[] = { &R, &L, &D, &U, &T, &S, &B, &A, &Y, &X, &W, &E, &G, &F };
    bool value[4] = {true, false, true, false};
    bool currentbutton;

    for (int i=0; i<12 && i < ARRAYSIZE(bools); i++) {
            currentbutton=valuestruct.button(i);

            if(currentbutton) {
                    *bools[i]=value[valuex];
                    valuex++;
                    if(valuex>ARRAYSIZE(value))
                            valuex=0;
            }
    }
}

Though I don't understand where it is thought you will only read the value of the bools, you just may not set all of them.

A: You could put the arguments to an array and pass the array instead. Depending on what the calling code is this could lead to less code.


text:
Q: How to specify the map attribute of HTML in a JSF page I am trying to replicate the below html page using JSF. But can't find the correct JSF tag to do so.
HTML content (Required HTML):

    <map name="Map" id="Map">
        <area shape="circle" id="circle" coords="135,596,34" href="http://www.google.co.in" alt="Circle" />
        <area shape="rect" id="square" coords="192,567,249,628" href="http://www.youtube.com" alt="Square" />
    </map>

JSF Page (JSF to be modified to get above HTML):

<f:view>
<h:outputText value="This is a JSF page"></h:outputText>

<h:form>
<h:graphicImage id="image" value="image.jpg" usemap="true">
    <h:commandLink action="#{managedBean.method}" id="links1" value="map1" coords="135,596,34" shape="circle"></h:commandLink>
    <h:commandLink action="#{managedBean.method}" id="links2" value="map2" coords="192,567,249,628" shape="rec"></h:commandLink>
</h:graphicImage>
</h:form>
</f:view>

Please suggest the correct JSF format to replicate the above HTML page using the  JSF page and it calls a method of ManagedBean when clicked on the link.