text:
Q: Can I make a method in an abstract class which constructs an instance for the instantiating class? I have two classes that extend an an abstract Model. Both classes implement a method called instance() to basically ensure that there is only one instance of the class at any time. The structure of instance() is exactly the same for both classes, so I thought it would be nice to move it up a level to the abstract class. However, the method calls the instantiating class' default constructor. Is it possible to call this constructor from the abstract class? If so how? What other approaches might work for generalizing this method?
Simplified Example Classes
I have an abstract class for a Model which looks like
public abstract class Models{
    public List<Model> models = new ArrayList<Model>();

    /** load the different models, with the models with pre-trained model*/
    public abstract void load();
}

And two instanciating classes which like this
 public class PageLanguageModels extends Models {
     /** ensure we only call one of them */
     protected static PageLanguageModels _instance = null;
     static Logger logger = Logger.getLogger(ProductLanguageModels.class.getName());

     public static synchronized PageLanguageModels instance() {
         if (_instance == null) {
             try {
                 _instance = new PageLanguageModels();
                 _instance.load();
             } catch (Exception e) {
                 logger.log(Level.SEVERE, "Couldn't load language models.", e);
             }
         }

         return _instance;
     }

     /** load the different models, with the models with pre-trained model*/
     @Override
     public void load() {
         models.clear();
         models.add(new BOWModel());
     }
 }

 public class ProductLanguageModels extends Models {
     /** ensure we only call one of them */
     protected static ProductLanguageModels _instance = null;
     static Logger logger = Logger.getLogger(ProductLanguageModels.class.getName());

     public static synchronized ProductLanguageModels instance() {
         if (_instance == null) {
             try {
                 _instance = new ProductLanguageModels();
                 _instance.load();
             } catch (Exception e) {
                 logger.log(Level.SEVERE, "Couldn't load language models.", e);
             }
         }

         return _instance;
     }

     /** load the different models, with the models with pre-trained model*/
     @Override
     public void load() {
         models.clear();
         models.add(new Word2VecModel());
     }
 }

Attempted Approaches
I have tried using a factory method pattern, but this doesn't work because instance is a static method and the abstract factory method cannot be called from a static method.

Cannot make a static reference to the non-static method makeModels()
  from the type Models

public abstract class Models{

    /** load the different models, with the models with pre-trained model*/
    public abstract void load();

    //Factory method
    public abstract Models makeModels();

    // Instance code moved up from instanciating classes
    protected static Models _instance = null;
    static Logger logger = Logger.getLogger(Models.class.getName());

    public static synchronized Models instance() {
        if (_instance == null) {
            try {
                _instance = makeModels();
                _instance.load();
            } catch (Exception e) {
                logger.log(Level.SEVERE, "Couldn't load language models.", e);
            }
        }

        return _instance;
    }
}

A: I don't think you can move all of your instantiating logic to a parent class due to its static nature and issues regarding type erasure, but you surely can organize your code in order to make it reusable. I wrote a simple copy/paste example for you by changing your design just a little bit with focus on the instantiation part, so I left out some attributes and logging code:
An interface
public interface Models {
    void load();
}

An abstract implementation
public abstract class BaseModels implements Models {

    protected static <T extends Models> T instance(Class<T> type, T candidate) {
        if (candidate == null) {
            try {
                candidate = type.newInstance();
                candidate.load();
            } catch (InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return candidate;
    }
}

A concrete implementation
public class HeroModels extends BaseModels {

    static HeroModels instance;

    public static HeroModels instance() {
        instance = instance(HeroModels.class, instance);
        return instance;
    }

    @Override
    public void load() {
        System.out.println("Loading HeroModels...");
    }
}

A simple test case
public class TestDrive {

    @Test
    public void testEquality() {

        HeroModels a1 = HeroModels.instance();
        HeroModels a2 = HeroModels.instance();

        Assert.assertEquals(a1, a2);

        System.out.println("a1: " + a1);
        System.out.println("a2: " + a2);
    }
}

Test case output
Loading HeroModels...
a1: HeroModels@736e9adb
a2: HeroModels@736e9adb
From the output you can see that the HeroModels class was loaded only once. The instance(...) method in BaseModel class is made protected to make clear it is intended to be used by children, which may have their own static instance attribute.

A: Yes, but you might want to extract it to a separate class.


text:
Q: Disable only the main feed? It's possible to make a site totally inaccessible via feeds (RSS, Atom, RDF) with a function like this:
function itsme_disable_feed() {
    wp_die( __( 'No feed available, please visit the homepage!' ) );
}
add_action('do_feed', 'itsme_disable_feed', 1);
add_action('do_feed_rdf', 'itsme_disable_feed', 1);
add_action('do_feed_rss', 'itsme_disable_feed', 1);
add_action('do_feed_rss2', 'itsme_disable_feed', 1);
add_action('do_feed_atom', 'itsme_disable_feed', 1);
add_action('do_feed_rss2_comments', 'itsme_disable_feed', 1);
add_action('do_feed_atom_comments', 'itsme_disable_feed', 1);

But that disables feeds for the entire site i.e. the main feed, feeds for categories, tags, comments, posts, pages, custom post types, etc.
How do I disable just the main feed and the main comments feed of the site? i.e. only make site.com/feed/ and site.com/comments/feed/ inaccessible.
Simply hiding feed using something like this (below) isn't an option:
remove_action( 'wp_head', 'feed_links_extra', 3 );
remove_action( 'wp_head', 'feed_links', 2 );

A: Very, very quick unscientific research suggests that there is only one query_var set for the main feed. Other feeds such as category, tag, author feeds have more than one query_var. Thus the following should kill the main feed but leave others intact.
add_filter(
  'pre_get_posts',
  function($qry) {
    if ($qry->is_feed()) {
      $fvars = array_filter($qry->query_vars);
      if (1 == count($fvars)) {
        wp_die( __( 'No feed available, please visit the homepage!' ) );
      }
    }
  },
  1
);

To remove the main comment feed, you need a small edit to check for the presence of $fvars['withcomments'].
add_filter(
  'pre_get_posts',
  function($qry) {
    if ($qry->is_feed() ) {
      $fvars = array_filter($qry->query_vars);
      if (1 == count($fvars) || isset($fvars['withcomments'])) {
        wp_die( __( 'No feed available, please visit the homepage!' ) );
      }
    }
  },
  1
);

Be warned: Barely tested. Possibly buggy. Caveat emptor. No refunds.

A: This is a modded version of @s_ha_dum answer.
I'm agree with him that when in main feed the only variable setted is 'feed' (for posts feed) and 'withcomments' for main comment feed, but instead of relying on current query object variables, and filter the many empty defaults using array_filter, I think that - probably - is more reliable looking at $wp->query_vars: an array that contain only the query variables effectively used to run the query:
add_action('pre_get_posts', 'no_main_feeds', 1);

function no_main_feeds( $q ) {
  if ( is_feed() || is_comment_feed() ) {
    $vars = $GLOBALS['wp']->query_vars;
    unset( $vars['feed'], $vars['withcomments'] );
    if ( empty($vars) ) wp_die( 'No feed available' );
  }
}

The check for is_comment_feed() is actually needless, because when in main comment feed is_feed() is true, but I think it makes code intentions more clear, probably is also more future proof, and finally it doesn't hurt...
Unlike other answers here it (should) works with any permalink structure and also if pretty permalinks are disabled at all.

A: add_filter('request', 'itsme_disable_main_feeds');

function itsme_disable_main_feeds($q)
{
    $exit_msg   = 'No feed available. Please visit the homepage.';
    $exit_title = 'No Feed Available';

    if (    !empty($q['feed'])         && count($q) === 1
         || !empty($q['withcomments']) && count($q) === 2 ) {

        $exit_msg = sprintf($exit_msg, esc_url( home_url('/') ));
        wp_die( $exit_msg, $exit_title, array('response' => 404) );
    }

    return $q;
}

A: using rewrite rules you can disable a url pattern that match main feed.
add_filter('rewrite_rules_array', 'rewrite_rules_array_feed_disable');
function rewrite_rules_array_feed_disable($rules){
    unset($rules['feed/(feed|rdf|rss|rss2|atom)/?$']);
    unset($rules['(feed|rdf|rss|rss2|atom)/?$']);
    return $rules;
}

A: The hook callback needs to check if it's a tag feed, or if it's a category feed or may be if it's a author feed. You can get a lot of information about the feed being produced if you add this two line in the callback. i.e function itsme_disable_feed(){ ... }
global $wp_query;
die(print_r($wp_query->query_vars));

You will notice that for a tag feed, or a category feed or a comment feed or even for an author feed there are certain parameters which contain values. Just do a check so that if those parameters have any value associated with it, you will do nothing. And if not, which means it's a main feed, you will call die().
Hope it helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to execute CMake's default find module from my own find module with the same name? For some reason I want to extend a find module (FindThreads in my case) to do some specific stuff if CMake's FindThreads fails. For the ordinary developer of other parts of our software system this should happen transparently, such that s/he could call find_package(Threads) as usual, so I don't want to give my own find module an exclusive name.
My idea is to add my own FindThreads.cmake in a folder contained in the CMAKE_MODULE_PATH. Because CMAKE_MODULE_PATH has priority find_package(Threads) will execute my own FindThreads.cmake.
But, inside my own FindThreads.cmake I need to execute find_package(Threads ...) such that it executes CMake's original FindThreads.cmake. How to do that?
If that fails my own FindThreads.cmake should try to add a specific Threads lib.
Unfortunately, there is no option NO_CMAKE_MODULE_PATH for find_package to fall back to CMake's own find modules and it seems not to be possible to pass a search path (for example ${CMAKE_ROOT}/Modules) to find_package to override CMAKE_MODULE_PATH.
Versions

*

*CMake 3.5 on Linux (Ubuntu 16.04)

*CMake 3.14 on Windows

A: You may set CMAKE_MODULE_PATH before find_package call and restore the variable after the call:
# Save old value of CMAKE_MODULE_PATH.
set(CMAKE_MODULE_PATH_OLD ${CMAKE_MODULE_PATH})
# Temporary replace CMAKE_MODULE_PATH
set(CMAKE_MODULE_PATH "${CMAKE_ROOT}/Modules")
# Call find_package() with specific CMAKE_MODULE_PATH set.
find_package(Threads ...)
# Restore CMAKE_MODULE_PATH
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH_OLD})

Note, that FindXXX.cmake is executed in the same scope as the caller code, so restoring CMAKE_MODULE_PATH variable is needed even if your script no longer calls find_package but simply returns.
Also, it is better to use some unique variable's name instead of CMAKE_MODULE_PATH_OLD: it is possible that caller already uses that variable for its own purposes. E.g. you may add some suffix to the variable's name which related to your organization or is unlikely to be used by others.


text:
Q: Vault for Kafka distributed connectors I am using a JBoss based vault to secure sensitive data such as the database credentials.
I use a Java based HTTP REST client to create distributed Kafka connectors but ended up with a security concern such that a request for the connector's "config" exposes the sensitive credentials in the response.
I referred this official documentation but could not get much help in the context of JBoss vault.
Any pointers or references that directly addresses this specific problem is very much appreciated.
Any references to alternate open source (and free to use) Vault based solutions would also be of great help.

A: You'd have to write code that implements the ConfigProvider interface of the Connect API, mentioned there.
You can browse Kafka source code on Github to see the existing File one, but that KIP (which references Hashicorp Vault) and the source files are the only such documentation for now.
Connect doesn't use JBoss, either, so you'd have to find a way around that


text:
Q: GetUrlCacheEntryInfo usage I tried to print out the information given by the function called "GetUrlCacheEntryInfo" but it's not working, it's printing me out only a character in the debug - log. How can i print all the data correctly?

A: Here is a working sample, with an url (https://h6.msn.com/library/8.8/dapmsn.js) that I found in my cache (since I don't use IE this was the first I got from FindFirstUrlCacheEntry. The possbile issue why you could be printing only one character is that maybe you are not using wide string print functions. The lpszSourceUrlName and lpszLocalFileName fields are wide string fields so you should print them accordingly (see usage of std::cout and std::wcout in the sample below).
#include <Windows.h>
#include <Wininet.h>

#include <memory>

#pragma comment(lib, "Wininet.lib")

#include <iostream>

bool GetUrlCacheEntryInfo(const wchar_t* pUrl, std::unique_ptr<unsigned char[]>& pUrlCacheEntryInfo, DWORD nBufferSize = sizeof(INTERNET_CACHE_ENTRY_INFO))
{
    std::unique_ptr<unsigned char[]> pTemporaryUrlCacheEntryInfo(new unsigned char[nBufferSize]);
    if (GetUrlCacheEntryInfo(pUrl, reinterpret_cast<LPINTERNET_CACHE_ENTRY_INFO>(pTemporaryUrlCacheEntryInfo.get()), &nBufferSize) == FALSE)
    {
        const DWORD nError = GetLastError();
        if (nError == ERROR_INSUFFICIENT_BUFFER)
        {
            pTemporaryUrlCacheEntryInfo.reset(new unsigned char[nBufferSize]);
            if (GetUrlCacheEntryInfo(pUrl, reinterpret_cast<LPINTERNET_CACHE_ENTRY_INFO>(pTemporaryUrlCacheEntryInfo.get()), &nBufferSize) == FALSE)
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }
    pUrlCacheEntryInfo = std::move(pTemporaryUrlCacheEntryInfo);
    return true;
}

void PrintUrlCacheEntryInfo(LPINTERNET_CACHE_ENTRY_INFO pUrlCacheEntryInfo)
{
    std::cout << "Cache Entry Info:\n\tSize: " << pUrlCacheEntryInfo->dwStructSize << "\n\tUrl: ";
    std::wcout << pUrlCacheEntryInfo->lpszSourceUrlName;
    std::cout << "\n\tLocal File:";
    std::wcout << pUrlCacheEntryInfo->lpszLocalFileName;
    std::cout << "\n\tType: ";
    switch (pUrlCacheEntryInfo->CacheEntryType)
    {
    case EDITED_CACHE_ENTRY:
        std::cout << "EDITED_CACHE_ENTRY";
        break;
    case SPARSE_CACHE_ENTRY:
        std::cout << "SPARSE_CACHE_ENTRY";
        break;
    case STICKY_CACHE_ENTRY:
        std::cout << "STICKY_CACHE_ENTRY";
        break;
    case TRACK_OFFLINE_CACHE_ENTRY:
        std::cout << "TRACK_OFFLINE_CACHE_ENTRY";
        break;
    case TRACK_ONLINE_CACHE_ENTRY:
        std::cout << "TRACK_ONLINE_CACHE_ENTRY";
        break;
    default:
        std::cout << "UNKNOWN";
        break;
    }
    std::cout << "\n\tHeaders: ";
    std::wcout << pUrlCacheEntryInfo->lpHeaderInfo;
    std::cout << "\n";
}

int main(int argc, char** argv)
{
    const wchar_t* pUrl = L"https://h6.msn.com/library/8.8/dapmsn.js";
    std::unique_ptr<unsigned char[]> pUrlCacheEntryInfo;
    if (GetUrlCacheEntryInfo(pUrl, pUrlCacheEntryInfo))
    {
        PrintUrlCacheEntryInfo(reinterpret_cast<LPINTERNET_CACHE_ENTRY_INFO>(pUrlCacheEntryInfo.get()));
    }
    else
    {
        std::wcout << L"Cache entry for url " << pUrl << L" was  not found!\n";
    }
    return EXIT_SUCCESS;
}


text:
Q: Blazor EditForm DataAnnotationsValidator validates unexpectedly when a custom child component changes state My EditForm with a DataAnnotationsValidator contains a custom component that can modify its own state. The trivial code below provides a repro.
When the button in MyComponent is clicked, validation fires on the form. This occurs even when none of the form fields have been modified, which is unexpected and undesirable.
Is this expected behaviour? If so, how can I avoid the validation being triggered by a change to the child component?
This is occurring in a Blazor Server project running .NET 6.0.3.
Index.razor
@page "/"
@using System.ComponentModel.DataAnnotations

<EditForm Model="model">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <label>
        Name:
        <InputText @bind-Value="model.Name" />
    </label>
    <MyComponent />
</EditForm>

@code {
    MyModel model = new();

    class MyModel
    {
        [Required]
        public string? Name { get; set; }
    }
}

MyComponent.razor
<p>
    MyComponent: @(Switch ? "ON" : "OFF")

    <button @onclick="() => Switch = !Switch">Toggle</button>
</p>

@code {
    bool Switch = false;
}

A: In your MyComponent, set the type to button:
<button type="button" @onclick="() => Switch = !Switch">Toggle</button>

For most (you can interpret this as meaning pretty much "all") browsers the default type of button is submit. In Blazor, validation is triggered when a form is submitted, in other words when a button in the EditForm with a type of submit is clicked. This is why you need to set the type to button.
I recommend reading the following article about the type attribute on buttons for some more background.


text:
Q: Many app store apps, one start screen I want users to download different apps within a suite, think MS Office, but have one main screen to pick each app from. Users can add (or remove) apps by downloading them from Google, etc.

*

*I don't want users to have to have multiple copies of the same start screen, one in each app, if possible, because I want to minimize internal or external memory storage use.

*Alternately, If you download and instal one app from my suite, can I use that to really install two apps, the useful app and a second mainscreen app that wont be installed if you have it already installed via another of my programs from my suite? I don't want the user bothered with options or HAVE TO download 2 apps. I want to allow users to install or uninstall apps as needed.

*If I start an app from the one apps "select which app you want", how do I make the second app in my suite open, e.g. Word, without opening the second apps "select which app you want" start screen. [e.g. should I send intents between apps, or have alternate start activities in the manifest?]

*Can I install new apps, but and then delete duplicate app select menu images within the new program if another program has already installed the app select menu screen.
Suggestions and or code welcome.

A: *

*Your approach is very honourable.

*Apps and apks do not have any programmatic control over what is being installed and what not during the installation process and are lacking the rights to alter their installation afterwards, so "install one or two apps" will not work as you describe it.

*You can launch the other app with a different intent or with intent extras, so avoiding the other splash screen wouldn't be a problem.

I'd say you'll have to have the splash screen code in all of your apps unless you publish your splash screen/dashboard as the only app of the suite and allow the user to download the suite's single functionalities as expansion files, which may or may not suit and/or complicate your licence approach.


text:
Q: str2double returning NaN MATLAB I have a vector of rock types, in the form
Rock_1             '1' % What I get after use regexp%
Rock_2             '2'
.                  .
.      --------->  .
.                  .
Rock_n             'n'

I'm interested in the number of the rock so I managed to get it using
Rocks = regexp(P(:,3),'\d*','Match')

Then I need to convert the cell array of numbers in a matrix of numbers, for statistical treatment. The problem is that after using str2double I get an array full of NaNs. I can't see what I'm doing wrong. Help please.
Many thanks.

A: I think your problem is that the output from regexp is a cell array of cell arrays of strings (i.e. two levels of cell encapsulation), but you want it to be a cell array of strings. You can achieve that by adding the 'once' option to the call to regexp. Then you will get a cell array of strings that can be passed to str2double:
>> P = {'Rock_1', 'Rock_2', 'Rock_3'};  % Sample data
>> Rocks = regexp(P, '\d*', 'match');   % How you did it above
>> str2double(Rocks)

ans =

   NaN   NaN   NaN

>> Rocks = regexp(P, '\d*', 'match', 'once');  % With the 'once' option
>> str2double(Rocks)

ans =

     1     2     3


text:
Q: Python allow accepting two strings depends on cases I found the error when I read excel using openpyxl library that the library reads '[Content_Types].xml' while all my .xlsx files to read contains '[content_types].xml'.
The library calls the file by string ARC_CONTENT_TYPES = '[Content_Types].xml' and read the file by
def read_manifest(self):
    src = self.archive.read(ARC_CONTENT_TYPES)
    root = fromstring(src)
    self.package = Manifest.from_tree(root)

I would like to change it to accept both '[Content_Types].xml' and '[content_types].xml' so that the library can accept both cases.
Will there be any helpful tips or any other methods to solve my issue?

A: Almost a year ago and I forgot to put how I managed it. I basically fixed the related python library so that it can accept both cases by putting 'if ... else ...' condition into the library.
if xmlstring.startswith('c'):
    ARC_CONTENT_TYPES = '[content_Types].xml'
else:
    ARC_CONTENT_TYPES = '[Content_Types].xml'


text:
Q: Documenting Blender Python code with Sphinx Blender runs its own Python. When I write Python code like this
import bpy
print(bpy.data.objects)

for Blender it runs fine with
$ blender --background --python my_code.py
<bpy_collection[3], BlendDataObjects>

But when I want to document my code with Sphinx and the autodoc extension it cannot import bpy because it is unknown outside Blender.
$ cd doc/
$ make html
[...]
ModuleNotFoundError: No module named 'bpy'

How can I create documentation output for my Blender code with Sphinx?

A: The solution involves modifying the Makefile generated by sphinx-quickstart as well as writing a little wrapper script around sphinx.cmd.build:
Replace the SPHINXBUILD variable in the Makefile:
SPHINXBUILD = blender --background --python blender_sphinx.py --

and make sure that the actual recipe line at the end of the file contains the -M flag.
Then create a file blender_sphinx.py in the same directory as the Makefile with the following contents:
import sys
from sphinx.cmd import build

first_sphinx_arg = sys.argv.index('-M')
build.make_main(sys.argv[first_sphinx_arg:])

Now if you run
$ make html

from the doc/ directory it will allow autodoc to find bpy and import all the modules.

A: There's another option: Using a fake (i.e. empty) bpy module: https://github.com/nutti/fake-bpy-module
You can install this simply via pip:
pip install fake-bpy-module-<version>

Afterwards, your Sphinx (i.e. the Python build used by Sphinx) will import these modules instead of the blender modules.
Note: I'm not the author and I don't know how this module works with Blender's GPL license.


text:
Q: Is there a way to know in Javascript percentage of HTML5 Video initial buffer percentage? Is there a way to retrieve the length needed to be buffered before a HTML5 video start to play? And also retrieve how much was buffered?
I've seen that question HTML5 Video - Percentage Loaded?, but it applies to video after started playing.

A: You can look at the buffered property. It returns a TimeRanges object. For more info, see here.


text:
Q: Web worker with Angular not updating view I have two files 1) app.js 2) worker.js
I try to update the $scope.time but it is not showing in the view. It is my first time with webworkers.
app.js
angular.module('App', [])

.controller('MainCtrl', ['$scope', '$window', function($scope, $window) {

    $scope.time = 100;

    var worker = new Worker('worker.js');

    worker.onmessage = function(e) {

        $scope.time = e.data.time;

      };

    worker.postMessage($scope.time);

}]);

worker.js
 self.onmessage = function(e) {
 var time = e.data;

 var timer = setInterval(toDo,1000);

 function toDo(){

   time = time-1;
   postMessage({
     time:time
   });

  }

}

A: When worker.onmessage is triggered it is going to be outside the Angular digest cycle. So even though you have updated the model, Angular does not know that it needs to update the views. In order for you to notify Angular that a new digest cycle has to happen you need to call $scope.$apply()
worker.onmessage = function(e) {
   $scope.$apply(function(){
      //do model changes here
      $scope.time = e.data.time;
   });
};

Instead of passing an anonymous function to $scope.$apply you could just do the changes and then call $scope.$apply() with no arguments. But I believe it is preferred that you use the anonymous function with $apply as it does under the hood work like wrapping it in try...catch.
$scope.time = e.data.time;
$scope.$apply();


text:
Q: Problem using Hibernate Projections I'm using Richfaces + HibernateQuery to create a data list. I'm trying to use Hibernate Projections to group my query result. Here is the code:
final DetachedCriteria criteria = DetachedCriteria
     .forClass(Class.class, "c")
     .setProjection(Projections.projectionList()
     .add(Projections.groupProperty("c.id")));
     ...

in the .xhtml file i have the following code:
  <rich:dataTable width="100%" id="dataTable" value="#{myBean.dataModel}" var="row">
<f:facet name="header">
 <rich:columnGroup>
                 ......
 </rich:columnGroup>
</f:facet>
<h:column>
 <h:outputText value="#{row.id}"/>
</h:column>
<h:column>
 <h:outputText value="#{row.name}"/>
</h:column>

But when i run the page it gives me the following error:
Error: value="#{row.id}": The class 'java.lang.Long' does not have the property 'id'.

If i take out the Projection from the code it works correctly, but it doesn't group the result. So, which mistake could be happening here?
EDIT: Here is the full criteria:
final DetachedCriteria criteria = DetachedCriteria.forClass(Event.class, "e");

...
        joins....
...

criteria.setProjection(Projections.distinct(Projections.projectionList()
        .add(Projections.groupProperty("e.id").as("e.id"))));

getDao().findByCriteria(criteria);

if i take the "setProjection" line it works fine. I don't understand why it gives that error putting that line.
Here is the query i'm trying to do:
select e.event_id from event e
inner join event_product_group epg
  on e.event_id = epg.event_id
inner join product_group pg
  on pg.product_group_id = epg.product_group_id
where pg.description like '%TEXT%'
group by e.event_id

A: ok if you are just wanting to project the unique id of an event then you do not need the group by.  Just use Projections.id().  Grouping by a unique id is just going to give you this list of ids anyway.
If you have unique idents 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 and you have a query that returns 1, 2, 3, 4 and tell it to group by the id then it is going to make 4 'groups' since those are unique ids :)
edit: well the project list and a collection of projection objects so you can append as many projection items as you want on there.  Just keep adding them.  I believe you use Projections.property("property_name").
edit2: also which what you are doing you don't really need criteria.  you could use HQL.


text:
Q: Equivalents definition of linear convergence Suppose that the sequence $\{x_n\}$ converges to $0$.
I want to prove that these definitions are equivalent:
a) We say that $\{x_n\}$ converges linearly to $0$, if there exists a number $q \in (0, 1) $ and a constant $C>0$ such that $x_n \leq C q^n$ for all $n \in \mathbb{N}$
b) We say that  $\{x_n\}$ converges linearly to $0$, if there exists a number $q \in (0, 1) $ and  constants $C>0$, $n_0 \in \mathbb{N}$ such that $x_n \leq C q^n$ for all $n \geq n_0$.
Clearly $a)\Rightarrow b)$.
Does $b)\Rightarrow a)$ ? How could I prove it?

A: We have $x_n \leq Cq^n \leq Dq^n$ for all $n\geq n_0$, if $C\leq D$. With this,
$$D = \max\left\{C,\frac{x_1}{q^1},\dots, \frac{x_{n_0}}{q^{n_0}}\right\}$$
is a suitable constant for a).


text:
Q: Azure App Service CORS MissingAllowOriginHeader Error I have a Web Application and Web API (both .NET Core) hosted in Azure App service. The Web API is behind Azure App Gateway. The Web App's client side script calls the Web API (HTTP PUT) through the app Gateway endpoint which results in a CORS policy error.
The Web API has the below code in the startup.cs.
services.AddCors(options =>
            {
                options.AddPolicy(name: MyAllowSpecificOrigins,
                                  builder =>
                                  {
                                      builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().Build();
                                  });
            });

The App Gateway has a ReWrite rule configured as follows:
If Access-Control-Request-Method == "PUT", then set the Response Headers:
access-control-allow-headers: content-type
access-control-allow-methods: PUT
access-control-allow-origin: https://webappurl

With this configuration, I can see that the Pre-flight OPTIONS request gets a 200 response with the above headers in the response. However, the subsequent HTTP PUT request to https://apipurl results in an error:

Cross-Origin Resource Sharing Error: MissingAllowOriginHeader

As an additional step, I also added the Web App URI to Web API App Service's allowed origins:
az webapp cors add --resource-group testrg --name appsvcwebapi --allowed-origins 'https://webappurl'

Why is this CORS error still showing up despite the Pre-Flight HTTP 200 response and the access-control-allow-* response headers?

A: Try with adding the CORS services. In the Configure method of your startup.cs.
Example:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {

 app.UseCors(MyAllowSpecificOrigins);

    }

For more details refer this document
And also  try with setting  the access-control-allow-origin in correct way
Access-Control-Allow-Origin : *

OR
Access-Control-Allow-Origin : http://www.my-domain.com


text:
Q: I can't export scraped data in CSV I can't get all data in CSV, only last. When scraping is done only last one scraped is saving CSV file but I want to save from all pages.
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
import time
import pandas as pd
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
mainurl = 'https://austin.craigslist.org/search/cta?s=0'
driver.get(mainurl)
res = driver.execute_script("return document.documentElement.outerHTML")
page_soup = BeautifulSoup(res, 'html.parser')

lnk_opener = driver.find_element_by_xpath('//*[@id="sortable-results"]/ul/li[1]/p/a').click()
time.sleep(4)
records = []
i = 1
while i <3:
    i+=1

    try:
        print(driver.current_url)
    except Exception:
        print('Internet Error Detected')

    try:
        title = driver.find_element_by_xpath('//*[@id="titletextonly"]').text
        print(title)
    except Exception:
        print('No Title Given')
    try:
        price = driver.find_element_by_xpath('/html/body/section/section/h2/span/span[2]').text
        print(price)
    except Exception:
        print('No Price Given')
    try:
        phone = driver.find_element_by_xpath('//*[@id="postingbody"]/h2[1]/big').text
        print(phone)
        records.append((phone))
    except Exception:
        print('No Mobile number avalible')
    try:
        loc = driver.find_element_by_xpath('/html/body/section/section/section/div[1]/div/div[2]').text
        print(loc)
    except Exception:
        print('No Location Data Avalible')
    try:
        img = page_soup.find('img')
        immg = print(img.get('src','\n'))
    except Exception:
        print('No img Found')

    nxtpg = driver.find_element_by_xpath('/html/body/section/section/header/div[1]/div/a[3]')
    nxtpg.click()
    time.sleep(4)
    url = driver.find_element_by_xpath("/html/body/section/section/header/div[1]/div/a[3]").get_attribute("href")
    if url == None:
        bckbtn = driver.find_element_by_class_name('backup').click()
        time.sleep(5)
        nextbuttton = driver.find_element_by_xpath('//*[@id="searchform"]/div[3]/div[3]/span[2]/a[3]').click()
        time.sleep(6)
        print(records)

records.append((driver.current_url, title, price, loc, immg))
df = pd.DataFrame(records, columns=['Product Url', 'Title/Model/Make', 'Price', 'GM Location', 'Image Link'])
print(df)
df.to_csv('zzz.csv')
time.sleep(4)
driver.quit()

A: I think this line
records.append((driver.current_url, title, price, loc, immg))

should be inside the while statement. Also, move i += 1 to the end of the statement, otherwise you're skipping the first iteration.


text:
Q: Referencing Eigen Matrices I expected that when I create an Eigen matrix and set it equal to another matrix, that I would see reference semantics. Specifically, I expected the output of this
#include <iostream>
#include "Eigen/Dense"

using Eigen::MatrixXd;
using Eigen::VectorXd;

int main() {

    MatrixXd A = MatrixXd::Identity(1, 2);
    MatrixXd B = A;
    A(0, 0) = 4;
    std::cout << "A: " << A << std::endl;
    std::cout << "B: " << B << std::endl;
    return 0;
}

to be
A: 4 0
B: 4 0

but I actually get
A: 4 0
B: 1 0

So I guess Eigen is using copy semantics for these constructors. But if I explicitly reference the input (like in a class constructor), I still seem to be getting copy semantics. Specifically, the output of
#include <iostream>
#include "Eigen/Dense"

using Eigen::MatrixXd;
using Eigen::VectorXd;

class Holder {

public:
    MatrixXd mat;

    Holder(MatrixXd &A) : mat(A) {
    }
};

int main() {

    MatrixXd A = MatrixXd::Identity(1, 2);
    Holder C(A);
    A(0, 0) = 4;
    std::cout << "A: " << A << std::endl;
    std::cout << "C: " << C.mat << std::endl;
    return 0;
}

is
A: 4 0
C: 1 0

So the question is... why does it seem like Eigen is copying the matrices instead of referencing them?
Also, in the end I would like to define a single matrix (e.g. A in the above example), then create many instances of the Holder class, where each instance has a reference to the same matrix. Specifically, I want the behavior that modifying A modifies the matrices in the Holder classes. The catch is that I cannot modify the Holder class itself. So, for instance, I could not change the Holder class to save a pointer to A instead of A itself. How would I accomplish that?
I have scoured the Eigen docs, but can't seem to find the explanation.

A: Eigen is copying because you are asking it to copy. If you want to have a reference to a Matrix, you have to specify it using the correct syntax. In C++, reference variables are specified with the & character:
MatrixXd A = MatrixXd::Identity(1, 2); // this is an object
MatrixXd& B = A; // this is a reference to an object (notice the &)


text:
Q: Tell suspended chat users which messages were flagged It appears there is a "feature" that's always existed where I get suspended from chat for having messages flagged.
It is annoying that suspended users do not get told why they were suspended.
Can we have a list of which messages were flagged when we get suspended.
At least this way people can learn why they were suspended and not do it again in the future.
As a further aside, the fact a room owner can get suspended for flagged messages in his room is rubbing salt in my wounds.

A: I suspect that some people treat "flags" like an opposite for "stars". Like a dislike button. That could be one of the reasons why people get flagged almost randomly.

A: This may just be Jeff's staff not listening to him: http://www.codinghorror.com/blog/2010/03/the-opposite-of-fitts-law.html .
Many of these flags might just be human error because we put the FM Radio next to the Ejector Seat button.

I can tell what you're thinking. Did he click Flag or Star Now? Well, to tell you the truth, in all the excitement of reading that message, I kind of lost track myself. Good thing we can easily undo a flag'd item! Oh wait, we totally can't.
To make it worse, the star is always highlighted on mouse-over of any of these items.

A: OK, I ran the queries. Your must "popular" remarks are:

*

*(redacted) you deserve to be called an idiot for writing code like that

*(redacted) because windows is for gays. gays

*Look google is full of shit

*dont like me random shit please.

*If I want my website to look like shit then I'll ask you

*I simply consider non english language noise and spam

*shit

*(redacted) don't be a dick :D

*Fuck thread safety

*(redacted) Anger issues my ass!

*my f key is acting up

*(redacted) I just defined a language limitation in this room

*You want to speak in a foreign tongue then take it somewhere else.

where "(redacted)" is any other user, just to keep it context free.
I think the flags were correctly earned. My main thought now is at what point the system should escalate the suspension time, or whether to just keep that manual. Please remain civil in the chats; it isn't an open forum for abusing people, nor an outlet for homophobia and xenophobia.
I will, however, think about ways in which we can make the "why was I suspended" automated so there is no uncertainty. In other news, there is a secondary issue with people using flags incorrectly; in this case, I don't think that applies.


text:
Q: Why dynamic radiobutton color is white? I read from a file a lot of data, and i a would like to create the ui from this. I create a lot of textview and a radiobutton, but when i try this on device or emulator i got white text everywhere, why?
If i create a radio button in the xml it is black! but my dynamic radio button color is white :(
public void buildScreen(){

    TextView header = new TextView(context);
    header.setText(dataManager.getHeaderString()+"\n"+dataManager.getqType());
    dataManager.setMainTable(tbl);

    TableRow row;
    for (Map.Entry<String, SimpleQuestionModel> entry : dataManager.getqDict().entrySet()){
        String question = entry.getKey();
        SimpleQuestionModel model = entry.getValue();

        row = new TableRow(context);
        TextView tv = new TextView(context);
        tv.setText(model.getQuestion());
        dataManager.getMainTable().addView(tv);

        RadioGroup rg = new RadioGroup(context);
        rg.setOrientation(RadioGroup.VERTICAL);
        for (int j=0;j<model.getAnswers().size();j++){
            RadioButton rb = new RadioButton(context);
            rb.setText(model.getAnswers().get(j));

            rg.addView(rb);
        }
        dataManager.getqAndA().put(tv, rg);
        row.addView(rg);
        dataManager.getMainTable().addView(row);

    }

}

Here is my class constuctor:
public UIBuilder(Context context, TableLayout tbl) {
    this.context = context;
    this.tbl = tbl;
    dataManager = DataManager.getInstance();
    DataReader dataReader = new DataReader();
    dataReader.readDataFromFile("first.txt");
}

And i call this class like this:
 builder = new UIBuilder(getApplicationContext(), tbl);

    builder.buildScreen();

and tbl is a tablelayout in my xml

A: Always use the Activity as the Context when instantiating widgets, if you want your theme to be honored. Using any other Context will just use the stock system theme.
This blog post by Dave Smith explains when to use what Context, including mentioning this problem.


text:
Q: 2d laplace equation with neumman boundary condition $$\Delta u(x,y)=0$$
$$x,y\in(0,1),$$
$$\frac{\partial u(0,y)}{\partial x}=0,\quad \frac{\partial u(1,y)}{\partial x}=0,\quad\frac{\partial u(x,0)}{\partial y}=0,\quad\frac{\partial u(x,1)}{\partial y}=\frac{1}{2}-x$$
Are the boundary conditions contradicting each other? $\frac{1}{2}-x$ only admit $\sin(2n \pi x)$ which violates boundary conditions at $(0,y) $ and $(1,y)$
MY attempted solution: finite fourier transform on the $x$ domain, then figure out the coefficient which runs into the above problem.
Can anyone enlighten me what is wrong with my method or the boundary condition? Thanks!

A: Laplace equation has solutions that are very restricted! One boundary condition determines the set of solutions, but it's still an infinite series of solutions, so the other boundary condition can be satisfied via Fourier series.
In your case, the Neumann boundary condition suggests functions
$$\cos(n \pi x)\cosh (n\pi y)$$
Notice several things: first of all, cosine is the one that has zero derivative at the boundary. Secondly, it's perfectly valid to have a half-period on the domain (no $2$ inside the cosine). And thirdly, I constructed a harmonic function that automatically satisfies also the boundary condition at $y=0$. In general, you would use both $\sinh$ and $\cosh$ or $\exp(\pm n\pi y)$, but $\cosh$ already has zero derivative at $y=0$ so we're done there.
Why precisely this function? Well, Laplace equation is satisfied by complex analytical functions, and it's not difficult to extend cosine to the complex plane. The above can be obtained from superposition of $\Re e^{\pm in\pi z}$ where $z=x+iy$.
Now your solution reads as
$$\sum_{n=1}^\infty a_n \cos(n \pi x)\cosh (n\pi y)$$
Notice that Laplace equation only permits a one-parametric family of solutions. Now you need to determine the coefficients $a_n$. This is almost trivial, because you just plug in $y=1$:
$$\frac12-x=\frac{\partial}{\partial y}\sum_{n=1}^\infty a_n \cos(n \pi x)\cosh (n\pi y) |_{y=1}$$
$$\frac12-x=\sum_{n=1}^\infty a_n n\pi \cos(n \pi x)\cosh (n\pi)$$
This is just a cosine Fourier transform. If you don't want a hassle with getting all the prefactors wrong, just multiply by $\cos (m\pi x)$ on both sides and integrate. Orthogonality will take care of the rest, and you will get $a_n$ in terms of coefficients of the left side.


text:
Q: How to get signed content from pkcs7 attached signature using Bouncy Castle using following code; when i tries to get access the signed from the PKCS7 attached  signature.
  cms = new CMSSignedData(envelopedData); //PKCS7 envelope
  String signedData = new String((byte[])cms.getSignedContent().getContent());

I got the output like this.
nº™(5š?¶ÁNšc«n'¶˜Êõûøˆ'<ùæB0¸ð¿ø"˜ZÊ×`—õWøž8¹¨c¼'Ç{¥é×Æx¢ôãÕ›|?€çžÆ3ÔÜç&¦¤X"õ·3c'Gž\³Ö/€Á<ž²¬ÿµƒÉâw…«b›¤?¤1®kB•ô?³Á2€¦?r`!¦÷nt¯*Ÿ

Same thing works fine for detached signature. For attached signature, i used the following code.
CMSSignedData sigData = gen.generate(msg, true);

Even. I tried all the charsets for the signedData String.

A: I found the problem and resolved it. It was due to the double signing process.


text:
Q: Exit loop in Fortran MPI I would like to ask about how to exit a loop in Fortran when using MPI with a condition sent by the master processor of rank = 0.
Actually I'm doing this as below. But every processes is stuck with the loop and the calculation does not end as expected. Do you know what I'm missing ?
loop: do i = 1, N
        if (rank == 0) then
            [master processor works]
        end if
        MPI_BCAST some value "dE" to every other processes
        if (dE < error) then
           exit loop
        end if
      end do loop


text:
Q: tableView Index # for Numbers? I have an indexed tableView that displays a list of songs from the user's iPod library.  But the sections start with 1, 2, etc., because I have songs that start with numbers.  How do I group all songs that start with a number into a section '#' in my index?
Right now this is my app (left) compared to what I'd like it to be (right, Music.app).  I've highlighted where the # should go (at the end of my index):

This is my code so far in my viewDidLoad:
songsQuery = [MPMediaQuery songsQuery];
songs = [songsQuery items];

NSMutableDictionary *songsInitials;

songsInitials = [[NSMutableDictionary alloc]init];
self.alphabetArray = [[NSMutableArray alloc] init];

for (int i=0; i< songs.count; i++)
{
    NSString *firstletter=[[[songs objectAtIndex:i] valueForProperty:MPMediaItemPropertyTitle] substringToIndex:1];

    if (songsInitials[firstletter] == nil) {
            songsInitials[firstletter] = [[NSMutableArray alloc] init];
            [self.alphabetArray addObject:firstletter];
    }

    [songsInitials[firstletter] addObject:songs[i]];

}

[self.alphabetArray sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];   //sorting array in ascending array

self.songsInitials = songsInitials;

....and my tableView data source:
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _alphabetArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return [_songsInitials[_alphabetArray[section]] count];
}

-(NSString *)titleForRow:(NSIndexPath *)indexpath{

    NSString *firstLetter = _alphabetArray[indexpath.section];
    MPMediaItem *myItem = [_songsInitials[firstLetter] objectAtIndex:indexpath.row];

    return [myItem valueForProperty:MPMediaItemPropertyTitle];
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    return self.alphabetArray;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{

    NSIndexPath *indexpath;

    for (int i=0; i < self.alphabetArray.count; i++)
    {
        NSString *titleToSearch=[self.alphabetArray objectAtIndex:i];  //getting sectiontitle from array
        if ([title isEqualToString:titleToSearch])  // checking if title from tableview and sectiontitle are same
        {
            indexpath=[NSIndexPath indexPathForRow:0 inSection:i];
            // scrolling the tableview to required section
            [self.songsTable scrollToRowAtIndexPath:indexpath atScrollPosition:UITableViewScrollPositionTop animated:YES];
            break;
        }
    }
    return indexpath.section;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.textLabel.text= [self titleForRow:indexPath];  //getting cell content

    return cell;
}

This is what I've tried so far, adjusting the for loop in viewDidLoad:
for (int i=0; i< songs.count; i++)
    {
        NSString *firstletter=[[[songs objectAtIndex:i] valueForProperty:MPMediaItemPropertyTitle] substringToIndex:1];
        if (songsInitials[firstletter] == nil) {
            NSString *songsInitialsFirstLetter = songsInitials[firstletter];

            if ([self stringIsNumeric:songsInitialsFirstLetter]){
                songsInitials[firstletter] = [[NSMutableArray alloc] init];
                [self.alphabetArray addObject:[NSString stringWithFormat:@"#"]];
                NSLog(@"There are numbers!");
            }
            else if (![self stringIsNumeric:songsInitialsFirstLetter]){
                songsInitials[firstletter] = [[NSMutableArray alloc] init];
                [self.alphabetArray addObject:firstletter];
            }

        }

        [songsInitials[firstletter] addObject:songs[i]];

    }

-(BOOL) stringIsNumeric:(NSString *) str {
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    NSNumber *number = [formatter numberFromString:str];
    return !!number; // If the string is not numeric, number will be nil
}

...but it didn't work.  I've searched around but I can't find any other questions that ask this, am I missing something obvious here?  Any help would be much appreciated!  :)

A: Did not test but changing first letter before looking in the arrays would give better result.
After the sort, not sure where the symbol (#) will end tough, you may have to manual push it to the end.
for (int i=0; i< songs.count; i++)
{
    NSString *firstletter=[[[songs objectAtIndex:i] valueForProperty:MPMediaItemPropertyTitle] substringToIndex:1];
    NSScanner *ns = [NSScanner scannerWithString:firstletter];
    if ( [ns scanInt:NULL] )
    {
         firstLetter = @"#";
    }

    if (songsInitials[firstletter] == nil) {
        songsInitials[firstletter] = [[NSMutableArray alloc] init];
        [self.alphabetArray addObject:firstletter];
    }

    [songsInitials[firstletter] addObject:songs[i]];

}


text:
Q: Switch Statement: Execute Code Once If I have a switch statement testing the value of integer i, how can I execute the same code once?
For example:
switch(i) {
case 0:
    if(j == 2) {
        booleanA = true;
        booleanB = false;
case 1:
    if(j == 4) {
        booleanA = true;
        booleanB = false;
}

With 5 different cases, instead of me having to type out
booleanA = true;
booleanB = false;

five times, is there a way to say if one of the if statements is true, use this block of code? Is that possible?
Thanks!

A: You can do it without a switch statement...
    int[] requiredJ = {2,4};
    if (j == requiredJ[i]) {
        booleanA = true;
        booleanB = false;
    }

A: I can not understand logic behind your code, but may be this can be done ( Like switch hit in cricket !!! :p).
Assign the values to your booleans, and revert in default case.
booleanA = true;
booleanB = false;

// more code blocks

switch(i) {
case 0:
    // Process
    break;
case 1:
    // Process
    break;
default :
    booleanA = false;
    booleanB = true;
}


text:
Q: Concatenate PDFs without ruining accessibility or PDF tags Would appreciate your help with the following:
I have 2 partially accessible PDFs (containing tags), and I want to concatenate them using some command line tool (as PDFtk or Ghostscript, or any Perl module):
I've tried doing this with PDFtk and Ghostscript and both output a non accessible PDF without the original tags (each of the concatenated PDFs had tags).
Do you know of any way to implement this with one of the mentioned tools or some other command line tool for Linux?
(Not necessarily freeware)
Perl modules are also an option.
Thanks!

A: pdfunite in-1.pdf in-2.pdf in-n.pdf out.pdf

You can read more in a similar question

A: Solved - new version of iText works (the former, which was the newest when writing the message didn't work- only since 5.4.4 it works).
It's important to mention (was missing in documentation in the past) that
when concatenating documents in tagged mode, you must keep all readers
opened until the resultant document is closed, i.e.:
first:
        document.close();
and only after this:
   reader.close();


text:
Q: Prove that $(p-1)(p-2)\cdots(p-r)\equiv(-1)^rr!(mod\, p) $ for $r=1,2\cdots,(p-1)$ Prove that $(p-1)(p-2)\cdots(p-r)\equiv(-1)^rr!(mod\, p) $ for $r=1,2\cdots,(p-1)$
MY TRY:I know  Wilson's lemma but here ,I am clueless to solve this problem.Thank you

A: Hint:
$$(p-1)\equiv-1\pmod p$$
$$(p-2)\equiv-2\pmod p$$
$$(p-3)\equiv-3\pmod p$$
$$\text{etc.}$$
Multiply the result together and see what you get.

A: Hint: Expand the product and note that any summand containing a factor $p$ gives a contribution of $0$.
Of course you can use induction to formalise the argument.


text:
Q: java Serialize Object to ByteArray Hy guys! I've been searching for some old posts about Serialization in Java.
I want to convert an Object into a ByteArray. So far I´ve done this:
public class test
{

    public static void main(String[] args) throws IOException
    {
        // 00111111 00111111 00111111 11110000  - in bytes: 63, 63, 63, 240
        int x = 1061109744;
        byte[] bytes = null;

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutput out = null;
        try {
            out = new ObjectOutputStream(bos);
            out.writeObject(x);
            bytes = bos.toByteArray();

        }
        finally
        {
            out.close();
            bos.close();
        }

        System.out.println("Lenght: " + bytes.length);

        for(int i=0; i < bytes.length; i++)
        {
            System.out.println(bytes[i]);
        }
    }
}

Apparently it works good but it introduces a lot of "junk" into the ByteArray. The values that really have interest to me are the last 4 bytes that correspond to my "int x = 1061109744;".
Why does this happen?
Is it possible to avoid the "junk" values?
Is it possible to surpass the "signed" values? (I have to write byte values bigger than 128).

A:
Is it possible to avoid the "junk" values?

Yes. Write out an int, not an Object. By passing an int to writeObject, you're promoting it (autoboxing it) to Integer, which means that the serialized information contains header information saying that it's an Integer object, not an int. Your ByteArrayOutputStream has a write(int) method that writes a byte (the low-order 8 bits of the int) to the output stream. Whether those are signed or not is purely a matter of interpretation, not the bits in the stream.

A: Use DataOutputStream and field by field serialization:
ByteOutputStream baos = new ByteOuputStream();
DataOutputStream dos = new DataOutputStream(baos);

dos.writeInt(x);

dos.close();
bytes = baos.toByteArray();

In the byte array all elements are signed (naturally). But if you want to print them unsigned:
for(int i=0; i < bytes.length; i++)
{
    System.out.println(0xFF & bytes[i]);
}


text:
Q: Refit requires Body(BodySerializationMethod.UrlEncoded]) but not required with httpclient I have encountered an issue with refit that took few hours to work out on why calls using refit would result in 403 forbidden whilst using httpclient is fine.
This happens on some servers but not on others.
To Make it work I had to use [Body(BodySerializationMethod.UrlEncoded)].
Cannot work it out why is required though..
I tried all sorts BodySerializationMethod - and googled to see if someone else had encountered the same issue but could not find anything..
any explanations?


text:
Q: Collision detection not working in Android This is the code that I have to detect when two ImageViews collide in Android:
Rect rc1 = new Rect();
brickimg.getDrawingRect(rc1);
Rect rc2 = new Rect();
playerimage.getDrawingRect(rc2);
if (Rect.intersects(rc1, rc2)) {
// intersection is detected
// here is your method call
  button.setText("Shrekt m9");
}
Rect rc3 = new Rect();
brickimg2.getDrawingRect(rc3);
Rect rc4 = new Rect();
playerimage2.getDrawingRect(rc3);
if (Rect.intersects(rc3, rc4)) {
// intersection is detected
// here is your method call
  button.setText("this works");
 }
if(Rect.intersects(rc2, rc3)){
 button.setText("this works too");
 }

When I run the app, it doesn't detect anything. Am I doing something wrong?

A: try like this :
change your Rect as the one of your created rectangle object.
if (rc1.intersects( rc2)) {
// intersection is detected
// here is your method call
  button.setText("Shrekt m9");
}
Rect rc3 = new Rect();
brickimg2.getDrawingRect(rc3);
Rect rc4 = new Rect();
playerimage2.getDrawingRect(rc3);
if (rc3.intersects( rc4)) {
// intersection is detected
// here is your method call
  button.setText("this works");
 }
if(rc2.intersects( rc3)){
 button.setText("this works too");
 }


text:
Q: Help with comparing opamp noise specs I need a DIP package quad opamp which has better output noise than LM324, anything less than 5mV output noise floor would be great.
I could only come across with the following:
LM324: https://www.ti.com/lit/ds/snosc16d/snosc16d.pdf
TL074: https://www.ti.com/lit/gpn/tl074-ep
OP470: https://www.analog.com/media/en/technical-documentation/data-sheets/OP470.pdf
What parameters in data-sheet should be looked at to compare the output noise of the above opamps?
(I know suggestions are not appreciated but would be nice if you have experience with a better(very low noise) IC alternative to LM324)

A: Read a good tutorial, e.g.
Analog Devices - Op Amp Noise
Texas instruments - Understanding Op Amp Noise

A: For most opamp circuits, the noise you see at the output is predominantly amplified input noise.  So you want to look at your input noise specs, both voltage and current noise.  When the surrounding circuit input impedance is significantly higher than their ratio, current noise will dominate the results (since it causes voltage noise across the input impedance), similarly if it is lower, the voltage noise will dominate.
Your choice of opamp will in general depend on the surrounding circuitry, particularly the input: JFET input opamps tend to produce best results with high impedance designs, BJT inputs tend to work better with intermediate to lower impedances.
If you have a smooth well-bypassed power supply, you'll need less PSRR than otherwise.  The LM324 is a quad opamp: obviously if you use the 3 other opamps for different purposes, you want high crossover suppression and it depends on what the others do whether they'll cause problems.  And so on.
Just waving model numbers around is of moderate use when the details of your circuit are in the dark.  And then we haven't even gotten to requirements about operating currents and operating voltages and how close you want the output swing to the rails at which output impedance in which time.

A: Define your overall design specs. Then choose these parameters and narrow your selection. You ought have at least half a dozen parameters of importance.
e.g. including: Rail to rail, ultra-low noise BW required might be 20x your step frequency of 2kHz or higher which if using low gain <=100, will required LP filtering.  OPA1655 is a possible choice using ~ 1~10K resistors.
https://www.ti.com/amplifier-circuit/op-amps/precision/overview.html


text:
Q: I am converting HTML2WORD document using APACHE POI Java , but not able to add Header and Footer to newly generated word document When am converting HTML 2 Word using POI am able to generate a new .doc with all styles and formatting used in html, but problem is not able to append header and footer in newly created .doc document. Does POI not support @page style of CSS? Also how to add header and footer to newly generated .doc document.
Below Code:
public void convertHtmltoWord(String html, OutputStream outputStream) throws IOException {

    POIFSFileSystem poifs = new POIFSFileSystem();
    DirectoryEntry directory = poifs.getRoot();

    try {
        directory.createDocument("WordDocument", getInputStream(html));
        poifs.writeFilesystem(outputStream);
    } finally {
        outputStream.close();
        poifs.close();
    }
}

public static InputStream getInputStream(String inputData) {
    InputStream targetStream = IOUtils.toInputStream(inputData);
    return targetStream;
}

Note: Converted .doc will give only give BODY part of .doc not Header and Footer. Like Page number in footer is not coming.

A: What you are doing using your code is not HTML to Word conversion.
Your code only creates a POIFSFileSystem having one DirectoryEntry containing the HTML. Microsoft Word will interpret that HTML and show it in the document body but the file is not a really binary *.doc file.
You can see this when you change something after opening in Word and then save. It will be saved as HTML and a additional directory [Filename]-Files will be created. That is needed because HTML does not provide embedding by default. So this directory contains all elements which could not embedded. This are pictures for example but also additional HTML files containing header and/or footer text.
So using your approach it is not possible to add header or footer to the HTML. It only can put HTML into the document body. And it not even creates a real MIcvrosoft Word file but only a HTML file which gets foisted  to Microsoft Word because of its fake file name *.doc.


text:
Q: sporadic timeouts on http connection In my application I use http to connect to my server (I am synchronizing the local database). Here is the code:
HttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),13500);
HttpConnectionParams.setSoTimeout(httpClient.getParams(),27000);

HttpResponse response = httpClient.execute(httpRequest);
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
if (entity != null) {
    String data = EntityUtils.toString(entity);
    JSONObject jObj = new JSONObject(data);
    entity.consumeContent();
}

This code is executed for a number of httpRequests to pull the data from the server as well as to send updates up to the server.
Till recently this code did not give me any trouble, but now I am struggling with a strange problem: Sometime the code works as it is supposed to work, but sometimes all I am getting is timeouts.
A little more details - when it does not work it is not like I am getting sporadic timeouts - every request I send ends up with a timeout. I can restart the app and see this behavior, and then after several app restarts it is like the curse is lifted - not a single timeout. And then again all I am getting is timeouts.
I am pretty sure that the problem is on the phone side, because I also have an IPhone app talking to the same app with no problems. Also several times I observed this problem with one android device, while the same app on a different device working fine.
What am I missing here?


text:
Q: cakephp get element value js helper I am beginner to CakePHP and tried searching this question but no any gold.
I have a select button and when user select an option I have to fire a event and pass the selected value to the controller's action.
The code goes below:

<?php
//I only need a select button why to bother of creating form
echo $this->Form->input('district',array('label'=>'labelhere','id'=>'idhere'));

//script handler for select option
$this->Js->get('#idhere');
$this->Js->event(
        'change',
        $this->Js->request(
            array('action' => 'listing',<the selected value of #idhere here>),
            array('async' => true,
                'method'=>'POST',
                'update' => '#HFNames')
        )
    );

?>

Div to include ajax returns.

Precisely,
What is the CakePHP equivalent for Jquery's $('selector').value();
Here is the Html code generated:

labelhere<select  name="data[district]" id="idhere">
<option value="01">Bhojpur</option>
<option value="02">Dhankuta</option>
<option value="03">Ilam</option>
<option value="04">Jhapa</option>
<option value="05">Khotang</option>
<option value="06">Morang</option>
<option value="07">Okhaldhunga</option>
<option value="08">Panchthar</option>
<option value="09">Sankhuwasabha</option>
<option value="10">Saptari</option>
<option value="11">Siraha</option>
</select>

A: try this
<?php
//I only need a select button why to bother of creating form
echo $this->Form->input('district',array('label'=>'labelhere','id'=>'idhere'));

//script handler for select option
$this->Js->get('#idhere');
$this->Js->event(
        'change',
        $this->Js->request(
            array('action' => 'listing'),
            array('async' => true,
                'method'=>'POST',
                'update' => '#HFNames',
                'data'   => '$("selector").value()')
        )
    );

?>

Div to include ajax returns.

make time to read this post: Dynamic Web With Cake


text: Q: Single login across multiple domain asp.net I would like to implement functionality such that i have 2 websites . i would like to login user from one website and allow user to perform operations on other website.


text:
Q: CString join method? I need to concatenate a list of MFC CString objects into a single CSV string. .NET has String.Join for this task. Is there an established way to do this in MFC/C++?

A: The + operator is overloaded to allow string concatenation. I'd suggest take a look at the documentation on MSDN:
Basic CString Operations has the following example:
CString s1 = _T("This ");        // Cascading concatenation
s1 += _T("is a ");
CString s2 = _T("test");
CString message = s1 + _T("big ") + s2;
// Message contains "This is a big test".

If you want the strings to be comma-separated, just add the commas yourself.

A: Iterate through the list of CString objects invoking the AppendFormat method.
//  Initialize CStringList
CStringList cslist ;
cslist.AddTail( "yaba" ) ;
cslist.AddTail( "daba" ) ;
cslist.AddTail( "doo"  ) ;

//  Join
CString csv ;
for ( POSITION pos = cslist.GetHeadPosition() ; pos != NULL ; )
    csv.AppendFormat( ",%s" , cslist.GetNext( pos ) ) ;
csv.Delete( 0 ) ;  //  remove leading comma


text:
Q: The same code that used to work is now returning an exception I'm trying to do a simple correlation between a few stock symbols. I've run the same code before and it worked. Now, it's returning an exception that references a bunch of files and contains other messages that I don't understand. Also, the command has to be manually stopped in the console. I'm very new to python and programming in general. I'm using Spyder 5.0.3 and anaconda3. I've tried reinstalling Spyder and updated the packages used, neither resolved the issue.
The problem appears to be with the yfinance package. When I tried to download price data for a single ticker a similar exception was returned. It doesn't appear to be pandas or numpy because I was able to make a small dataframe and run corrcoeff() without any problem. For what it's worth this is the code I used:
import pandas as pd
import numpy as np

d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)

r = np.corrcoef(df)

The following is the code that used to work but is no longer working:
import pandas as pd
import numpy as np
import yfinance as yf

AAPL = yf.download('AAPL', period='32D', interval='1D')
MSFT = yf.download('MSFT', period='32D', interval='1D')
NVDA = yf.download('NVDA', period='32D', interval='1D')

corr3 = pd.DataFrame([AAPL['Close'],
                   MSFT['Close'],
                   NVDA['Close']])

r = np.corrcoef(corr3)

When I run the file I receive the following exception in the console:
Exception in thread Thread-10:
Traceback (most recent call last):
  File "C:\Users\jdejo\anaconda3\lib\threading.py", line 932, in _bootstrap_inner
    self.run()
  File "C:\Users\jdejo\anaconda3\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\jdejo\anaconda3\lib\site-packages\multitasking\__init__.py", line 102, in _run_via_pool
    return callee(*args, **kwargs)
  File "C:\Users\jdejo\anaconda3\lib\site-packages\yfinance\multi.py", line 167, in _download_one_threaded
    data = _download_one(ticker, start, end, auto_adjust, back_adjust,
  File "C:\Users\jdejo\anaconda3\lib\site-packages\yfinance\multi.py", line 179, in _download_one
    return Ticker(ticker).history(period=period, interval=interval,
  File "C:\Users\jdejo\anaconda3\lib\site-packages\yfinance\base.py", line 157, in history
    data = data.json()
  File "C:\Users\jdejo\anaconda3\lib\site-packages\requests\models.py", line 900, in json
    return complexjson.loads(self.text, **kwargs)
  File "C:\Users\jdejo\anaconda3\lib\json\__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "C:\Users\jdejo\anaconda3\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\jdejo\anaconda3\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I am wanting to know what went wrong with my code. It used to work, now it doesn't. Any guidance would be greatly appreciated.

A: I have solved the problem. I needed to update yfinance through the console in spyder. I had been using the command prompt to update packages.


text:
Q: Кто может объяснить в чем есть ошибка, не компилируется код Дано натуральное n > 0. Найти произведение первых n простых чисел.
Подсказка: используйте булевскую функцию для проверки,
является число простым числом или нет.(Массивы использовать нельзя)ю
var
  pr,  j,n,i: integer;
  b:boolean;
   begin

     write('Введите натуральное число N= ');
      readln(n);
         for i:=1 to n do

      begin
        j:=2;b:=true;
        while(j<i div 2)and(b) do
               begin
               if i mod j =0 then b:=false;
          inc(j)
        end;
        begin
          if b then pr:=pr*i;
          writeln(pr);
        end.
        ```

A: основной алгоритм:
произведение = 1
кол-во простых числе = 0
текущее число = 2

выполнять до тех пор, пока кол-во простых чисел не будет равно N
    проверить текущее число на простоту
    если текущее число простое
        увеличить кол-во простых чисел
        увеличить произведение в текущее число раз
    увеличить текущее число на 1

тест на простоту:
в цикле от 2 до корня из числа
    если число делится на число из цикла без остатка - выйти с провальным результатом
выйти с успешным результатом


text:
Q: Python: iterate through lines after reverse reading a text file I am using Python 3.4.
I have a log file like this:
10001 ...
10002 * SMTP *
10003 skip me
10004 read me
10005 read me

The goal of the script is to open the file in reverse mode, and iterate through lines untill I found '* SMTP *' in it (in the example is line 10002), then I have to go back and skip a line and read the next 2 lines (in the example lines 10004 and 10005).
How can I do that?

A: mmap is a good way to go:
import mmap

SEARCH_TEXT = b'* SMTP *'
SKIP_LINES = 2
KEEP_LINES = 2

with open('log.txt', 'rb') as f:
    log = mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ)
    n = log.rfind(SEARCH_TEXT)
    if n == -1:
        print('{!r} not found'.format(SEARCH_TEXT))
    else:
        log.seek(n)
        for i in range(SKIP_LINES):
            _ = log.readline()

        print(''.join(log.readline().decode() for _ in range(KEEP_LINES)))

Output

10004 read me
10005 read me

This code mmaps the log file, searches from the end of the file with rfind() for the target string '* SMTP *'. Then it positions the file pointer at the target string (using seek()), consumes the 2 unwanted lines, and finally reads the 2 lines of interest.
mmap is efficient because the OS handles paging of data from the disk into memory for your application. It does not read the whole file, so it is a good strategy for large files.

A: with open (file) as textfile:
    lines = textfile.read().split("\n")
    lines.reverse()
    if lines.index("* SMTP *"):
        Ind =  int(lines.index("* SMTP *"))
        print lines[Ind-2]
        print lines[Ind-3]
        break

this will only find the latest occurance of * SMTP * in your log file and it is dirty, but gets the job done.
did some testing to compare @mhawke mmap vs mine. Testing is done on a 150k line test file.
mmap
real 0m0.024s
user 0m0.016s
sys  0m0.008s

my solution
real 0m0.038s
user 0m0.026s
sys  0m0.012s


text:
Q: d3 - reading JSON data instead of CSV file I'm trying to read data into my calendar visualisation using JSON. At
the moment it works great using a CSV file:
d3.csv("RSAtest.csv", function(csv) {
  var data = d3.nest()
    .key(function(d) { return d.date; })
    .rollup(function(d) { return d[0].total; })
    .map(csv);

 rect.filter(function(d) { return d in data; })
      .attr("class", function(d) { return "day q" + color(data[d]) +
"-9"; })
      .select("title")
      .text(function(d) { return d + ": " + data[d]; });

});

It reads the following CSV data:
date,total
2000-01-01,11
2000-01-02,13
.
.
.etc

Any pointers on how I can read the following JSON data instead:
{"2000-01-01":19,"2000-01-02":11......etc}
I tried the following but it not working for me (datareadCal.php spits
out the JSON for me):
d3.json("datareadCal.php", function(json) {
  var data = d3.nest()
    .key(function(d) { return d.Key; })
    .rollup(function(d) { return d[0].Value; })
    .map(json);

thanks

A: Turn your .json file into a .js file that is included in your html file. Inside your .js file have:
var countsByDate = {'2000-01-01':10,...};

Then you can reference countsByDate....no need to read from a file per se.
And you can read it with:
var data = d3.nest()
.key(function(d) { return d.Key; })
.entries(json);

As an aside....d3.js says it's better to set your json up as:
var countsByDate = [
  {Date: '2000-01-01', Total: '10'},
  {Date: '2000-01-02', Total: '11'},
];

A: You can use d3.entries() to turn an object literal into an array of key/value pairs:
var countsByDate = {'2000-01-01': 10, ...};
var dateCounts = d3.entries(countsByDate);
console.log(JSON.stringify(dateCounts[0])); // {"key": "2000-01-01", "value": 10}

One thing you'll notice, though, is that the resulting array isn't properly sorted. You can sort them by key ascending like so:
dateCounts = dateCounts.sort(function(a, b) {
    return d3.ascending(a.key, b.key);
});


text:
Q: Filter ComboBox by selected item of another ComboBox I have a County ComboBox bound to an entity (EF). There is another ComboBox for Area's. These controls are in an edit form.
So the user has chosen these values. In this form the user can edit the chosen values. So when the window is loaded, the chosen values are selected as default. Each of these ComboBoxes has an SelectionChanged event.
The problem is that when the default value is selected (when the window is being loaded), the SelectionChanged event is triggered. Pretty obvious. But I want the event to be triggered only when the user really chooses another item (from County ComboBox) to filter the Area ComboBox.
How can I achieve this?

A: Use a public variable. Name it something obvious and intuitive like EnableEvents.
An example of using it, with a default value of True, would be:
Whenever you do NOT want your code to trigger the ComboBox's events, set EnableEvents=False and then inside the event handler, use something like a If Not EnableEvents Then Exit Sub.
Whether you default this variable to True, which will allow all events unless when you specifically change the flag to False, or default the variable to False which will disallow events unless you change it to True, is probably a matter of preference based on your specific needs.  Whatever initial value you assign to it, just remember to reset it after each time you change it.


text:
Q: How to use Alamofire with JSONDecoder? I am try to parsing google Direction API as below.
https://developers.google.com/maps/documentation/directions/start
but unable to get any result from  JSONDecoder , it always return Error block
I am using Alamofire code as below for parsing .
 let decoder = JSONDecoder()
                        do {
                            let userDictionary    =  try   decoder.decode(DirectionParser.self, from: response.data!)
                        print("The Parser \(userDictionary)")

                        } catch {
                            print("Error")
                        }

A: I think you are doing right. Just make sure you are trying to parse what you want. You can do this by printing out
print(response.anythingYouWant)
Can you show us DirectionParser.
Make sure it is like below code
struct DirectionParse: Decodable {
   //things you want to fetch
}

P.S I would have commented if I had reputation 50+.


text:
Q: Fourier cosine series expansion of $f(x)=1$
Fourier cosine series expansion of $$f(x)=1,~~~ x\in (0,\pi)$$

Hint is "thought is better than calculation".

A:
So, do I just let the Fourier series for cosine equal $1$?

Yes, the cosine expansion of this function has just one nonzero term: $1$. The rest of coefficients are therefore zero.
This is something that always happens when you expand a vector in a basis which contains that vector. If your basis of $\mathbb{R}^2$ is
$\{(2,3), (1,-5)\}$, and you want to expand the vector $v=(1,-5)$ in this basis, the expansion is just that:
$$(1,-5) = 0\cdot (2,3)+1\cdot (1,-5)$$
Indeed, this particular choice of coefficients evidently works, and since the coefficients are unique, any other method would produce same ones.


text:
Q: WordPress Network install error Reinstalling wordpress multisite
Warning: an existing wordpress network was detected.
I tried multiple solutions including dropping tables, resetting .htaccess and completely resetting wp_config. It installs fine the first time but when I log out and log in I get this error.

A: Follow the steps in this order
1) Reset your wp-config.php file back to its original state, remove any MULTISITE references
2) Delete the .htaccess file or move it temporarily
3) Drop the following tables from your DB, use a tool like phpMyAdmin if you are not comfortable directly modifying table data

*

*wp_blogs

*wp_blog_versions

*wp_registration_log

*wp_site

*wp_sitemeta

*wp_signups

*wp_sitecategories

4) Log out and Log back into your site and initiate the Network Setup.
5) Recreate the .htaccess file with the copy pasted data
6) Modify the wp-config.php file, remember to paste those lines above the line where it says
/* That's all, stop editing! Happy blogging. */
Step 6 is important see below :
http://premium.wpmudev.org/forums/topic/multisite-not-working-warning-an-existing-wordpress-network-was-detected
Also read :
http://blog.ashfame.com/2010/07/remove-wordpress-multisite-data/

A: WordPress version: 5.4.2
The documentation to install WordPress multi-site needs revision. The instructions say to add these two lines. Adding both of these lines doesn't activate the multi-site:
define('WP_ALLOW_MULTISITE', true);
define('MULTISITE', true);

Instead, just using the following line and it works:
define('MULTISITE', true);

A: Just in case it helps anyone else, I was experiencing this error after I forget to manually clear my OpCache after making the changes to wp-config.php, so the database indicated a multisite network but wp-config did not reflect it. Clearing the OpCache fixed the problem.

A: After hundreds of attempts, what worked for me was to add the code from wp_config.php to the beginning of the file.

A: Make sure that the code is put before the line
/* That's all, stop editing! Happy blogging. */

and that the following 2 lines are after this comment
/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
        define('ABSPATH', dirname(__FILE__) . '/');

/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');

resource Stack Overflow


text:
Q: recognize_google gives "recognition request failed: Forbidden" error I am using an Ubuntu 20.04 Virtual Machine and running the following code :
import speech_recognition as sr

# Initialize recognizer class (for recognizing the speech)
r = sr.Recognizer()

# Reading Audio file as source
# listening the audio file and store in audio_text variable

with sr.AudioFile('I-dont-know.wav') as source:

    audio_text = r.listen(source)

# recoginize_() method will throw a request error if the API is unreachable, hence using exception handling
    try:

        # using google speech recognition
        text = r.recognize_google(audio_text)
        print('Converting audio transcripts into text ...')
        print(text)

    except Exception as ex:
         print(ex)

It gives the error message "recognition request failed: Forbidden"
I have also tried generating a key from google cloud and setting its path on the device but still the same error occurs.
If anyone can suggest something, it would be great help. Any alternate and efficient methods for speech to text conversion can also be suggested.
Thanks


text:
Q: Storing key value dictionary in Elgg I am working on a plugin for Elgg that keeps track of device ids that are sent to the application when logging in from your mobile phone. For this, I would like to store these device ids in the database and would like to use ElggObjects for this.
This is what I do now:
function initialize() {
     $androidTokens = elgg_get_entities(array(
          'type' => 'object',
          'subtype' => 'androidTokens',
          'limit' => 0
     ));
     $iosTokens = elgg_get_entities(array(
          'type' => 'object',
          'subtype' => 'iosTokens',
          'limit' => 0
     ));

     if ($androidTokens == 0) {
          $tokenObject = new ElggObject();
          $tokenObject->subtype = 'androidTokens';
          $tokenObject->tags = array();
          $tokenObject->save();
     }

     if ($iosTokens == 0) {
          $tokenObject = new ElggObject();
          $tokenObject->subtype = 'iosTokens';
          $tokenObject->tags = array();
          $tokenObject->save();
     }
}

So this generates two ElggObjects that hold ids for android and for ios devices, stored in the metadata field tags. This array of tags can however not be retrieved anymore. When I do:
$tokenObject = elgg_get_entities(array(
                         'type' => 'object',
                         'subtype' => $os.'Tokens',
                         'limit' => 0
                    ));
               $tokens = $tokenObject->tags

tokens remains empty. Does someone know what I am doing wrong? Am I using the Elgg objects wrong?

A: I think the reason you're running into issues there is that elgg_get_entities returns an array of entities.
Am I correct in assuming that you'll only ever have one of each token object subtype? (One for iOS and one for Android?)
If so, I would modify your code as follows:
function initialize() {
 $androidTokens = elgg_get_entities(array(
      'type' => 'object',
      'subtype' => 'androidTokens',
      'limit' => 1 // only expecting one entity
 ));
 $iosTokens = elgg_get_entities(array(
      'type' => 'object',
      'subtype' => 'iosTokens',
      'limit' => 1 // only expecting one entity
 ));

 if (count($androidTokens) == 0) {
      $tokenObject = new ElggObject();
      $tokenObject->subtype = 'androidTokens';
      $tokenObject->tags = array();
      $tokenObject->save();
 }

 if (count($iosTokens) == 0) {
      $tokenObject = new ElggObject();
      $tokenObject->subtype = 'iosTokens';
      $tokenObject->tags = array();
      $tokenObject->save();
 }
}

Later, when grabbing the entity:
$tokenObject = elgg_get_entities(array(
                     'type' => 'object',
                     'subtype' => $os.'Tokens',
                     'limit' => 1 // only grab one
                ));
$tokens = $tokenObject[0]->tags; // get tag data for first (and only) entity


text:
Q: what do the parentheses accomplish around the assignment More of a JavaScript question. But I ran into it while learning about Angular!
Why does the assignment to $scope.clock have curly braces? I took them out, it certainly doesn't produce a correct outcome without them! What is the technique called in Javascript?
function MyController($scope) {
   $scope.clock = {
      now: new Date()
   };
   var updateClock = function() {
      $scope.clock.now = new Date();
   };
   setInterval(function() {
      $scope.$apply(updateClock);
      }, 1000);
   updateClock();
};

A: In this case, $scope.clock is being assigned to a Javascript object. More correctly, this is known as an 'object literal' notation.

A: the curly brackets define the clock variable as an object. What this means if you can assign variables on this object, like the now variable. so that you can do this. angular aside.
var clock = {
  now: new Date()
};
alert(click.now);

This will show an alert box with the result of new Date(). You can add variables to object in other ways as well.
var clock = {};
clock.now = new Date();

This is the same thing as above.
With angular all you are doings is assigning the clock variable on the $scope. and then giving the newly assigned clock variable a now variable. Which would look like this.
var iAmAnObject = {};
iAmAnObject.clock = {
    now: new Date()
};


text:
Q: Bijection from $\mathbb{Z}\rightarrow S=\{x\in\mathbb{R}:\sin x =1\}$ In looking for a bijection from $\mathbb{Z}\rightarrow S=\{x\in\mathbb{R}:\sin x =1\}$ I came up with $f(x)=\sin(\frac{\pi}{2}+2x\pi)$.
But now how would I prove this bijection? I know to start with injectivity and show $f(x)=f(y)\Rightarrow x=y$ but having trouble simplifying
$\sin(\frac{\pi}{2}+2x\pi)=\sin(\frac{\pi}{2}+2y\pi)$.
This is probably rather simple but if someone could inform me how to show injectivity and surjectivity that would be great!

A: Your original bijection maps every integer to $1$, clearly $1 \notin S$ since $sin(1) \neq 1$.
The bijection you are looking for from $\Bbb{Z} \rightarrow S$ is given by
$$f(k)=\frac{\pi}{2}+2k\pi$$
With this new bijection i'm sure you'll be able to prove injectivity and surjectivity.

A: Hint:
The sine function is increasing on $[-\frac\pi2,\frac\pi2]$ and continuous,hence a bijection onto its image.
Then use  $\sin(\pi-x)=\sin x$ for all $x$ to show $\sin x=1$ has only one solution on $[0,2\pi]$.
Finally, use periodicity.


text:
Q: How to show product information in a costume module page like Magento product page built? I would like to show a product with its details in my module view page. There is summery of my code, it maybe boring but I have exhibit my issue clearly.
1)File name, path and code: MyVendor/MyModule/Api/Data/ViewInterface.php
namespace MyVendor\MyModule\Api\Data;
interface ViewInterface
{
    const VALUE            = 'value ';
    /**
     * Get Value
     *
     * @return string|null
     */
    public function geValue();
    /**
     * Set $Value
     *
     * @param string $Value
     * @return $this
     */
    public function setValue($Value);
}

2)File name, path and code: MyVendor/MyModule/Model/View.php
<?php

namespace MyVendor\MyModule\Model;

use \Magento\Framework\Model\AbstractModel;
use \Magento\Framework\DataObject\IdentityInterface;
use \MyVendor\MyModule\Api\Data\ViewInterface;

/**
 * Class File
 * @package MyVendor\MyModule\Model
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class View extends AbstractModel implements ViewInterface, IdentityInterface
{
    /**
     * Cache tag
     */
    const CACHE_TAG = 'MyVendor_MyModule_view';

    /**
     * Post Initialization
     * @return void
     */
    protected function _construct()
    {
        $this->_init('MyVendor\MyModule\Model\ResourceModel\View');
    }
    /**
     * Get Value
     *
     * @return string|null
     */
    public function geValue()
    {
        return $this->getData(self::VALUE);
    }
    /**
     * Return identities
     * @return string[]
     */
    public function getIdentities()
    {
        return [self::CACHE_TAG . '_' . $this->geValue()];
    }
    /**
     * Set $Value
     *
     * @param string $Value
     * @return $this
     */
    public function setValue($Value)
    {
        return $this->setData(self::VALUE, $Value);
    }
}

3)File name, path and code: MyVendor/MyModule/ResourceModel/View.php(Maybe here would be modify):
namespace MyVonder\MyModel\Model\ResourceModel;

use \Magento\Framework\Model\ResourceModel\Db\AbstractDb;

class View extends AbstractDb
{
    /**
     * Post Abstract Resource Constructor
     * @return void
     */
    protected function _construct()
    {
        $this->_init('catalog_product_entity_media_gallery', 'value_id');
    }
}

In magento DB there are many tables that I do not know how to use or join them to fetch data. I only applied "catalog_product_entity_media_gallery"  which had value of image or product.
4)File name, path and code: MyVendor/MyModule/view/frontend/templates/View.phtml
<?php /** @var MyVendor\MyModel\Block\Product $block */ ?>
<?php $productCollection = $block->getCollection(); ?>
<?php
$pic_number=time()%(count($productCollection));// for selecting a random product
echo $pic_number;
dd($productCollection[0]['value']);// test the value data of table
 ?>

5) File name, path and code: MyVendor/MyModule/Block/Product.php
class Product extends Template
    {

        protected $_viewCollectionFactory = null;

        /**
         * Constructor
         *
         * @param Context $context
         * @param ViewCollectionFactory $viewCollectionFactory
         * @param array $data
         */
        public function __construct(
            Context $context,
            ViewCollectionFactory $viewCollectionFactory,
            array $data = []
        ) {
            $this->_viewCollectionFactory  = $viewCollectionFactory;
            parent::__construct($context, $data);
        }

        /**
         * @return Post[]
         */
        public function getCollection()
        {
            /** @var ViewCollection $viewCollection */
            $viewCollection = $this->_viewCollectionFactory ->create();
            $viewCollection->addFieldToSelect('value')->load();
            return $viewCollection->getData();
        }

    }

Overall: I could not fetch the Qty, Details, Name and other extra information of product. While all of them are in default page of product in Magento home page.


text:
Q: C# datagridview row toggle I'm looking to get some help with the datagridview.
What I want to do is when I click an item (a row) in the receiptView (datagridview) list, it should toggle that row's selection (i.e. If it was already selected, it would deselect and vice-versa).
So far I've found this code, however, this doesn't work all the time:
    private void receiptView_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        if (!_selectionChanged)
        {
            //do other stuff here
            receiptView.ClearSelection();
            _selectionChanged = true;
        }
        else
        {
            //do other stuff here
            _selectionChanged = false;
        }
    }

    private void receiptView_SelectionChanged(object sender, EventArgs e)
    {
        _selectionChanged = true;
    }

FYI

*

*When a row is clicked and no row is already selected OR a row is already selected and a new row is now selected it triggers the
events in this following order:

*

*receiptView_SelectionChanged

*receiptView_CellClick

*When a row is clicked and it is already selected it only triggers the receiptView_CellClick event

Problem
What's happening is that when I select/deselect a row really quickly (akin to like a double click) it would end up "de-syncing" the actual selection state and _selectionChanged. What I mean by this is that:

*

*When a row is selected once it'll highlight/select that row (normal)

*When the same row is now selected again (in quick succession to the first click) it doesn't deselect the row, but seems to stay selected while the wrong "do other stuff here" gets exectuted (not normal, should have deselected)

*On the third click it deselects (normal if it were step 2, should only be two steps)

This doesn't happen every time I click quickly but it does happens regularly (about every second/third click-pair). It NEVER happens if I click slowly and deliberately.
Theory
I don't really know why this is happening but I suspect that as Clicks 1 and 2 happen very close to one another, the second click's event triggers while the first's is still running, causing the first click to change the _selectionChanged to false, and the second to change it back to true, while keeping the row selected. However, since I'm not creating any new threads and this is all running on the main UI thread, should it not be a serialized execution? i.e. Click 1's events trigger, and once it has completed, click 2's events trigger?
Question
If any of you know an easier way to do this (toggling in a datagridview), or can see the bug and/or have a solution it would be greatly appreciated.
Thanks.

A: TL;DR
Your second click is being hijacked by the CellDoubleClick event. Subscribe to it using the same code from your CellClick event handler.
- See the Solution at the end of the answer.
DEBUGGING EXPLANATION
To demonstrate what's happening, we add the following outputs to your methods, then run through the scenario you described in the OP.
private void receiptView_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (!_selectionChanged)
    {
        Console.WriteLine("Cleared.......");
        receiptView.ClearSelection(); // NOTE: Triggers SelectionChanged event.
        _selectionChanged = true;
    }
    else
    {
        Console.WriteLine("Highlighted...");
        _selectionChanged = false;
    }
}

private void receiptView_SelectionChanged(object sender, EventArgs e)
{
    Console.WriteLine("Changed!");
    _selectionChanged = true;
}

With no rows currently selected, the following test, expected results, and actual results:
+======================+=================+================+=================+
|       ACTION         | EXPECTED OUTPUT | ACTUAL OUTPUT  |   GUI RESULTS   |
+======================+=================+================+=================+
| Single-click 1st row | Changed!*       | Changed!*      | Row Highlighted |
|                      | Highlighted...  | Highlighted... |                 |
+----------------------+-----------------+----------------+-----------------+
| Double-click 1st row | Cleared.......  | Cleared....... | Row Highlighted |
|                      | Changed!^       | Changed!^      |                 |
|                      | Changed!*       | Changed!*      |                 |
|                      | Highlighted...  |                |                 |
+----------------------+-----------------+----------------+-----------------+
| Single-click 1st row | Cleared.......  | Highlighted... | Row Highlighted |
|                      | Changed!^       |                | (Still...?)     |
+----------------------+-----------------+----------------+-----------------+

* SelectionChanged triggered in behind code; non-selected row is now selected.
^ SelectionChanged triggered by call to ClearSelection().
Analysis: Your first click triggers SelectionChanged and highlights the row as expected. Next, you double-click the row, thinking the first click will clear the row (which you will manually cause to trigger SelectionChanged), and the second click (again, triggering SelectionChanged in the background) re-highlights it. This is where we go wrong.
From the double-click, the first click triggers the clear and SelectionChanged event as expected. We even see the second expected printout from SelectionChanged, but not the highlight printout from the CellClick event. Why?
When you click on a row/cell once, CellClick is triggered. When you click twice in quick succession, CellClick triggers for the first click and CellDoubleClick triggers for the second click. Thus, your first click hits your code as expected. The second click never hits your code, except that in the background the non-selected row was still selected and thus SelectionChanged is still triggered a second time. From this point on, your _selectionChanged flag is off - causing more inaccurate results.
Solution: Subscribe to the CellDoubleClick event and perform the same code in it as in CellClick and you'll be fine.
private void receiptView_CellClick(object sender, DataGridViewCellEventArgs e)
{
    this.DoStuff();
}

private void receiptView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
    this.DoStuff();
}

private void DoStuff()
{
    if (!_selectionChanged)
    {
        //do other stuff here
        receiptView.ClearSelection();
        _selectionChanged = true;
    }
    else
    {
        //do other stuff here
        _selectionChanged = false;
    }
}


text:
Q: Swagger-codegen generated code having issues Routing requests with parameters in path I created my api definition using swagger and have generated the server code using Swagger-tools in NodeJs. The SwaggerRouter handles all routes properly excepts the routes with ID.
For example , routes like
/v1/factoris/self
/v1/factoris/create
are directed to the right controller
but calls with IDs
/v1/factoris/{factoris_id}
are returned as invalid routes.
Any idea what I might be missing ?
Here is a sample of the swagger specs
/factoris/create:
post:
  tags:
  - "Factoris"
  summary: "Create New Factori"
  description: ""
  operationId: "factorisCreatePOST"
  parameters:
  - in: "body"
    name: "FactoriCreate"
    description: "Create a new factory"
    required: true
    schema:
      $ref: "#/definitions/FactoriCreate"
  responses:
    201:
      description: "A single factori object"
      schema:
        $ref: "#/definitions/inline_response_201"
    405:
      description: "Method not allowed"
      schema:
        $ref: "#/definitions/inline_response_405"
  security:
  - oauth2:
    - "admin"
  x-swagger-router-controller: "Factoris"

/factoris/{factori-id}:
get:
  tags:
  - "Factoris"
  summary: "Factori Information"
  description: ""
  operationId: "factorisFactori_idGET"
  parameters:
  - name: "factori-id"
    in: "path"
    description: "The factori identifier string"
    required: true
    type: "string"
  - name: "expand"
    in: "query"
    description: "Provide expanded information on Assemblies or Products or Users"
    required: true
    type: "string"
  responses:
    200:
      description: "A single factori object"
      schema:
        $ref: "#/definitions/inline_response_201"
    404:
      description: "Factori not found"
      schema:
        $ref: "#/definitions/inline_response_404"
  security:
  - oauth2:
    - "codeadmin"
  x-swagger-router-controller: "Factoris"

A: After some trial and error, I figured out that  path parameter does not work if its has a "-" (factori-id)
so changing factori-id to factori_id fixed it.  But its still a bug since the path parameter cannot handle "-"
here is the open issue created in Swagger-codegen
https://github.com/swagger-api/swagger-codegen/issues/5763


text:
Q: How to convert String to Time and insert it MySQL I have a JSP page, so the user can insert the time when he/she arrives and goes from the place manually.
My question is: how can I convert that String, from the input box (JSP) to then insert it to query thus into my MySQL table.
I am using Java - servlet.
Thanks

A: You can use SimpleDateFormat to parse a String in the given pattern to a java.util.Date object.
Assuming that it's HH:mm, then you can do so:
String time = request.getParameter("time");
Date date = null;

try {
    date = new SimpleDateFormat("HH:mm").parse(time);
}
catch (ParseException e) {
    request.setAttribute("time_error", "Please enter time in format HH:mm");
}

Once having the java.util.Date object, you can store it in a TIME column by converting it to java.sql.Time and using PreparedStatement#setTime().
preparedStatement = connection.prepareStatement("INSERT INTO tablename (columname) VALUES (?)");
preparedStatement.setTime(1, new Time(date.getTime()));
preparedStatement.executeUpdate();