text:
Q: What is the difference between the core, vendor and site locations in Perl? I recently ran into some trouble installing some modules and discovered to my surprise that many of the modules that had been installed, have duplicated installations and versions. Trying to track where stuff goes in a standard (if there is such a thing) installation using cpanm, I found the following results very confusing.
The reports show these locations:

*

*Using cpan -V:

# cpan -V

/usr/bin/cpan script version 1.672, CPAN.pm version 2.22
--------------------------------------------------
Checking install dirs...
Checking core
        + /usr/share/perl5/5.26
        + /usr/lib/perl5/5.26/x86_64-cygwin-threads
Checking vendor
        + /usr/share/perl5/vendor_perl/5.26
        + /usr/lib/perl5/vendor_perl/5.26/x86_64-cygwin-threads
Checking site
        + /usr/local/share/perl5/site_perl/5.26
        + /usr/local/lib/perl5/site_perl/5.26/x86_64-cygwin-threads
Checking PERL5LIB
        no directories for PERL5LIB
Checking PERLLIB
        no directories for PERLLIB

*

*Using perl -V:.*site.*:

# perl -V:.*site.* |column -t -s "=" |sort -d -i -k 1.22

d_sitearch           'define';
usesitecustomize     'undef';
siteprefix           '/usr/local';
siteprefixexp        '/usr/local';
installsitebin       '/usr/local/bin';
installsitescript    '/usr/local/bin';
sitebin              '/usr/local/bin';
sitebinexp           '/usr/local/bin';
sitescript           '/usr/local/bin';
sitescriptexp        '/usr/local/bin';
installsitearch      '/usr/local/lib/perl5/site_perl/5.26/x86_64-cygwin-threads';
sitearch             '/usr/local/lib/perl5/site_perl/5.26/x86_64-cygwin-threads';
sitearchexp          '/usr/local/lib/perl5/site_perl/5.26/x86_64-cygwin-threads';
installsitehtml1dir  '/usr/local/share/doc/perl/html/html1';
sitehtml1dir         '/usr/local/share/doc/perl/html/html1';
sitehtml1direxp      '/usr/local/share/doc/perl/html/html1';
installsitehtml3dir  '/usr/local/share/doc/perl/html/html3';
sitehtml3dir         '/usr/local/share/doc/perl/html/html3';
sitehtml3direxp      '/usr/local/share/doc/perl/html/html3';
installsiteman1dir   '/usr/local/share/man/man1';
siteman1dir          '/usr/local/share/man/man1';
siteman1direxp       '/usr/local/share/man/man1';
installsiteman3dir   '/usr/local/share/man/man3';
siteman3dir          '/usr/local/share/man/man3';
siteman3direxp       '/usr/local/share/man/man3';
installsitelib       '/usr/local/share/perl5/site_perl/5.26';
sitelib              '/usr/local/share/perl5/site_perl/5.26';
sitelib_stem         '/usr/local/share/perl5/site_perl/5.26';
sitelibexp           '/usr/local/share/perl5/site_perl/5.26';

*

*Using @INC:

# perl -e 'print join("\n",@INC,"")'

/usr/local/lib/perl5/site_perl/5.26/x86_64-cygwin-threads
/usr/local/share/perl5/site_perl/5.26
/usr/lib/perl5/vendor_perl/5.26/x86_64-cygwin-threads
/usr/share/perl5/vendor_perl/5.26
/usr/lib/perl5/5.26/x86_64-cygwin-threads
/usr/share/perl5/5.26

The result is that cpan-outdated -p --verbose show a completely different (and shorter) list of outdated modules than what cpan -lO does. Needless to say, modules are installed all over the place and I don't see how to understand if there is a default install location and where it goes, or should go.

QUESTION:

*

*So what is the difference between the core, vendor and site type of paths?

*Why are there 2 paths in each type?

A: UPDATE:
Thanks to ikegami's SO link, I have since done some source browsing, where we can find a lot of info about this. To get the more specific locations:
# perl -V:'install(privlib|archlib|vendorlib|vendorarch|sitelib|sitearch)' |column -t -s "="

installarchlib     '/usr/lib/perl5/5.26/x86_64-cygwin-threads';
installprivlib     '/usr/share/perl5/5.26';
installsitearch    '/usr/local/lib/perl5/site_perl/5.26/x86_64-cygwin-threads';
installsitelib     '/usr/local/share/perl5/site_perl/5.26';
installvendorarch  '/usr/lib/perl5/vendor_perl/5.26/x86_64-cygwin-threads';
installvendorlib   '/usr/share/perl5/vendor_perl/5.26';

Then for the meaning of those, we can look (in the perl sources) in the file: ./Porting/Glossary:
installarchlib    '- is the same for modules with arch- or build-dependent components.'
installprivlib    '- contains the "pure Perl" modules that came with Perl.'
installsitearch   '- is the same for modules with arch- or build-dependent components.'
installsitelib    '- contains the "pure Perl" modules installed by you.'
installvendorarch '- is the same for modules with arch- or build-dependent components.'
installvendorlib  '- contains the "pure Perl" modules installed by your distro.'

with the additional interesting note about the installstyle option:

installstyle (installstyle.U):
This variable describes the style of the perl installation. This
  is intended to be useful for tools that need to manipulate entire perl
  distributions. Perl itself doesn't use this to find its libraries --
  the library directories are stored directly in Config.pm. Currently,
  there are only two styles:  lib and lib/perl5. The default
  library locations (e.g. privlib, sitelib) are either $prefix/lib or
  $prefix/lib/perl5. The former is useful if $prefix is a
  directory dedicated to perl (e.g. /opt/perl), while the latter is
  useful if $prefix is shared by many packages, e.g. if
  $prefix=/usr/local.
Unfortunately, while this "style" variable is used to set defaults for
  all three directory hierarchies (core, vendor, and site), there is no
  guarantee that the same style is actually appropriate for all those
  directories.  For example, $prefix might be /opt/perl, but
  $siteprefix might be /usr/local. (Perhaps, in retrospect, the "lib"
  style should never have been supported, but it did seem like a nice
  idea at the time.)
The situation is even less clear for tools such as MakeMaker that can
  be used to install additional modules into non-standard places.  For
  example, if a user intends to install a module into a private
  directory (perhaps by setting PREFIX on the Makefile.PL command line),
  then there is no reason to assume that the Configure-time
  $installstyle setting will be relevant for that PREFIX.
This may later be extended to include other information, so be careful
  with pattern-matching on the results.
For compatibility with perl5.005 and earlier, the default setting is
  based on whether or not $prefix contains the string "perl".

All the gritty details can then be found in the INSTALLATION file, under the Installation Directories heading.

*

*Directories for the perl distribution:
By default, Configure will use the following directories (5.28.1):
    Configure variable  Default value
    $prefixexp          /usr/local
    $binexp             $prefixexp/bin
    $scriptdirexp       $prefixexp/bin
    $privlibexp         $prefixexp/lib/perl5/$version
    $archlibexp         $prefixexp/lib/perl5/$version/$archname

*Directories for site-specific add-on files:
   Configure        Default
   variable          value
 $siteprefixexp    $prefixexp
 $sitebinexp       $siteprefixexp/bin
 $sitescriptexp    $siteprefixexp/bin
 $sitelibexp       $siteprefixexp/lib/perl5/site_perl/$version
 $sitearchexp      $siteprefixexp/lib/perl5/site_perl/$version/$archname

*Directories for vendor-supplied add-on files:
If are building a binary distribution of perl for distribution, Configure
can optionally set up the following directories for you to use to
distribute add-on modules.
   Configure          Default
   variable            value
 $vendorprefixexp    (none)

 (The next ones are set only if vendorprefix is set.)

 $vendorbinexp       $vendorprefixexp/bin
 $vendorscriptexp    $vendorprefixexp/bin
 $vendorlibexp       $vendorprefixexp/lib/perl5/vendor_perl/$version
 $vendorarchexp      $vendorprefixexp/lib/perl5/vendor_perl/$version/$archname

*otherlibdirs:
As a final catch-all, Configure also offers an $otherlibdirs variable.
This variable contains a colon-separated list of additional directories
to add to @INC. By default, it will be empty.

*APPLLIB_EXP:
There is one other way of adding paths to @INC at perl build
time, and that is by setting the APPLLIB_EXP C pre-processor
token. The directories defined by APPLLIB_EXP get added to
@INC first, ahead of any others.
sh Configure -Accflags='-DAPPLLIB_EXP=\"/usr/libperl\"'

A: The best reference for these install locations is probably the ExtUtils::MakeMaker documentation for where it installs things. In essence:

*

*core (also known as privlib) - is where core modules that are installed with Perl goes. On Perls older than 5.12, updates to dual-life modules also need to be installed here over the core versions instead of into site or vendor lib, because privlib came first in @INC before 5.12. This is especially dangerous in a system Perl where the files in privlib are usually managed by a package manager.

*vendor - is where a distribution vendor may install modules to. This is usually where system package managers install non-core modules to.

*site - is where CPAN clients install modules to when invoked directly, barring unusual configuration like for dual-life modules as mentioned above.

(Dual-life modules are core modules which are also available separately on CPAN, which means that you can install an updated version.)
Each of these lib locations have an arch variant, which is where distributions with build-specific output files are installed to. Pure-perl distributions with no dynamic configuration are installed into the standard architecture-agnostic directory, and can usually run unmodified in other installations of Perl and architectures provided their requirements are still satisfied (though it's not a good idea unless you really know what you are doing). Distributions with any compiled XS modules or that generate modules dynamically in the build process are installed into the arch directory and are not safe to use from another Perl.
All of these locations are configured when the Perl is built and can be discovered using the perl -V option as you showed. They also each have accompanying script and bin directories (which are usually the same) and directories for manpages.
As to the discrepancy of cpan-outdated - this tool (like many tools using ExtUtils::Installed) is restricted to finding modules that have packlists, which are included when installing a module using a CPAN client, but not with core modules and they are generally stripped from vendor packages. So most likely cpan-outdated will only discover modules in sitelib, but this is usually all you need to find. I'm not sure what mechanism the cpan command uses.


text:
Q: PostgreSQL JSONB Execution Plan with high Offset How does PostgreSQL work i.e. the execution plan on JSONB query with high Offset number and how to improve the performance?
Considering the below "Test Query", help me to clarify the following:

*

*As the SubYear is 2050 which is a future date on which there are no cases available yet does it require a full table scan or is there any alternative approach to tune this ?

*When the same query is modified to retrieve the data with "SubYear" < 2050, there are lot of results i.e. 35k+. How does PostgreSQL works on it when the Offset is set to a high number lets say 30k ?
Test Query :
select
    *
from
    sub_test df,
    jsonb_array_elements(json_data) jba
where
    (jba->>'name')::text = 'SubYear'
    and (jba->>'value')::numeric > '2050';

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I continue pulling from subversion from a git clone which was not originally pointing to svn Given I have created a git repo on machine1 by pointing to svn with git svn clone --trunk=http://foo/project
And I keep pulling in new revisions from svn on machine1 with 'git svn rebase'
When I clone the git repo from machine1 to machine2
How do I repoint to svn my git repo on machine2 ???
So far I have done this:
Given I have repointed to svn with git svn init --trunk=http://foo/project on machine2
When I do 'git svn rebase'
Then nothing happens, prompt just hangs.
When I do 'git svn fetch'
Then git wants to reimport all of svn revisions as if it's brand new and that takes me 2 hours, but after that git svn rebase works fine.
When I do 'git svn fetch -r XXX' where XXX is the last svn revision id visible in last commit then I get some files from svn but after that git svn rebase just hangs and nothing happens.
I am looking for a procedure to repoint to a subversion trunk to keep pulling in new changes. I do not plan to commit back to SVN at all.
Any ideas?
My env setup:
git-svn version 1.7.9.5 (svn 1.6.17)
git version 1.7.9.5
on linux mint 13

A: on machine2
git svn init --trunk=http://foo/project
Ready to fetch from Subversion?
Not yet. We need metadata for the relationship between git commit and svn revision.
Find out the last commit SHA1 that has svn revision git show or git log -1
And write SHA1  to .git/refs/remotes/trunk
echo <SHA1> > .git/refs/remotes/trunk
Now you can git svn fetch  (git will rebuild rev map on first try (5 minutes maybe)).
The above worked for me on a branch git repo used to pull the latest updates form svn.

A: You can set up your local repository to have svn and the remote knowing that they are pointing to the same commits.
When you run (on machine2)
git svn init --trunk=http://foo/project

svn doesn't know that the repository it is pointing to is the same as the one you pulled from machine1.
To let git svn know that this is the case, you can use a prefix:
git svn init --prefix=origin/ --trunk=http://foo/project

(The trailing slash is important if you are going to use branches)
If you have already run the first init command, you can get the same result by editing your .git/config file to look like:
[svn-remote "svn"]
    fetch = http://foo/project:refs/remotes/origin/trunk

note the origin/ before trunk. If you don't want to edit the file manually, you can run:
git config --replace svn-remote.svn.fetch http://foo/project:refs/remotes/origin/trunk

Which will insert the line for you.
After doing this, you should be able to run git svn fetch and git will update your rev map.


text:
Q: Class Interfaces: Basic or Complex? I'm writing a container class for fun and education.  Previously when writing container classes I had limited myself to just a few very basic methods: GetValue, SetValue, GetSize and Resize.  I did this to avoid "code spaghetti" so my class would be easier to debug.
However, it occurred to me that users of the class might want to do more than just simple substitution.  So I added a few more methods:
void Replace(const std::size_t Start, const std::size_t End, const T Value);
void Replace(const std::size_t Start, const std::size_t End, const MyClass Other);
void Insert(const std::size_t Index, const T Value);
void Insert(const std::size_t Index, const MyClass Other);
void Delete(const std::size_t Index);
void Delete(const std::size_t Start, const std::size_t End);

In general, should classes provide only the most basic interface and let the users of the class make their own functions to do the complex stuff?  Or should the complex stuff be built-in at the cost of maintainability?

A: Classes should only provide a basic/minimal interface of member-functions (and preferably no data!). You can then add convenience methods as non-friend non-member functions. According to the interface-principle however, these functions are still part of your classes interface.
You already named the prime reason for this: it makes the class a lot easier to maintain. Also, implementing your "convienence" method part will serve as a nice test to see if you interface is good enough.
Note that the member function part of a container should usually be very generic and powerful, and care not about much more than maintaining class invariants.
This is most modern opinion on the subject, as far as I know. It is prominently advocated in Scott Meyer's "Effective C++" (In the most recent 3rd edition) and in Sutter's and Alexandrescu's "C++ Coding Standards".

A: The problem is that as soon as you write another container class (there are plenty of them in the wild, you may need different kinds), you will find that your design squares in O(N * M), where N is the number of container classes and M the number of algorithms.
The solution is to decouple the containers from the algorithms, and this is why iterators were introduced in the STL.
There are alternatives to iterators, using eg. polymorphism. You can factor out the traversing interface in an abstract common base class, and implement the algorithms in term of it.
In short, keep the most logic out of your container classes.

A: You should try to keep your interface lean, especially if you might want to implement different container types, e.g. array-based and linked-list. If you provide some basic methods in all your containers, you can create external algorithms which perform certain tasks but which can work on all containers:
 void Replace(const std::size_t Start, const std::size_t End, const T Value);

could become
 template<class ContainerType>
 void ReplaceAllElementsInContainer(ContainerType& Container, const std::size_t Start, const std::size_t End, const T Value);

outside the classes. If you don't do this, you have to write all those methods In all your containers.
Another possibility is to use the template method pattern (not related to C++ templates) and write all these methods in a base class (which defines the basic methods as pure virtual and calls them from the implemented "convenience" methods). This leads to possibly many virtual function calls which might not be desired in a container class for performance reasons.

A: I had a similar case like these. My suggestion is, that you have 2 "base classes" or "super classes".
The first class, very general class, represents the "conceptual root" for all containers classes, almost not methods, similar to an interface, and should be like:

    containers.hpp
class Container
{
protected:
   int GetValue();
   void SetValue(int newValue);

   size_t GetSize();

   void Resize(size_t);
};

The second class, starts to be a little less conceptual and more "real world":

    mcontainers.hpp
#include "containers.hpp";

class MethodContainer: public Container
{
protected:
  void Replace(const std::size_t Start, const std::size_t End, const T Value);
  void Replace(const std::size_t Start, const std::size_t End, const MyClass Other);
  void Insert(const std::size_t Index, const T Value);
  void Insert(const std::size_t Index, const MyClass Other);
  void Delete(const std::size_t Index);
  void Delete(const std::size_t Start, const std::size_t End);

    }
And, finally, some classes that are concrete:

    stacks.hpp
#include "containers.hpp";
#include "mcontainers.hpp";

#define pointer void*

class Stack: public MethodContainer
{
public:
  // these methods use "mcontainer::Insert", "mcontainer::Replace", etc
  void Push(pointer Item);
  void Pop();
  pointer Extract();
}

AS @Chris mentioned, there are several libraries for doing this, but there is always an exception to the rule, and you may want to "reinvent the wheel" if you need it.
I had an application, with its set of libraries, that included some containers / collections. It was made in another progr. langr. and need it to migrate it to C++.
Altought, I also check the c++ standard libraries, I ended migrating my libraries to C++, because I had several libraries calling my container libraries, and need it to do it fast.
When using "base classes", you may want to "protect" its members, and "take it to the public", in child classes. I usually don't make "private" fields or methods, unless necessarily.
Summary: Some very common complex stuff (like memory allocation or storage) may be done in your base classes, but, most of those complexity should be leave it to child classes.

A: If this container is used only by you in your code and the methods of your interface are sufficient for a specific purpose it is fine doing it this way.
However, as soon as someone else is going to use the container, or you plan to use it in other areas I'd recommend adding interface methods working with iterator types, then your container is much more open to be used with the stdlib containers and algorithms. Use the interfaces of the stdlib containers as example.


text:
Q: Tkinter | 'str' object has no attribute 'items' У меня есть программа которая берет статистику игрока с сайта и показывает ёё в программе.
Но когда я ввожу никнейм то мне выходит ошибка:

Traceback (most recent call last):
  File "C:\Program Files\Python\lib\tkinter\__init__.py", line 1550, in __call__
    return self.func(*args)
  File "C:\Users\MAKSIK\Desktop\Fortnite\test3.py", line 23, in Search
    Label(root, stats.wins).place(y = 50)
  File "C:\Program Files\Python\lib\tkinter\__init__.py", line 2606, in __init__
    Widget.__init__(self, master, 'label', cnf, kw)
  File "C:\Program Files\Python\lib\tkinter\__init__.py", line 2135, in __init__
    classes = [(k, v) for k, v in cnf.items() if isinstance(k, type)]
AttributeError: 'str' object has no attribute 'items'

Вот весь код:
from fortnite_python import Fortnite
from fortnite_python.domain import Platform
from fortnite_python.domain import Mode
import tkinter as tk
from tkinter import *

root = Tk()
root.geometry('700x600')

ment = StringVar()

entryBox = Entry(root,textvariable=ment)
entryBox.place(x = 280, y = 5)

fortnite = Fortnite('dc4c889e-af19-4e65-8257-8061d3fc453f')

def Search():
    mtext = ment.get()
    player = fortnite.player(mtext, Platform.PSN)
    stats = player.getStats(Mode.DUO)
    Label(root, stats.wins).place(y = 50)

Button(root, text='Search', command=Search).place(x = 410, y = 5)

A: Label(root, text=stats.wins).place(y = 50)

Если в stats.wins строка конечно.


text:
Q: Flutter Acces token was called null at the start and work fine after second I ma trying to pass token to header .i am accessing the token from my sharepreference. Data has been siccessfully save to preference. But on network call it passes a null value at start but works fine after getting back and reopen the page.
My error:
E/flutter (23190): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: NoSuchMethodError: The getter 'accessToken' was called on null.

  E/flutter (23190): Receiver: null
    E/flutter (23190): Tried calling: accessToken
    E/flutter (23190): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
    E/flutter (23190): #1      NetworkUtil.get (package:example/apihandler/network/NetworkUtil.dart:55:52)

My Network Class
class NetworkUtil {
  Dio _dio;
String token;
  LoginResponse loginResponse;

  NetworkUtil() {
    ///Create Dio Object using baseOptions set receiveTimeout,connectTimeout
    BaseOptions options = BaseOptions(receiveTimeout: 5000, connectTimeout: 5000);
    options.baseUrl = ApiConstants.BASE_URL;
    _dio = Dio(options);

      AppPrefernces.getLoginPref().then((data) {
        this.loginResponse = LoginResponse.fromJson(jsonDecode(data));
      });

    _dio.interceptors.add(LogInterceptor());

  }

  ///used for calling Get Request
  Future<Response> get(String url, Map<String, String> params) async {
    Response response = await _dio.get(url,
        queryParameters: params,
        options: Options(responseType: ResponseType.json,headers: {
          "Authorization": "Bearer ${loginResponse.accessToken==null?"":loginResponse.accessToken}"
        }));
    return response;
  }

  ///used for calling post Request
  Future<Response> post(String url, Map<String, dynamic> params) async {
    Response response = await _dio.post(url,
        data: params, options: Options(responseType: ResponseType.json));
    return response;
  }
}

Here is my  Sharedpreference file:
class AppPrefernces {
  static final String LOGIN_PREF = "login";

  static Future<String> getLoginPref() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.get(LOGIN_PREF) ?? null;
  }

  static setLoginPref(String value) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.setString(LOGIN_PREF, value);
  }
}

A: In your constructor NetworkUtil() you have async operation before you set the loginResponse with a token. And it is not finished when you make an API callout. You should redesign NetworkUtil initiation and add a flag to know if it is ready to be used.
You can use git_it and create async lazy singleton for your NetworkUtil.

A: When you call the get method, the loginResponse value doesn't assign yet.
class NetworkUtil {
  Dio _dio;
  String token;
  LoginResponse loginResponse;

  NetworkUtil() {
    ///Create Dio Object using baseOptions set receiveTimeout,connectTimeout
    BaseOptions options = BaseOptions(receiveTimeout: 5000, connectTimeout: 5000);
    options.baseUrl = ApiConstants.BASE_URL;
    _dio = Dio(options);

    _dio.interceptors.add(LogInterceptor());
  }

  ///used for calling Get Request
  Future<Response> get(String url, Map<String, String> params) async {
    loginResponse ??= LoginResponse.fromJson(jsonDecode(await AppPrefernces.getLoginPref()));

    Response response = await _dio.get(url,
        queryParameters: params,
        options: Options(responseType: ResponseType.json, headers: {
          "Authorization": "Bearer ${loginResponse.accessToken == null ? "" : loginResponse.accessToken}"
        }));
    return response;
  }

  ///used for calling post Request
  Future<Response> post(String url, Map<String, dynamic> params) async {
    Response response = await _dio.post(url, data: params, options: Options(responseType: ResponseType.json));
    return response;
  }
}


text:
Q: Color values with Reactable I am trying to make some conditional coloring for the values. The thing is that I already read some posts here on StackOverflow and in the reactable wiki but none of them are working!
reactable(prueba,
          defaultColDef = colDef(
            header = function(value) gsub(".", " ", value, fixed = TRUE),
            cell = function(value) format(value, nsmall = 1),
            align = "center",
            minWidth = 150,
            headerStyle = list(background = "#f7f7f8")
          ),
          bordered = TRUE,
          highlight = TRUE,
          defaultSortOrder = "desc",
          filterable = TRUE, minRows = 20,
          groupBy = "linea",

          columns = list(
            Inventory = colDef(aggregate = "sum"),
            OCC = colDef(aggregate = "mean"),
            Tickets.Vendidos = colDef(aggregate = "sum"),
            Revenue = colDef(aggregate = "sum"),
            RASK = colDef(aggregate = "mean"),
            CASK = colDef(aggregate = "mean"),
            Rating = colDef(aggregate = 'mean'),
            CpS = colDef(aggregate = 'mean'),
            Red.discount = colDef(aggregate = 'sum'),
            PC1 = colDef(aggregate = 'mean'),
            PC1_margin = colDef(aggregate = 'mean'),
            ASP = colDef(aggregate = 'mean')
            )
)

this is my code!!! And I wish to add conditions to the OCC column.
I would like for it to be:
RED if
0 <= OCC < 0.25
ORANGE if
0.25 <= OCC < 0.5
YELLOW if
0.5 <= OCC < 0.75
GREEN if
0.75 <= OCC <= 1
I tried using this inside my OCC column:
style = function(value) {
      if (value > 0) {
        color <- "#008000"
      } else if (value < 0) {
        color <- "#e00000"
      } else {
        color <- "#777"
      }
      list(color = color, fontWeight = "bold")
    }

but didnt work :(
please help me!!!!

A: I assume you're not still thinking about this, but in case anyone else stumbles here. The nested ifelse isn't elegant but in any case it functions for setting font color.
styler <- function(value){
      color <- ifelse(value > 0, "#008000", ifelse(value < 0, "#e00000", ifelse(is.na(value), "#777", NA)))
      list(color = color, fontWeight = "bold")
    }

Define the function outside the table, and you can call it like this. (I had two places in the function, value and params$my_comparator, so I could use these throughout).
colDef(aggregate = "mean",
    style = function(value){
    styler(value)
})


text:
Q: How to use relative imports in both, module and main I have the following setup of a library in python:
library
  | - __init__.py
  | - lib1.py
  | - ...
  | - tools
        | - __init__.py
        | - testlib1.py

so in other words, the directory library contain python modules and the directory tools, which is a subdirectory of library contains e.g. one file testlib1.pyto test  the library lib1.py.
testlib1.py therefore need to import lib1.py from the directory above to do some tests etc., just by calling python testlib1.py from somewhere on the computer, assuming the file is in the search path.
In addition, I only want ONE PYTHONPATH to be specified.
But we all know the following idea for testlib1.py does not work because the relative import does not work:
from .. import lib1
...
do something with lib1

I accept two kind of answers:

*

*An answer which describes how still to be possible to call testlib1.py directly as the executing python script.

*An answer that explains a better conceptual setup of of the modules etc, with the premise that everything has to be in the directory project and the tools has to be in a different directory than the actual libraries.

If something is not clear I suggest to ask and I will update the question.

A: Try adding a __init__.py to the tools directory. The relative import should work.

A: You can't. If you plan to use relative imports then you can't run the module by itself.
Either drop the relative imports or drop the idea of running testlib1.py directly.
Also I believe a test file should never use relative imports. Test should check whether the library works, and thus the code should be as similar as possible to the code that the users would actually use. And usually users do not add files to the library to use relative imports but use absolute imports.
By the way, I think your file organization is too much "java-like": mixing source code and tests. If you want to do tests then why not have something like:
project/
   |
   +-- src/
   |    |
   |    +--library/
   |    |     |
   |    |     +- lib1.py
   |    |     |
   |    |    #...
   |    +--library2/ #etc.
   |
   +-- tests/
        |
        +--testlibrary/
        |      |
        |      +- testlib1.py
        #etc

To run the tests just use a tool like nosetests which automatically looks for this kind of folder structure and provide tons of options to change the search/test settings.

A: Actually, I found a solution, which does

*

*works with the current implementation

*does not require any changes in PYTHONPATH

*without the need to hardcode the top-lebel directory

In testlib1.py the following code will do (has been tested):
import os
import sys
dirparts = os.path.dirname(os.path.abspath(__file__)).split('/')
sys.path.append('/'.join(dirparts[:-1]))

import  mylib1

Not exactly sure this is a very clean or straightforward solution, but it allows to import any module from the directory one level up, which is what I need (as the test code or extra code or whetever is always located one level below the actual module files).


text:
Q: Ícone errado no mat stepper angular Estou tentando colocar um ícone de edit quando o state é address, mas o ícone mostrado é do primeiro estado.
Eu tentei:
Primeiro step:
<ng-template matStepperIcon="edit">
    <mat-icon>home</mat-icon>
</ng-template>

<mat-step label="Antes de começar..." state="home">

..........
Segundo step
<ng-template matStepperIcon="address">
    <mat-icon>edit</mat-icon>
</ng-template>

<mat-step label="Dados do seu pet..." [stepControl]="secondFormGroup" state="address">
        <div>
            <button mat-button matStepperPrevious>Back</button>
            <button mat-button matStepperNext>Next</button>
        </div>

Esse é o resultado:

O segundo step deveria ser o edit icon mas está com o ícone do primeiro step. Por quê?

A: Pode não ser o mais intuitivo, mas... quando o Material Step é editável (editable), que é o default, após completar o step e acionar o próximo step, o anterior fica com o ícone de "edit".
No seu caso com o ícone "home" por conta da diretiva matStepperIcon que usou para mudar o ícone que vem por padrão.
Até o momento, o o Material Step utiliza apenas os ícones: 'create', 'edit' e 'done' que podem ser modificados, porém após mudar de step ele usará, somente, o ícone 'edit' ou o 'done' no step anterior.


text:
Q: AutoFill Right Index Match with column variation The below code applies a formula  every 7th row, and i would like it to AutoFill Right until the last column -1 (Because the last column has a SUM).
Sub test5()

'Prv. Cheg

Dim ShtPlan     As Worksheet
Dim ActSht      As Worksheet
Dim lastRow     As Long
Dim sheetName   As String
Dim lookupFrom  As String
Dim myRange     As String
Dim myRange2    As String
Dim i           As Long

Set ActSht = Sheets("Plan1")
lastRow = ActSht.Cells(ActSht.Rows.Count, 2).End(xlUp).Row ' Checks last row with data

sheetName = 'mysheet
Set ShtPlan = Sheets("Plan1")

myRange = "'" & sheetName & "'!$A:$P"
myRange2 = "'" & sheetName & "'!$A:$A"

For i = 5 To lastRow Step 7
    lookupFrom = ActSht.Cells(i - 3, 1).Address
    Cells(i, 3).Formula = "=INDEX(" & myRange & "," & "MATCH" & "(" & lookupFrom & "," & myRange2 & "," & "0)+3" & "," & "COLUMN(A1)+3)"
'The formula COLUMN (A1) changes the result accordingly.

Next i

End Sub


text:
Q: Redirect user that tries to view malicious URL or one that is not on the snort rule list? I have a fairly simple inline IPS set up that is using Snort as the detection system. I was wondering if it is possible with Snort to redirect a user that tries to view a URL that is on a disallowed list.
I'm subscribed to the Snort live-updated/most recent database and it is working and giving me alerts, but the only thing I have seen so far on the topic of redirections is to go:
Malicious attack -> Snort recognizes attack -> redirected to honeypot, and not:
User on LAN -> snort recognized disallowed site -> redirects to xyz page

A: You can use Snort's replace keyword in a rule to replace the disallowed URL with a URL of your choosing.  The only qualifications when using the keyword is the new text must be the same length as the previous text.
You can also use the react keyword to respond with an html page of your choice, but that will block the connection too.


text:
Q: Set input text box font size equal to input text box height Okay I basically have a .search_bar_container class that looks like below:
#search_bar_container{
    width: 81%;
    overflow: hidden;
    z-index: 1;
    position: absolute;
    top: 45%;
    left: 13.3%;
    height: 10%;
}

And a .search_bar class:
#search_bar{
    width: 80%;
    height: 99%;
    font-family: cursive;
    font-size: vh;
    box-shadow: 1px 1px 5px black;
}

Next my HTML looks like this

<input id='search_bar'/>

THE QUESTION
My question to you is how do I set the font-size of the search bar equal to the height of the search_bar? Things I have tried so far:
100%...Hmmm I have no idea why this never works for setting font size relative to the text box.
100vh...sets the size to 100% of body...Any way I can change the viewport and set it to the search_bar container...?

A: I know it's late but I want to share my solution with you. I use JavaScript to change input font when page loads and when page is being resized. Set font-size to offsetHeight of input. Then font size will be equal to input height. I think text won't fit then, that's why I use 70% of height like this:

//when window changes its size, make text fit again
window.onresize = function(event) {
    document.getElementById("username").style.fontSize = (document.getElementById("username").offsetHeight*0.7) + "px";
    document.getElementById("password").style.fontSize = (document.getElementById("password").offsetHeight*0.7) + "px";
};

//when page loads make text fit text box
function myFunction(){
document.getElementById("username").style.fontSize = (document.getElementById("username").offsetHeight*0.7) + "px";
document.getElementById("password").style.fontSize = (document.getElementById("password").offsetHeight*0.7) + "px";
}
#username{
width:85%;
height:100px;
font-size:25px;
padding-left:20px;
padding-right:20px;
}

#password{
width:85%;
height:50px;
font-size:25px;
padding-left:20px;
padding-right:20px;
}

body{
text-align:center;
}

<input type="text" id="username" placeholder="Username"/>

<input type="password" id="password" placeholder="Password"/>

If you want to set font size to more or less than 70% of input height, change 0.7 to number you want.


text:
Q: How do i initialize a binary tree in c# Can someone please tell me what i need to put in place of the '//code missing here'?
Where i have put "code missing" is where i am stuck. I am not sure what i need to put in place. I am new to binary trees so unfortunately am not very experienced with how they work. For my assignment this is the format my teacher wants so other tutorials online have not been particularly useful
using System;

public class Program
{

public class binarytree

{
    public class node
    { // Single element of tree (node)
        public string data;
        public node //CODE MISSING HERE
        public node rightPointer;
    }

    public node root;

    public bool add(string item)
    {
        try //in case of memory overflow (full)
        {
            // store new item in memory and start looking from root of tree
            node newNode = new node();
            newNode.data = item;
            newNode.//CODE MISSING HERE
            newNode.rightPointer = //CODE MISSING HERE
            node currentNode = root;
            //Case that tree is empty
            if (currentNode == null)
            {
                root = newNode;
                return true;
            }
            else
            {
                //work out where to put new item, by traversing tree until we find a left
                node previous = currentNode;
                while (currentNode != null)
                {
                    previous = currentNode;
                    //compareTo compares two strings, returns val <0 if lower
                    if (item.CompareTo(currentNode.data) //CODE MISSING HERE
                    {
                        currentNode = //CODE MISSING HERE
                    }
                    else
                    {
                        currentNode = currentNode.rightPointer;
                    }
                }
                if (item.CompareTo(previous.data)<0)
                {
                    //CODE MISSING HERE
                }
                else
                {
                    previous.rightPointer = newNode;
                }
                return true;
            }
        }
        catch
        {
            return false;
        }
    }
}

public static void Main()
{
    binarytree bt = new binarytree();
    bt.add("I am root");
    bt.add("Avengers");
    bt.add("Marvel");
    Console.WriteLine(bt.root.data);
    Console.WriteLine(bt.root.//CODE MISSING HERE
    Console.WriteLine(bt.root.rightPointer.data);
 }
}

A: I have sorted it
using System;

public class Program
{
public class binarytree
{
    public class node
    { // Single element of tree (node)
        public string data;
        public node leftPointer;
        public node rightPointer;
    }

    public node root;

    public bool add(string item)
    {
        try //in case of memory overflow (full)
        {
            // store new item in memory and start looking from root of tree
            node newNode = new node();
            newNode.data = item;
            newNode.leftPointer = null;
            newNode.rightPointer = null;
            node currentNode = root;
            //Case that tree is empty
            if (currentNode == null)
            {
                root = newNode;
                return true;
            }
            else
            {
                //work out where to put new item, by traversing tree until we find a left
                node previous = currentNode;
                while (currentNode != null)
                {
                    previous = currentNode;
                    //compareTo compares two strings, returns val <0 if lower
                    if (item.CompareTo(currentNode.data)<0)
                    {
                        currentNode = currentNode.leftPointer;
                    }
                    else
                    {
                        currentNode = currentNode.rightPointer;
                    }
                }
                if (item.CompareTo(previous.data)<0)
                {
                    previous.leftPointer = newNode;
                }
                else
                {
                    previous.rightPointer = newNode;
                }
                return true;
            }
        }
        catch
        {
            return false;
        }
    }
}

public static void Main()
{
    binarytree bt = new binarytree();
    bt.add("I am root");
    bt.add("Avengers");
    bt.add("Marvel");
    Console.WriteLine(bt.root.data);
    Console.WriteLine(bt.root.leftPointer.data);
    Console.WriteLine(bt.root.rightPointer.data);
}

}


text:
Q: Publishing .Net core Web App in VS 2015 not working because of missing references in project.json I am currently trying to publish a web application out of VS2015. The solution is building, but when I want to publish I continuously get the error message:
"Your project is not referencing the ".NETFrameworkVersion=v2.0" framework. Add a reference to ".NETFramewor, Version=v2.0" in the "frameworks" section of your project.json, and then re-run NuGet restore.
I already tried to change project.json in several ways that were suggested in StackOverflow ansers, but this was not working.
Can someone please help me out?
As a reference, I will add my project.json file and a screenshot of the problem.
Screenshot of the problem: https://imgur.com/l9a4Eru
`{
  "userSecretsId": "aspnet-KrisnaldoApp-009a51e2-478c-4020-ac03-0a98477155a1",
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.1",
      "type": "platform"
    },
    "Microsoft.AspNetCore.Authentication.Cookies": "1.0.0",
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore": "1.0.0",
    "Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.1",
    "Microsoft.AspNetCore.Razor.Tools": {
      "version": "1.0.0-preview2-final",
      "type": "build"
    },
    "Microsoft.AspNetCore.Routing": "1.0.1",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
    "Microsoft.AspNetCore.StaticFiles": "1.0.0",
    "Microsoft.EntityFrameworkCore.SqlServer": "1.0.1",
    "Microsoft.EntityFrameworkCore.SqlServer.Design": {
      "version": "1.0.1",
      "type": "build"
    },
    "Microsoft.EntityFrameworkCore.Tools": {
      "version": "1.0.0-preview2-final",
      "type": "build"
    },
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0",
    "Microsoft.Extensions.Configuration.UserSecrets": "1.0.0",
    "Microsoft.Extensions.Logging": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.Extensions.Logging.Debug": "1.0.0",
    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0",
    "Microsoft.VisualStudio.Web.CodeGeneration.Tools": {
      "version": "1.0.0-preview2-final",
      "type": "build"
    },
    "Microsoft.VisualStudio.Web.CodeGenerators.Mvc": {
      "version": "1.0.0-preview2-final",
      "type": "build"
    },
    "System.Xml.XmlSerializer": "4.0.11",
    "System.Xml.XmlDocument": "4.0.1"
  },
  "tools": {
    "BundlerMinifier.Core": "2.0.238",
    "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final",
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final",
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
    "Microsoft.Extensions.SecretManager.Tools": "1.0.0-preview2-final",
    "Microsoft.VisualStudio.Web.CodeGeneration.Tools": {
      "imports": [
        "portable-net45+win8"
      ],
      "version": "1.0.0-preview2-final"
    }
  },
  "frameworks": {
    "netcoreapp1.0": {
      "dependencies": {
        "System.ServiceModel.Duplex": "4.0.1",
        "System.ServiceModel.Http": "4.1.0",
        "System.ServiceModel.NetTcp": "4.1.0",
        "System.ServiceModel.Security": "4.0.1"
      },
      "imports": [
        "dotnet2.0",
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },
  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },
  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },
  "publishOptions": {
    "include": [
      "wwwroot",
      "**/*.cshtml",
      "appsettings.json",
      "web.config"
    ]
  },
  "scripts": {
    "prepublish": [
      "bower install",
      "dotnet bundle"
    ],
    "postpublish": [
      "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%"
    ]
  }
}`

A: I usually resolve this by clicking on Restore Nuget Packages at the solution level. Also try to save your project.json to a different file, Delete the one in your solution and clean your project and add it back manually. Sometimes these files become locked.


text:
Q: Can I redirect output of a program to gvim? I want to redirect the output of some Windows program directly to gvim basically for searching the output. Say for example the result of findstr cmd. Is it possible to do this without dumping it to a file and subsequently loading that file in gvim?

A: sure:
dir | gvim -

the - option tells vim to open stdin
This works for Windows and Linux versions.

A: You can read it from vim with
:r !dir (for example)

A: If you're already in Vim you can use the r command to read like this:
:r !<cmd>

E.g.
:r !dir

A: AFAIK, there is no gvim on Mac OS.
If you are using MacVim on mac, this is what I do:
dir | /Applications/MacVim.app/Contents/MacOS/Vim -

When Vim starts in the terminal, then type
<esc>:gui

That should start the MacVim (gui version of vim)


text:
Q: Second router in another building I've bought a Technicolor router for my summer house like the one I have in the house.
Can it be plugged in the ONT box on the wall in anyone as the manual says port 1 but that one is for the house. Or can it be plugged into a LAN port in the house router?

A: If you already have a router in the house I would recommend using it as a switch and a WLAN access point. If you can set your router to "bridge mode" you should be all set, then you just need to plug it into a LAN port in the house and configure the WiFi.
If the router doesn't have "bridge mode" you need to disable DHCP on your router and make sure to use the router's LAN port (not the WAN port).
If you want to add a second router to your ONT you'll have to check with your provider. It depends on the setup but a common one is that your router will establish a PPPoE connection with your internet provider through the ONT and most providers don't allow multiple connections.

A: You cannot connect two routers to one ONT box. The router you connect to the ONT box is the single connection point to your provider. If you want to extend your Internet connection to a second building, use a switch which you connect to one of the LAN ports of your router.


text:
Q: Having trouble deselecting my CCSprite on drag event, selectedSprite = nil not working I'm using code that has previously worked in other project the only difference is that this time I'm using a custom sprite class which seems to be not deselecting itself
Ive made a video here of the problem
https://www.youtube.com/watch?v=VHaTpiVPP_w&feature=youtu.be
-(void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{

NSSet *allTouch = [event allTouches];
UITouch *touch = [[allTouch allObjects]objectAtIndex:0];
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector]convertToGL:location];

DragItems = [[NSMutableArray alloc]initWithObjects:

         Bubble01,
         Bubble02,
         Bubble03,
         Bubble04,
         Bubble05,
         Bubble06,
         nil];

for(int i = 0; i < [DragItems count]; i++)
{
sprite = (Bubble *)[DragItems  objectAtIndex:i];
//if(sprite.tag ==12 && CGRectContainsPoint([sprite boundingBox],location))
if(CGRectContainsPoint([sprite boundingBox], location))
{
    selectedSprite = sprite;
}
}
}

-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
//Move touched sprite
NSSet *allTouch = [event allTouches];
UITouch *touch = [[allTouch allObjects]objectAtIndex:0];
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector]convertToGL:location];

selectedSprite.position = ccp(location.x, location.y);
NSLog(@"Position: %f %f",location.x, location.y);
}

-(void) ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
NSSet *allTouch = [event allTouches];
UITouch *touch = [[allTouch allObjects]objectAtIndex:0];
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector]convertToGL:location];

selectedSprite = nil;

}

A: drag on CCLayer sometimes working
With the very kind help of rahul_send89 we solved the problem,
firstly the custom class a cclayer was changed to accept its own touches, then in the init
[self setContentSize:[BackBubble boundingBox].size]; was used to size the layer
(so other touches fire, this is what was probably messing up the touches for me)
the link above contains all the code. thanks again for the help!


text:
Q: Line breaks in Sitecore single line textbox When I press ENTER in Sitecore single line field textbox it renders TWO linebreaks

This issue appears only in Chrome/Firefox. In IE ENTER leads only to one
Can I disable somehow automatic adding of  in these browsers?

A: Issue is caused by Sitecore Intranet.WebEdit.js
Modifiying this piece of code helped with problem:
 if (evt.keyCode == 13 && this.activeElement && this.activeElement.contentEditable() && this.activeElement.parameters["linebreak"] == "br") {
        try {

            if (document.selection != null) {

                var sel = document.selection.createRange();
                sel.pasteHTML('
');
                evt.stop();
            }

            if (!Prototype.Browser.IE) {
                evt.srcElement.innerHTML = evt.srcElement.innerHTML + "
";
                evt.stop();
            }
        }


text:
Q: VM Service not connecting when debugging for iOS | Flutter macOS iOS Simulator I have just set up a Ryzen Hackintosh to be able to develop for iOS as well but after tweaking my app config for having firebase working also on the iOS version, I try to debug it on the iOS Simulator and this error appears:

If I try to debug a fresh newly created app it will run with no problems at all, same thing happens if I debug a fresh newly created app but with Firebase in it. This exception only happens when trying to debug a quite complete app I was developing on Windows and just for Android.
Any tips? Thank you so much.

A: I have found the solution:

*

*Opening XCode and opening the iOS folder as a project there

*Adding the "GoogleServices-Info.plist" file via "Add Files" (right click on "Runner" in the left bar and choose "Add Files to 'Runner'") => Select the "GoogleServices-Info.plist" file


text:
Q: Problem with accessing in DOM with jQuery I changed the tree of my JSON-P output, and i cannot access to my object DOM anymore :
Here's my output :
jsonp1271634374310(
{"Inter-Medias":
    {"name":"Inter-Medias","idGSP":"14","average":"80","services":"8.86"}
});

And here's my jQuery script :
success: function(data, textStatus, XMLHttpRequest){
widget = data.name;
widget += data.average ;
....

*

*I know one level is missing, but if I try to do : data.Inter-Medias.name or data.name.name
it's still not working.
Any idea please ?
Thank you.

A: Your question is a bit confusing but I think what your issue is the JSON key. Try doing this:
data["Inter-Medias"].name

Now if you are expecting multiple objects you want the root element in your JSON to be an array.
[
    {
        "name" : "A",
        "average" : 1
    },
    {
        "name" : "B",
        "average" : 2
    }
]

In code you can access it like this.
var obj = null, length = data.length;
for (var i = 0; i < length; i++) {
    obj = data[i];
    if (obj.name === "A") {
        runningAverage += obj.average;
    }
}


text:
Q: How does Scala's apply() method magic work? In Scala, if I define a method called apply in a class or a top-level object, that method will be called whenever I append a pair a parentheses to an instance of that class, and put the appropriate arguments for apply() in between them. For example:
class Foo(x: Int) {
    def apply(y: Int) = {
        x*x + y*y
    }
}

val f = new Foo(3)
f(4)   // returns 25

So basically, object(args) is just syntactic sugar for object.apply(args).
How does Scala do this conversion?
Is there a globally defined implicit conversion going on here, similar to the implicit type conversions in the Predef object (but different in kind)? Or is it some deeper magic? I ask because it seems like Scala strongly favors consistent application of a smaller set of rules, rather than many rules with many exceptions. This initially seems like an exception to me.

A:
I ask because it seems like Scala strongly favors consistent application of a smaller set of rules, rather than many rules with many exceptions.

Yes. And this rule belongs to this smaller set.

A: I don't think there's anything deeper going on than what you have originally said: it's just syntactic sugar whereby the compiler converts f(a) into f.apply(a) as a special syntax case.
This might seem like a specific rule, but only a few of these (for example, with update) allows for DSL-like constructs and libraries.

A: It is actually the other way around, an object or class with an apply method is the normal case and a function is way to construct implicitly an object of the same name with an apply method. Actually every function you define is an subobject of the Functionn trait (n is the number of arguments).
Refer to section 6.6:Function Applications of the Scala Language Specification for more information of the topic.


text:
Q: Rotating svg element looks like bouncing slightly I looked at the existing question related yo my query but could not get help.
I am Using basic animation of css3. Below is the fiddle..
https://jsfiddle.net/gamerVinod/d21c6bcb/5/
Below is the css
@keyframes rotate {
    from {
       transform: rotate(0deg);
       transform-origin: center;
    }
    to {
        transform: rotate(359deg);
        transform-origin: center;
    }
}

.rotate-element {
    animation: rotate 1s infinite linear;
}

Whenever i use SVG and rotate it then it bounces slightly.
I am not able to find out whether it is due to SVG path or anything else.Can someone please let me know the reason of it and how to fix it?

A: As @Ouroborus said, bezier curves can only approximate circular arcs.  If you need to rotate those shapes then, unless your shape is carefully and accurately crafted, you are likely to see some shimmy.
You could use the arc (A) path element instead. But you don't need to. By far the simplest solution here is to use an actual <circle>.

@keyframes rotate {
    from {
        transform: rotate(0deg);
    }
    to {
        transform: rotate(359deg);
    }
}

.rotate-element {
    animation: rotate 1s infinite linear;
}

.parent{
  height: 200px;
  width: 200px;
  background: red;
  display: flex;
  align-items:center;
  text-align: center;
}

.child{
  height: 200px;
  width: 200px;
}
<div class="parent">
 <svg class="child rotate-element" version="1.1" id="loader-1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
   viewBox="0 0 40 40" enable-background="new 0 0 40 40" xml:space="preserve">
    <circle cx="20" cy="20" r="13.25" opacity="0.2" fill="none"
            stroke="#000" stroke-width="3"/>
    <circle cx="20" cy="20" r="13.25" fill="none"
            stroke="#000" stroke-width="3"
            stroke-dasharray="6 80"/>
  </svg>
</div>

Here I am using two circles with thick strokes (lines) and transparent fill.  The one at the back is semi-transparent (like the original SVG).  The one on top has only part of it's stroke drawn by using a dash array.


text:
Q: StreamingHttpResponse not working with ASGI but work fine with WSGI I'm trying to use channels for some WebSockets-related stuff, but it keeps loading and not showing any streaming response when I reload my web page. Here is my code which works fine with this setting:
# settings.py
# WSGI_APPLICATION = 'main.wsgi.application' # work fine
ASGI_APPLICATION = "main.asgi.application"  # not working

And here is my views.py:
@gzip.gzip_page  # for performance
def video_stream(request: HttpRequest):
    video = VideoContainer.objects.last()
    video_path = video.file.path
    return StreamingHttpResponse(generate_frames(VideoCamera(video_path)),
                                 content_type="multipart/x-mixed-replace;boundary=frame")

Here is my code for generate_frames and VideoCamera:
import cv2

class VideoCamera:
    def __init__(self, video_path: str):
        self.video = cv2.VideoCapture(video_path)

    def __del__(self):
        self.video.release()

    def get_frame(self):
        while (self.video.isOpened()):
            img = self.video.read()[1]

            # because web-page looking for image/jpeg content type
            jpeg = cv2.imencode(".jpg", img)[1]
            return jpeg.tobytes()  # we stream it in byte form for frontend

def generate_frames(camera) -> bytes:
    while True:
        frame = camera.get_frame()
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')


text:
Q: How to optimize a bash script? (Find files, ignore those on whitelist, report rest) I wrote this script to find all files/directories to which $WWWUSER has write permissions. At first I stored the remaining, matching items in a temporary file. I new there must be a way without using files, so this is my "solution". It works, but it's pretty slow. Any tips?
Update:
On a directory structure containing about 7k directories and 30k files (~8k whitelistings) the script takes about 15 minutes... (ext3 filesystem, UW320 SCSI harddisk).
#!/usr/bin/env bash
# Checks the webroot for files owned by www daemon and
# writable at the same time. This is only needed by some files
# So we'll check with a whitelist

WWWROOT=/var/www
WWWUSER=www-data
WHITELIST=(/wp-content/uploads
/wp-content/cache
/sitemap.xml
)
OLDIFS=$IFS
IFS=$'\n'

LIST=($(find $WWWROOT -perm /u+w -user $WWWUSER -o -perm /g+w -group $WWWUSER))
IFS=$OLDIFS

arraycount=-1
whitelist_matches=0

for matchedentry in "${LIST[@]}"; do
        arraycount=$(($arraycount+1))

        for whitelistedentry in "${WHITELIST[@]}"; do
                if [ $(echo $matchedentry | grep -c "$whitelistedentry") -gt 0 ]; then
                        unset LIST[$arraycount]
                        whitelist_matches=$(($whitelist_matches+1))
                fi
        done
LISTCOUNT=${#LIST[@]}
done

if [ $(echo $LISTCOUNT) -gt 0 ]; then
        for item in "${LIST[@]}"; do
                echo -e "$item\r"
        done
        echo "$LISTCOUNT items are writable by '$WWWUSER' ($whitelist_matches whitelisted)."
else
        echo "No writable items found ($whitelist_matches whitelisted)."
fi

A: There is another possibility. Changing the whitelist to a regex pattern you could use the =~ bash regex operator (version 3 and up) to match any found word quickly against the list:
    if($word=~$pattern)
$pattern could be
    "^(whitelistentry1|whitelistentry2|whitelistentry3|...)$".

A: (I don't have a setup handy to test this on, but it should work...)
#!/usr/bin/env bash
# Checks the webroot for files owned by www daemon and
# writable at the same time. This is only needed by some files
# So we'll check with a whitelist

WWWROOT=/var/www
WWWUSER=www-data
WHITELIST="(/wp-content/uploads|/wp-content/cache|/sitemap.xml)"

listcount=0
whitelist_matches=0

while IFS="" read -r matchedentry; do
    if [[ "$matchedentry" =~ $WHITELIST ]]; then
        ((whitelist_matches++))
    else
        echo -e "$matchedentry\r"
        ((listcount++))
    fi
done < <(find "$WWWROOT" -perm /u+w -user $WWWUSER -o -perm /g+w -group $WWWUSER)

if (( $listcount > 0 )); then
        echo "$listcount items are writable by '$WWWUSER' ($whitelist_matches whitelisted)."
else
        echo "No writable items found ($whitelist_matches whitelisted)."
fi

Edit: I've incorporated Dennis Williamson's suggestions on the math; also, here's a way to build the WHITELIST pattern starting from an array:
WHITELIST_ARRAY=(/wp-content/uploads
/wp-content/cache
/sitemap.xml
)

WHITELIST=""
for entry in "${WHITELIST_ARRAY[@]}"; do
    WHITELIST+="|$entry"
done
WHITELIST="(${WHITELIST#|})"  # this removes the stray "|" from the front, and adds parens

Edit2: Sorpigal's comment about eliminating new processes got me thinking -- I suspect most of the speedup in this version comes from not running ~40 invocations of grep per scanned file, and just a little bit from removing the array manipulation, but it occurred to me that if you don't need the totals at the end, you could remove the main while loop and replace it with this:
find "$WWWROOT" -perm /u+w -user $WWWUSER -o -perm /g+w -group $WWWUSER | grep -v "$WHITELIST"

...which does run grep, but only once (and runs the entire file list through that single instance), and once it's started grep'll be able to scan the list of files faster than a bash loop...


text:
Q: No one will come to my vault on fallout shelter, how do i fix this? No dwellers will come to my vault and I don't have enough dwellers for a radio tower. I tried babies but it takes too long. How do I fix this?

A: There are only those two options:  First, make babies. Second, wait for random people to want to join. If you don't have enough for a radio tower, then I assume you don't have enough for an overseer's room (I can't recall offhand how many dwellers that takes) because there it's possible to come across people in the wasteland while on a quest from the overseer's room, and invite them back to your vault, but that's even slower than making babies. Find a couple people who have 100% happiness (they will mate faster) and make sure they're not already related (zoom in, and if they talk about spending time with family, swap one out for another dweller) and just wait for the famous yellow-shirted pregnant dweller to come strolling out.
I try to do that before I turn the game off, so the baby will be ready to be born as soon as I start playing the next day.


text:
Q: Traverse thru array elements and extract delimited values when condition is satisfied I want to loop thru an array and extract its delimited values that match every date in a range. For e.g., in the picture below:

*

*I have a date range, say 01-01 to 01-10.

*I also have a list of strings (see second pic).

*In the array below (see first pic), I have three different values delimited by a semi-colon.

*For all matching strings (from second pic) e.g., SISBTXTRPR-(number) and date, I want to extract the last part of the array value.

Picture 1

Picture 2

So, for all array values that match "SISBTXTRPR-4649" (the string from picture 2) and a date  (in this case 12-12), I want to extract "2h" from the array. The date range for each string, in this case, "SISBTXTRPR-4649" will be 10 days. I am racking my brain on how to do this :(
This is all I could come up with so far:
While i < UBound(sTimeStamp)
If StrComp(Trim(Format(Now(), "MM-DD")), Trim(Split(sTimeStamp(9), ";")(1))) = 0 And StrComp(Trim(Worksheets("KPIs").Range("AN" & iCounter)), Trim(Split(sTimeStamp(1), ";")(0))) Then

End If
i = i + 1
Wend

Link to file
Sample File

A: The next code will return occurrences for each string in 'Task' range matching the date from its corresponding 'sTimeStamp Array' string with the one from the 'Date Range Array'. Each occurrence will be add to the next column of 'Task' string column:
Private Sub findOccurrences()
  Dim sTask As Worksheet, sStamp As Worksheet, sDate As Worksheet
  Dim arrTask As Variant, arrStamp As Variant, arrDate As Variant
  Dim i As Long, j As Long, arrS As Variant, El As Variant, dtRef As Date

  Set sTask = ThisWorkbook.Sheets("Task")
  Set sStamp = ThisWorkbook.Sheets("sTimeStamp Array")
  Set sDate = ThisWorkbook.Sheets("Date Range Array")
    arrTask = sTask.Range("A2:A" & sTask.Range("A" & sTask.Rows.Count).End(xlUp).Row).Value
    arrStamp = sStamp.Range("A2:A" & sStamp.Range("A" & sStamp.Rows.Count).End(xlUp).Row).Value
    arrDate = sDate.Range("A2:A" & sDate.Range("A" & sDate.Rows.Count).End(xlUp).Row).Value

    '____________________________________________________________________________
    sTask.Range("B2:K" & sTask.Range("A" & sTask.Rows.Count).End(xlUp).Row).Clear
    Do While i < UBound(arrStamp)
        i = i + 1
        arrS = Split(arrStamp(i, 1), ";")
        For j = 1 To UBound(arrTask)
            If arrS(0) = arrTask(j, 1) Then
                For Each El In arrDate
                    dtRef = DateValue(Format(El, "MM-DD"))
                    If dtRef = DateValue(Format(arrS(1), "MM-DD")) Then
                        Debug.Print arrS(0) & " (row number " & j + 1 & "), interval """ & _
                                                                        El & """ exists."
                        sTask.Cells(j + 1, sTask.Cells(j + 1, _
                            sTask.Columns.Count).End(xlToLeft).Column).Offset(0, 1).Value = El
                    End If
                Next
            End If
        Next j
    Loop

End Sub

And the short variant working similar to your approach, finding the occurrences for Today date (if I correctly deduced what you intended to achieve), replace the looping part with this:
'______________________________________________________________________________
    sStamp.Range("B2:B" & sStamp.Range("A" & sStamp.Rows.Count).End(xlUp).Row).Clear
sTask.Range("A2:A" & sTask.Range("A" & sStamp.Rows.Count).End(xlUp).Row).Interior.ColorIndex = -4142
While i < UBound(arrStamp)
    i = i + 1
    If StrComp(DateValue(Format(Date, "MM-DD")), DateValue(Split(arrStamp(i, 1), ";")(1))) = 0 And _
                                Not isMatchErr(CStr(Split(arrStamp(i, 1), ";")(1)), arrDate) Then
        Debug.Print "OK for """ & Split(arrStamp(i, 1), ";")(0) & """ of row """ & i & """."
        sStamp.Range("B" & i + 1).Value = "OK"
        If Not isMatchErr(CStr(Split(arrStamp(i, 1), ";")(0)), arrTask) Then
            rowOK = WorksheetFunction.Match(Split(arrStamp(i, 1), ";")(0), arrTask, 0) + 1
            sTask.Range("A" & rowOK).Interior.ColorIndex = 3
        End If
    End If
Wend

And add the next function:
Function isMatchErr(strTime As String, arrDate As Variant) As Boolean
   Dim k As Long
   On Error Resume Next
     k = WorksheetFunction.Match(strTime, arrDate, 0)
     If Err.Number <> 0 Then
        Err.Clear: On Error GoTo 0: isMatchErr = True
     End If
   On Error GoTo 0
End Function

Besides the message in Immediate Window, an "OK" will be put on column B:B for all occurrences (in 'sTimeStamp Array' sheet) and background of the matching cell (in 'Task' sheet will be colored in red... In order to do that, I added a new record and modified an existing cell, for "Today" ("01-12"). Please do the same in order to obtain at least two results in column B:B.
Please confirm that this is what you wanted. If not, please better clarify the need...


text:
Q: Dynamic SELECT and place result in variable columns Edit: I use Microsoft SQL Server Management Studio, I believe it's SQL 2008R2. Sorry, new to this.
I've got a complex question, at least, I think so since I can't find the answer after excessive googling.
Simplified situation:
Table | QuestionAnswers
id
user_id
question_id
answer

Table | Questions
id
question_id
question_name

Now I want to write a query that gives the following result:
user_id | question 1 | question 2 | question 3 | que...etc
1         Something
1                                   Something
2                      Something
3         Something
3                      Something

Or (but that shouldn't be too difficult if I have the above?):
user_id | question 1 | question 2 | question 3 | que...etc
1         Something                 Something
2                      Something
3         Something    Something

Where 'something' is the answer to the question.
Now I have a possible query:
SELECT [user_id]
      ,[answer] as Question1
      ,''       as Question2
      ,etc
FROM [QuestionAnswers]
WHERE [question_id] = 1

UNION ALL

SELECT [user_id]
       ,''       as Question1
       ,[answer] as Question2
       ,etc
FROM [QuestionAnswers]
WHERE [question_id] = 2

UNION ALL

SELECT etc...

Works like a charm. Downside is that this way, I have to make x SELECT statements with x rows, where x is the number of questions I have (50+).
How can this be done dynamically? Is that possible?
I hope I explained myself good enough...
Kind regards,
Tjab

A: Adding an example to Michael's answer.  The problem with the PIVOT is two fold. 1st, it wants to aggregate.  You can get around this by defining your dataset to be distinct and using MAX or MIN functions.  But your example above makes that impossible, due to a user being able to have multiple answer sets for a given question.  You would end up with only one row with the two datasets aggregated for the dupe user.  To get around this I added a "question_set" field, adding a date (distinct enough for this example) to each question/answer set.
2nd, you still have to define the pivoted fields.  If you have 50 questions, that's 50 definitions.  And if you add a question, you will have to add the definition to the query.  Using a loop, I created a question list dynamically and inserted it into the pivot query.  Hope this helps.
--> Create the test data
if OBJECT_ID('QuestionAnswers','u') is not null
    drop table QuestionAnswers

create Table  QuestionAnswers
(
id int identity,
question_set date, --> need something to delineate repeats
user_id varchar(255),
question_id int,
answer varchar(255)
)

if OBJECT_ID('Questions','u') is not null
    drop table Questions

create Table  Questions
(
id int identity,
question_id int,
question_name varchar(255)
)
go

with CTEquestion
as
(
    select 1 QID
    union all
    Select QID+1
    from CTEquestion
    where QID < 11
)
insert questions
select QID, 'Question'+cast(QID as varchar(50))
from CTEquestion

insert QuestionAnswers
values ('2015-04-23', 'a1', 1, 'Canswer1')
    ,  ('2015-04-23', 'a1', 2, 'Ianswer2')
    ,  ('2015-04-23', 'a1', 3, 'Canswer3')
    ,  ('2015-04-23', 'a1', 4, 'Canswer4')
    ,  ('2015-04-23', 'a1', 5, 'Ianswer5')
    ,  ('2015-04-23', 'a1', 6, 'Ianswer6')
    ,  ('2015-04-23', 'a1', 7, 'Canswer7')
    ,  ('2015-04-23', 'a1', 8, 'Canswer8')
    ,  ('2015-04-23', 'a1', 9, 'Canswer9')
    ,  ('2015-04-23', 'a1', 10,'Canswer10')

insert QuestionAnswers
values (CONVERT(DATE, GETDATE()), 'b2', 1, 'Canswer1')
    ,  (CONVERT(DATE, GETDATE()), 'b2', 2, 'Canswer2')
    ,  (CONVERT(DATE, GETDATE()), 'b2', 3, 'Canswer3')
    ,  (CONVERT(DATE, GETDATE()), 'b2', 4, 'Canswer4')
    ,  (CONVERT(DATE, GETDATE()), 'b2', 5, 'Canswer5')
    ,  (CONVERT(DATE, GETDATE()), 'b2', 6, 'Ianswer6')
    ,  (CONVERT(DATE, GETDATE()), 'b2', 7, 'Canswer7')
    ,  (CONVERT(DATE, GETDATE()), 'b2', 8, 'Canswer8')
    ,  (CONVERT(DATE, GETDATE()), 'b2', 9, 'Canswer9')
    ,  (CONVERT(DATE, GETDATE()), 'b2', 10, 'Ianswer10')

insert QuestionAnswers
values (CONVERT(DATE, GETDATE()), 'c3', 1, 'Ianswer1')
    ,  (CONVERT(DATE, GETDATE()), 'c3', 2, 'Ianswer2')
    ,  (CONVERT(DATE, GETDATE()), 'c3', 3, 'Canswer3')
    ,  (CONVERT(DATE, GETDATE()), 'c3', 4, 'Ianswer4')
    ,  (CONVERT(DATE, GETDATE()), 'c3', 5, 'Canswer5')
    ,  (CONVERT(DATE, GETDATE()), 'c3', 6, 'Ianswer6')
    ,  (CONVERT(DATE, GETDATE()), 'c3', 7, 'Canswer7')
    ,  (CONVERT(DATE, GETDATE()), 'c3', 8, 'Canswer8')
    ,  (CONVERT(DATE, GETDATE()), 'c3', 9, 'Canswer9')
    ,  (CONVERT(DATE, GETDATE()), 'c3', 10, 'Ianswer10')

insert QuestionAnswers
values (CONVERT(DATE, GETDATE()), 'a1', 1, 'Canswer1')
    ,  (CONVERT(DATE, GETDATE()), 'a1', 2, 'Ianswer2')
    ,  (CONVERT(DATE, GETDATE()), 'a1', 3, 'Canswer3')
    ,  (CONVERT(DATE, GETDATE()), 'a1', 4, 'Canswer4')
    ,  (CONVERT(DATE, GETDATE()), 'a1', 5, 'Canswer5')
    ,  (CONVERT(DATE, GETDATE()), 'a1', 6, 'Canswer6')
    ,  (CONVERT(DATE, GETDATE()), 'a1', 7, 'Canswer7')
    ,  (CONVERT(DATE, GETDATE()), 'a1', 8, 'Canswer8')
    ,  (CONVERT(DATE, GETDATE()), 'a1', 9, 'Canswer9')
    ,  (CONVERT(DATE, GETDATE()), 'a1', 10, 'Ianswer10')
-->End test data creation

--straight join
select qa.user_id, qa.question_set, q.question_id, qa.answer
from Questions q
    join QuestionAnswers qa on qa.question_id=q.question_id
order by qa.user_id

--dynamic pivot
DECLARE
    @questionList varchar(max)
, @maxQID int
, @qid int

select @questionList='',@maxQID = MAX(question_id), @qid= MIN(question_id)
FROM Questions

while @qid <= @maxQID
begin
    set @questionList=@questionList+'['+cast(@qid as varchar(10))+']'

    select @qid=min(question_id)
    from Questions
    where question_id > @qid

    if @qid<=@maxQID
        set @questionList=@questionList+', '
end

DECLARE @SQL NVARCHAR(MAX)

SET @SQL = N'
select user_id, '+@questionList+'
from
(select q.question_id, qa.question_set, qa.user_id, qa.answer
from Questions q
    join QuestionAnswers qa on qa.question_id=q.question_id) x
PIVOT
(
max(answer)
FOR question_id in ('+@questionList+')
) pvt
order by user_id'

exec sp_executesql @SQL

A: I use something like this to create dynamic pivots with a dynamic number of columns. Perhaps it will help you with your solution. It's a single statement to avoid looping or cursors.
declare @strSQL as varchar(max)
declare @columns as varchar(max)
declare @columns1 as varchar(max)

set @columns = (select stuff ((select ',cast(' + quotename(columnname) + ' as ' + fieldDataType + ') as ' + quotename(fieldname) as [text()] from MyTable for xml path ('') ),1,1,''))
set @columns1 = (select stuff ((select ',' + quotename(columnnumber) as [text()] from MyTable for xml path ('') ),1,1,''))

set @strSQL = 'select rownumber, ' + @columns + ' from
    (select rownumber, columnnumber, fieldData from MyTable
    pivot
    ( max(fieldData) for columnNumber in (' + @columns1 + ')) p'

exec (@strSQL)


text:
Q: Trouble when trying to check list with another list One part of my program allows the user to check whether the clues they have entered are correct with the  solved version which is in an external file named solved.txt... So far I have the code shown below however it is only showing the three clue pairings at the beginning of the program which are correct, not the ones which I have added throughout the program. I think this is just something minor but I am a bit stuck on what to change.
Here is my code so far...
def check_clues():
    # Dictionary to hold all of the symbol/letter combos
    coded_dict = {}

    # Go through each symbol/letter combination together
    with open("words.txt") as fw, open("solved.txt") as fs:
        for fw_line, fs_line in zip(fw, fs):
            for fw_symbol, fs_letter in zip(fw_line.strip(), fs_line.strip()):
                # Add the symbol/letter combination to the dictionary
                coded_dict[fw_symbol] = fs_letter

    correct_clues = []
    with open("clues.txt") as fc:
        for fc_line in fc:
            # If the symbol is in the dictionary and the letter matches the symbol
            if fc_line[1] in coded_dict and coded_dict[fc_line[1]] == fc_line[0]:
                # Add a correct clue to your list
                correct_clues.append(fc_line.strip())

    print("You got a total of {0} correct: {1}".format(len(correct_clues), ", ".join(correct_clues)))

if __name__ == "__main__":
    check_clues()

Below is a link to what is in each of the files...
http://www.codeshare.io/vgwrC
If needed, I will add the code for all of my program...


text:
Q: CheckBoxList not updating it's checked/not checked state Hey, I have a CheckBoxList that gets populated with the database. When I make any changes to the state (check or uncheck) of a single checkbox, it doesn't get returned when I submit my form.
To its simplest form, I have:
<asp:CheckBoxList runat="server" ID="listEmployes" RepeatDirection="Horizontal">
</asp:CheckBoxList>

C#:
protected void btnSubmit_Click(object sender, EventArgs e)
{
    _connection.Open();

    var employes = listEmployes.Items;

    foreach (ListItem employe in employes)
    {
        if (employe.Selected)
        {
            _command = new MySqlCommand(String.Format("INSERT IGNORE INTO Liste_Employes (Projet_ID, User_ID) VALUES ({0}, {1})", _projetId, employe.Value), _connection);
        }
        else
        {
            _command = new MySqlCommand(String.Format("DELETE IGNORE FROM Liste_Employes WHERE Projet_ID = {0} AND User_ID = {1}", _projetId, employe.Value), _connection);
        }

        _command.ExecuteNonQuery();
    }

}

Am I missing something? Thanks.

A: Make sure your CheckBoxList is not being rebound on postbacks (if you're databinding from code).
If(!Page.IsPostBack)
{
    // Bind code
}

A: What is in your Page_Load method? I am guessing that you are not checking for !Page.IsPostBack before you bind the checkboxes.


text:
Q: Load a JSON file from API with JavaScript I am hanging with this problem:
I am trying to get the JSON file from http://finance.google.com/finance/info?client=ig&q=NASDAQ:TSLA with this code:
$("document").ready(function () {
    // Calling function
    reLoad();

    function reLoad() {
        $.getJSON("http://finance.google.com/finance/info?client=ig&q=NASDAQ:TSLA", function(data) {
            alert(data);
        });

        setTimeout(reLoad, 1000);
    };
});

But this isn't working.
Any ideas?

A: You need to define the function before you call it, or it won't work.
In this case, that means you need to write reLoad(); after function reLoad() { ... } instead of before.

A: Thanks for your respond, but when i am testing my code with another json file it works! So my problem is just getting this spezial file from the url "http://finance.google.com/finance/info?client=ig&q=NASDAQ:TSLA", which looks like this:
// [ { "id": "12607212" ,"t" : "TSLA" ,"e" : "NASDAQ" ,"l" : "216.22" ,"l_fix" : "216.22" ,"l_cur" : "216.22" ,"s": "1" ,"ltt":"4:00PM EDT" ,"lt" : "May 23, 4:00PM EDT" ,"lt_dts" : "2016-05-23T16:00:01Z" ,"c" : "-4.06" ,"c_fix" : "-4.06" ,"cp" : "-1.84" ,"cp_fix" : "-1.84" ,"ccol" : "chr" ,"pcls_fix" : "220.28" ,"el": "217.50" ,"el_fix": "217.50" ,"el_cur": "217.50" ,"elt" : "May 24, 7:52AM EDT" ,"ec" : "+1.28" ,"ec_fix" : "1.28" ,"ecp" : "0.59" ,"ecp_fix" : "0.59" ,"eccol" : "chg" ,"div" : "" ,"yld" : "" } ]
Do you have any ideas how to get this?
Best wishes,
Vinc


text:
Q: Multiplication by n on E(K) is surjective What's the easiest way to see this?
I can imagine a proof for $n=2^k$ since for some $P \in E(K)$ you can just move a line intersecting P round the curve till it's tangent, then that point, say $Q \in E(K)$ would be such that $2Q=P$ and induction would get the rest.
Struggling to see the proof for n not a power of 2 however.

A: The claim is true if $K$ is algebraically closed, and it follows from a more general fact about algebraic curves: every map $\phi\colon X\to Y$ of algebraic curves over an algebraically closed field is either constant or surjective. So you just need to show that multiplication by $n$ is not constant, which is a very easy exercise.


text:
Q: zero size malloc Very simple question, I made the following program :
#include <stdlib.h>
int main(int argc, char ** argv)
{
    void * ptr;
    ptr = malloc(0);
    free(ptr);
}

And it does not segfault on my machine. Is it a portable behaviour of stdlib malloc and free, or am I looking for trouble ?
Edit : What seems non portable is the value returned by malloc. The question is about the malloc(0) + free combination, not the value of ptr.

A: The behaviour is implementation defined, you will receive either a NULL pointer or an address. Calling free for the received pointer should however not cause a problem since:

*

*free(NULL) is ok, no operation is done

*free(address) is ok, if address was received from malloc (or others like calloc etc.)

A: Sorry for the trouble, I should have read the man pages :
malloc() allocates size bytes and returns a pointer to the allocated memory.  The memory is not cleared.  If size is 0, then malloc() returns either NULL, or  a
   unique pointer value that can later be successfully passed to free().
free()  frees  the  memory  space  pointed  to  by  ptr,  which must have been returned by a previous call to malloc(), calloc() or realloc().  Otherwise, or if
   free(ptr) has already been called before, undefined behavior occurs.  If ptr is NULL, no operation is performed.
It seems it is true at least for the gnu libc

A: It's allowed to return NULL, and it's allowed to return a non-NULL pointer
you can't dereference. Both ways are sanctioned by the standard (7.20.3):

If the size of the space requested is zero, the behavior is
  implementation-defined: either a null pointer is returned, or the
  behavior is as if the size were some nonzero value, except that the
  returned pointer shall not be used to access an object.

A: According to the c standard
7.20.3
If the size of the space requested is zero, the behavior is implementation defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.

A: Though it might be legal C/C++, it is indicative a bigger problems. I generally call it 'pointer slopiness'.
See "Do not make assumptions about the result of malloc(0) or calloc(0)", https://www.securecoding.cert.org/confluence/display/seccode/VOID+MEMxx-A.+Do+not+make+assumptions+about+the+result+of+malloc%280%29+or+calloc%280%29.

A: In my experience, I have seen that malloc (0) returns a pointer which can be freed.
But, this causes SIGSEGV in later malloc() statements.
And this was highly random.
When I added a check, for not to call malloc if size to be allocated is zero, I got rid of this.
So, I would suggest not to allocate memory for size 0.
-Ashutosh

A: Updated taking into account libt & Pax's comments:
The behaviour of calling malloc(0) is implementation dependant or in other words non-portable and undefined.
Link to CFaq question for more detail.


text:
Q: Why doesn't Android's shadowRadius work with a 0 value in XML? In an Android app that's targeting Marshmallow, I want to apply a non-blurry shadow to the text of a button. With a shadowRadius of 1 or higher, I see the shadow:

But if I try to make the shadowRadius anything between 0 and 0.99, nothing shows up:

I'm just trying to achieve a no-blur shadow like you can do with the text-shadow property in CSS:

Here is the associated XML that I have set up for my button style.
    <style name="ButtonStyle" parent="@style/Widget.AppCompat.Button">
    .
    .
    .
    <item name="android:shadowColor">@android:color/holo_green_light</item>
    <item name="android:shadowDx">2</item>
    <item name="android:shadowDy">7</item>
    <item name="android:shadowRadius">0.99</item>
    .
    .
    .
</style>

The only thing I could think of that was unique to my style was that I set stateListAnimator to null, but even without that I have this problem. I see a lot of example code online mentioning that you can make the shadowRadius something small like 0.01 but I'm not seeing any shadow once I make it smaller than 1. Did something change in the Android platform recently?


text:
Q: construction of the rectangle with the highest area I have 2 times a square with side length 2, 2 times a square with side length 3, 1 times a square with side length 4 and 1 times a square with side length 5. I have to create the rectangle with the biggest area with some or all of the squares.
I have already found the solution (I think), which is   2 x square (side 2) +  2 x square (side 3) + square (side 4), but I can't really argument, why that is the solution. Can I please have some help?
*This is not homework.

A: If you are thinking of the rectangle with side lengths of 6 and 7, then I believe you have it right but the proofing is more difficult and I can only think of drawing it out as a proof.
Sorry if this doesn't help.


text:
Q: Is there a setting in Excel that prevents pictures from being added to the workbook? I have a code that inserts pictures into a workbook.
The purpose of the pictures is to add signatures to the workbook via an add-in I have built.
This code for pics sometimes doesn't work though.
Each user has the pictures saved on their computer in the same place.
This is my code:
Dim ws As Worksheet
Set ws = ActiveSheet
imagePath = "C:\Users\" & Environ("UserName") & "\AppData\Roaming\Microsoft\AddIns\Ticks\B1.png"
imgLeft = ActiveCell.Left
imgTop = ActiveCell.Top
ws.Shapes.AddPicture _
Filename:=imagePath, _
LinkToFile:=msoFalse, _
SaveWithDocument:=msoTrue, _
Left:=imgLeft, _
Top:=imgTop, _
Width:=12.15, _
Height:=12.15
ActiveCell.Offset(1, 0).Select

I occasionally get the unable to get the insert property of the picture class error, and I don't know why.
The pictures are there and the names are all correct.
It only gives the error on certain documents - which is why I think there is a setting that can be changed.
The rest of the time this works perfectly, and the 7 people who use it regularly, very rarely report an issue.
I thought it was only on old XLS files (this was where it broke down most frequently), but it happens on XLSX files too.


text:
Q: User Online List PHP I'm trying to make a online user list output all my usernames in a row like this (username, username, username)
The code I'm trying:
        $result2 = $db->query("SELECT * FROM `online`");
        $fetched2 = $result2->fetch_assoc();
        $user_id = $fetched2['user_id'];
        $result = $db->query("SELECT * FROM `users` WHERE id = $user_id");
        while ($fetched = $result->fetch_assoc())
        {
            $users_arr[] = array("username"=> $fetched['username']);
        }

But it's only returning 1 username from online table and not all in a row, how can i do this?
return json_encode(array("status" => 200, "message" => $users_arr)));

This only outputted 1 username, and also it's outputted in json format which i do not want, i want it outputted like so: User, User, User and not like [{'username': 'vanilla'}]"
Can someone please show me the correct way of using an array or a solution to my problem, thanks!
UPDATE:
Tried this and it worked, but now the dilemma is how do i make the outputted json array to look like User, User instead of ['user1', 'user2']
    $users = array();
    $result = $db->query('SELECT user_id, ident, u.group_id FROM '.$db->prefix.'online LEFT JOIN '.$db->prefix.'users AS u ON (ident=u.username) WHERE idle=0 ORDER BY ident', true) or error('Unable to fetch online list', __FILE__, __LINE__, $db->error());

    while ($user_online = $result->fetch_assoc())
    {
        $users[] = $user_online["ident"];
    }

I tried to use:
$trimmed = trim($users, '[]');
But this threw a warning/error:
PHP Warning:  trim() expects parameter 1 to be string

Also tried:
$string = implode('[]', $users);
It does output 2 users, but its formated/outputted like:
user1[]user2

A: (Moved solution to answer space on behalf of the question author to move it from the question).
Fixed by using:
$string = implode(", ", $users);


text:
Q: Oracle SQL French script file I need to do a mass insert into my database. I have French characters(e.g é) into my table
When i connect to SQLPlus and run the query manually
INSERT INTO TEST VALUES ('é');

Data is inserted properly.
When i save the same query in an Sql file and execute same through SQLplus
I get below error:
SQLPLUS>@test.sql;
ERROR:
ORA-01756: quoted string not properly terminated

Can anyone guide me.
thanks


text:
Q: Can you interpret "Waltz for Venus" differently? I think you can have two interpretations for this. One being, a dance or music. Two being, accomplish something with little to no effort. Are these two interpretations correct or is it just the former that's correct?

A: The word "waltz" most definitely has two meanings.
A "waltz" is a particular type of music usually with 3/4 time and the dance that's done along to it:

A waltz (German: Walzer; French: Valse, Italian: Valzer, Spanish: Vals, Polish: Walc), probably deriving from German Ländler, is dance music in triple meter, and if written, often written in time signature 3/4. A waltz typically sounds one chord per measure, and the accompaniment style particularly associated with the waltz is (as seen in the example to the right) to play the root of the chord on the first beat, the upper notes on the second and third beats.

In addition, the phrase "was a waltz" or "waltzed through something" means that it was easy or simple:

n. an easy task. The job was a waltz. We did it in a day.
   in. to get through something easily. I waltzed through my comps and started on my research in my second year.

"Venus" has nothing to do with this use, though.

In relation to Cowboy Bebop, the show is highly influenced by music. It's part of the show title (bebop) and the titles of the individual episodes. Yoko Kanno's score is also a hugely important part of the show.
I don't think that the double meaning of the musical style and "easy" are necessarily intentionally used here. One of the main themes of the show is that the main characters are constantly struggling, so I'm not sure how "easy" ties into that.
That being said, some of the titles certainly have multiple meanings. For example, episode 9 "Jamming with Edward" - "jamming" means both "signal jamming" and "playing music" - which certainly coincides with the theme of the episode.


text:
Q: Jquery break line between data fields I tried to break line between fields, but nothing i red on previous cases has worked for me : ""    "\n"
$(function() {
    var body = $(document.body);
    for (var i = 0; i `enter code here`< data.length; i++) {
        $('
</div').text(data[i].name + " " + data[i].age + " \n" + data[i].email).appendTo(body);

    }
});

A:

$('button').click(function(){
    $('input').each(function(){
        $(this).after('
');
    });
});

<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" />
<button>fix it up</button>

Of course, another way is just to use CSS:
CSS:
input{display:block;}

input {display:block;}
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" />

A: Linebreaks are not relevant in HTML, you need to use the
 tag to achieve the desired affect.
See this MDN article.


text:
Q: How do I set up an application that holds files in IIS 7 I have a folder location that contains .txt files (say C:\Files). I need to be able to access it using http://localhost/Files/myFile.txt
I created a Virtual directory and mapped it to C:\Files. However, when I browse to the .txt file using the URL, it gives me an error. It appears that its looking for web.config file. I tried creating an application in IIS with the same result.
EDIT

A: IIS 7 will always try to walk directories to look for additional config data (stored in web.config files).
You're throwing a 500.19 because the security context that your worker process is running under does not have rights to check if the web.config file exists in c:\files.
You need to grant NTFS permissions to your worker process to read from that location.
Depending on the version of windows and your worker process configuration granting Read/list folder contents to the IIS_IUSRS group is probably what you need.
Feel free to reply back with your windows/IIS version and the security context that your worker process is running under (Application Pools -> Identity) if the above suggestion doesn't work.


text:
Q: If $A$ is a semisimple algebra, then every irreducible $A$-module is cyclic over $A$ Let $A$ be a finite-dimensinoal associative algebra with unit $1$ over $K$. Then $A$ is a $A$-right module (by module I always mean right module) over itself by right multiplication (the so called right regular module), denote it by $A^{\circ}$. An $A$-right module $V$ is semisimple if it is the sum of irreducible $A$-submodules, and this is equivalent with the fact that for every $A$-submodule $U \le V$ there exists another $A$-submodule $W$ such that $V = U\oplus W$. An algebra $A$ is called semisimple if $A^{\circ}$ is semisimple as a module. With this we could show that if $A^{\circ}$ is semisimple, then every irreducible $A$-right module is isomorphic to a submodule of $A^{\circ}$.
Now I noticed the following, but see it nowhere mentioned. So I ask myself if my reasoning is correct. If $W$ is an irreducible $A$-module for a semisimple algebra $A$, then I guess $W$ must be cyclic as an $A$-module, i.e. generated by a single element. This follows because an $A$-isomorphism commutes with multiplication by elements from $A$, and every element from $A$ (or $A^{\circ}$) could be written as a multiple of $1 \in A$.

Let $A$ be a semisimple algebra and let $W$ be an irreducible $A$-right module, then $W$ is generated by a single element.
Proof: By the above there exists a submodule $W_0$ of $A^{\circ}$ such that $W_0 \cong W$. Let $\varphi \in \operatorname{Hom}_A(W_0, W)$ be such an isomorphism, then for $x \in W_0$, as also $x \in A$, we have $\varphi(x) = \varphi(x1) = \varphi(1x) = \varphi(1)x$, hence every element $y \in W$ has the form $\varphi(1)\cdot x = y$ where $x \in A$ is choosen such that $\varphi(x) = y$, i.e. we have $\varphi(1)A = W$. $\square$

Is this correct? Or have I overlooked something? And is this of use, or not; as I see it nowhere mentioned?

A: You're overthinking! ;-)
Let $M$ be an irreducible left module over the (unital) ring $R$. By definition, $M\ne\{0\}$ and the only submodules of $M$ are $\{0\}$ and $M$.
Take $x\in M$, $x\ne0$; then $Rx$ is a nonzero submodule of $M$, so $Rx=M$.


text:
Q: Dynamicaly add buttons to asp table cell without deleting the cells text i have an asp.table where all the cells contains text and the following function to add buttons to the cells
  Button btnactiv = new Button();
                    btnactiv.ID = y.ToString();
                    btnactiv.Text = "Dept " + dr_depts["code_dept"].ToString() + "(" + nbr + " )";
                    cell.Controls.Add(btnactiv);

the buttons are added and it works fine but the text of cells gets deleted after i add the buttons how can i add butoons and keep the text please ?

A: first dynamically create a table cell and then add your text and button to it:
 TableCell commentCell = new TableCell();
 Label lblComment = new Label();
 lblComment.Text = "Text to remain in the cell."
 commentCell.Controls.Add(lblComment);
 Button btnactiv = new Button();
 btnactiv.ID = y.ToString();
 btnactiv.Text = "Dept " + dr_depts["code_dept"].ToString() + "(" + nbr + " )";
 commentCell.Controls.Add(btnactiv);


text:
Q: How do I call upon Tkinter labels defined in a different function? I am making a simple little clicker game using Python. This is currently what I have:
from tkinter import *

x = [0]
y = [1]

class Game:
    def __init__(self, master):
        master.title('Game')

        Amount = Label(master,text=x[0])
        Amount.pack()

        Butt = Button(master,text='Press!',command=self.click)
        Butt.pack()

    def click(self):
        x[0] = x[0] + y[0]
        Amount.config(root,text=x[0])
        print(x[0])

root = Tk()
root.geometry('200x50')
game = Game(root)
root.mainloop()

When I run this, it tells me that 'Amount' is not defined within the click function. I know this is because it's defined in a different function. I want to know how to make it so the click function recognizes 'Amount'.

A: You should either define your amount as data member(each instance has his value) or static member(same value withing all classes instances).
I would go with data member.
In order to use it as a data member you should use self.Amount.
So, this is what you need:
from tkinter import *

x = [0]
y = [1]

class Game:
    def __init__(self, master):
        master.title('Game')

        self.Amount = Label(master,text=x[0])
        self.Amount.pack()

        Butt = Button(master,text='Press!',command=self.click)
        Butt.pack()

    def click(self):
        x[0] = x[0] + y[0]
        self.Amount.config(text=x[0])
        print(x[0])

root = Tk()
root.geometry('200x50')
game = Game(root)
root.mainloop()

self is shared among your class methods, so you can access the Amount variable through it.


text:
Q: Zoomer in html5 in mobile I am working in images which should zoom in and zoom out on touch like  this . I used many examples from net like this example and i also used meta tag viewport. but i did not acheive the functionality which i required. I serached alot but did not find any desireable solution . any help regarding this issue.
At that time i am using meta tag but when i double touch on the image the image got smaller and not come to the orignal position.
    <meta name="viewport"
            content="width=device-width, initial-scale=1.0,  maximum-scale=5.0, minimum-scale=0.25;, user-scalable=yes">

and from net i am using one css and js files of zoom but they also behave like same

A: For that time i found a solution to this problem that is to use animate function and increase height ,width or individual height or width to accomplish zooming.
Here is my code that will zoom in and out image on mouse over:

Image to Zoom In and Zoom Out

and in js:
$(document).ready(function(){
   $('#image1').width(200);

   $('#image1').mouseover(function()

   {

      $(this).css("cursor","pointer");

      $(this).animate({width: "300px"}, 'slow');

   });

$('#image1').mouseout(function()

  {

      $(this).animate({width: "200px"}, 'slow');

   });

});