text:
Q: Android Retrofit parallel file download issue I have an usecase in my application for downloading two zip files from the server. For that i have been using retrofit+rxjava(created two seperate retrofit services). For parallel I execution have been subscribing both retrofit service in new thread and later combining it using zip operator. It's working fine. But later I added map operator to both service for unzipping operation but it not executing the code written in the map operator and the control is passing directly to zip operation. I don't how to tackle this and i am newbie in reactive world.
What I have been tried so far
    Observable<Response<ResponseBody>> dFileObservable = dbDownloadApi.downloadDealerData(WebServiceConstants.ACTION_DEALER_DATA,
            params.getDealerNumber(),params.getUserId(),params.getClientId(), params.getSessionId()).subscribeOn(Schedulers.newThread());
    dFileObservable.map(new Function<Response<ResponseBody>, String>() {
        @Override
        public String apply(Response<ResponseBody> responseBody) throws Exception {
            String header = responseBody.headers().get("Content-Disposition");
            String filename = header.replace("attachment; filename=", "");
            String downloadFolderPath = fileManager.makeAndGetDownloadFolderPath();
            String dealerZipPath = fileManager.makeFolder(downloadFolderPath, StrConstants.DEALER_FOLDER_NAME);
            fileManager.writeDownloadedFileToDisk(dealerZipPath,filename, responseBody.body().source());
            String dealerFilePath = dealerZipPath+File.separator+filename;
            unzipUtility.unzip(dealerFilePath, fileManager.makeAndGetDownloadFolderPath()+File.separator+ StrConstants.GENERAL_FOLDER_NAME);
            return dealerFilePath;
        }
    });

   Observable<Response<ResponseBody>> generalFileObservable = dbDownloadApi.downloadGeneralData(WebServiceConstants.ACTION_GENERAL_DATA,
            params.getDealerNumber(),params.getUserId(),params.getClientId(), params.getSessionId()).subscribeOn(Schedulers.newThread());;
    generalFileObservable.map(new Function<Response<ResponseBody>, String>() {
        @Override
        public String apply(Response<ResponseBody> responseBody) throws Exception {
            String header = responseBody.headers().get("Content-Disposition");
            String filename = header.replace("attachment; filename=", "");
            String downloadFolderPath = fileManager.makeAndGetDownloadFolderPath();
            String generalZipPath = fileManager.makeFolder(downloadFolderPath, StrConstants.GENERAL_FOLDER_NAME);
            fileManager.writeDownloadedFileToDisk(generalZipPath,filename, responseBody.body().source());
            String generalFilePath = generalZipPath+File.separator+filename;
            unzipUtility.unzip(generalFilePath, fileManager.makeAndGetDownloadFolderPath()+File.separator+ StrConstants.GENERAL_FOLDER_NAME);
            return generalFilePath;
        }
    });

   Observable<String> zipped = Observable.zip(dealerFileObservable, generalFileObservable, new BiFunction<Response<ResponseBody>, Response<ResponseBody>, String>() {
        @Override
        public String apply(Response<ResponseBody> responseBodyResponse, Response<ResponseBody> responseBodyResponse2) throws Exception {
            System.out.println("zipped yess");
            return null;
        }
    }).observeOn(Schedulers.io());

    zipped.subscribe(getObserver());

and the getObserver() function
    private Observer<String> getObserver(){

    return new Observer<String>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(String value) {

            System.out.println("------------total time-----------");
            System.out.println("result value-->"+value);
        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onComplete() {

        }
    };
}

When the code executes the control is transferred to the apply() function in zip operator and the map operator in both observable is not getting executed.
And there is another question
I am merging/zipping the two observables and the type passed to the operator is  Response<"ResponseBody">. Actually i  need the downloaded file path there(string type)and for that what should i do?
**

Updated the Solution as described by @Yaroslav Stavnichiy and now its working

**
    Observable<String> deObservable =  dbDownloadApi.downloaddData(WebServiceConstants.ACTION_DATA,
            params.getNumber(),params.getId(),params.getCtId(), params.getSessionId())
            .flatMap(new Function<Response<ResponseBody>, ObservableSource<String>>() {
                @Override
                public ObservableSource<String> apply(Response<ResponseBody> responseBody) throws Exception {
                    String zipPath = fileManager.processDownloadedFile(StrConstants.FOLDER_NAME,
                            StrConstants.FILE_NAME,responseBody.body().source());
                    return Observable.just(zipPath);
                }
            }).map(new Function<String, String>() {
                @Override
                public String apply(String filePath) throws Exception {
                    String unzipDestinationPath = fileManager.makeAndGetDownloadFolderPath()+
                            File.separator+ StrConstants.FOLDER_NAME;
                    unzipUtility.unzip(filePath, unzipDestinationPath);
                    return unzipDestinationPath;
                }
            }).subscribeOn(Schedulers.newThread());

A: What you are effectively doing is:
Observable a = ...;
Observable b = ...;
a.map(...);
b.map(...);
Observable.zip(a, b).subscribe(f);

map() (as well as all other rx-operators) does not mutate the source. It returns new observable that you can use in further computations. In your code you are ignoring those returned objects. You are zipping original observables, not the mapped ones, that's why mapper functions do not get invoked.
I think you wanted to do the following:
Observable a = ... .map(...);
Observable b = ... .map(...);
Observable.zip(a, b).subscribe(f);


text:
Q: Ingest mobile events data into hdfs I have a mobile app that generates events frequently and there are millions of users who will use this app.
What's the best way to capture these events and persist them into hdfs for later analysis?

A: As I assume from your tags, you are inclined to use Kafka and Flume with Kafka source and HDFS Sink. Your mobile app can publish data to Kafka topic and then by using Kafka source or Kafka channel (in case you do not need to use interceptors) you can consume these events and write to HDFS sink. Kafka is scalable so you don't have to worry about handling a high rate of events. However, I would suggest you use HBase as data storage. It will allow you later access each event with O(1) times. This can be done with HBase Sink. Check out this article from Cloudera blog.

redpajama_set_name: RedPajamaStackExchange


text:
Q: passing variable to django custom template tag Im using django-profiles. In my profile_detail template I know that I will receive a profile variable.
I want to make a custom tag that gets the content per user via user id. Like this:
{% get_user_content book.review profile.user.id as review_list %}

However, when  my parser runs It seems like profile.user.id was not transformed to an id number and throws an exception.
I can verify that my custom tag works by changing profile.user.id to say 1 for admin.
{% get_user_content book.review 1 as review_list %}

Has anyone deals with it before? What did you do?

A: Template tags never translate arguments. You need to do the lookup in the context yourself.


text:
Q: How to assign different values for a variable for different values of arrays? import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

n = [x / 10 for x in range(0, 11)]
Inv = 500000
E = np.multiply(n,Inv)
D = np.subtract(Inv,E)

for D in np.arange(1,100000):
    I = 0.1

for D in np.arange(100000,300000):
    I = 0.15

for D in np.arange(300000,500000):
    I = 0.2

Int = np.multiply(I,D)

fig = plt.figure()
ax = fig.subplots()
ax.plot(Int,D, marker = 'o')
ax.grid()
plt.show()

This is my code. When I run it I simply get Int = 100K, it by-passes all the for loops and considers only the last for loop.
How do I assign different values for I for different values of D?
Output for the program:


text:
Q: Visual Studio: copy dependent DLLs to target folder I realize that this question has been asked before - but none of the answers apply to my specific case:

*

*I have a solution containing a native C++ EXE project, which in turn depends on 40+ native C++ DLL projects (in the same solution).

*The EXE project has the usual Debug, Release (and Profile) configuration, but since them same source code base is used to build three different applications (say A1, A2 and A3). In addition, it targets x32 and x64, so that's a total of 3 x 3 x 2 = 18 project configurations.

*The DLL projects are shared by all three target applications, so there are only 3 (Debug, Release, Profile) times 2 (x32, x64) = 6 configurations.

*Since the EXE project depends on the DLLs, it needs to copy the relevant output of the DLL projects to its target folder (or a subfolder thereof) whenever they are modified.
How would you handle updating of the DLLs?

*

*A post-build action in each DLL project doesn't work (well), as it would have to copy the DLL to the relevant output folder of A1, A2 and A3. Any change in an output folder results in having to modify the post-build action in each of the 50 DLL projects.

*I currently added the DLLs themselves as project items to the EXE project, and configured a custom build tool to copy it to the output folder. But that requires me to add each DLL 6 times, so I end up with 6 x 50 = 300 DLLs!
What I really need is something like a Copy Local option, which unfortunately only works assemblies. Do solution do you suggest to simplify this build setup?

A: What I'd do is to put all DLLs in a single folder (specific to Debug/Release etc), and copy them back to the appropriate output folder of your EXE.
This can be done in only two actions:

*

*Set the output directory of all DLLs to a folder like $(ConfigurationName)_$(PlatformShortName)

*

*select all DLL projects

*right-click -> propoerties

*select all configurations and all platform

*set the output dir

*Add a post-build action to the EXE project, common to all configurations that copies $(ConfigurationName)_$(PlatformShortName)\*.dll to $(TargetDir)
EDIT
There is a problem in the second step since the $(ConfigurationName) of your EXE is not the same as your DLL projects. Not sure but maybe you can have a way to deduce the corresponding configuration, in order to still have a single post-build event for all your 18 configs. It can be a new SO question:)

A: This works on VisualStudio 2019 (maybe previous versions also but not tried)
I tried several ways and this is the best compromise:

*

*copied to the final target folder (the most important !)

*copied in project bin folder

*appears in the VS project view

*can have different x64/x86 files

*renamable (label Link)

Edit your *.vcxproj file and add this ItemGroup like any other
<ItemGroup>
  <None Include="MyDllFolder\myDll.dll" CopyToOutputDirectory="PreserveNewest" Link="myDll.dll"/>

  <!-- x86/x64 different dlls -->
  <None Include="MyDllFolder\x86\myDll2_x86.dll" Link="myDll2_x86.dll">
    <CopyToOutputDirectory Condition="$(PlatformTarget) == x86">PreserveNewest</CopyToOutputDirectory>
  </None>
  <None Include="MyDllFolder\x64\myDll2_x64.dll" Link="myDll2_x64.dll">
    <CopyToOutputDirectory Condition="$(PlatformTarget) == x64">PreserveNewest</CopyToOutputDirectory>
  </None>
</ItemGroup>

Inspired from Automatic copy files to output during application building


text:
Q: Lock folder when running cron I am setting up my first cron on a Ubuntu Desktop system.  I was curious to know if there is a way to lock a folder before a cron is ran and how to set it up?  I am following this article.  I am just trying to make sure I don't damage any files when moving them from and to the cron folder because it is on a shared network.

A: A simple script with locking and a delay before accessing files:
#!/bin/sh
if mkdir /tmp/myscript-running; then
    cd /mnt/share/whereever
    find . -type f -mmin +1 -print0 | xargs -i -n 1 -0 myscript.sh "{}"
    rmdir /tmp/myscript-running
else
    : # previous instance still running, do nothing
fi

GNU find or equivalent required for the -mmin option. You can run this as often as required via cron. Replace myscript.sh with your processing script.
The main features are:

*

*use mkdir to create a lock directory to prevent overlapping instances

*use find with -mmin +1 which limits the output to files modified more than 1 minute ago, this is to try to ensure new files are fully copied

*use xargs to process the files one at a time, "{}" is replace by the filename

*use \0 terminated filenames with find | xargs so that troublesome filenames don't cause problems

You should be able to modify the find parameters to match what you need. You can also use the above logic to move completed files from an "uploading/" to a "ready/" directory, which might simplify things.
Ubuntu also has lockfile and shlock which can be useful, see the man page of the latter for more ideas.

A: This isn't ideal, but effective.  You have a separate, 'feeder' directory that you copy new files into, when copying them onto the network.  Your cron script can then perform an /ls of /var/feeder, then lsof each file in that directory looking for any open file handles.  Files that aren't in use are then moved into the main shared directory, files that are open (presumably you're copying them or some such) are left in the feeder.  Ensure the main /shared directory isn't writable except by your script, and you should be good.

A: step by step guide to lock folders in linux
http://linux-all-over.blogspot.in/2014/10/how-to-lock-filefolder-in-linux-kali.html


text:
Q: cmake проблема со сборкой Собрался настроить сборку у себя на компьютере скачал последний cmake 3.9.0 с офф сайта под винду (поставил галку установить все нужные пути в PATH) и для проверки создал в папке C:/cin файл main.cpp вместе с CMakeLists.txt в нем:
CMakeLists.txt:
add_executable(main main.cpp)

после чего прописал cmake C:/cin -G "MinGW Makefiles" в cmd
процесс пошел, но после ввода make вот что вылезло...
(без cmake до этого компилил через cmd командой gcc main.c или g++ main.cpp
и в CodeBlocks)

Может у кого-то уже была такая проблема (или кто-то может ссылку кинуть с её решением)?

A: В общем полазив ещё немного по интернету и подумав решил скачать make.exe отдельно, указал в Path путь к нему, но оказалось что отсутствует libgmp-10.dll а это как раз та библиотека которая есть в MinGW, в общем прописал mingw32-make в cmd все заработало. Мне кажется ошибка была из за того что make изначально как-то к Delphi относился поэтому и возникала данная ошибка.


text:
Q: ValueError: Compute method failed to assign (Python3 odoo) There are three compute functions in my code.
But I got the error.
Odoo Server Error

Traceback (most recent call last):
  File "/vagrant/odoo/odoo/addons/base/models/ir_http.py", line 237, in _dispatch
    result = request.dispatch()
  File "/vagrant/odoo/odoo/http.py", line 682, in dispatch
    result = self._call_function(**self.params)
  File "/vagrant/odoo/odoo/http.py", line 358, in _call_function
    return checked_call(self.db, *args, **kwargs)
  File "/vagrant/odoo/odoo/service/model.py", line 94, in wrapper
    return f(dbname, *args, **kwargs)
  File "/vagrant/odoo/odoo/http.py", line 346, in checked_call
    result = self.endpoint(*a, **kw)
  File "/vagrant/odoo/odoo/http.py", line 911, in __call__
    return self.method(*args, **kw)
  File "/vagrant/odoo/odoo/http.py", line 530, in response_wrap
    response = f(*args, **kw)
  File "/vagrant/odoo/addons/web/controllers/main.py", line 1359, in call_kw
    return self._call_kw(model, method, args, kwargs)
  File "/vagrant/odoo/addons/web/controllers/main.py", line 1351, in _call_kw
    return call_kw(request.env[model], method, args, kwargs)
  File "/vagrant/odoo/odoo/api.py", line 396, in call_kw
    result = _call_kw_multi(method, model, args, kwargs)
  File "/vagrant/odoo/odoo/api.py", line 383, in _call_kw_multi
    result = method(recs, *args, **kwargs)
  File "/vagrant/odoo/odoo/models.py", line 6165, in onchange
    value = record[name]
  File "/vagrant/odoo/odoo/models.py", line 5640, in __getitem__
    return self._fields[key].__get__(self, type(self))
  File "/vagrant/odoo/odoo/fields.py", line 979, in __get__
    raise ValueError("Compute method failed to assign %s.%s" % (record, self.name))
Exception

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/vagrant/odoo/odoo/http.py", line 638, in _handle_exception
    return super(JsonRequest, self)._handle_exception(exception)
  File "/vagrant/odoo/odoo/http.py", line 314, in _handle_exception
    raise exception.with_traceback(None) from new_cause
ValueError: Compute method failed to assign meeting.request(<NewId 0x7f4760a316d8>,).description

I have assigned empty value in my function.
Like  self.request_srcmst_names = ''、self.date = ''、self.editable = False
But it still can't work. I don't know which function is wrong.
class MeetingRequest(models.Model):

    _name = 'meeting.request'

    request_srcmst_names = fields.Char(compute=_compute_request_srcmst_names)
    date = fields.Date(compute=compute_date, search=search_date)

    @api.depends('request_srcmst_ids')
    def _compute_request_srcmst_names(self):
        self.request_srcmst_names = ''
        for record in self:
            name = []
            for request_srcmst in record.request_srcmst_ids:
                name.append(request_srcmst.meeting_srcmst_id.name)
            record.request_srcmst_names = ', '.join(name)

    @api.depends('start_date')
    def compute_date(self):
        self.date = ''
        for record in self:
            if record.start_date:
                real_date = pytz.utc.localize(datetime.datetime.strptime(record.start_date, '%Y-%m-%d %H:%M:%S')).astimezone(pytz.timezone(config['timezone'])).date()
                record.date = real_date

class MeetingRequestSrcmst(models.Model):

    _name = 'meeting.request.srcmst'

    editable = fields.Boolean(compute=_compute_editable)

    def _compute_editable(self):
        self.editable = False
        for record in self:
            if record.hre_empbas_id.res_users_id.id == self.env.uid or record.create_uid.id == self.env.uid:
                record.editable = True

How can I fix the function? Please give me some suggestions. Thanks!

A: I think it's syntax error. You forget to put a quote around function name. Computed function name should be inside a quote – compute='compute_date'. So is search function.
In your case,
date = fields.Date(compute='compute_date', search='search_date')
request_srcmst_names = fields.Char(compute='_compute_request_srcmst_names')

Inside your functions for computed fields, you can remove :
self.editable = False
self.date = ''
self.request_srcmst_names = ''

A: As I can see, you are trying to assign value to a field that does not exist in the database.
Your code:
request_srcmst_names = fields.Char(compute=_compute_request_srcmst_names)
Replace it with below then it will work:
request_srcmst_names = fields.Char(compute='_compute_request_srcmst_names', store=True)
compute field by default has store=False. To make it store you need pass parameter store=True.
Hope the provided solution works for you!


text:
Q: How to render templates dynamically for a static user choice I don't know how to put this question as a title. But my question is I have 2 templates for each view in my django project templates folder. One template for english language and another for spanish language. My templates structure is
Project
   |
  app
   |
  templates
     |
    app
      |
   home_en.html
   home_es.html
   about_en.html
   about_es.html

I need to render the templates according to the user choice of language. I have the project now fully in english running. As a start I only have the templates converted to spanish and ready to render. I am sorry this is a vague question but some directions to this problem would help.
My main urls are
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^en/', include('app.urls')),
    url(r'^es/', include('app.urls')),
]

my app urlpatterns are
 urlpatterns = [
        url(r'^about$', views.about, name='about'),
        url(r'.*', views.home, name='home'), ]

I also tried checking the request url with /en/ or /es/ and then render according to it in each views like below.
def home(request):
    if request.path == '/en/':
        return render(request, 'app/home_en.html', {'title':'HOME'})
    else:
        return render(request, 'app/home_es.html', {'title':'HOME'})

def about(request):
        if request.path == '/en/about':
            return render(request, 'app/about_en.html', {'title':'ABOUT'})
        else:
            return render(request, 'app/about_es.html', {'title':'ABOUT'})

This works fine when I explicitly give url request as /en/ or /es/. How could i set it on the url based on the users selection of language ?
If I explicitly make request to http://127.0.0.1/es/about, my about page is shown in spanish but when I switch to home from there, it goes back to English home page. I want the url to stay as /es/ as the start even if I change the url. Now it changes to english since it is upper level in pattern

A: Please read Django translation docs. here: https://docs.djangoproject.com/en/1.10/topics/i18n/translation/#module-django.conf.urls.i18n
See the part: Language prefix in URL patterns
in your urls.py:
from django.conf.urls.i18n import i18n_patterns

urlpatterns += i18n_patterns (
        url(r'^about$', views.about, name='about'),
        url(r'.*', views.home, name='home'),
)

This will automatically prefix you urls with language codes.
in the views.py you can get language code fomr request.LANGUAGE_CODE like this: from request.LANGUAGE_CODE == 'en'
To choose language put in your html templates:
{% load i18n %}
<form action="{% url 'set_language' %}" method="POST">{% csrf_token %}
    <select name="language" id="language">
        <option value="en">en</option>
        <option value="ru">ru</option>
        <option value="az">az</option>
    </select>
    <button type="submit">send</button>
</form>

or
{% load i18n %}
<form action="{% url 'set_language' %}" method="post">{% csrf_token %}
    <input name="next" type="hidden" value="{{ redirect_to }}" />
    <select name="language">
    {% get_current_language as LANGUAGE_CODE %}
    {% get_available_languages as LANGUAGES %}
    {% get_language_info_list for LANGUAGES as languages %}
    {% for language in languages %}
    <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected="selected"{% endif %}>
        {{ language.name_local }} ({{ language.code }})
    </option>
{% endfor %}
    </select>
    <input type="submit" value="Go" />
</form>

A: A very simple solution is to use a single pattern with a named group:
url(r'^(?P<language>en|es)/', include('app.urls'))

Your views must then accept the language parameter:
def home(request, language):
    # language is either "es" or "en".
    return render(request, 'app/home_{}.html'.format(language), {'title': 'HOME'})

You may also consider Django's localization and avoid duplicating the views.


text:
Q: Python - upload the completed file ignoring the one in use p1 = subprocess.Popen(["arecord", "-Dhw:1,0", "-fS16_LE", "-d120", "-r44100"],stdout=subprocess.PIPE)
p2 = subprocess.Popen(["lame", "-", "test/%s/%s" %(dirname, filename)], stdin=p1.stdout)

output = p2.communicate()[0]

As you see here, I'm recording using arecord directly to mp3.
The problem i'm facing is that I need to upload the files i'm recording but as soon as the recording start it's generating a file and appending the audio to it rather than generating the mp3 file when the duration of the record is finished. The result is each time it checks for the file, it uploads the chunk of the file that is ready.
I only want the script to upload the file when the file is completed or i want lame to generate me the file when the duration is finish.
How can i check that the file is not in use anymore or maybe make lame use a temporary file then save the completed file to the main directory.

A: Why not just wait for the process to complete? Just do the upload after communicate returns.


text:
Q: HP2035 printer prints gibberish Issue

We have HP2035 on our network that for no apparent reason, on its own accord will print this gibberish:

Additional Background

Now, it'll print other documents just fine, it's just between the print jobs it'll print those gibberish pages.  The print queue is complete empty, when that happens.

Setup

It is running on print server Windows 2008 R2.  It is a PCL driver and up-to-date.

What was done

I restarted the print spooler as well as the server (stop and start, emptying the %windir%\System32\spool\PRINTERS).  Checked for to make sure the driver is up-to-date.  I checked the settings on the printer as well and nothing jumped out.

Help!

So, please, help!  I have seen someone suggesting installing PS driver instead or uninstalling and reinstalling drivers, I really would do as a total last ditch effort as it's a remote site and I might have to deal it individual drivers as well, it'll be a big pain, but I will do it if I have to.  Thank you!

A: The gibberish print job could actually be spooled from another PC with the wrong drivers.  When a print job is created, the local drivers generate the data to be sent to the spooler on the print server, and not the drivers installed on the print server.
You'll have to see what clients are pointing to this print server, which might be challenging.  But you do have a hint -- the client has the PCL driver.

A: As far as I can see (here and here), the 2035 supports PCL5E. PCL-XL (i.e. PCL6) does not seem to be supported - which is why you are getting that garbage. However, when I look for the drivers here, only a GDI driver is available - and none at all for Server 2008.
Someone has a PCL6 driver installed, and you'll need to replace it with the correct driver. If the printer is networked, the PCs can print direct to it, bypassing the server.


text:
Q: MVC 4 - Dictionary not saved I've added some Dictionaries to the entity "portfolio". The values therein are not updated directly by the user, rather the entity itself has a method to fill / refresh this dictionary.
I'm calling this refresh method from another Controller, right before the return action:
..
portfolio.refreshDicts();
db.SaveChanges();

By debugging, I can see that refreshDicts() adds 6 values to the dict, just as it should. But these are not getting stored, though calling db.SaveChanges() ... When I try to access a dict in another controller, I can see that it is empty.
I'm performing another operation on portfolio in the same Controller method just some steps before trying to call refreshDicts() (adding an object to a list in portfolio) and this is saved correctly.
How can that be? Thank you for your help!
Update
Class Portfolio with the Dictionaries
public class Portfolio
{
    [Key]
    public int ID { get; set; }
    public string GroupID { get; set; }

    public virtual List<KassenwirksamesEreignis> KassenwirksameEreignisse { get; set; }
    public virtual List<InternMsg> InterneNachrichten { get; set; }
    public virtual List<StockPosition> StockPositions { get; set; }
    public virtual List<BondPosition> BondPositions { get; set; }
    public virtual List<FuturePosition> FuturePositions { get; set; }
    public virtual List<OptionPosition> OptionPositions { get; set; }
    public virtual List<FondsPosition> FondsPositions { get; set; }
    public virtual List<Regelereignis> RegelEreignisse { get; set; }

    public Dictionary<DateTime, double> FondsVolumenDict { get; set; }
    public Dictionary<DateTime, double> KasseDict { get; set; }
    public Dictionary<DateTime, double> StockDict { get; set; }
    public Dictionary<DateTime, double> OptionDict { get; set; }
    public Dictionary<DateTime, double> FutureDict { get; set; }
    public Dictionary<DateTime, double> FondsDict { get; set; }
    public Dictionary<DateTime, double> BondDict { get; set; }

    public Portfolio()
    {
        FondsVolumenDict = new Dictionary<DateTime, double>();
        KasseDict = new Dictionary<DateTime, double>();
        StockDict = new Dictionary<DateTime, double>();
        OptionDict = new Dictionary<DateTime, double>();
        FutureDict = new Dictionary<DateTime, double>();
        FondsDict = new Dictionary<DateTime, double>();
        BondDict = new Dictionary<DateTime, double>();
    }

Controller:
   public ActionResult Create(StockPosition position)
    {
        if (ModelState.IsValid)
        {
            // find user's portfolio
            string currentUser = User.Identity.Name;
            string userGroupId = db.UserProfiles.Single(x => x.UserName == currentUser).GroupId;
            Portfolio portfolio = db.Portfolios.Single(x => x.GroupID == userGroupId);

            // add Stock to portfolio
            position.PortfolioID = portfolio.ID;
            db.StockPositions.Add(position);

            // book costs
            var ke = new KassenwirksamesEreignis();
            ke.Art = "Kauf";
            ke.Bezeichnung = position.Bezeichnung;
            ke.Date = DateTime.Now;
            ke.Wert = Math.Round((-1.0) * (position.Menge * position.Kaufpreis), 2);
            portfolio.KassenwirksameEreignisse.Add(ke);

            // Dictionaries refreshen
            portfolio.refreshDicts();
            db.Entry(portfolio).State = EntityState.Modified;

            // Save & Back
            db.SaveChanges();
            return RedirectToAction("../Portfolio/Index");
        }
        return RedirectToAction("../Portfolio/Index");
    }

my Context:
public class PlanspielContext : DbContext
{
    public DbSet<Portfolio> Portfolios { get; set; }
    public DbSet<UserProfile> UserProfiles { get; set; }
    public DbSet<GlobalMsg> GlobalNachrichten { get; set; }
    public DbSet<InternMsg> InterneNachrichten { get; set; }
    public DbSet<Price> Prices { get; set; }
    public DbSet<KassenwirksamesEreignis> KassenwirksameEreignisse { get; set; }
    public DbSet<Zinsanspruch> Zinsansprüche { get; set; }
    public DbSet<StockPosition> StockPositions { get; set; }
    public DbSet<OptionPosition> OptionPositions { get; set; }
    public DbSet<FuturePosition> FuturePositions { get; set; }
    public DbSet<BondPosition> BondPositions { get; set; }
    public DbSet<FondsPosition> FondsPositions { get; set; }
    public DbSet<Regelereignis> Regelereignisse { get; set; }

    // Am not sure if i need those here .. ?
    //public Dictionary<DateTime, double> FondsVolumenDict { get; set; }
    //public Dictionary<DateTime, double> KasseDict { get; set; }
    //public Dictionary<DateTime, double> StockDict { get; set; }
    //public Dictionary<DateTime, double> OptionDict { get; set; }
    //public Dictionary<DateTime, double> FutureDict { get; set; }
    //public Dictionary<DateTime, double> FondsDict { get; set; }
    //public Dictionary<DateTime, double> BondDict { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
}

the refreshDict method i'm calling
    public void refreshDicts()
    {
        refreshBondDict();
        refreshFondsDict();
        refreshFutureDict();
        refreshOptionDict();
        refreshStockDict();
        refreshKasseDict();
        refreshFondsVolumenDict();
    }

    public void refreshFondsDict()
    {
        DateTime today = DateTime.Now;

        for ( var i = - 4; i <= 1; i++)
        {
            DateTime currentDay = today.AddDays(i).Date;

            if (this.FondsDict.ContainsKey(currentDay))
            {
                this.FondsDict[currentDay] = getFondsValue(currentDay);
            }
            else
            {
                this.FondsDict.Add(currentDay, getFondsValue(currentDay));
            }
        }
    }
    ....

A: Try specifying to the framework that you modified the entity:
..
portfolio.refreshDicts();
db.Entry(portfolio).State = EntityState.Modified;
db.SaveChanges();

Edit
After seeing the updated code, it looks like you are trying to save the Dictionary objects directly to the database. It is not possible to map a Dictionary to a database table with Entity Framework. See this SO answer.

A: For what you have written i think you have 2 different Objects of typeof(db). That is to say you have 2 dbContexts and you are adding objects to one and saving the other.
By default dbContexts track the entities and hance if you call save from another the added entities are not tracked by this instance and therefore are not saved.
call .SaveChanges() on the context in which your are making changes and everything should work fine
UPDATE:-
there is some problem with your code. The Dictionary Items cannot be stores directly in the database. instead try adding the items to a table or to a DbSet


text:
Q: how to filter "RelatedItems" column using rest api? I have one RelatedItems object like :
var RelatedItem = "[{'ItemId':5,'WebId':'fc433b74-bae4-4548-9e6d-56062ef6da7e','ListId':'d635a608-bdf1-496c-a335-975bcb61a836'}]";

var ItemCollection = $.ajax({
  url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/GetByTitle('"+TaskListTitle+"')/items?$Filter=RelatedItems eq "+RelatedItem,
  type: "GET",
  async: false,
  headers:{
         "accept":"application/json;odata=verbose"
  },
  dataType: "json"
});

This above call not working!
I want to retrieve all listitemCollection which have the same RelatedItem object in its RelatedItems field using REST API.
Please help!

A: You can't filter that column like traditional columns. You can get the related item for a specific item, but you can't filter what data comes back for that specific item. Once you've retrieved the item, you can parse/filter the specific data out.


text:
Q: launcher icons cannot be changed I deleted something in a cache folder and since then I cannot move or delete icons from the launcher bar. I did a reset of the icons, reinstalled desktop and unity, the whole system (didn't touch /home) could someone help me? I have Ubuntu 14.04.

A: My problem is solved by deleting the ~/.local/share/zeitgeist folder and then restart.


text:
Q: Google Apps: Transfer File Ownership to Centralized Drive File Server Using Google Apps Script The Problem
Organizations using Google Apps have no simple solution for creating central "file servers" where users may add files, forfeiting their ownership to the repository. The problem is mainly that Google does not offer a central file storage option for organizations.
Current Workarounds
There exists several workarounds which offer partial solutions to this problem.

*

*As explained in this article, organizations may create a 'storage' user and use it to build the desired folder structure (Marketing, Operations, etc). These folders can be shared with the appropriate users within the organization and files they add to them are visible to other users, provided that sharing settings are properly configured. The problem with this option is that files added to the file server remain in the ownership of the users and end up counting against their storage quotas.

*As described here, there  exists paid Google Drive add-ons, such as AODocks which allow organizations to achieve this.

*Several fragments of solutions mentioning the use of Google Apps Script, Domain-Wide Delegation of Authority and Drive API, but all are outdated (making reference to the deprecated Documents List API) or incomplete. Novice users with little to no understanding of Google Developer tools are left with confusion.
Objective
Create a simple and free solution which uses a 'storage' user's Drive space as a central file server for users of an organization.
Requisites

*

*Utilize Google Apps Script and time-based triggers to run the script necessary to change ownership of files and folders added to a folder shared by the 'storage' user.

*Take advantage of Domain-Wide Delegation of Authority and the Drive API to change ownership of those files.

*The script should only have to be implemented by the domain's superuser and not require manual authorization from every user in the organization.

Solution in progress
I've started writing part of the Google Apps Script. However, I'm lacking the pieces which would authenticate to the Drive API using the OAuth credentials created as per this Delegation of Authority post.
var superUserEmail = "admin@mydomain.com";

var folderId = "TARGET_FOLDER_ID";  // This folder belongs to the superuser and is shared so that other members of the organization can edit its contents

var folderObject = DriveApp.getFolderById(this.folderId);

// List all folders, sub folders and files within the folder
var listItems = function(folder) {
    var items = [];
    function _listItemsRecursive(folder) {
            var files = folder.getFiles();
            var subfolders = folder.getFolders();
            while(files.hasNext()) {
                items.push(files.next());
            }
            while(subfolders.hasNext()) {
                _listItemsRecursive(subfolders.next());
            }
            items.push(folder);
    }
    _listItemsRecursive(folder);
    return items;
}

// Get all the items which don't already belong to the superuser
var getRestrictedItems = function(items) {
    var restrictedItems = [];
    for(i = 0; i < items.length; i++) {
        var item = items[i];
        var userEmail = item.getOwner().getEmail();
        if(userEmail != superUserEmail) {
            restrictedItems.push(item);
        }
    }
    return restrictedItems;
}

// Change ownership to superuser
var changeItemOwner = function(items) {
    for(i = 0; i < items.length; i++) {
        var item = items[i];

        item.setOwner(superUserEmail); //This obviously doesn't work

    }
}

function doGet() {
    var items = listItems(folderObject);
    var restrictedItems = getRestrictedItems(items)
    changeItemOwner(restrictedItems);
}

Regarding the actual change of ownership, this post proposes a solution, but using a deprecated method.
function changeOwner(newOwnerEmail, file)
{
  var fileId = file.getId();
  var oldOwnerEmail = file.getOwner().getEmail();

  if (oldOwnerEmail == newOwnerEmail) { return; }

  file.removeEditor(newOwnerEmail);  //should this be oldOwnerEmail?
  var base = 'https://docs.google.com/feeds/';

  var options = OAuthApp.getAuth('docs');

  options.method = 'POST';
  var rawXml = "<entry xmlns='http://www.w3.org/2005/Atom' xmlns:gAcl='http://schemas.google.com/acl/2007'>"
      +"<category scheme='http://schemas.google.com/g/2005#kind' "
      +"term='http://schemas.google.com/acl/2007#accessRule'/>"
      +"<gAcl:role value='owner'/>"
      +"<gAcl:scope type='user' value='"+newOwnerEmail+"'/>"
      +"</entry>";
  options.payload = rawXml;
  options.contentType = 'application/atom+xml';

  var API_KEY = getAPIKey();
  var url = base + oldOwnerEmail+'/private/full/'+fileId+'/acl?v=3&alt=json&key='+API_KEY

  try
  {
    var result = UrlFetchApp.fetch(url, options);
    docsObject  = Utilities.jsonParse(result.getContentText());
  }
  catch (err) { Logger.log(err.message) }

}//end changeOwner()

The Question
What I'm looking for is for someone to guide me in updating the changeOwner function to one which works and utilizes Drive API. One I've implemented it and have a working solution, I plan on writing a detailed step-by-step tutorial on getting to help the rest of the people out there trying to get this working.


text:
Q: Error from using shred on drive I used shred to erase my HDD but after leaving for a few hours and then returning, I found the screen was filled with "Error failed to write to entry ignoring read only file system". I restarted my machine, now it gives me the 1962 no OS found error, as I expected. Was the "failed to write to entry" suppose to happen? and did it securely wipe the files as I wanted? this is the first time I've used shred on a whole drive, so I'm not sure what to expect.
I used the command:
shred -vfz -n 10 /dev/sda


text:
Q: How can I group a list of objects by continuity? Given a very large (gigabytes) list of arbitrary objects (I've seen a similar solution to this for ints), can I either group it easily into sublists by equivalence? Either in-place or by generator which consumes the original list.
l0 = [A,B, A,B,B, A,B,B,B,B, A, A, A,B] #spaces for clarity

Desired result:
[['A', 'B'], ['A', 'B', 'B'], ['A', 'B', 'B', 'B', 'B'], ['A'], ['A'], ['A', 'B']]

I wrote a looping version like so:
#find boundaries
b0 = []
prev = A
group = A
for idx, elem in enumerate(l0):
    if elem == group:
        b0.append(idx)
    prev = elem
b0.append(len(l0)-1)

for idx, b in enumerate(b0):
    try:
        c = b0[idx+1]
    except:
        break
    if c == len(l0)-1:
        l1.append(l0[b:])
    else:
        l1.append(l0[b:c])

Can this be done as a generator gen0(l) that will work like:
for g in gen(l0):
    print g
....
['A', 'B']
['A', 'B', 'B']
['A', 'B', 'B', 'B', 'B']
....

etc?
EDIT: using python 2.6 or 2.7
EDIT: preferred solution, mostly based on the accepted answer:
def gen_group(f, items):
    out = [items[0]]
    while items:
        for elem in items[1:]:
            if f(elem, out[0]):
                break
            else:
                out.append(elem)

        for _i in out:
            items.pop(0)
        yield out
        if items:
            out = [items[0]]

g = gen_group(lambda x, y: x == y, l0)

for out in g:
    print out

A: Maybe something like this:
def subListGenerator(f,items):
    i = 0
    n = len(items)
    while i < n:
        sublist = [items[i]]
        i += 1
        while i < n and not f(items[i]):
            sublist.append(items[i])
            i += 1
        yield sublist

Used like:
>>> items = ['A', 'B', 'A', 'B', 'B', 'A', 'B', 'B', 'B', 'B', 'A', 'A', 'A', 'B']
>>> g = subListGenerator(lambda x: x == 'A',items)
>>> for x in g: print(x)

['A', 'B']
['A', 'B', 'B']
['A', 'B', 'B', 'B', 'B']
['A']
['A']
['A', 'B']

A: I assume that A is your breakpoint.
>>> A, B = 'A', 'B'
>>> x = [A,B, A,B,B, A,B,B,B,B, A, A, A,B]
>>> map(lambda arr: [i for i in arr[0]], map(lambda e: ['A'+e], ''.join(x).split('A')[1:]))
[['A', 'B'], ['A', 'B', 'B'], ['A', 'B', 'B', 'B', 'B'], ['A'], ['A'], ['A', 'B']]

A: The following works in this case. You could change the l[0] != 'A' condition to be whatever. I would probably pass it as an argument, so that you can reuse it somewhere else.
def gen(l_arg, boundary):
    l = l_arg.copy()    # Optional if you want to save memory
    while l:
        sub_list = [l.pop(0)]
        while l and l[0] != boundary:   # Here boundary = 'A'
            sub_list.append(l.pop(0))
        yield sub_list

It assumes that there is an 'A' at the beginning of your list. And it copies the list, which isn't great when the list is in the range of Gb. you could remove the copy to save memory if you don't care about keeping the original list.

A: Here's a simple generator to perform your task:
def gen_group(L):
    DELIMETER = "A"
    out = [DELIMETER]
    while L:
        for ind, elem in enumerate(L[1:]):
            if elem == DELIMETER :
                break
            else:
                out.append(elem)

        for i in range(ind + 1):
            L.pop(0)

        yield out
        out = [DELIMETER ]

The idea is to cut down the list and yield the sublists until there is nothing left.  This assumes the list starts with "A" (DELIMETER variable).
Sample output:
for out in gen_group(l0):
    print out

Produces
['A', 'B']
['A', 'B', 'B']
['A', 'B', 'B', 'B', 'B']
['A']
['A']
['A', 'B']
['A']

Comparitive Timings:
timeit.timeit(s, number=100000) is used to test each of the current answers, where s is the multiline string of the code (listed below):
                       Trial 1  Trial 2  Trial 3  Trial 4 |  Avg
This answer (s1):      0.08247  0.07968  0.08635  0.07133   0.07995
Dilara Ismailova (s2): 0.77282  0.72337  0.73829  0.70574   0.73506
John Coleman (s3):     0.08119  0.09625  0.08405  0.08419   0.08642

This answer is the fastest, but it is very close.  I suspect the difference is the additional argument and anonymous function in John Coleman's answer.
s1="""l0 = ["A","B", "A","B","B", "A","B","B","B","B", "A", "A", "A","B"]

def gen_group(L):
    out = ["A"]
    while L:
        for ind, elem in enumerate(L[1:]):
            if elem == "A":
                break
            else:
                out.append(elem)

        for i in range(ind + 1):
            L.pop(0)

        yield out
        out = ["A"]

out =gen_group(l0)"""

s2 = """A, B = 'A', 'B'
x = [A,B, A,B,B, A,B,B,B,B, A, A, A,B]
map(lambda arr: [i for i in arr[0]], map(lambda e: ['A'+e], ''.join(x).split('A')[1:]))"""

s3 = """def subListGenerator(f,items):
    i = 0
    n = len(items)
    while i < n:
        sublist = [items[i]]
        i += 1
        while i < n and not f(items[i]):
            sublist.append(items[i])
            i += 1
        yield sublist

items = ['A', 'B', 'A', 'B', 'B', 'A', 'B', 'B', 'B', 'B', 'A', 'A', 'A', 'B']
g = subListGenerator(lambda x: x == 'A',items)"""


text:
Q: Clash Royale loading problem Whenever I open Clash Royale, the progress bar will stop at 50 %, and doesn't go further. I even tried reinstalling the game, but that didn't work. Can somebody tell me how to fix this tricky problem?
I'm playing on an iPhone 8.

A: Try to clear the cache for the game and then open it
if not then clear the cache and reinstall
---hopes to work fine

A: For iOS (expected answer) this may be found from a bug or your phone does not meet ping or quality.
 Improvements/Solutions
You can clear your data from the phone, although I do not recommend deleting your game data. Restarting your phone or force stop for a few hours may help with the problem, and if these do not help, do the following:

*

*Contact Supercell Support

*Contact Apple about the game bug/leave a review on the game (There is a small chance of Supercell responding)
 Common Solutions
Some common solutions to this **without deleting game data** is that you may update your phone on the App Store, or you can just uninstall the game and reinstall it back.

 Conclusion
Try all these methods and hopefully one will help the loading screen load to 100% and you can start playing.


text:
Q: Comparing predictability of outcomes across leagues From time to time I encounter newspaper articles with titles like "Unpredictable English Premier League Keeps Us Guessing", which make claims about the difference in predictability of outcomes across leagues. My question is: how would one test such claims?
The method that I thought of (and later found at https://theconversation.com/just-how-unpredictable-is-the-premier-league-scientists-have-done-the-maths-59839) has one compute the average MSE between predictions (based on betting odds) and actual outcomes. But what test should be employed for comparing such averages?


text:
Q: angular automatically removes parameters form url In my application i am passing parameters for controller and read it using javascript as below.
localhost:8080/app/conroller#parameter=value
now problem is if i open my conroller in url and than append #parameter=value than only it works.
but i want to put whole link in anchor tag.
and when i click outside application than it automatically reroute localhost:8080/app/conroller and don't accept parameters.Although when opening that url if i apped #parameter=value* part than it works perfect.
i am using html5mode = true.
i search lots of document but didnt find right solution for this.

A: Not exactly sure if I get what you are asking but I think this is what you are getting at:
href="/app/conroller#parameter=value" target="_self"

Try adding the target self.
If that doesn't work you could try setting a base url <base href="/"></base>
You could try using ? for the query parameter instead of the #


text:
Q: Siunitx comma as separator in unit exponent I'm writing a report in French in which I want to display units with non-integer exponents:
\documentclass[10pt,letterpaper]{article}
\usepackage{siunitx}
\begin{document}
    \sisetup{locale=FR}
    Value of \SI{39.2}{\mega\pascal\metre\tothe{0.5}}.
\end{document}

In French commas are used as decimal separators. It works fine for the value of 39.2, but the comma does not follow in the exponent.

The same happens with the macro \raiseto. Any ideas how to get this right?

A: There's currently an oversight here in the code. For the present, use
\documentclass[10pt,letterpaper]{article}
\usepackage{siunitx}
\ExplSyntaxOn
\cs_set_protected:Npn \__siunitx_unit_format_power_aux: {
  \str_if_eq:VnTF \l__siunitx_per_mode_tl { repeat }
    { \__siunitx_unit_format_power_repeat: }
    { \__siunitx_unit_format_power_per: }
  \str_if_eq:VnF \l__siunitx_tmpa_tl { 1 }
    {
      \__siunitx_unit_format_power_brackets:
      \tl_put_right:Nx \l__siunitx_unit_current_tl
        {
          \exp_not:N \PrintSuperscript
            {
              \__siunitx_unit_format_power_aux:n
                { \exp_after:wN \__siunitx_unit_format_power:w \l__siunitx_tmpa_tl . . \q_stop }
            }
        }
    }
}
\cs_new:Npn \__siunitx_unit_format_power:w  #1 . #2 . #3 \q_stop
  {
    \exp_not:n {#1}
    \tl_if_blank:nF {#2}
      {
        \exp_not:V \l__siunitx_output_decimal_tl
        \exp_not:n {#2}
      }
  }
\ExplSyntaxOff
\begin{document}
    \sisetup{locale=FR}
    Value of \SI{39.2}{\mega\pascal\metre\tothe{0.5}}.
\end{document}


text:
Q: How do I create a method binding a stored procedure in Entity Framework 6? How do I create a function mapping a SQL stored procedure?
I have tried
var order = context.CustomerDetails.SqlQuery("DisplayTotalOrders @CustomerID", new SqlParameter("CustomerID", "1"));

var order = context.CustomerDetails.SqlQuery("DisplayTotalOrders @CustomerID", 1);

but nothing has worked.
Error message is shown as below. And this method seems quite an ad-hoc execution. Is there a way destined to create a method which binds a SQL Server stored procedure in EF? I am not talking about just INSERT, UPDATE, DELETE functions. I am referring to executing any SQL Server stored procedure.

Unhandled Exception:
System.Data.Entity.Core.EntityCommandExecutionException: The data
reader is incompatible with the specified
'TestEF_Code.CustomerDetail'. A member of the type, 'CustomerID', does
not have a corresponding column in the data reader with the same name.
at
System.Data.Entity.Core.Query.InternalTrees.ColumnMapFactory.GetMemberOrdinalFromReader(DbDataReader
storeDataReader, EdmMember member, EdmType currentType, Dictionary2 renameList)    at System.Data.Entity.Core.Query.InternalTrees.ColumnMapFactory.GetColumnMapsForType(DbDataReader storeDataReader, EdmType edmType, Dictionary2 renameList)    at
System.Data.Entity.Core.Query.InternalTrees.ColumnMapFactory.CreateColumnMapFromReaderAndType(DbDataReader
storeDataReader, EdmType edmType, EntitySet entitySet, Dictionary2 renameList)    at System.Data.Entity.Core.Objects.ObjectContext.InternalTranslate[TElement](DbDataReader reader, String entitySetName, MergeOption mergeOption, Boolean streaming, EntitySet& entitySet, TypeUsage& edmType)    at System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQueryInternal[TElement](String commandText, String entitySetName, ExecutionOptions executionOptions, Object[] parameters)    at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass691.b__68()
at
System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)    at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass691.b__67()
at
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func1 operation)    at System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQueryReliably[TElement](String commandText, String entitySetName, ExecutionOptions executionOptions, Object[] parameters)    at System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQuery[TElement](String commandText, String entitySetName, ExecutionOptions executionOptions, Object[] parameters)    at System.Data.Entity.Internal.Linq.InternalSet1.<>c__DisplayClass11.b__10()
at System.Data.Entity.Internal.LazyEnumerator1.MoveNext()    at System.Linq.Enumerable.Single[TSource](IEnumerable1 source)    at
TestEF_Code.Program.Main(String[] args) in
B:\Users\trio\Programming\TestEF-Code\TestEF-Code\Program.cs:line 17


text:
Q: Undefined offset after Json deserialization I made a code for deserialize a JSON, all working good for some content but for this link I get this error:

Notice: Undefined offset: 0 in C:\xampp\htdocs\SF\Teams.php on line 12

on this line: $current_object = $decoded[$i];
this is my code:
$variable = file_get_contents("http://api.football-data.org/alpha/soccerseasons/351/teams");
$decoded = json_decode($variable, true);

for ($i = 0; $i < count($decoded); $i++) {

 $current_object = $decoded[$i];
 var_dump($current_object); ...

A: The following code the output the team name and Short name
Try Example
$variable = file_get_contents("http://api.football-data.org/alpha/soccerseasons/351/teams");
$decoded = json_decode($variable, true);

foreach($decoded['teams'] as $team)
{
    echo "Team name: ".$team['name']."
";
    echo "Short name: ".$team['shortName']."
";
    echo "
";
}


text:
Q: Use Collectors to convert List to Map of Objects - Java How do I use Collectors in order to convert a list of DAOs, to a Map<String, List<Pojo>>
daoList looks something like this:
[0] : id = "34234", team = "gools", name = "bob", type = "old"
[1] : id = "23423", team = "fool" , name = "sam", type = "new"
[2] : id = "34342", team = "gools" , name = "dan", type = "new"

I want to groupBy 'team' attribute and have a list for each team, as follows:
"gools":
       ["id": 34234, "name": "bob", "type": "old"],
       ["id": 34342, "name": "dan", "type": "new"]

"fool":
       ["id": 23423, "name": "sam", "type": "new"]

Pojo looks like this:
@Data
@NoArgsConstructor
@AllArgsConstructor(access = AccessLevel.PUBLIC)
public class Pojo{

    private String id;
    private String name;
    private String type;
}

This is how I'm trying to do that, obviously the wrong way:
public Team groupedByTeams(List<? extends GenericDAO> daoList)
    {

        Map<String, List<Pojo>> teamMap= daoList.stream()
            .collect(Collectors.groupingBy(GenericDAO::getTeam))
    }

A: Use mapping as:
public Map<String, List<Team>> groupedByTeams(List<? extends GenericDAO> daoList) {
    Map<String, List<Team>> teamMap = daoList.stream()
            .collect(Collectors.groupingBy(GenericDAO::getTeam,
                    Collectors.mapping(this::convertGenericDaoToTeam, Collectors.toList())));
    return teamMap;
}

where a conversion such as convertGenericDaoToTeam could be possibly like:
Team convertGenericDaoToTeam(GenericDAO genericDAO) {
    return new Team(genericDAO.getId(), genericDAO.getName(), genericDAO.getType());
}

A: Your current collector - .collect(Collectors.groupingBy(GenericDAO::getTeam)) - is generating a Map<String,List<? extends GenericDAO>>.
In order to generate a Map<String, List<Pojo>>, you have to convert your GenericDAO instances into Pojo instances by chaining a Collectors.mapping() collector to the Collectors.groupingBy() collector:
Map<String, List<Pojo>> teamMap =
    daoList.stream()
           .collect(Collectors.groupingBy(GenericDAO::getTeam,
                                          Collectors.mapping (dao -> new Pojo(...),
                                                              Collectors.toList())));

This is assuming you have some Pojo constructor that receives a GenericDAO instance or relevant GenericDAO properties.


text:
Q: Encrypting a Private Message I am using both the Private Message module and the Encrypt modules.  I can of course create a field which is encrypted, but it looks like I must alter the PM module since its storage in the database is not encrypted.  Isn't exactly private then is it.  Permissions are not enough to make it a Private Message.
I assume I will need to add the Encrypt code directly to the module itself.  Does anyone have any idea where I would add it and how?
Thanks

A: The module is named "private messages" because the messages are private between the sender & recipient, no one else can see the messages.
If you want to encrypt the database, then you can directly use the database API hooks. You will also have to alter the schema of private messages module I believe.
For HTTPS you can use https://drupal.org/project/securepages
And for encrypting the form submitted data, you can go with http://www.jcryption.org/ or even more interesting http://crypto.stanford.edu/sjcl/

A: I've done something similar before to store encrypted images directly in the DB (for passport photos).
I've just had a quick look at the private messages module and it looks like you'll need to modify the main .module file. Search though it for db_insert. At around line 1836 is the bit that saves the message to the db.
If you add:
$message->body = encrypt($message->body);

before the line:
$args['body'] = $message->body;

Then that will handle the encryption.
Then you need to find where it gets back out the DB and put the decryption function in there.


text:
Q: Mocked repository doesn't get populated I had an initial unit test using a fake class
var dbContext = new FakeMyDbContext
        {
            Users = { new IdentityUser {
                               Id="94ccfbae-8567-405e-8e2e-70a038cdde40" }
            },
        };

var repository = new MyRepository<IdentityUser>(dbContext);

When I run it I have 1 user in repository, fine. I wanted however to use Moq instead so I tried this
var user = new Mock<IdentityUser>();
user.Setup(x => x.Id).Returns("94ccfbae-8567-405e-8e2e-70a038cdde40");

var users = new Mock<IDbSet<IdentityUser>>();
users.Setup(x => x.Add(user.Object));

var dbContext = new Mock<MyDbContext<IdentityUser>>();
dbContext.Setup(x => x.Users).Returns(users.Object);

var repository = new MyRepository<IdentityUser>(dbContext.Object);

But in this case the repository is empty. What am I missing? Thanks.
Update
A minor change to get the accepted answer to work. DbSet is not directly accessible so created a FakeDbSet
public class FakeDbSet<T> : IDbSet<T> where T : class

And used
var user = new IdentityUser { Id = "94ccfbae-8567-405e-8e2e-70a038cdde40" };
IDbSet<IdentityUser> users = new FakeDbSet<IdentityUser> { user };

A: I think that the users-mock provides no users. You mock Add() method of IDbSet<IdentityUser> but it actually does not add anything so there are no users. You need to setup some other method which provides the users or do not mock the users at all, something like this:
IDbSet<IdentityUser>  users = new DbSet<IdentityUser>
{
    new IdentityUser { Id = "94ccfbae-8567-405e-8e2e-70a038cdde40" }
};

var dbContext = new Mock<MyDbContext<IdentityUser>>();
dbContext.Setup(x => x.Users).Returns(() => users);

var repository = new MyRepository<IdentityUser>(dbContext.Object);


text:
Q: How to dynamically insert an orderby statement in a query array I'm trying to dynamically assign the sort order (stored in $current_sort below) for a query that lists menu items.
If I hard code the sort order it works fine, however, when I try to dynamically assign the sort parameters to a string, it fails. What am I missing?
$current_sort = ", 'orderby' => 'title', 'order' => 'asc'";
$myposts = get_posts(
    array(
        'cat' => "$cat,-$catHidden",
        'numberposts' => $my_current_count . $current_sort
        ));

//If I hard code the value of $current_sort it works fine
$myposts = get_posts(
    array(
        'cat' => "$cat,-$catHidden",
        'numberposts' => $my_current_count,
        'orderby' => 'title',
        'order' => 'asc'));

A: You cannot turn a string into PHP source code. (At least you shouldn't.)
Try this:
$current_sort_order = "title";
$current_sort_direction = "asc";

$myposts = get_posts(array(
      'cat' => "$cat,-$catHidden",
      'numberposts' => $my_current_count,
      'orderby' => $current_sort_order,
      'order' => $current_sort_direction
      )             );

A: you are doing it wrong, you don't have to concate..try this:
$current_sort = "title";
$order = "asc";
$myposts = get_posts(
    array(
        'cat' => "$cat,-$catHidden",
        'numberposts' => $my_current_count,
        'orderby'=> $current_sort,
        'order' => $order
        ));

A: The string concatenation on the line
'numberposts' => $my_current_count . $current_sort

is not equivalent to creating multiple array elements as in
'numberposts' => $my_current_count,
'orderby' => 'title',
'order' => 'asc'));

In the first instance, numberposts becomes a string containing information about the sort.
In the second instance, numberposts only contains the current count.
A better option may be:
$orderoption="<TITLE HERE>";
$order_dir="<SORT OPTION HERE>";
$myposts = get_posts(
array(
    'cat' => "$cat,-$catHidden",
    'numberposts' => $my_current_count,
    'orderby' => $orderoption,
    'order' => $order_dir));


text:
Q: Can kernel be written in other than assembly language? I never did kernel programming. I am a good programmer in the Java language and frequently use it. Now i feel to do something interesting with kernels. A kernel resides between hardware and OS. It communicates with hardware using system calls. Every programming language require a compiler to compile the code written in high level language and then it generate low level code, which is generally assembly language code. Here comes my doubt, if we have kernel written in C, then should we have a C compiler installed on the machine? At the end, when kernel interacts with hardware it uses assembly language, can i create kernel in Java language? If yes, then what are the requirements for the same? Thank you.

A:
A kernel resides between hardware and OS

Usually, the kernel is considered to be part of the operating system.

It communicates with hardware using system calls

System calls are the interface that is provided by the OS to user applications. The operating system communicates with the hardware through other mechanisms (for example interrupts or memory-mapped registers).

Every programming language require a compiler to compile the code written in high level language and then it generate low level code, which is generally assembly language code.

The compiler output is typically either native machine code or a language-specific bytecode (like in the case of Java). Sometimes, compilers also target another programming language such as C or Javascript (transpilation).

Here comes my doubt, if we have kernel written in C, then should we have a C compiler installed on the machine?

That's not necessary. The C compiler produces output that can execute directly on the hardware  without interpretation.

At the end, when kernel interacts with hardware it uses assembly language

The CPU doesn't understand assembly. It understands machine code.

can i create kernel in Java language?

It has been done.

If yes, then what are the requirements for the same?

If you want to write a kernel in Java, then you either have to

*

*compile your entire Java codebase to machine code

*get yourself a CPU that can execute Java bytecode

*find or build a Java VM and runtime that can run on bare metal and run your Java code in it (if you do it cleverly, you can write much of the runtime and maybe also parts of the VM in Java itself).

Now to the unspoken, almost rhethorical question:

Is this a good idea?

Probably not. Why? First of all, because it would take ages to set up. Second, because you couldn't just code the way you develop an average business application. You'd have to think about performance of very time-critical code (e.g. context switching, which often requires hand-tuned assembly to be fast enough), manual memory management (as in: your MRU might expect you to give it the physical address where the page table lies), system-/hardware-specific mechanisms (how to access a XYZ controller on this particular architecture?), ...
So you would lose many of the advantages that Java has over a low-level language like C in the first place.

A: Yes a kernel can be written in Java, see the JNode. It would have the advantage of having no problems with: dangling pointers, mix up of pointers and array addresses, unitialised data, and many more features of C.


text:
Q: cmake - weird side effects when find_package is called from function as opposed to global scope I have a very simple cmake project here which builds a single Qt application.
Works:
find_package called from global scope in CMakeLists.txt
CMakeLists.txt:
cmake_minimum_required(VERSION 3.2.2)
project(gui CXX)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14")

find_package(Qt5Widgets REQUIRED)

qt5_wrap_cpp         (moc_output message.h)
add_executable       (gui main.cpp ${moc_output})
target_link_libraries(gui Qt5::Widgets)

As listed above, the code builds successfully.
$ make

[ 25%] Generating moc_message.cpp
Scanning dependencies of target gui
[ 50%] Building CXX object CMakeFiles/gui.dir/main.cpp.o
[ 75%] Building CXX object CMakeFiles/gui.dir/moc_message.cpp.o
[100%] Linking CXX executable gui
[100%] Built target gui

Does not work:
find_package called from function scope in CMakeLists.txt
However, if I change the call to find_package to be within a function:
CMakeLists.txt:
cmake_minimum_required(VERSION 3.2.2)
project(gui CXX)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14")

function(load_qt)
    find_package(Qt5Widgets REQUIRED)
endfunction()

load_qt() # this is the only change - find_package called from function load_qt

qt5_wrap_cpp         (moc_output message.h)
add_executable       (gui main.cpp ${moc_output})
target_link_libraries(gui Qt5::Widgets)

The code no longer compiles.
$ make

 [ 25%] Generating moc_message.cpp
 make[2]: execvp: /.../build/moc_message.cpp_parameters: Permission denied
 make[2]: *** [moc_message.cpp] Error 127
 make[1]: *** [CMakeFiles/gui.dir/all] Error 2
 make: *** [all] Error 2

Questions:

*

*Why does this happen?

*Is there any way to conditionally call find_package, eg: only when a user calls my function?

Full source code:
main.cpp:
#include <QApplication>
#include <QMainWindow>
#include <QVBoxLayout>
#include <QPushButton>
#include "message.h"

class App
{
public:
    App(int& argc, char** argv)
        : app(argc, argv)
    { }

    int exec()
    {
        QMainWindow* window = new QMainWindow;
        QWidget*     widget = new QWidget;
        QVBoxLayout* layout = new QVBoxLayout;
        QPushButton* button = new QPushButton("go");
        Message*     msg    = new Message;

        window->setCentralWidget(widget);
        widget->setLayout(layout);
        layout->addWidget(button);

        QObject::connect(button, &QPushButton::clicked, msg, &Message::onGo);

        window->show();
        return app.exec();
    }

    QApplication app;
};

int main(int argc, char** argv)
{
    return App(argc, argv).exec();
}

message.h:
#include <QMessageBox>
#include <QObject>

class Message : public QObject
{
    Q_OBJECT
public slots:
    void onGo()
    {
        QMessageBox(
            QMessageBox::Icon::Information,
            "Hello",
            "World",
            QMessageBox::StandardButton::NoButton,
            nullptr).exec();
    }
};

CMakeLists.txt:
cmake_minimum_required (VERSION 3.2.2)
project (gui CXX)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14")

function(load_qt)
    find_package(Qt5Widgets REQUIRED)
endfunction()

# this doesn't work
# load_qt()

# this does work
find_package(Qt5Widgets REQUIRED)

qt5_wrap_cpp         (moc_output message.h)
add_executable       (gui main.cpp ${moc_output})
target_link_libraries(gui Qt5::Widgets)

A: The root cause of the problem here is that functions create a new scope
From the documentation:

A function opens a new scope: see set(var PARENT_SCOPE) for details.

Macros, on the other hand, operate at parent scope.
Therefore, to fix the problem, change load_qt() to a macro:
CMakeLists.txt:
cmake_minimum_required(VERSION 3.2.2)
project(gui CXX)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14")

# note here, load_qt is now a macro rather than a function
macro(load_qt)
    find_package(Qt5Widgets REQUIRED)
endmacro()

load_qt()

qt5_wrap_cpp         (moc_output message.h)
add_executable       (gui main.cpp ${moc_output})
target_link_libraries(gui Qt5::Widgets)


text:
Q: OSX - Compiling training tools for Tesseract 4.0 -Need to reconfigure project, so there are no errors I followed this wiki (https://github.com/tesseract-ocr/tesseract/wiki/Compiling#macos) .
But when run make training ,
I get :
Need to reconfigure project, so there are no errors
So how should I compile the training tools?

A: Please check the output of ./configure, it may contain the below text:
You can not build training tools because of missing dependency.
Check configure output for details.
So you need to check the whole output of ./configure to find the missing dependency and install it.
An example of missing dependency prompt:
configure: WARNING: icu 52.1 or higher is required, but was not found.
configure: WARNING: Training tools WILL NOT be built.
configure: WARNING: Try to install libicu-devel package.


text:
Q: Creating a Clipping Mask using Graphics32 I'm using Graphics32 for image processing. Looking at its capabilities, it strikes me that I've yet to see a proper implementation of a clipping mask. I do see the term "clipping" pop up here and there, but it seems to refer to something else.
Simply put, I need one layer to function as a "peeking hole" to another; layer A should be projected onto layer B, but only where layer B is visible. (I see no further need to redefine what a clipping mask is.)
If it were just the bitmap of that other layer that I'd like to present, it wouldn't be so hard to do - then I could use this trick - but what complicates things, is that the bitmap of a layer does not tell much about what would be displayed by the layer; the layer can be:

*

*(partially) invisible (when out of the view)

*moved/stretched + optionally resampled

*rotated

with no effects on its bitmap.
Is it actually so that there is no ready implementation for this? Any suggestions for doing this myself?
Progress
I found some useful elements in the source of Graphics32. For example, using this declaration:
type
  TLayerAccess = class(TBitmapLayer);

to gain access to protected methods, I can call TLayerAccess(ABitmapLayer).Paint(ABitmap32) to have just this layer painted to a bitmap, exactly as it would to the screen.

A: Have a look at TByteMap and its writeTo method.

A: I have looked into this myself a year ago, and quickly resorted to using a black layer with transparent parts. It suited my then needs. But what you want is possible..
You want to couple one TBitmapLayer to another and consider it its mask. I want to avoid these references however (and its potential problems and Graphics32 rework) and see this only as a last resort.
There is a way to do without a dedicated TBitmapLayer, using your own pixel combiner. But it doesn't know about TBitmapLayers and its XY pixels.
To proper occlude (or leave out) parts of a TBitmapLayer while drawing  to screen, you could  use create a method of type TPixelCombineEvent and assigning this as its OnPixelCombine and setting TBitmapLayer.DrawMode to dmCustom.
Inside that TPixelCombineEvent method you decide what pixels result given the background B and the foreground F given the current M master alpha.
procedure TMyObj.MyPixCombine(F: TColor32; var B: TColor32; M: TColor32);
begin
  if not PseudoThisPixelShouldBeMasked then B := F; // ugly and aliased
end;

Problem here is, that (the pseudo code) PseudoThisPixelShouldBeMasked doesn't really know what pixel this concerns and whether it is inside a mask. So you'd have to extract that value from a component of F, such as its Alpha value.
Back then i opted for the quite fast B := ColorMin(F,B); where F is black or white. This layer is on top always and results in black instead of transparent masks however.
This because any rendering to the TBitmapLayer would destroy the mask data and i need to reapply it. Using a TByteMap however as suggested below (who downvoted that?) by iamjoosy might be interesting, perhaps that performance penalty turns out negligible.


text:
Q: Symfony2 post submit event on a form input that is generated after a pre set data event My case is the following:
I have a multi step registration form. At the first step the user selects his role (Buyer, Supplier) and proceeds to the second step. If user has selected role Buyer then the input field isCompany is included in the form. When user selects isCompany = true then additional fields appear. I want to attach a post_submit event to the field "isCompany" but I don't know how to do this as this field is generated by a pre_set event and it is not included when form is rendered for the first time.
My form type:
    $builder
        ->add('firstName')
        ->add('lastName')
        ->add('telephone')
        ->add('email', 'email')
        ->add('password', 'repeated', array(
            'first_name' => 'password',
            'second_name' => 'confirm',
            'type' => 'password',
        ));

    $formModifier = function (FormInterface $form, $isCompany) {
        if ($isCompany == true) {
            $form->add('company', new CompanyType());
        }
    };

    $builder->addEventListener(
        FormEvents::PRE_SET_DATA,
        function (FormEvent $event) use ($formModifier) {
            $user = $event->getData();
            $form = $event->getForm();

            if ($user->getRole()->getRole() === 'ROLE_BUYER') {
                $form->add('isCompany', 'choice', array(
                    'choices'   => array('0' => 'Citizen', '1' => 'Company'),
                ));

                $formModifier($event->getForm(), $user->getIsCompany());
            }
        }
    );

    $builder->get('isCompany')->addEventListener(
        FormEvents::POST_SUBMIT,
        function (FormEvent $event) use ($formModifier) {
            // It's important here to fetch $event->getForm()->getData(), as
            // $event->getData() will get you the client data (that is, the ID)
            $isCompany = $event->getForm()->getData();

            // since we've added the listener to the child, we'll have to pass on
            // the parent to the callback functions!
            $formModifier($event->getForm()->getParent(), $isCompany);
        }
    );

    $builder
        ->add('nextStep', 'submit')
        ->add('previousStep', 'submit', array(
            'validation_groups' => false,
        ));
}

A: Add the second event listener inside the first event listener: i.e:
$builder->addEventListener(
    FormEvents::PRE_SET_DATA,
    // put your POST_SUBMIT listener inside $otherListener, see below for more details
    function (FormEvent $event) use ($formModifier, $otherListener) {
        $user = $event->getData();
        $form = $event->getForm();

        if ($user->getRole()->getRole() === 'ROLE_BUYER') {
            $form->add( //note this part:
                $builder->create('isCompany', 'choice', array(
                    'choices'   => array('0' => 'Citizen', '1' => 'Company'),)
                )->addEventListener(FormEvents::POST_SUBMIT, $otherListener) // $otherListener is the listener you use in the post submit event (just like you've included in the question)
            );

            $formModifier($event->getForm(), $user->getIsCompany());
        }
    }
);


text:
Q: Vertx FileUpload Unit Test My backend code is very similar to this question.
Router router  = Router.router(vertx);
router.route().handler(BodyHandler.create().setDeleteUploadedFilesOnEnd(true));

router.route("/api/*")
                    .produces(Constants.JSON_CONTENT_TYPE)
                    .failureHandler(rc -> {
                        // handling failure code
                });

router.post("/api/upload").handler(uploadHandler::uploadHandler);
vertx.createHttpServer(httpOptions)
                    .requestHandler(router::accept)                             // The router::accept, method passes all routes defined in Router.
                    .listen(// do things);
class UploadHandler() {
    void uploadHandler(RoutingContext context) {
        uploads.forEach(// do things);
    }
}

I have been using postman to test the methods. It is working perfectly.
In postman, I choose POST, no headers, form-data as body, and choose files instead of text to upload files.
I checked in the server that postman include the content-type automatically.
I am assuming this is a good approach. Please let me know if there's a better approach.
My problem is at unit testing.
I used the code similar to this. https://github.com/vert-x/vertx-examples/blob/master/src/raw/java/upload/UploadClient.java
There are other snippets which does similar things. But the server keeps saying that no files are attached.
What is the a good way to send a file to the server?

A: The link in your question points to an old version of Vert.x
With a recent version, you should use the Vert.x Web Client.
String filename = "upload.txt";
FileSystem fs = vertx.fileSystem();

WebClient client = WebClient.create(vertx);

fs.props(filename, ares -> {
  FileProps props = ares.result();
  System.out.println("props is " + props);
  long size = props.size();

  HttpRequest<Buffer> req = client.put(8080, "localhost", "/");
  req.putHeader("content-length", "" + size);

  fs.open(filename, new OpenOptions(), ares2 -> {
    req.sendStream(ares2.result(), ar -> {
      if (ar.succeeded()) {
        HttpResponse<Buffer> response = ar.result();
        System.out.println("Got HTTP response with status " + response.statusCode());
      } else {
        ar.cause().printStackTrace();
      }
    });
  });
});

For a full client/server sample, check out the Vert.x examples repository


text:
Q: Stack Overflow doesn't accept my answers While posting answers, why doesn't Stack Overflow accept my answers? The message says that answers from this account cannot be accepted.
What can I do so that I can post answers again?

A: Most of your answers were deleted because they weren't actually answers (one of them was deleted by me). They were questions. You shouldn't have posted an answer unless you were trying to answer the question. We don't tolerate people repeatedly misusing the answer field, hence the answer ban.


text:
Q: Should I used "submits" or "submitted" after "We used to wait"? I have one confusion with one sentence structure. We know that we can use any tense with present tense, future tense and past for only past. But in this case I am really confused. If someone told me about this, that would be really helpful.

We used to wait till someone brave submits his exam papers.

Is it ok or I should have used "submitted" instead of submit?


text:
Q: Data structure for fast line queries? I know that I can use a KD-Tree to store points and iterate quickly over a fraction of them that are close to another given point. I'm wondering whether there is something similar for lines.
Given a set of lines L in 3D (to be stored in that data structure) and another "query line" q, I'd like to be able to quickly iterate through all lines in L that "are close enough" to q. The distance I'm planning to use is the minimal Euclidean distance between two points u and v where u is some point on the first line and v is some point on the second line. Computing that distance is not a problem (there's a nice trick involving the cross product).
Maybe you guys have a good idea or know where to look for papers, descriptions, etc...
TIA,
s.

A: Another option - and the most commonly used one for spatial indexing in disk-based database systems - is the R-Tree. It's a bit more complicated to implement than a KD-Tree, but it's generally considered to be faster, and has no problem indexing lines and polygons.

A: You can use KD-Trees for this as well.
It's possible to build a KD-Tree that works on primitives, not points.  Many ray tracers do this to make triangle hit testing much faster.  The best description I've seen is in this ray tracing tutorial.
A potentially faster, though not 100% accurate, solution, is to just keep a list of points per line segment, and insert these into a standard point-based KD-Tree.  Find the nearest points, then have them tagged with the line segment, and use that to get the nearest lines.  It's crude, but often very fast compared to other options.  The "trick" is to find the right balance of keeping large spaces between points along the segment (faster) vs. breaking the segment into more points (slower, but more accurate).


text:
Q: How to use Casablanca to call /files (POST) in Dropbox API I'm using c++ and Casablanca to add Dropbox functionality to our software.
I can log in using OAuth 2, get metadata, open files, and save files using files_put successfully.
I can't however figure out how to save a file using /files (POST).
I'm using code similar to this: (i.e. I have removed some functions to just show the hardcoded strings I end up with)
{
    using concurrency::streams::file_stream;
    using concurrency::streams::basic_istream;

    utility::string_t strURI = L"https://api-content.dropbox.com/1/files/dropbox/";
    uri url(uri::encode_uri(strURI));

    utility::string_t sb = url.to_string();
    sb += L"?oauth_consumer_key=" + consumerKey + L"&";
    sb += L"oauth_nonce=" + nonce + L"&";
    sb += L"oauth_timestamp=" + timestamp + L"&";
    sb += L"oauth_version=2.0";
    sb += L"&access_token=" + accessToken;
    sb += L"&file=" + strFilename; // I've tried with and without this line

    return file_stream<unsigned char>::open_istream(strPath)
        .then([sb, url, &bRet](task<basic_istream<unsigned char>> previousTask)
    {
        try
        {
            auto fileStream = previousTask.get();
            //get the content length, used to set the Content-Length property
            fileStream.seek(0, std::ios::end);
            auto length = static_cast<size_t>(fileStream.tell());
            fileStream.seek(0, 0);

            // Make HTTP request with the file stream as the body.
            http_request req;
            http_client client(sb);
            req.set_body(fileStream);
            req.set_method(methods::POST);
            return client.request(req)
                .then([fileStream, &bRet](task<http_response> previousTask)
            {
                // Process response
            }
        }
    };
}

I get a bad request response.
I assume the problem is that I'm not giving it the filename parameter correctly, but I don't know where it's supposed to go. Or maybe I'm missing something else entirely.
Can anyone please help clarify this for me?

A: One side-note, I think you're using OAuth 2, but you're constructing a signature sort of like an OAuth 1 signature. I believe you can just do this:
utility::string_t sb = url.to_string();
sb += L"?access_token=" + accessToken;

Though it's slightly preferable to put the access token in the auth header: Authorization: Bearer <access token>.
I'm not 100% sure, but I believe /files (POST) requires a multipart-form-encoded body (and so the file name comes from the attachment in the body). I'm not sure how to accomplish that with Casablanca. But I would really stick to /files_put for Dropbox and use POST requests only for the platforms that require it (and perhaps they have simpler interfaces for that call).


text:
Q: How to get index of duplicates in array? I would like to know how to get the index of two or more objects that is a duplicate in an array. How would i do this in swift?
My array looks like this : [1, 2, 3, 1]
I would then like to return the index of 1, since they are duplicates.(0, 3)
I have tried to find any answers regarding this, but I could not find any answers. Therefore I hope I can get an answer.

A: I did find a solution!
names = ["Shrek", "Shrek", "Pinocchio"]
for name in names{
        print(names.index(of: name))
    }

Prints(0,0,2) because names has to duplicates


text:
Q: Android searchview filter in recyclerview pagingDataAdapter with Paging3 is not updating the data I am trying to search a value from database with the search filter. but not updating the searched values in adapter.
Note: loading the data using Paging3 library.
  private val mDiffer: AsyncListDiffer<Data?> = AsyncListDiffer(this, DataComparator)

 object DataComparator: DiffUtil.ItemCallback<Data>() {
        override fun areItemsTheSame(oldItem: Data, newItem: Data): Boolean {

            return oldItem.mobileNo == newItem.mobileNo
        }

        override fun areContentsTheSame(oldItem: Data, newItem: Data): Boolean {
            return oldItem == newItem
        }
    }

    fun submitList(list: List<Data?>?)
    {
        mDiffer.submitList(list)

    }
 override fun publishResults(charSequence: CharSequence?, filterResults: FilterResults)
            {
                submitList(filterResults.values as MutableList<Data>)

                if (filterResults.count > 0) {
                    notifyDataSetChanged();
                }

            }

iam getting the searched values in inmDiffer.submitList(list) method. but values are not added in adapter.
kindly help me to achieve this.
links referred https://howtodoandroid.com/pagination-with-paging-3-android/
link 2
thanks in advance

A:  submitList(filterResults.values as MutableList<Data>)

When using DiffUtil, you should submit an immutable list or new list everytime. Otherwise, DiffUtil won't work.
Excerpt from DiffUtil doc:

Note that DiffUtil, ListAdapter, and AsyncListDiffer require the list
to not mutate while in use. This generally means that both the lists
themselves and their elements (or at least, the properties of elements
used in diffing) should not be modified directly. Instead, new lists
should be provided any time content changes. It's common for lists
passed to DiffUtil to share elements that have not mutated, so it is
not strictly required to reload all data to use DiffUtil.


text:
Q: Storing data on separate storage volumes I'm just looking for some design options around Postgresql.
I'm looking at using Postgresql as the backend for a SCADA system that I'd like to develop, this essentially means that it would have a combination of both OLTP loads (for instantaneous state / config of system) as well as quite a lot of OLAP involving time series data.
One particular item that I'd be worried about is performance, and in particular around disk I/O performance.
I see that Postgresql allows for Tablespaces to be used to put tables on different storage volumes, is there any way to do this with particular columns of data also?
My current schema approach would entail the following (exposed) tables:

*

*Objects

*Historical Data

*Historical Events

For the Historical Data and Historical Events I'd ideally like to able to partition these across a number of different storage volumes, but not in time order, and instead perhaps by a hashing partition or similar.  I think this wouldn't be a problem, although it appears that it would require the use of Inherited tables (i.e. the Historical Data / Events being hidden Parent tables, real tables inheriting from these along some hash of the ObjectId FK or similar).
It's the Objects table that I'm most unsure about.  Each row would consist of something like:

*

*ObjectId (Unique, Primary Key)

*Security (ACL etc)

*Data (JSON(B) format)

*Config (JSON(B) format)

What I'd really like to be able to do is split out the Data column so that it's stored elsewhere.  It will be write heavy, and I would prefer not to have that same disk I/O impacting on the Object Config.
Is there any nice way to do this in Postgresql? (or should I be normalising the schema to have Data into a separate table? just with FK against ObjectId..)


text:
Q: Date-Time Stamp not proper on gmail while inserting mail in c# using google apis I am trying to add mails using Google APIs.
Mail is getting inserted properly but date-time stamp is not proper.
 Message msg = new Message();
                String[] objidsArr = new String[1];
                objidsArr[0] = labelId;
                msg.LabelIds = objidsArr.ToList();
                msg.Raw = f_MsgRawStr;

                m_MailService.Users.Messages.Insert(msg, "me").Execute();

Here its showing current date-time.
But if I open it, it shows proper date like..
To insert mail I use .EML file.
Please suggest solution to insert email with proper date-time in both views.

A: f_ReqforMail = m_MailService.Users.Messages.Insert(msg, "me");
f_ReqforMail.InternalDateSource  = Google.Apis.Gmail.v1.UsersResource.MessagesResource.InsertRequest.InternalDateSourceEnum.DateHeader;
f_ReqforMail.Execute();

Its Working.


text:
Q: Find the average depth of the number of children in a dataframe I have a data frame (df) with a parent_id and child_id columns. A small portion of the df is shown below to explain the problem.

child_id
parent_id

11
10

12
11

17
16

18
17

19
18

20
10

21
20

22
21

32
13

33
32

34
33

35
34

41
33

42
41

43
42

44
43

56
44

57
56

I want to get an array that shows for each original (parentless) parent_id (e.g. 10, 16, 13), how many steps below (rollout) the children and the grandchildren went.
For example, for parent_id:10, there will be two elements in the returned array. The first element will have a value of 2 as it went two steps deep. It has child_id:11, and then 11 has 12.
parent_id:10 also starts another rollout with child_id:20 that goes 3 steps deep. Hence, for 10 the returned array shall have 2 elements [2, 3].
Similarlry, for parent_id 16, 3 steps deep. For parent_id:13, 10 steps deep. Thus the returned array would be [2, 3, 3, 10].


text:
Q: How to have DropWizard JUnit App Rule definition use startup information from a docker rule? The general problem I am trying to solve is this. I have a solution, but it's very clunky, and I'm hoping someone knows of a more orderly one.
Dropwizard offers a JUnit TestRule called DropwizardAppRule, which is used for integration tests. You use it like this:
@ClassRule
public static final DropWizardAppRule<MyConfiguration> APP_RULE = new DropwizardAppRule(MyApplication.class, myYmlResourceFilePath, ConfigOverride("mydatabase.url", myJdbcUrl));

It will start up your application, configuring it with your yml resource file, with overrides that you specified in the constructor. Note, however, that your overrides are bound at construction time.
There are also JUnit rules out there to start up a Docker container, and I'm using one to start up MySql, and a JUnit RuleChain to enforce the fact that the container must start up before I launch my Dropwizard application that depends on it.
All that works great, if I'm willing to specify in advance what port I want the MySql container to expose. I'm not. I want these integration tests to run on a build machine, quite possibly in parallel for branch builds of the same project, and I would strongly prefer to use the mechanism where you ask Docker to pick any available port, and use that.
The problem I run into with that, is that the exposed container port is not known at the time that the DropwizardAppRule is constructed, which is the only time you can bind configuration overrides.
The solution I adopted was to make a wrapper JUnit Rule, like so:
public class CreateWhenRunRuleWrapper<T extends ExternalResource> extends ExternalResource {
    private final Supplier<T> wrappedRuleFactory;
    private T wrappedRule;

    public CreateWhenRunRuleWrapper(Supplier<T> wrappedRuleFactory) {
        this.wrappedRuleFactory = wrappedRuleFactory;
    }

    public T getWrappedRule() {
        return wrappedRule;
    }

    @Override
    protected void before() throws Throwable {
        wrappedRule = wrappedRuleFactory.get();
        wrappedRule.before();
    }

    @Override
    protected void after() {
        wrappedRule.after();
    }
}

This works, allowing me to construct the DropWizardAppRule class in the before() method, but is quite obviously outside JUnit's design intent, as shown by the fact that I had to locate it in the org.junit.rules package, in order to empower my class to be able to call the before() and after() methods of the late-created Rule.
What would be a more orderly, best practice way to accomplish the same objective?

A: 2 Options we came up with:
The hacky solution is to use static {} which executes the code after spinning up the container but before initialising the dropwizard instance:
public static final GenericContainer mongodb = new GenericContainer("mongo:latest").withExposedPorts(27017);
static {
    mongodb.start();
    System.setProperty("dw.mongoConfig.uri", "mongodb://" + mongodb.getContainerIpAddress() + ":" + mongodb.getMappedPort(27017));
}

@ClassRule
public static final DropwizardIntegrationAppRule<Config> app1 = new DropwizardIntegrationAppRule<>(Service.class);

The second option is cleaner and much like yours.
private static final MongoDContainerRule mongo = new MongoDContainerRule();

private static final DropwizardIntegrationAppRule<Config> app = new DropwizardIntegrationAppRule<>(Service.class);

@ClassRule
public static final RuleChain chain = RuleChain
        .outerRule(mongo)
        .around(app)

MongoDContainerRule is like your wrapper but it also sets the right port through system properties.
public class MongoDContainerRule extends MongoDBContainerBase {

    private static final GenericContainer mongodb = new GenericContainer("mongo:latest").withExposedPorts(27017);

    @Override
    protected void before() throws Throwable {
        mongodb.start();
        System.setProperty("dw.mongoConfig.uri", "mongodb://" + mongodb.getContainerIpAddress() + ":" + mongodb.getMappedPort(27017));
        System.setProperty("dw.mongoConfig.tls", "false");
        System.setProperty("dw.mongoConfig.dbName", DB_NAME);
    }

    @Override
    protected void after() {
        mongodb.stop();
    }
}

The container will expose mongodb on a free port. mongodb.getMappedPort(internalPort) will return it. System.setProperty("dw.*") injects values into the dropwizard config.


text:
Q: DREAMFACTORY : Create User with Suspended State and Activate them with custom URL First i will explain what i need in Dreamfactory. After that i will explain the problem which i am facing.
I want to create a user registration form my back end is Dreamfactory and front end is Angular,
My open Registration options is enabled in Dreamfactory, Initially when registering a user with the URL "https://.cloud.dreamfactory.com:443/rest/user/register" The user's Conformation column and Active Column should be set to FALSE. After the Success Registration i need to send a E-Mail with my custom URL to the mail ID (NOTE : i like to have the activation code in URL itself ).
The user should redirect to my website after clicking the URL in mail (NOT TO DREAM FACTORY WEBSITE). from there i should retrieve the activation code from the URL and generate a POST request from angular to make the Active Column and Conformation column to SET TRUE.
Now i will explain the problem i am facing.
I created the POST request to register user with URL
"https://APP-NAME.cloud.dreamfactory.com:443/rest/user/register"
{
'display_name' : NAME,
'email' : EMAIL,
'first_name' : FIRST NAME,
'last_name' : LAST NAME,
'new_password' : PASSWORD,
'is_active' : false,
'confirmed' : false
}

but "is_active" and "confirmed" column is not setting to false. its still TRUE in DSP admin panel. I don't know why.
After this
It will be helpful for me if anyone explain how to generate a activation code and pass it through URL and receive in Angular.. After that How to post request to DSP and make that particular user Active and Confirmed.
Thanks in Advance.

A: Currently the API does not support setting the active flag during registration. However, if you're using the confirmation code for registration, then this effectively makes the user inactive until they have confirmed their code. If the user tries to login without having confirmed their code they will get an error indicating they have not yet confirmed.