text:
Q: How to ignore properties with empty values during deserialization from JSON I'm trying to deserialize a JSON string into a ConcurrentHashMap object and I'm getting errors because my JSON contains properties with null values, but ConcurrentHashMap does not accept null values. Here is the fragment of code:
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(jsonString, ConcurrentHashMap.class);

Is there a way to ignore properties with null values during deserialization? I know that we can ignore these properties during serialization:
mapper.setSerializationInclusion(JsonInclude.NON_NULL);

But what about deserialization process?

A: There may be a better way but a workaround would be:
Map<String, Object> map = mapper.readValue(jsonString, HashMap.class);
map.values().removeIf(o -> o == null);
return new ConcurrentHashMap<> (map);

A: The following trick has worked for me:
ObjectMapper mapper = new ObjectMapper();

String jsonString = "{\"key1\": 1, \"key2\": null, \"key3\": 3}";

ConcurrentHashMap<String, Object> map = mapper.readValue(jsonString, new ConcurrentHashMap<String, Object>() {
    @Override
    public Object put(String key, Object value) {
        return value != null ? super.put(key, value) : null;
    }
}.getClass());

System.out.println(map); // {key1=1, key3=3}

The idea is to simply override ConcurrentHashMap.put() method so that it ignores null values that are to be added to the map.
Instead of an anonymous inner class, you could create your own class that extends from ConcurrentHashMap:
public class NullValuesIgnorerConcurrentHashMap<K, V>
    extends ConcurrentHashMap<K, V> {

    @Override
    public V put(K key, V value) {
        return value != null ? super.put(key, value) : null;
    }
}

Then you would use this class to deserialize to a ConcurrentHashMap:
ConcurrentHashMap<String, Object> map =
    mapper.readValue(jsonString, NullValuesIgnorerConcurrentHashMap.class);

System.out.println(map); // {key1=1, key3=3}

With this approach, the returned map would never throw NullPointerException on put() when given a null value.


text:
Q: RAILS_ENV=production rails assets:precompile - ruby_racer_runtime.rb:73: Segmentation fault It return the following error when i run RAILS_ENV=production bundle exec rake assets:precompile --trace
** Execute assets:precompile
.rvm/gems/ruby-2.4.1@rails5/gems/execjs-2.7.0/lib/execjs/ruby_racer_runtime.rb:73: [BUG] Segmentation fault at 0x00000000000018
ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-linux]
The following are the environment details
ruby version : ruby-2.4.1
Rails Version: 5.1.7
Distributor ID: Ubuntu
Description:    Ubuntu 18.04.2 LTS
Release:        18.04
Codename:       bionic
My Gemfile
source 'https://rubygems.org'

git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.1.7'
gem 'execjs'
gem 'therubyracer', :platforms => :ruby
gem 'mysql2'
gem 'puma', '~> 3.7'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'

# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'

group :development, :test do
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  gem 'capybara', '>= 2.15'
  gem 'selenium-webdriver'
end

group :development do
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '>= 3.0.5', '< 3.2'
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

After I install ruby 2.5.5. The below is my Gemfile
source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

gem 'rails', '~> 5.2.3'
gem 'mysql2'
gem 'therubyracer', platforms: :ruby
gem 'puma', '~> 3.11'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'

# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
gem 'turbolinks', '~> 5'
gem 'jbuilder', '~> 2.5'
gem 'bootsnap', '>= 1.1.0', require: false

group :development, :test do
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
end

group :development do
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '>= 3.0.5', '< 3.2'
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

group :test do
  gem 'capybara', '>= 2.15'
  gem 'selenium-webdriver'
  gem 'chromedriver-helper'
end

gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

redpajama_set_name: RedPajamaStackExchange


text:
Q: What's wrong with const? What are the known shortfalls of const in C++ and C++0x?

A: The only thing wrong with const is that it is seriously underrated by to many developers. It's one of the best tools in C++'s toolbox, very sharp, and yet not dangerous to cut yourself with.

A: The main problem is that you have to write it. It should be the default, and all mutable variables or parameters should be specified explicitly.

A: The problem with const is the programmers that use it incorrectly our inconsistently

A: One thing that is "wrong" is that you cannot convert T** to T const * const * which should be allowed because it is not dangerous. Not allowing T** to convert to T const ** is correct, that conversion is not valid.
I have sometimes mentioned that const actually is a cheap way to "split" your interface into read-only methods and write methods. It would probably be impractical in C++. It would be more practical in Java to have ReadOnly versions of collections though, where they don't have const and where their collection types are more object-orientated.
const-ness does not propagate: The issue here is that if I pImpl my class, the constness is not "checked" by the compiler, i.e. my interface class can have a "const" method call a non-const method on the pImpl and the compiler won't complain. That is because the only thing my const method is guaranteed not to do is change the pointer to point to a different object, and my pImpl is never going to change. It could even be a const pointer (not pointer to const).
The lack of proper co-variance between shared_ptr<T> and shared_ptr<const T> might be an issue too, although in general I have seen that not to be the problem, but that developers usually typedef their shared_ptrs and rarely typedef the shared_ptr to const. And they will sometimes pass const shared_ptr<T> & and think that they are passing a shared pointer to a const T (as with const T*) which they are not.

A: What's wrong with const is that many programmers don't seem to be able to understand it completely, and a "half-const-correct" project simply does not work. This is what you need to know:

*

*Foo vs. const Foo (or Foo const)

*Foo& vs. const Foo& (or Foo const&)

*

*references-to-const bind to all kinds of things, while references-to-non-const don't

*Foo* vs. const Foo* (or Foo const*)

*

*pointer variables can also be Foo* const and const Foo* const (or Foo const* const)

*void Foo::mutator() vs. int Foo::accessor() const

*

*but pointer members inside const member functions still point to non-const objects

*so we can accidentally return non-const data from a const-function

*iterator vs. const_iterator

*

*iterator variables can also be const iterator and const const_iterator
Migrating to C++ from a language that has no const concept is quite hard, any many fail to see the point.

A: The two main issues that I have seen frequent complaints about in newsgroups, are

*

*The need to waste a lot of time on supporting non-const-aware APIs (especially Microsoft's).

*The need to define both const and non-const version of a method.
I think the latter could/should be supported by the language.
Possibly in conjunction with support for covariant member function implementations, because both need some way to pick up the type of the this pointer.
A third issue is that

*

*const does not propagate to owned objects.

Cheers & hth.,

A: "issues"?
If you aren't going to be modifying the value of a passed pointer (it is used purely for pass-by-reference input to a function), mark it is const.  Ditto if the value of a particular variable will not change after its initialization.  If a function is safe to call on a const class instance, mark it const too.  The more items are correctly annotated const, the less likely you are to inadvertently make a mistake and the more optimizations the compiler will be theoretically able to perform in the absence of complete knowledge (such as when compiling with only function prototypes available).
Modern versions of gcc have support for warning when you try to cast a const variable to a non-const one.  I suggest you leave those warnings enabled.
The only thing to watch out for is exactly what you are marking const; const char * foo() is not the same as char * foo() const.

A: Another problem that has not been mentioned yet is the possibility for a badly designed interface to subvert const (even in the absence of casts).
Example:
class TreeNode {
public:
    TreeNode& getParent() const { return *parent_; }
    TreeNode& getLeft()   const { return *left_;   }
    TreeNode& getRight()  const { return *right_;  }
private:
    //TreeNode has a pointer to the Tree to enable navigation of the tree.
    //Assume that other design constraints mean that this must be a pointer
    //rather than a reference.
    TreeNode* parent_;
    TreeNode* left_;
    TreeNode* right_;
};
//This function demonstrates the ability for const to be subverted.
TreeNode& remove_const(TreeNode const& toRemoveConstFrom) {
    TreeNode& parent(toRemoveConstFrom.getParent());
    TreeNode& leftChild(parent.getLeft());
    TreeNode& rightChild(parent.getRight());
    return &toRemoveConstFrom == &leftChild ? leftChild : rightChild;
}

The intransitive nature of const means that it is possible to have an interface where a non-const reference to an object can be obtained from a const reference to an object. This is something to be careful of when designing interfaces.

A: Most of the answers below state things such as "what is wrong with const is that X people do Y". Those are not answers but symptoms. Those are not things wrong with const. There's barely any wrong thing with const...  Those are things wrong with people who can't RTFM.

A: const is great. const is important. const-correctness is necessary condition for an API to be good.
Yet there are two issue I've had with const, repeatedly.

*

*There's no way to mark a variable as const retroactively. You must either declare a variable code, in which case you have to initialize it immediatly. What if the initialization code contains an if, though? You have the choice of either omitting the const (undesirably), using operator ? instead of if (harms readability). Java get's that right, BTW - const variables don't have to be initialized right away, they just have to be initialized before they're first read, and they have to be initialized in all branches of an if.

*There's no way to specifiy that an object passed by reference to a function won't change for the duration of the function call. const T& t does not mean that the object pointed to by t won't change, but only that the reference t cannot be used to change it. The compiller still has to assume that any function call which it does not see into might change the object. It some cases, that prevents quite a few optimizations.

A: One thing is that it is still possible subvert it.  i.e. it is still legal to do something like this:
void foo(const inst& x)
{
   const_cast<int&> x = 3;
}

You can even use things like memset to subvert it without an explicit const_cast.
This is a trade-off between having the compiler enforce const and allowing some flexibility for non const aware interfaces.
Which leads to another limitation, in that it has not been universally embraced, which is in part due to another problem, which is that using const is an all-or-nothing proposition.  If you start using it, you will need to propagate it throughout your code base.

A: One problem is that the language also lets you const_cast it away, which defeats the purpose of using const in the first place.


text:
Q: Given lodash map, how to limit the # of results or slice? I have the following:
import itemsMap from '../libs/items-map';
const _ = require('lodash');
const options = {};

_.map(itemsMap, (item, key) => {
  options[key] = key;
});

I then output in React like so:
  {
    _.map(itemsMap, (item, key) => (
        {key}
      />
    ))
  }

This currently outputs the entire items list,, I would like to output only 5.. I tired using slice like so:
  {
    _.map(itemsMap.slice(2), (item, key) => (
        {key}
      />
    ))
  }

This results in a TypeError: .default.slice is not a function
How can I limit the results?

A: Whatever loader/bundler is resolving your import isn't exposing itemsMap as an array. You may need to use require syntax like the 2 lines below that.
Also, since the key in your return statement is wrapped in curly brackets but no jsx tags, it's parsed as an object and doesn't render anything. see what happens on this codepen when you remove the <span> around {key}.
To your original question, the idiomatic way to limit items in lodash would be to use lodash.take like so:

_.map(_.take(itemsMap, 2), (item, key) => ( … ))


text: Q: Verify domain in client side JS in iOS When using a web service like Google Maps, I expose the API key and set the domain on their server so it won't be abused. When working with JS in iOS, like React Native, how do I replace the "domain" step.


text: Q: How to backup Windows Live Mail data (ex: to move from Vista to 7) I am using Windows Live Mail to access my 6 mail accounts including hotmail and gmail. Currently I am using windows vista but planning a clean install of Windows 7. Is there any way I can backup the downloaded mails on windows vista and retrieve it again on windows 7. I do not want live mail to download all mails again (its more than 3GB).


text:
Q: Without measure, need $\int_a^b |f|^pd\alpha =0\Rightarrow \int_a^b |f|d\alpha=0$ As in the title, I want to show $\int_a^b |f|^pd\alpha =0\Rightarrow \int_a^b |f|d\alpha=0$
With measure theory, this implication is obvious. But using the definition, as a Riemann Integral, seems impossible to me right now. This material was so long ago for me. Could someone get me started?
EDIT: sorry, important details: $f$ is continuous and $p>1$.

A: This is a consequence of the more general result:
If $f\colon[a,b]\to\Bbb R$ is continuous, $f\ge0$ and $\int_a^bf=0$, then $f(x)=0$ for all $x\in[a,b]$.
Proof. Suppose that $f(\xi)\ne0$ for some $\xi\in[a,b]$ and show (using the fact that $f$ is continuous at $\xi$) that then $\int_a^bf>0$.


text:
Q: How to replace existing key in a dictionary in python? So , I have this code.
I want to replace the specific existing key at index 1 in a dictionary in python.
Anyone have an idea on this?
from collections import OrderedDict
regDict= OrderedDict()
regDict[("glenn")] = 1
regDict[("elena")] = 2
print("dict",regDict)

prints:
dict OrderedDict([('glenn', 1), ('elena', 2)])

target output:
dict OrderedDict([('glenn', 1), ('new', 2)])  # replacing key in index 1

A: Your approach towards making a dictionary is a little bit off. Let's start by making a new dictionary from two lists (one for keys and one for values):
keys = ['a', 'b', 'c']
vals = [1.0, 2.0, 3.0]

dictionary = {keys[i]:value for i, value in enumerate(vals)}

This gives us the following:
{'a': 1.0, 'b': 2.0, 'c': 3.0}

You can also go here for some more help with making dictionaries: Convert two lists into a dictionary
To replace the 'a' key with 'aa', we can do this:
new_key = 'aa'
old_key = 'a'

dictionary[new_key] = dictionary.pop(old_key)

Giving us:
{'b': 2.0, 'c': 3.0, 'aa': 1.0}

Other ways to make a dictionary:
dictionary = {k: v for k, v in zip(keys, values)}
dictionary = dict(zip(keys, values))
Where 'keys' and 'values' are both lists.

A: This is a very bad approach for a dictionary but a solution would look like below
index = len(regDict)-1
key = list(regDict.keys())[index]
value = regDict[key]
regDict["new"] = value

Note: This will only work if you want to change the last inserted key


text:
Q: click on element with specified data

$(document).on('click', $('[data-what="abc"]'), function() {
console.log('323');
$(this).hide();
});
.title{
background:gold;
cursor:pointer;
}

title

console.log - works.
element.hide - doesn't work
Any help?

A: It doesn't work because this is the element the event was bound to: document. You're not trying to hide the whole document.
Try
$(document).on('click', $('[data-what="abc"]'), function(event) {
    console.log('323');
    $(event.target).hide();
});


text:
Q: Could someone please me figure out what I am doing wrong in jQuery in order to get this "Can't find Variable: $" code whenI try and open my modal?

$(function(){
        var $modal = $('#ModalContact');
        var $open = $('#jsOpenContact');
        var $close = $('.CloseX');
        var $win = $("window");

        $open.on('click', function(e){
            e.preventDefault();
            $modal.show();
        });

        $close.on("click", function(e){
            e.preventDefault();
            $modal.addClass('.out')
        });

        $win.on('click', function(e){
            e.preventDefault();
            $modal.addClass('.out')
        });

    });
    .NavContact a {
        margin: 0;
        padding: 0;
        text-decoration: none;
        color: white;
        font-family: 'Cinzel Decorative', cursive;
        float: right;
        display: inline-block;
    }
    #ModalContent {
        background-color: darkred;
        margin: 25% auto;
        padding: 10px;
        width: 75%;
        box-shadow: 0 5px 8px 0 rgba(0,0,0,0.2), 0 7px 20px 0 rgba(0,0,0,0.2);
    }
    .Contact {
        display: none;
        background-color: rgba(0, 0, 0, 0.5);
        position: fixed;
        z-index: 1;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        overflow: auto;
        transform:scaleY(.01) scaleX(0);
        animation:unfoldIn 1s cubic-bezier(0.165, 0.840, 0.440, 1.000) forwards;
    }
    .open {
        transform:scaleY(.01) scaleX(0);
        animation:unfoldIn 1s cubic-bezier(0.165, 0.840, 0.440, 1.000) forwards;
    }
    #ModalBackground {
        transform:scale(0);
        animation: zoomIn .5s .8s cubic-bezier(0.165, 0.840, 0.440, 1.000) forwards;
    }

    @keyframes unfoldIn {
        0% {transform:scaleY(.005) scaleX(0);}
        50% {transform:scaleY(.005) scaleX(1);}
        100% {transform:scaleY(1) scaleX(1);}
    }
    @keyframes zoomIn {
        0% {transform:scale(0);}
        100% {transform:scale(1);}
    }

    .out {
        transform:scale(1);
        animation:unfoldOut 1s .3s cubic-bezier(0.165, 0.840, 0.440, 1.000) forwards;
    }
    #ModalBackground .out {
        animation: zoomOut .5s cubic-bezier(0.165, 0.840, 0.440, 1.000) forwards;
    }
    @keyframes unfoldOut {
        0% {transform:scaleY(1) scaleX(1);}
        50% {transform:scaleY(.005) scaleX(1);}
        100% {transform:scaleY(.005) scaleX(0);}
    }
    @keyframes zoomOut {
        0% {transform:scale(1);}
        100% {transform:scale(0);}
    }

    .CloseX {
        color: black;
        float: right;
        font-size: 25px;
    }
    .CloseX:hover {
        color: green;
        text-decoration: none;
        cursor: pointer;
    }

 Contact

           ×

 Contact Me

 Email
   sumayyahameerah@yahoo.com

 Instagram
    sumayyah.ameerah

 **

I got my modal to work using Javascript yet, I wanted the function using jQuery instead. I really don't understand where I am incorrect here. Do I not have the correct scripts? I'm not sure why my modal won't open on the on click. HELP. every time I go to the console to check it says "Can't find variable: $" I have used all of those scripts that are there to try and figure it out.

A: First of you dont need to include so many jquery references. Second you don't need to use the . in $modal.addClass('.out') it has to be $modal.addClass('out')
Demo

$(function() {
  var $modal = $('#ModalContact');
  var $open = $('#jsOpenContact');
  var $close = $('.CloseX');
  var $win = $("window");

  $open.on('click', function(e) {
    e.preventDefault();
    $modal.show();
  });

  $close.on("click", function(e) {
    e.preventDefault();
    $modal.addClass('out')
  });

  $win.on('click', function(e) {
    e.preventDefault();
    $modal.addClass('out')
  });

});
.NavContact a {
  margin: 0;
  padding: 0;
  text-decoration: none;
  font-family: 'Cinzel Decorative', cursive;
  float: right;
  display: inline-block;
}

#ModalContent {
  background-color: darkred;
  margin: 25% auto;
  padding: 10px;
  width: 75%;
  box-shadow: 0 5px 8px 0 rgba(0, 0, 0, 0.2), 0 7px 20px 0 rgba(0, 0, 0, 0.2);
}

.Contact {
  display: none;
  background-color: rgba(0, 0, 0, 0.5);
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  transform: scaleY(.01) scaleX(0);
  animation: unfoldIn 1s cubic-bezier(0.165, 0.840, 0.440, 1.000) forwards;
}

.open {
  transform: scaleY(.01) scaleX(0);
  animation: unfoldIn 1s cubic-bezier(0.165, 0.840, 0.440, 1.000) forwards;
}

#ModalBackground {
  transform: scale(0);
  animation: zoomIn .5s .8s cubic-bezier(0.165, 0.840, 0.440, 1.000) forwards;
}

@keyframes unfoldIn {
  0% {
    transform: scaleY(.005) scaleX(0);
  }
  50% {
    transform: scaleY(.005) scaleX(1);
  }
  100% {
    transform: scaleY(1) scaleX(1);
  }
}

@keyframes zoomIn {
  0% {
    transform: scale(0);
  }
  100% {
    transform: scale(1);
  }
}

.out {
  transform: scale(1);
  animation: unfoldOut 1s .3s cubic-bezier(0.165, 0.840, 0.440, 1.000) forwards;
}

#ModalBackground .out {
  animation: zoomOut .5s cubic-bezier(0.165, 0.840, 0.440, 1.000) forwards;
}

@keyframes unfoldOut {
  0% {
    transform: scaleY(1) scaleX(1);
  }
  50% {
    transform: scaleY(.005) scaleX(1);
  }
  100% {
    transform: scaleY(.005) scaleX(0);
  }
}

@keyframes zoomOut {
  0% {
    transform: scale(1);
  }
  100% {
    transform: scale(0);
  }
}

.CloseX {
  color: black;
  float: right;
  font-size: 25px;
}

.CloseX:hover {
  color: green;
  text-decoration: none;
  cursor: pointer;
}

 Contact

        ×

 Contact Me

 Email
  sumayyahameerah@yahoo.com

 Instagram
   sumayyah.ameerah


text:
Q: SyntaxError: Unexpected token in JSON usanso class-transformer Tengo el siguiente error en mi api con nestjs usando typescript y node, al intentar parsear una varibale en un archivo dto con la el paquete de class-transformer
SyntaxError: Unexpected token , in JSON at position 4\n    at JSON.parse

import { Transform } from "class-transformer";
import {  IsNotEmpty } from "class-validator";
export class GetAllKpiDto {
  @IsNotEmpty()

  @Transform((item): object  => {
  return item.obj.idFranquicias  = JSON.parse(item.value)
  })
  idFranquicias:number[];
}

*El problema esta en esta linea
return item.obj.idFranquicias  = JSON.parse(item.value)

Lo que envio con el postman


text:
Q: Unable to retrieve Chinese texts while scraping I have created a script that scrape website: 1688.com and the problem is, the site is in Chinese so whenever i try to retrieve the text, it gives me a bunch of unicode and when i export to a CSV file, there's nothing in the file.
My code:
# -*- coding: utf-8 -*-
import csv
from urllib import urlopen
from bs4 import BeautifulSoup as BS

csv_content = open('content.csv', 'w+')
writer_content = csv.writer(csv_content)

url = urlopen('https://fuzhuang.1688.com/nvzhuang?
spm=a260k.635.1998214976.1.7eqUGT')
html = BS(url, 'lxml')
container = html.find('ul', {'class' : 'ch-box fd-clr'})
offers = container.find_all('div', {'class' : 'ch-offer-body'})
lst = []

for offer in offers:
    offer_box = offer.find('div', {'component-name' : '@alife/ocms-
component-1688-pc-ch-offer-pic'})
    images = offer_box.find('img')['src']
    title = offer.find('div', {'class' : 'ocms-component-1688-pc-ch-offer-
title-0-1-11'}).text
    price = offer.find('div', {'class' : 'ocms-component-1688-pc-ch-offer-
price-0-1-14'}).text
    lst.append(price)

for item in lst:
    writer_content.writerow([item])
print lst

The output is
[u'\n\n\n\xa5\n109.00\n\n\n\u6210\u4ea4\n329\n\u4ef6\n\n\n', u'\n\n\n\xa5\n56.00\n\n\n\u6210\u4ea4\n195\n\u4ef6\n\n\n', u'\n\n\n\xa5\n83.00\n\n\n\u6210\u4ea4\n109\n\u4ef6\n\n\n', u'\n\n\n\xa5\n69.00\n\n\n\u6210\u4ea4\n208\n\u4ef6\n\n\n', u'\n\n\n\xa5\n46.00\n\n\n\u6210\u4ea4\n204\n\u4ef6\n\n\n', u'\n\n\n\xa5\n45.00\n\n\n\u6210\u4ea4\n54\n\u4ef6\n\n\n', u'\n\n\n\xa5\n82.00\n\n\n\u6210\u4ea4\n38\n\u4ef6\n\n\n', u'\n\n\n\xa5\n48.90\n\n\n\u6210\u4ea4\n318\n\u4ef6\n\n\n']

And i have already tried encoding and decoding utf-8, i would really appreciate it if you show me how to solve this problem.

A: this code will save chinese symbols to txt:
for Python3:
         ...
(all your code above)
for i in range(len(lst)):
    lst[i]=lst[i].replace('\n','') #getting rig of `'\n'` newlines

writing to txt:
with open(r'C:\Users\Username\list.txt','w',newline='',encoding='utf-8-sig') as f:
    for i in lst:
        f.write(i+'\t')

for Python2:
import unicodecsv as ucsv
with open(r'C:\Users\Username\list1.txt','wb') as f:
    w = ucsv.writer(f,encoding='utf-8-sig')
    for i in lst:
        w.writerow([i+'\t'])


text:
Q: Trigger an Outlook script after the email has entered the inbox I'm trying to finalize an integration between my access system and Outlook.
The basis of the system is that Outlook needs to trigger a script when an email enters a specific Inbox. This script then opens the Access DB and runs it's own function to go through that inbox, take the attachment in the email and import it into the database.
Currently both scripts "Work" in so far as Outlook calling Access and Access doing it's thing. The problem is when Outlook executes the script, it's BEFORE the message is actually in the mailbox. The access app will launch, scan the inbox as empty and close just before the message actually enters the inbox.
I've tried adding a "Pause" loop in the script, to try and have it wait until the email is readable before opening the access app, but that just froze outlook for the duration of the "Pause" instead of letting the email become readable.
Here is my script in Outlook:
Sub ExecuteDealRequest(item As Outlook.MailItem)
    Dim currenttime As Date

    currenttime = Now
    Do Until currenttime + TimeValue("00:00:30") <= Now
    Loop

    Dim AccessApp As Access.Application
    Set AccessApp = CreateObject("Access.Application")
    AccessApp.OpenCurrentDatabase ("C:\commHU\Comm HU Request.accdb"), False
    AccessApp.Visible = True
    AccessApp.DoCmd.RunMacro "Macro1"
    Set AccessApp = Nothing
End Sub

At this point: I'm using outlook rules to launch the script:
Apply this rule after the message arrives
With Pricing Request in the Subject
 and on this computer only
Move it to the Pricing Requests folder
 and run Project.ExecuteDealRequest
 and stop processing more rules

Any help would be great, as this is the last piece that I need to get working

A: You don't need Rule, Try it this way- code in ThisOutlookSession
Private WithEvents Items As Outlook.Items

Private Sub Application_Startup()
    Dim olNs As Outlook.NameSpace
    Dim Inbox  As Outlook.MAPIFolder

    Set olNs = Application.GetNamespace("MAPI")
    Set Inbox = olNs.GetDefaultFolder(olFolderInbox)
    Set Items = Inbox.Items
End Sub

Private Sub Items_ItemAdd(ByVal Item As Object)
    If TypeOf item Is Outlook.MailItem Then
        ExecuteDealRequest Item
    End If
End Sub

' ---- Your Code
Sub ExecuteDealRequest(Item As Outlook.MailItem)
    Dim currenttime As Date
    Dim AccessApp As Access.Application
    Set AccessApp = CreateObject("Access.Application")
    AccessApp.OpenCurrentDatabase ("C:\commHU\Comm HU Request.accdb"), False
    AccessApp.Visible = True
    AccessApp.DoCmd.RunMacro "Macro1"
    Set AccessApp = Nothing
End Sub

A: You could try something like this,
Add this code to wait for a new email
Private Sub Application_NewMailEx(ByVal EntryIDCollection As String)
    ThisOutlookSession.GetNamespace("MAPI").GetItemFromID(EntryIDCollection).Subject
    ' Check for the email subject / any property
    'then call your method
End Sub


text:
Q: UTF-8 greek chars show incorectly on android im building this site:
http://flou.sait-a.gr/
and i have the following problem:
on some older android devices, some greek chars (usually the ones with a tone, for example: έ) display as a box with an x inside, on PC everything works well. Any idea?

A: This is a font issue.  The box-with-an-x means the device does not have a font installed that supports the Unicode character being displayed.
Also, your site pages are using HTML5 (as evident by use of <!DOCTYPE html>), but instead of using HTML5's <meta charset="utf-8"> tag, they are using HTML4's <meta http-equiv="content-type" content="text/html; charset=utf-8" /> tag instead.  You should not even be using that tag in HTML5.  Thankfully, your webserver is reporting Content-Type: text/html; charset=UTF-8 in the HTTP header of each page, otherwise HTML5 browsers might not interpret them as UTF-8 correctly.  You need to fix your <meta> tags.  Don't mix HTML4 and HTML5 on the same page.


text:
Q: Why the frequency of single-core CPUs has stopped increasing? I wonder why CPU vendors stopped producing CPU with frequencies above 3.0 - 3.6 Ghz and switched to using multi-core CPUs?
What was the reason behind this step? Was there a physical constraint or the new approach came up being more feasible?

A: If you keep raising the clock, eventually you will have power consumption/temperature problems (you probably remember Pentium 4 CPUs which ran fast and hot). You can work around those, of course, but then your cooling system becomes more expensive.
Thus, multi-core (and other approaches, like improving the CPU architecture/organization - so much that comparing CPUs of different families/manufacturers is useless) were born.
Moreover, modern software is multithreaded and will benefit from multicore more than it does benefit from faster clocks.

A: There are a number of related factors at work.  For one thing, main memories have really lagged behind CPU speeds; if hypothetically one were running a single core at 50GHZ and it had to wait 10ns for a value to be fetched from RAM [quite fast, actually], would forfeit an opportunity to do 500 clock cycles' worth of useful work.  By contrast, if one had 10 cores which ran at 2GHz each, then such a main-memory fetch would only forfeit 20 clock cycles' worth of work.
Another factor is that CPU speeds are to some measure limited by the ability to get current into a chip and heat out.  Making a core run twice as fast would require more than double the current and produce more than double the heat.  If using two cores will allow one to do as much work as could be done with one core running twice as fast, it makes more sense to use two cores.
Incidentally, one place where the interaction of hardware and software needs to be improved, IMHO, is in establishing when it's important for code running in one core to be able to see things written into memory by code running in another.  Some architectures assume that anything written into memory by any processor should be seen as soon as possible by any other processor that tries to read that location; others require code that wants the most recent thing written to memory to explicitly request that or risk getting "stale data".  It's very difficult to make hardware for the former style run as quickly as hardware for the latter style, and the difficulty increases with the number of CPU cores, but it's very difficult to make software for the latter style which is efficient but doesn't occasionally malfunction under circumstances which are essentially impossible to track down.  I'd like to see hardware and software support a hybrid approach, with e.g. four groups of four cores each, and a guarantee that all the cores within each group will "see" the same memory, relaxed assurances for cores in different groups, and a default CPU assignment algorithm that would assure that code for any particular application domain would only be run on groups of processors that saw the same memory.  In cases where there were four or more separate application domains which each had their own independent work to do, this would allow the cores to be run faster than would be possible if all 16 had to share the same memory image.

A: As the other answers mention heat. But also the speed of light is a limiting factor.
http://www.google.co.uk/search?q=3+ghz%2F+speed+of+light
Assuming the electrons travel at the speed of light at 3ghz the signal can make it 10cms before the next clock tick


text:
Q: TypeScript interface mapped property generic type I'm trying to make this work
interface ObjectPool<Ids, T> {
  pool: {
    [K in Ids]: T<K>;
  };
};

interface Player<Id> {
  id: Id;
}

let playerPool: ObjectPool<0 | 1 | 2, Player>;

so that
playerPool[0].id === 0;
playerPool[1].id === 1;
playerPool[2].id === 2;
// playerPool[3] error

but typescript says I need a generic parameter at Player in let playerPool: ObjectPool<0 | 1 | 2, Player>; so I tried let playerPool: ObjectPool<0 | 1 | 2, Player<_>>; but that doesn't work too

A: If you write T<K>, then T needs to be some particular type operation (e.g., type T<K> = ... or interface T<K> { ...  or class T<K> ...).
There's no way to write T<K> where T is a generic type parameter.  That would require so-called higher-kinded types, of the sort requested in microsoft/TypeScript#1213, and TypeScript has no direct support for that.
You could step back and try to think of exactly what you want to do, and if there's any way to represent it without needing higher kinded types.  If all you want is for ObjectPool<P, T> to have all property keys in P, and for each such key K, you want the property value to have an id property equal K in addition to some other properties specified by T, then you can separate out the id part in the definition so that T is just a regular type.  For example:
type ObjectPool<P extends PropertyKey, T> =
  { [K in P]: { id: K } & T };

Now you could define Player without making it generic:
interface Player {
  id: number,  // <-- you don't necessarily need this anymore
  name: string,
}

And now an ObjectPool<0 | 1 | 2, Player> should behave as desired:
function processPlayerPool(playerPool: ObjectPool<0 | 1 | 2, Player>) {
  playerPool[0].id === 0;
  playerPool[1].id === 1;
  playerPool[2].id === 2;
  playerPool[2].name;
  playerPool[3] // error
}

You can then define other types to use instead of Player and use them too:
interface Wall {
  location: string
  orientation: string
}

function processSmallWallPool(wallPool: ObjectPool<0 | 1, Wall>) {
  wallPool[0].location // okay
  wallPool[0].id === 0; // okay
  wallPool[1].orientation // okay
  wallPool[2] // error
}

You mentioned in a comment that you have 2,000 Wall objects in the pool.  That's a lot of elements to put in a union, but sure, you could do it (code generation is going to be easier than trying to convince the compiler to compute it):
// console.log("type WallIds = " + Array.from({ length: 2000 }, (_, i) => i).join(" | "));
type WallIds = 0 | 1 | 2 | 3 | 4 | // ✂ SNIP!
  | 1995 | 1996 | 1997 | 1998 | 1999

And then ObjectPool<WallIds, Wall> will also behave as desired:
function processWallPool(wallPool: ObjectPool<WallIds, Wall>) {
  wallPool[214].location
  wallPool[100].id // 100
  wallPool[1954].orientation
  wallPool[2021] // error
}

Please note though that the compiler really can't do much analysis on a union of numeric literals.  You might have more trouble than you expected with this. If you try to loop over the elements of wallPool with a numeric index i, the compiler will complain:
  for (let i = 0; i < 2000; i++) {
    wallPool[i] // error!
  //~~~~~~~~~~~
  // No index signature with a parameter of type 'number'
  // was found on type 'ObjectPool<WallIds, Wall>'
  }

It has no idea that i is guaranteed to be a value of type WallIds in that loop.  It infers number, and you can't index into wallPool with any old number.  It needs to be a value of the WallIds union.  You could assert that i is a WallIds:
  for (let i = 0 as WallIds; i < 20000; i++) {
    wallPool[i] // no error, but, 20000 is an oopsie
  }

but, as shown above, you run into the problem that the compiler can't understand that i++ might make i no longer a valid WallIds, as explained in this comment of microsoft/TypeScript#14745.
If you're only ever going to be indexing into WallPool with a numeric literal value, like wallPool[123] or wallPool[1987], then that's fine.  But as soon as you start storing and manipulating indices of type number, you will likely hit a roadblock with this approach.  It might still be worth it to you, but it's important to be aware of it.
Playground link to code


text:
Q: AngularJS - Convert Object to Array for UI Bootstrap Pagination I know this might have been already answered, but I have been unsuccessful in applying any solutions I found to my example. I am trying to enabled pagination on my products list page using UI Bootstrap and allow the user to filter said results with a search.
I have an object that is defined as such:
$scope.products = [{"_id": ObjectID("0000000"), "name":"Product", "description": "Product Description"}];

So far I have been able to pull my products from a restangular service, but I am getting the following console error: Error: [filter:notarray] Expected array but received {} when I added the pagination/search functionality. I know I need to convert my object to an array, but I have not been able to successfully convert it. The two examples I tried are posted below. Any help will be greatly appreciated.
My Products list view

            <form>

                    Search

                    <input type="text" class="form-control" id="searchProducts" ng-model="search.name" placeholder="Search for products">

                        <button type="button" ng-click="clearSearch()">

                        </button>

            </form>

 {{product.name}}

                    <span class="pull-right product-price {{product.price | currency}}

                {{product.description}}

        <pagination class="pull-right" page="currentPage" total-items="totalItems" ng-model="currentPage" max-size="maxSize" ng-change="pageChanged() items-per-page="itemsPerPage" num-pages="numPages"></pagination>

I know I might have some extra dependencies injections, which I will remove once I get it working correctly.
My controller
angular.module('gemStoreApp')
   .controller('paginationCtrl', ['$scope', '$log', 'filterFilter', 'productsService', 'Restangular', '$filter', function ($scope, $log, filterFilter', productsService, Restangular, $filter) {

   $scope.search = {}

   $scope.filteredProducts = [];

   //Option 1
   angular.forEach($scope.products, function(product) {
       $scope.filteredProducts.push(product);
   });

   //Option 2
   //for (var key in $scope.products) {
       //var tempProducts = {};
       //tempProducts[key] = $scope.products[key];
       //$scope.filteredProducts.push(tempProducts);
   //});

   $scope.currentPage = 1;
   $scope.maxSize = 100;
   $scope.itemsPerPage = 10;

   $scope.$watch('search', function(newVal, oldVal) {
       $scope.filteredProducts = filterFilter($scope.products, newVal);
       $scope.totalItems = $scope.filteredProducts.length;
   }, true);

   //I also tried this
   //$scope.$watch('search, function(newSearch) {
       //$scope.filteredProducts = $filter('filter')($scope.products, $scope.search);
       // $scope.totalItems = $scope.filteredProducts.length;
   //});

   }])

My service
angular.module('gemStoreApp.productService',['ngResource'])
    .factory('productsService', function(Restangular) {
        return Restangular.service('products');
    });

My Products Controller
angular.module('gemStoreApp')
    .controller('ProductsCtrl', ['$scope', 'productsService', function ($scope, productsService) {
        $scope.products = {};
        productsService.getList().then(function(products){
            $scope.products = products;
        });
    }]);

Added the Restangular setRestangularFields and setRequestInterceptor methods to my app.js file, which gets the search/filtering function working, but I am still getting an Expected array but received {} error
RestangularProvider.setRestangularFields({
  id: '_id.$oid'
});

RestangularProvider.setRequestInterceptor(function(elem, operation) {

  if (operation === 'put') {
    elem._id = undefined;
    return elem;
  }
  return elem;
});

I have created a Plunker version that appears to be working correctly..
Plunker example.
Created an updated Plunker with the issue I am seeing my local. The issue is that the Pagination is not working correctly. It is displaying only 10 items as I want it to, but clicking on the two does not switch to page 2. Plunker example

A: I saw several things wrong in your example. I believe you don't need the ng-controller="SearchCtrl" in your html.
Also, the main point of having the filter in your ng repeat is to not use the watch event of the search text input. So you should use the products array and apply the filter against it. If you want to use filteredProducts, I left a function in my example below. I initialized the variables since I don't have access to your restless apis.

var app = angular.module('myApp', []);
app.filter('startFrom', function() {
    return function(input, start) {
        if(input) {
            start = +start; //parse to int
            return input.slice(start);
        }
        return [];
    }
});

app.controller('paginationCtrl', ['$scope', '$log', '$filter', function ($scope, $log, $filter) {
   $scope.search = {name: "Product"}
   $scope.products = [{"_id": "0000000", "name":"Product", "description": "Product Description"},
   {"_id": "0000000", "name":"Product 2", "description": "Product Description 2"}];
      $scope.filteredProducts = [];

   $scope.currentPage = 2;
   $scope.maxSize = 100;
   $scope.itemsPerPage = 10;
   $scope.startFrom = ($scope.currentPage - 1) * $scope.itemsPerPage;
   var filterProducts = function(newVal){
        $scope.filteredProducts.splice(0, $scope.filteredProducts.length);
         angular.forEach($scope.products, function(product) {
           if(product.name == newVal){
            $scope.filteredProducts.push(product);
           }
       });
   }
   $scope.$watch('search.name', function(newVal, oldVal) {
        filterProducts(newVal);
       $scope.totalItems = $scope.filteredProducts.length;
   }, true);

    $scope.$watch('currentPage', function(newVal, oldVal) {
        $scope.startFrom = ($scope.currentPage - 1) * $scope.itemsPerPage;
   }, true);
    $scope.$watch('itemsPerPage', function(newVal, oldVal) {
       $scope.startFrom = ($scope.currentPage - 1) * $scope.itemsPerPage;
   }, true);

   }])
<!DOCTYPE html>

    <link rel="stylesheet" href="style.css" />

                    Search

                    <input type="text" class="form-control" ng-model="search.name" placeholder="Search for products" />

                        <button type="button" ng-click="clearSearch()">
                            test
                        </button>

                {{product.name}}
                {{product.description}}

        <pagination class="pull-right" page="currentPage" total-items="totalItems" ng-model="currentPage" max-size="maxSize" ng-change="pageChanged()" items-per-page="itemsPerPage" num-pages="numPages"></pagination>

Edit
After watching your plunker, you do not need to add the filteredProducts to your controller since you are doing the filtering in your view. By adding the filteredProducts to your view, it will also be accessible in your controller with $scope.filteredProducts.
So replace the bottom of your html with the code below and also delete all that code that handles the filteredProducts from your controller:

              {{product.name}}

              {{product.description}}

          <pagination class="pull-right" page="currentPage" total-items="filteredProducts.length" ng-model="currentPage" max-size="maxSize" ng-change="pageChanged()" items-per-page="itemsPerPage" num-pages="numPages"></pagination>

If you want to do everything manually (which I do not recommend), you have to change your html to be product in filteredProducts, when it starts add all your products to the filteredProducts list and keep your code in the controller. Also you will have to fill the filteredProducts list again when the search is empty.


text:
Q: Unable to connect to Amazon RDS from EC2 wordpress site I'm migrating my website from a CPanel hosting to Amazon EC2. I'm using Amazon RDS to host my WordPress database.
I followed the following steps:

*

*Created a folder with the WordPress files from the old server.

*Created a database in RDS and uploaded the old site's DB dump.

*Edited the wp-config.php file to change the parameters to connect to the RDS instance.

While everything worked out fine, except that I'm getting the following error "Error establishing a database connection" while I open my site in the browser. I tried changing the security group on RDS and to allow all and also added a user on MySQL with the required permission for the database.
The problem is the connection to RDS is not getting established. I'm able to connect to RDS from my EC2 instance but WordPress is not able to.
My wp-config.php looks like:
/** The name of the database for WordPress */
define('DB_NAME', 'wordpress');

/** MySQL database username */
define('DB_USER', 'db_username');

/** MySQL database password */
define('DB_PASSWORD', 'db_password');

/** MySQL hostname */
define('DB_HOST', 'wordpress-site.something.rds.amazonaws.com:3306');

/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8');

/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');

EDIT: I changed my localhost's wp-config.php to point to RDS and the site is working perfectly fine on my localhost. The only problem is the connection issues from EC2.

A: Go to your AWS settings and have a look to see what ports you have open. IIRC, most are shut, you will probably have to open the port for the DB.

A: While using a barebones server, you have to install everything yourself. Please go ahead and check if you have PHP, Apache and mysql installed on your EC2 server, else it will not work!
When you opened ports on the security group, I hope you didn't open all the incoming ports for EC2/RDS as well - Do have a different security group for both of them.
If the site is working from your localhost, it means that the RDS is also accepting incoming connections from anywhere. Ideally, to make the database secure - RDS must only accept incoming connections from one IP (the elastic IP of your EC2 instance)
Cheers!


text:
Q: CRON Job with an R script giving a warning then execution haulted I am trying to schedule a CRON job to run every day at the same hour. It appears from the logfile that the script is executing but it gets haulted due to not being able to find packages.
I have the following crontab
34 23 * * * echo "$(date) Log File" > /home/bscuser/Escritorio/testCRONOUPUT.txt
34 23 * * * /usr/bin/Rscript /home/myuser/Desktop/myProject/rscripts/myRScript.R 2> /tmp/cronerror

So at minute 34 of hour 23 it will execute the two CRON lines.
However, from the cronerror file I see the following:
During startup - Warning messages:
1: package "methods" in options("defaultPackages") was not found
2: S3 methods '[.getAnywhere', '[.news_db', '[.roman', 'Ops.roman', 'Summary.roman', 'as.character.person', 'as.character.roman', 'as.person.default', 'as.personList.default', 'as.personList.person', 'close.txtProgressBar', 'edit.data.frame', 'edit.default', 'edit.matrix', 'edit.vignette', 'format.MethodsFunction', 'format.aspell', 'format.news_db', 'format.object_size', 'format.roman', 'getRcode.vignette', 'head.array', 'head.array', 'head.default', 'head.function', 'head.matrix', 'head.ftable', 'print.aspell', 'print.aspell_inspect_context', 'print.Bibtex', 'print.changedFiles', 'print.fileSnapshot', 'print.findLineNumResult', 'print.getAnywhere', 'print.help_files_with_topic', 'print.hsearch', 'print.hsearch_db', 'print.Latex', 'print.ls_str', 'print.MethodsFunction', 'print.news_db', 'print.object_size', 'print.packag [... truncated]
3: package 'utils' in options("defaultPackages") was not found
4: S3 methods 'print.recordedplot', 'print.colorConverter', 'print.RGBcolorConverter', 'checkFont.default', 'checkFont.Type1Font', 'checkFont.CIDFont', 'matchEncoding.Type1Font', 'matchEncoding.CIDFont', 'as.raster.raster', 'as.raster.logical', 'as.raster.numeric', 'as.raster.character', 'as.raster.matrix', 'as.raster.array', 'as.matrix.raster', 'is.na.raster', 'anyNA.raster', '[.raster', '[<-.raster', 'Ops.raster', 'print.raster', 'prettyDate', 'prettyDate' were declared in NAMESPACE but not found
5: package 'grDevices' in options("defaultPackages") was not found
6: S3 methods 'print.recordedplot', 'print.colorConverter', 'print.RGBcolorConverter', 'checkFont.default', 'checkFont.Type1Font', 'checkFont.CIDFont', 'matchEncoding.Type1Font', 'matchEncoding.CIDFont', 'as.raster.raster', 'as.raster.logical', 'as.raster.numeric', 'as.raster.character', 'as.raster.matrix', 'as.raster.array', 'as.matrix.raster', 'is.na.raster', 'anyNA.raster', '[.raster', '[<-.raster', 'Ops.raster', 'print.raster', 'prettyDate', 'prettyDate' were declared in NAMESPACE but not found
7: package 'graphics' in options("defaultPackages") was not found
8: S3 methods 'print.recordedplot', 'print.colorConverter', 'print.RGBcolorConverter', 'checkFont.default', 'checkFont.Type1Font', 'checkFont.CIDFont', 'matchEncoding.Type1Font', 'matchEncoding.CIDFont', 'as.raster.raster', 'as.raster.logical', 'as.raster.numeric', 'as.raster.character', 'as.raster.matrix', 'as.raster.array', 'as.matrix.raster', 'is.na.raster', 'anyNA.raster', '[.raster', '[<-.raster', 'Ops.raster', 'print.raster', 'prettyDate', 'prettyDate' were declared in NAMESPACE but not found
9: package 'stats' in options("defaultPackages") was not found
10: package 'methods' in options("defaultPackages") was not found
Error in namespaceExport(ns, exports) :
  undefined exports: cmpfun, cmpfile, loadcmp, compile, disassemble, enableJIT, compilePKGS, getCompilerOption, setCompilerOptions
Calls: getNamespace -> loadNamespace -> namespaceExport
Execution halted

However, this script works perfectly in my RStudio and I can also execute the script in the terminal without issue.
SessionInfo RStudio
R version 4.2.0 (2022-04-22)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: openSUSE Leap 15.3

Matrix products: default
BLAS:   /opt/R/4.2.0/lib64/R/lib/libRblas.so
LAPACK: /opt/R/4.2.0/lib64/R/lib/libRlapack.so

Random number generation:
 RNG:     Mersenne-Twister
 Normal:  Inversion
 Sample:  Rounding

locale:
 [1] LC_CTYPE=es_ES.UTF-8       LC_NUMERIC=C               LC_TIME=ca_ES.UTF-8
 [4] LC_COLLATE=ca_ES.UTF-8     LC_MONETARY=ca_ES.UTF-8    LC_MESSAGES=es_ES.UTF-8
 [7] LC_PAPER=es_ES.UTF-8       LC_NAME=C                  LC_ADDRESS=C
[10] LC_TELEPHONE=C             LC_MEASUREMENT=ca_ES.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] netstat_0.1.2       futile.logger_1.4.3 RSelenium_1.7.9     xml2_1.3.3
 [5] forcats_0.5.2       stringr_1.4.1       dplyr_1.0.10        purrr_0.3.4
 [9] readr_2.1.2         tidyr_1.2.1         tibble_3.1.8        ggplot2_3.3.6
[13] tidyverse_1.3.2     rvest_1.0.3

SessionInfo Terminal
R version 4.2.0 (2022-04-22)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: openSUSE Leap 15.3

Matrix products: default
BLAS:   /opt/R/4.2.0/lib64/R/lib/libRblas.so
LAPACK: /opt/R/4.2.0/lib64/R/lib/libRlapack.so

locale:
 [1] LC_CTYPE=es_ES.UTF-8       LC_NUMERIC=C
 [3] LC_TIME=ca_ES.UTF-8        LC_COLLATE=ca_ES.UTF-8
 [5] LC_MONETARY=ca_ES.UTF-8    LC_MESSAGES=es_ES.UTF-8
 [7] LC_PAPER=es_ES.UTF-8       LC_NAME=C
 [9] LC_ADDRESS=C               LC_TELEPHONE=C
[11] LC_MEASUREMENT=ca_ES.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
[1] compiler_4.2.0

EDIT:
New error:
── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
✔ ggplot2 3.3.6      ✔ purrr   0.3.4
✔ tibble  3.1.8      ✔ dplyr   1.0.10
✔ tidyr   1.2.1      ✔ stringr 1.4.1
✔ readr   2.1.2      ✔ forcats 0.5.2
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter()         masks stats::filter()
✖ readr::guess_encoding() masks rvest::guess_encoding()
✖ dplyr::lag()            masks stats::lag()
Error in library(RSelenium) : there is no package called 'RSelenium'
Execution halted


text:
Q: bash how to properly handle spaces in variable I have an sittuation when I try to handle variables in bash scripts.
dev.sh
#!/bin/bash
params="--context_param token_env=a c"
echo  ${params}
echo "$@"
sh job.sh $params "$@"

and destination script(originally provided by talend open studio, but changed for testing purpose)
job.sh
#!/bin/sh
for a in "$@"; do
   echo $a;
done

And then when I invoke the script like that:
./dev.sh --context_param token_param="a b"
I got:
--context_param token_env=a c
--context_param token_param=a b
-e
Using "$@":
--context_param
token_env=a
c
--context_param
token_param=a b

But I expect
--context_param token_env=a c
--context_param token_param=a b
-e
Using "$@":
--context_param
token_env=a c
--context_param
token_param=a b

How can I pass this variable to handle spaces, or where is the source of this difference?


text:
Q: while I was trying to train a DeepSpeech model on google colab, I'm getting an error saying that .whl file is not suported commands i used
!wget https://github.com/mozilla/DeepSpeech/releases/download/v0.9.3/ds_ctcdecoder-0.9.3-cp36-cp36m-manylinux1_x86_64.whl

!pip install /content/~path~/ds_ctcdecoder-0.9.3-cp36-cp36m-manylinux1_x86_64.whl

this gives me an error

ERROR: ds_ctcdecoder-0.9.3-cp36-cp36m-manylinux1_x86_64.whl is not a supported wheel on this platform.

how can i solve this ?

A: You are using wget to pull down a .whl file that was built for a different version of Python. You are pulling down
ds_ctcdecoder-0.9.3-cp36-cp36m-manylinux1_x86_64.whl
but are running Python 3.7. You need a different .whl file, such as:
ds_ctcdecoder-0.9.3-cp37-cp37m-manylinux1_x86_64.whl
This is available here from the DeepSpeech releases page on GitHub.


text:
Q: Google API Apps Script Function Execution Consistently Gets 500 Error I successfully obtain an access token and initialize the script service.  I have tried changing the scopes they are correct now.  Can you see the problem?  The result is this:

GoogleJsonResponseException error response: null error: 500 Internal
  Server Error {   "code" : 500,   "errors" : [ {
      "domain" : "global",
      "message" : "Internal error encountered.",
      "reason" : "backendError"   } ],
      "message" : "Internal error encountered.",
      "status" : "INTERNAL" }

The code:
public static String replaceProjectDetail(String docTitle, String projectTitle, String customerName, String projectNumber)
    throws GoogleDriveClientException, IOException, Exception {

            initialize_script();
            // ensure the properties were loaded
    if(!isInitialized) {
        throw new GoogleDriveClientException("Cannot process request because client objects are not initialized.");
    }

    final File content = getFileByTitle(docTitle);

            // ID of the script to call. Acquire this from the Apps Script editor,
            // under Publish > Deploy as API executable.
            String scriptId = SUPER SECRET SCRIPT ID;
            Object status = null;
            // Apps Script function to call.
            String functionName = "Function Name";
            String txtUrl = content.getWebViewLink();
            if(LOGGER.isDebugEnabled()) {
               LOGGER.debug("Google file captured: " + content.getName()
                        + ", url : " + txtUrl);
            }
            //isInitialized = false;
            //initialize_script();

            /** ensure the properties were loaded
    if(!isInitialized) {
        throw new GoogleDriveClientException("Cannot process request because client objects are not initialized.");
    }**/

            byte[] projNum = projectNumber.getBytes("UTF-8");
            byte[] projTitle = projectTitle.getBytes("UTF-8");
            byte[] custName = customerName.getBytes("UTF-8");
            byte[] URL = txtUrl.getBytes("UTF-8");

            // Initialize parameters for that function.
            List<Object> params = new ArrayList<>();
            params.add(projNum);
            params.add(projTitle);
            params.add(custName);
            params.add(URL);

            // Create execution request.
            ExecutionRequest request = new ExecutionRequest()
                .setFunction(functionName)
                .setParameters(params)
                .setDevMode(Boolean.FALSE);

            Credential client_credential = null;

            if(LOGGER.isDebugEnabled()) {
                LOGGER.debug("Google file apps script successfully configured.");
            }

            int high = 1000;
            Random r = new Random();
            int low = 1;

            // Attempt to execute our main action, retrying up to 4 times
            // if an exception is thrown
            for (int n = 0; n <= 4; n++) {
                try {

                    // The main action you want to execute goes here
                    // If this does not come in the form of a return
                    // statement (i.e., code continues below the loop)
                    // then you must insert a break statement after the
                    // action is complete.
                    // Make the API request.
                    client_credential = authorize();
                    //String accessToken = client_credential.getAccessToken();
                    /**if (LOGGER.isDebugEnabled())  {
                        LOGGER.debug("Google access token: " + accessToken);
                    }**/
                    op = service.scripts()
                            .run(scriptId, request)
                            .setAccessToken(client_credential.getAccessToken())
                            .execute();

                    if (LOGGER.isDebugEnabled())  {
                        LOGGER.debug("Successfully executed function: " + op.toPrettyString());
                    }

                    Map<String,Object> response = (ExecutionResponse) op.getResponse();

                    status = response.get("result");

                    if (LOGGER.isDebugEnabled())  {

                        for (Map.Entry<String, Object> entry : response.entrySet()) {
                            if (entry.getValue() instanceof String) {
                                LOGGER.debug("Google file apps script response:  entry.getKey()=" + entry.getKey().toString()
                                        + ", entry.getValue()=" + entry.getValue().toString());
                                return entry.getValue().toString();
                            } else if (entry.getValue() instanceof Class) {
                                LOGGER.debug("Google file apps script response: entry.getValue() = instance of Class.");
                                return "class";
                            } else {
                                throw new IllegalStateException("Expecting either String or Class as entry value");
                            }
                        }
                    }

                    if(LOGGER.isDebugEnabled()) {
                        LOGGER.debug("Google file apps script executed successfully. Return value: " + status.toString());
                    }

                    return "success";
                    } catch (GoogleJsonResponseException e) {

                        String googleErrors = getScriptError(op);

                        if (LOGGER.isDebugEnabled())  {
                            LOGGER.debug("GoogleJsonResponseException error response: " + googleErrors);
                        }

                        LOGGER.error("Failed to execute with error: " + e.getMessage());

                        // If we've exhausted our retries, throw the exception
                        if (n == 4) {
                            throw e;
                            }

                        // Wait an indeterminate amount of time (range determined by n)
                        try {

                            Thread.sleep(((int) Math.round(Math.pow(2, n)) * 1000)
                                + (r.nextInt(high - low) + low));
                        } catch (InterruptedException ignored) {
                            // Ignoring interruptions in the Thread sleep so that
                            // retries continue
                        }
                    } catch (NullPointerException npe)  {
                        LOGGER.debug("NullPointerException error response: " + npe.getMessage());
                        // If we've exhausted our retries, throw the exception
                        if (n == 4) {
                            throw npe;
                            }

                        // Wait an indeterminate amount of time (range determined by n)
                        try {

                            Thread.sleep(((int) Math.round(Math.pow(2, n)) * 1000)
                                + (r.nextInt(high - low) + low));
                        } catch (InterruptedException ignored) {
                            // Ignoring interruptions in the Thread sleep so that
                            // retries continue
                        }
                    } catch (SocketTimeoutException ste)  {
                        LOGGER.debug("SocketTimeoutException error response: " + ste.getMessage());
                        // If we've exhausted our retries, throw the exception
                        if (n == 4) {
                            throw ste;
                            }

                        // Wait an indeterminate amount of time (range determined by n)
                        try {

                            Thread.sleep(((int) Math.round(Math.pow(2, n)) * 1000)
                                + (r.nextInt(high - low) + low));
                        } catch (InterruptedException ignored) {
                            // Ignoring interruptions in the Thread sleep so that
                            // retries continue
                        }
                } catch (SocketException se)  {
                        LOGGER.debug("SocketException error response: " + se.getMessage());
                        // If we've exhausted our retries, throw the exception
                        if (n == 4) {
                            throw se;
                            }

                        // Wait an indeterminate amount of time (range determined by n)
                        try {

                            Thread.sleep(((int) Math.round(Math.pow(2, n)) * 1000)
                                + (r.nextInt(high - low) + low));
                        } catch (InterruptedException ignored) {
                            // Ignoring interruptions in the Thread sleep so that
                            // retries continue
                        }
                    } catch (Exception ex)  {
                        LOGGER.debug("SocketException error response: " + ex.getMessage());
                        // If we've exhausted our retries, throw the exception
                        if (n == 4) {
                            throw ex;
                            }

                        // Wait an indeterminate amount of time (range determined by n)
                        try {

                            Thread.sleep(((int) Math.round(Math.pow(2, n)) * 1000)
                                + (r.nextInt(high - low) + low));
                        } catch (InterruptedException ignored) {
                            // Ignoring interruptions in the Thread sleep so that
                            // retries continue
                        }
                    }

                }

        return "success";
}

A: 1)  An Apache Tomcat web service that searches for a Google Doc
2)  Get it's url
3)  Initialize the script service
4)  create a Google API Apps Script Function Execution which
         a)  searches for a document with the url
         b)  replaces text on the google document which is a copy of a template
5)  logs the error
It is programmed with retry of up to 4 times.

A: The problem was not this code.  I did not realize you had to use the same credential to start the Script service and get the access token for the Google API Apps Script Function Execution.


text:
Q: Javax-mail with multithread I am working on a java application which takes and saves all mails with attachemnts.But i want to do it multithread.My idea is like that.
One timer thread is getting all mails and put them in a BlockingQueue.I am putting Javax.mail.Message object to the queue.Then my worker threads are taking and processing them.
Problem is that when worker threads are taking Message and calling the methods:
Message.getFolder.open();

Message.getFolder.close();

causes problems.If one thread opens the folder and another one try to open same folder, application is throwing Operation is not allowed exception.
Can someone help me ?

A: Try Folder.isOpen() - Indicates whether this Folder is in the 'open' state. before opening it, like
Folder folder = Message.getFolder();

if(folder.isOpen()==false){
folder.open();
}

Similarly before closing, check if it already open then only close:
  if(folder.isOpen()){
    folder.close();
  }


text:
Q: Windows Deployment SErver TFTP connection issues Having a strange issue with WDS, During the boot process, an I wanted to get some opinions.
What is happening is The TFTP boot process is failing with a with a PXE-E32 Time out error, during the boot process. The Boot server is on another subnet with DCHP coming from a Juniper firewall.
I have configured the bootserver and boot file options on the juniper firewall.
I have been able to verfiy that TFTP is allowed through the firewall, by making a direct connection with TFTPD to the exact same boot file (boot\x86\wdsnbp.com)
I did a wireshark trace when the workstation was pxe booting and saw not TFTP packets at all.
Any thoughts?

A: Figured this one out we use a juniper srx 220 and we needed to configure the next server parameter as the wds server to alow the pxe boot process to complete


text:
Q: How to deal with routing density issues near uController I am routing a board that I cannot make larger. It is fairly dense with lots of SMD parts. I am trying to route traces to and from a 100 pin uController to various chips on the board.
It is a 4 layer board with GND on layer 2. Mostly power planes on layer 3 so I have layer 1 and 4 for the signal traces. But layer 1 is really dense with parts.
I have routed about 80 percent of the lines but now I'm finding I'm running out of space to route the remainder. I'm finding the need to make long winding traces for the rest of the lines.
On two of the sides of the uController there are some traces going to a 20 mhz crystal and a 32768 khz crystal. There are grounded copper pours oing around those crystals so that takes up some board real-estate there.
In the middle of the chip there are fan-outs of lots of vias and I have run out of room there.
What techniques are there for routing these things short of going to more layers?
I've gotten the trace width and clearances down to the minimum the board manufacturer will allow me (.006)
I've used the smallest vias I can, but I cannot make blind, buried vias nor do I want to put vias inside of the larger pads.
I cannot put parts on the underside of the board. I cannot make the board bigger.
How much of an issue will there be if I use a part of the layer 2 (GND) for this?  The highest frequency item on the board is the 20 mhz crystal. Everything else runs at 1/4 that speed. I have a buck converter running at around 1.2 mhz but that's in an area that I'm done routing.
Or would it be best to rip up the lines and try re-routing from the uController chip out? I didn't want to do that since my uController allows a lot of pin re-arrangement in software.
I'm using Diptrace.

A: You have a few options.
You neglected to mention which PCB house you are using.  Change to a PCB house with tighter tolerances, copper filled microvias, and smaller pad to drill size.
You neglected to mention which router you are using. A better router may help.
Look at the density of the routing, most CAD has a density map.  Open up the power plane where the density is high.
You could also switch to a hash pattern with the power and ground leaving some area between the traces for signal routing. This could also be done just in the high density areas.


text:
Q: css property for changing font color of links Which CSS property changes color of fonts of links in SharePoint 2013. I want to do the changes in customized master page of mysite15.master.

A: For all links:
a:link
{
   color: #000000;
}

For all links where class="whatever":
a.whatever:link
{
   color: #000000;
}


text:
Q: C++ How to avoid array of function pointers for derived objects? I have a base class color. I would like to have an different derived class for every color. When I transverse the enumeration, in case to avoid the if, else if situation for every derived class, I created an array of function pointers to create every time the appropriate object ( red, blue etc ).
But, at the end, I still have function pointers to do my job, even if in C++, it is supposed that they are not needed. Is there a way to avoid it, but without having an if, else if situation?
enum colors {
RED = 0,
BLUE,
GREEN,
.....,
.....,
.....,
.....,
.....,
.....,
.....,
.....,
MAX
};

class color {
    public:
        virtual void whatever() const {}
};
class red : public color {
    public:
        virtual void whatever() const {}
};
class blue : public color {
    public:
        virtual void whatever() const {}
};
class green : public color {
    public:
        virtual void whatever() const {}
};

template < class T >
static color const* make() { return new T(); }

color const* ( *array[MAX] )() = { make<red>, make<blue>,make<green>....};

int main ()
{
    for ( int i = 0; i < MAX; ++i ) {
        color const* i_color = (*array[i])();
            i_color->whatever();
    }

    return 0;
}


text:
Q: outputting a php function to xml. I have a Function (within the class Database)
            function locTo (){//return the location of the to currency
                $con = dbconnect(); //instantiate db connection
                $locationTo= mysql_query ("SELECT location  FROM Sheet1 where currency_code = '$this->to'", $con);
                $lol = mysql_fetch_array($locationTo);
                return $lol['location'];
                mysql_close();
                  }

when I call the function
$foo = new Database($from,$to);
$hey = $foo->LocTo();
echo $hey;

or
 $foo = new Database($from,$to);
 echo $foo->LocTo();

It out puts correctly.
Im trying to put into XML and im getting an encoding error.
This is my XML
echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<conv>';
echo'<at>'.$timefrom.'</at>';
echo'<rate>'.$rate.'</rate>';
echo'<from>';
echo''.$from.'';
echo'<curr>'.$currencyFrom.'</curr>';
echo'<loc>'.$locFrom.'</loc>';
echo'<amnt>'.$amount.'</amnt>';
echo'</from>';
echo'<to>';
echo''.$to.'';
echo'<curr>'.$currencyTo.'</curr>';
echo'<loc>'.$locTo.'</loc>';
echo'<amnt>'.$convertedAmount.'</amnt>';
echo'</to>';
echo'</conv>';

Does anyone know why I am getting an encoding error? I have checked the source code and it gets as far as the location.
here is an example of the location out put.
AED to GBP
 United Arab Emirates
 United Kingdom, Crown Dependencies (the  Isle of Man and the Channel Islands), certain      British Overseas Territories ( South Georgia and the South Sandwich Islands,  British      Antarctic Territory and  British Indian Ocean Territory)

A: htmlspecialchars() is quite probably your friend, as in
echo '<loc>' . htmlspecialchars($locFrom) . '</loc>';

Also, as mentioned by ZiTAL, header('Content-Type: text/xml, charset=utf-8') before any output is a must.

A: I recommend switching to (for example) DOM so your code would look like this:
<?php

$dom = new DOMDocument('1.0', 'UTF-8');
$dom->formatOutput = true; // Just for presentation, don't use this in real app
$main = $dom->createElement( 'conv');
$dom->appendChild( $main);

// Generic attributes
$main->appendChild( $dom->createElement( 'at', $timefrom));
$main->appendChild( $dom->createElement( 'rate', $rate));

// Fill form
$from = $dom->createElement( 'from');
$from->appendChild( $dom->createElement( 'code', $row['from']));
$from->appendChild( $dom->createElement( 'curr', $currencyFrom));
$from->appendChild( $dom->createElement( 'loc', 'time'));
$from->appendChild( $dom->createElement( 'amnt', 'time'));
$main->appendChild( $from);

// Fill to
$to = $dom->createElement( 'to');
$to->appendChild( $dom->createElement( 'at', 'time'));
$to->appendChild( $dom->createElement( 'code', 'time'));
$to->appendChild( $dom->createElement( 'curr', 'time'));
$to->appendChild( $dom->createElement( 'loc', 'time'));
$to->appendChild( $dom->createElement( 'amnt', ''));
$main->appendChild( $to);

echo $dom->saveXML();

This should make your XML always valid. The result would look like (filled just with string 'time'):
<?xml version="1.0" encoding="UTF-8"?>
<conv>
  <at>time</at>
  <rate>time</rate>
  <from>
    time
    <curr>time</curr>
    <loc>time</loc>
    <amnt>time</amnt>
  </from>
  <to>
    <at>time</at>
    time
    <curr>time</curr>
    <loc>time</loc>
    <amnt><img /></amnt>
  </to>
</conv>

Take a look at last <amnt /> it's correctly "xml escaped", you don't have to worry about it anymore, but be careful when using DOMELement->noveValue = html AFAIK this doesn't escape your values.
And of course don't forget to set correct header(), use (before sending any output):
header('Content-Type: text/xml, charset=utf-8');

Also take a look at 14.17 Content-Type and MIME types on wiki.


text:
Q: How to append new data to a list View inside a Fragment? So I've two fragments. One that posts data and one that shows the data in the activity.
So, once the post is done, I don't want to reload the entire Fragment, call the server, get all the data and show it. I just want to append the new piece of data to the fragment. How do I manage that?
Example: Twitter Direct Messages. When I send a direct Message, I don't have to load the entire list of Messages but just append the new message that I sent in the list View. How do I do that here?

A: Add the new data in the data structure you are passing to your adapter and call notifyDataSetChanged() on the list view. It will refresh to show the new data.


text:
Q: Query on concatenated fields across tables I have 2 tables in PostgreSQL a & b.
CREATE TABLE a
(
  id serial PRIMARY,
  name character varying(50) NOT NULL,
);

CREATE TABLE b
(
  id serial PRIMARY,
  name character varying(50) NOT NULL,
  a_id integer,
  CONSTRAINT a_id_fk FOREIGN KEY (a_id) REFERENCES a (id)
);

Additionally, I have these 2 partial indexes on b to ensure that b.name is unique if a is null else the pair (a.name, b.name) is unique.
  CREATE UNIQUE INDEX idx1 ON b (name, a_id) WHERE a_id IS NOT NULL;
  CREATE UNIQUE INDEX idx2 ON b (name) WHERE a_id IS NULL;

If I want to query a string that is of the form: a.name + ' ' + b.name, is this the most efficient way to do it ? Is there anyway I can create an index that also ensures the uniqueness of (a.name, b.name) and use that to efficiently query it?
SELECT * FROM b
INNER JOIN a on b.a_id = a.id
WHERE CONCAT(a.name, ' ' , b.name) = 'some string';

I need an exact lookup, LIKE / CONTAINS is not needed.

A: First, you need an additional UNIQUE constraint to fulfill your requirement:

else the pair (a.name, b.name) is unique.

CREATE TABLE a (
 , id   serial PRIMARY KEY
 , name text UNIQUE NOT NULL
);
MATERIALIZED VIEW
That would work fast in any case: a MATERIALIZED VIEW with concatenated strings. Since a and b are linked, we only get as many rows as there are in b, no Cartesian product.
CREATE MATERIALIZED VIEW ab AS
SELECT b.a_id, b.id, concat_ws(' ', a.name, b.name) AS abname
FROM   b
LEFT   JOIN a ON a.id = b.a_id;

Since you only use equality, a simple b-tree index does the trick now:
CREATE INDEX ab_abname_idx ON ab (abname);

And the query:
SELECT *
FROM   ab
-- optionally (left) join to a and b ...
WHERE  abname = 'some string';

*

*LEFT JOIN is essential to include rows from b with a_id IS NULL.

*concat_ws() only inserts the space where a.name isn't NULL.

*Refresh the materialized view according to your access patterns. That may be the tricky part if you have concurrent write access.
Without MATERIALIZED VIEW
'some string' LIKE (a.name || '%')

is not sargable. Index support is not possible. You would have to reverse the expression:
a.name = left('some string', length(a.name))

which is still not sargable. You would have to do it step-by-step:
a.name = left('some string', 1) OR
a.name = left('some string', 2) OR
a.name = left('some string', 3) OR
...

And this can be supported with indexes. Related answer on dba.SE:

*

*Algorithm for finding the longest prefix
I would use a recursive CTE to find all matches ...


text:
Q: customize error message in django-allauth How can I customizs error message in django-allauth?
I already implement overriding input forms for login
and it does work very well.
but, i want to build new error message when password mismatch.

A: I'm not 100% on this, but I believe you would have to make a custom form to do that. If you look into the directory: lib/allauth/account/forms.py in your project you should see all of the forms with their default error messages. It's bad practice to edit this file directly so you would have to make a custom form with the error messages you would like.


text:
Q: C# post requests not identified as session I've been trying to have a WPF client connecting to a PHP server, logging itself in and fetching 'IsLogged.php' to validate that the client is logged in. However, 'IsLogged.php' always returns that the client isn't authenticated, what am I doing wrong?
Servercode:
"CreateAccount.php"
session_start();

if (isset($_POST['user']))
{
    $_SESSION['UserName'] = $_POST['user'];
    echo "check";
}

"IsLogged.php"
session_start();

if (isset($_SESSION['UserName']))
{
    echo "allowed";
}
else
{
    echo "not allowed";
}

Client code:
"Post" method
    public static string Post(string RequestName, string PostData, out HttpStatusCode ReturnCode)
    {
        byte[] byteArray = Encoding.UTF8.GetBytes(PostData);

        WebRequest Request = WebRequest.Create(ChatAPI.Settings.BaseUrl + RequestName);
        Request.Method = "POST";
        Request.ContentType = "application/x-www-form-urlencoded";
        Request.ContentLength = byteArray.Length;

        Stream dataStream = Request.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();

        WebResponse response = Request.GetResponse();
        dataStream = response.GetResponseStream();

        ReturnCode = ((HttpWebResponse)response).StatusCode;

        StreamReader reader = new StreamReader(dataStream);
        string returnedData = reader.ReadToEnd();

        reader.Close();
        dataStream.Close();
        response.Close();

        return returnedData;
    }

And finally the window triggering the POST requests.
        HttpStatusCode Code;
        MessageBox.Show(General.Post("IsLogged", "", out Code)); --> Not allowed (intended)
        MessageBox.Show(General.Post("CreateAccount", "user=jan", out Code)); --> check (intended)
        MessageBox.Show(General.Post("IsLogged", "", out Code)); --> Not allowed (should be allowed)

Why is the server not registering the requests as a session?

A: The way the server identifies the client (and the corresponding session state) is through cookies.
Basically, in the CreateAccount request, the server attaches a cookie to its response and expects the client to present the cookie on every subsequent request.
If the cookie is not present in a request, the server has no way of identifying the client and treats the request as coming from an unknown source.
Your code does not manage cookies at all, so this is why the C# client always appears to be a new client to the PHP server.
The easiest way to save the cookie received from the server and present it on every new request is to use an instance of CookieContainer and attach it to every request you make.
I didn't try this code, so I'm not 100% sure of the syntax, but here's a starting point:
// this instance will be reused across multiple requests
private static CookieContainer cookieContainer = new CookieContainer();

public static string Post(string RequestName, string PostData, out HttpStatusCode ReturnCode)
{
    byte[] byteArray = Encoding.UTF8.GetBytes(PostData);

    WebRequest Request = WebRequest.Create(ChatAPI.Settings.BaseUrl + RequestName);
    Request.Method = "POST";
    Request.ContentType = "application/x-www-form-urlencoded";
    Request.ContentLength = byteArray.Length;

    Request.CookieContainer = cookieContainer; // this line is new

    Stream dataStream = Request.GetRequestStream();
    dataStream.Write(byteArray, 0, byteArray.Length);
    dataStream.Close();

    WebResponse response = Request.GetResponse();
    dataStream = response.GetResponseStream();

    ReturnCode = ((HttpWebResponse)response).StatusCode;

    StreamReader reader = new StreamReader(dataStream);
    string returnedData = reader.ReadToEnd();

    reader.Close();
    dataStream.Close();
    response.Close();

    return returnedData;
}


text:
Q: Quotient Groups question In my book it gives the example of a quotient group $\mathbb{R}^2/\mathbb{Z}^2$
 and you have to find all the elements of order 2.
so if we take $\overline{(x,y)}$ an element of the above quotient group then
$\overline{(2x,2y)}=0$
Now it says $2x= ...,-1, 0, 1, 2, 3,....$ and same for $2y$. Now shouldnt it be $2x=0,1$ because $\overline{(x,y)}$ is between 0 and 1. This is the method they give for the example in
$\mathbb{R}/\mathbb{Z}$ so i am confused on how that is changed for $\mathbb{R}^2/\mathbb{Z}^2$.

A: Observe that $\;\overline{(x,y)}=(x,y)+\Bbb Z^2\;$ has order two iff
$$\;2(x,y)\in\Bbb Z^2\iff (2x,2y)\in\Bbb Z^2\iff x,y\in\frac12\Bbb Z$$
i.e.: both $\;x,y\;$ are rational half integers (like $\;\frac12,\,\frac{-17}2\;,\;\;\frac{51}2,\,\text{etc.}\;$) .
Suppose now that we have two such elements
$$\;\overline{(x,y)}\;,\;\overline{(a,b)}\;,\;\;a,b,x,y\in\frac12\Bbb Z\,,\,\,\text{say}\;\;a=\frac\alpha2,\,b=\frac\beta2,\,x=\frac\xi2,\,y=\frac\upsilon2$$
then we have that
$$\overline{(a,b)}=\overline{(x,y)}\iff(a-x,\,b-y)\in\Bbb Z^2\iff\frac{\alpha-\xi}2\,,\,\frac{\beta-\upsilon}2\in\Bbb Z\iff$$
$$\iff \alpha-\xi=0\pmod 2\;,\;\;\text{and also}\;\;\beta-\upsilon=0\pmod2$$
and this means $\;\alpha,\,\xi\;$ have the same parity, and $\;\beta,\,\upsilon\;$ have the same parity.
Try now to take it from here...


text:
Q: Get value of multiselect box using jQuery or pure JS and display on input text I am trying to get the value of the multi-select box using jQuery or pure JS and display it on an input text.
I am getting value using var value = $(this).val(); and assign the value get to variable Round 1 i.e var result = "round 1"; so as to display in array like in a input text like this Round 1, Round 2, ....
Note: I want values of select option tag to remain numeric e.i value="90".

$("select[name='no_of_rounds']").change(function() {
  var value = $(this).val();
  if (value == "90") {
    var result = "round 1";
  } else if (value == "100") {
    var result = "round 2";
  } else if (value == "110") {
    var result = "round 3";
  } else if (value == "120") {
    var result = "round 4";
  } else if (value == "130") {
    var result = "round 5";
  }
  $("input#optionOutput").val(result);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="selectpicker" name="no_of_rounds" multiple id="no_of_rounds">
  <option value="90">Round 1</option>
  <option value="100">Round 2</option>
  <option value="110">Round 3</option>
  <option value="120">Round 4</option>
  <option value="130">Round 5</option>
  <option value="140">Round 6</option>
  <option value="150">Round 7</option>
  <option value="160">Round 8</option>
  <option value="880">Round 1 - Round 8</option>
</select>

<input type="text" id="optionOutput">

So far, I am getting only one attribute i.e. round 1, on select multiple

A: The data is already in array form, just join() it after mapping it to the option.text().

$("select[name='no_of_rounds']").change(function(){
    let v = $(this).val().map(n => $(this).find(`option[value="${n}"]`).text());
    $('#optionOutput').val(v.join(", "));
 })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="selectpicker" name="no_of_rounds" multiple id="no_of_rounds">
    <option value="90">Round 1</option>
    <option value="100">Round 2</option>
    <option value="110">Round 3</option>
    <option value="120">Round 4</option>
    <option value="130">Round 5</option>
    <option value="140">Round 6</option>
    <option value="150">Round 7</option>
    <option value="160">Round 8</option>
    <option value="880">Round 1 - Round 8</option>
</select>

<input type="text" id="optionOutput">

A: The value is an array. You can use .map() to loop through it and return an array of all the values you want to put into the input field.

$("select[name='no_of_rounds']").change(function() {
  var result = $(this).val().map(value => {
    if (value == "90") {
      return "round 1";
    } else if (value == "100") {
      return "round 2";
    } else if (value == "110") {
      return "round 3";
    } else if (value == "120") {
      return "round 4";
    } else if (value == "130") {
      return "round 5";
    }
  }).join(", ");
  $("input#optionOutput").val(result);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="selectpicker" name="no_of_rounds" multiple id="no_of_rounds">
  <option value="90">Round 1</option>
  <option value="100">Round 2</option>
  <option value="110">Round 3</option>
  <option value="120">Round 4</option>
  <option value="130">Round 5</option>
  <option value="140">Round 6</option>
  <option value="150">Round 7</option>
  <option value="160">Round 8</option>
  <option value="880">Round 1 - Round 8</option>
</select>

<input type="text" id="optionOutput">


text:
Q: Not saving image from ImageView I am trying to save an Image from image view but i am getting exception (Read-only file system)
I have tried this code,
bitmap1 = imageView.getDrawingCache(); //for retrieving the Image

public void saveOnClick(View view)
{
    try
    {
            String filename="qrimage";
            FileOutputStream out = new FileOutputStream(filename);
            bitmap1.compress(Bitmap.CompressFormat.PNG, 90, out);
            Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_SHORT).show();

    }
    catch (Exception e)
    {
           e.printStackTrace();
           Toast.makeText(getApplicationContext(), e.getMessage()+" Not Saved!", Toast.LENGTH_SHORT).show();
    }
}

A: User permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

A: here is a saving function
void Save() {
    final File myDir = new File(folder);
    myDir.mkdirs();
    final Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);
    final String fname = "StyleMe-" + n + ".png";
    file = new File(myDir, fname);
    if (file.exists())
        file.delete();
    try {

        mCBitmap.compress(CompressFormat.JPEG, 100, out);

        out.flush();
        out.close();
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                Uri.parse("file://"
                        + Environment.getExternalStorageDirectory())));
        Toast.makeText(getApplication(), "Image Saved", Toast.LENGTH_SHORT)
                .show();

    } catch (final Exception e) {

    }
}

just call Save(); in onClick of your button.
P.S you'll have to modify the name and the Bitmap name.
--- Declare these as global
    static File file;
String folder = "/sdcard/Pictures/YourFolderName";

and don't forget to set the permission to read and write to the storage.

A: Try this way
public void saveOnClick(View view)
    {
        try
        {

                imageView.setDrawingCacheEnabled(true); //UPDATE HERE
                imageView.buildDrawingCache(); //UPDATE HERE
                bitmap1 = imageView.getDrawingCache(); //UPDATE HERE

                String filename="qrimage";
                FileOutputStream out = new FileOutputStream(filename);
                bitmap1.compress(Bitmap.CompressFormat.PNG, 90, out);
                Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_SHORT).show();

        }
        catch (Exception e)
        {
               e.printStackTrace();
               Toast.makeText(getApplicationContext(), e.getMessage()+" Not Saved!", Toast.LENGTH_SHORT).show();
        }
    }

A: First make sure that your app has the storage permission enabled:
Go to Device Settings>Device>Applications>Application Manager>"your app">Permissions>Enable Storage permission!
Permissions in manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

So, if you want to create your own directory in your File Storage you can use somethibng like:
String myDate = getCurrentDateAndTime();
FileOutputStream outStream = null;
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/YourFolderName");
dir.mkdirs();
String fileName = "YourFileName_"+myDate+".jpg";
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
//to refresh the gallery
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
sendBroadcast(intent);
}

Hope this helps!


text:
Q: Calculating when the center points of two orbiting bodies will be at the same circumferential position I'm working on a game idea that includes objects orbiting around a common center point. I would like to have some way of knowing (mathematically) when two given objects/bodies will be at the same circumferential position (in radians) in their respective orbits.
What is known:

*

*The movement of objects is 2 dimensional

*All objects follow a circular orbital path around a common center point.

*The distance of the orbiting object from the center point is known, but may vary from object to object.

*The time it takes for any given object to complete one full revolution is known in seconds. This will also vary from object to object.

*The starting point of any given object is known in radians. This will also vary from object to object.

*All objects begin moving/orbiting at the same time.

*All objects are circles and their positions on the coordinate plane are dictated by their center points.

*All objects will continue their orbits indefinitely.

*No external forces are acting on the objects.

*Let's assume we are only comparing two objects at a time.
Example:
Object 1 is at a radius of 180 pts from the common center point and is located at 0.5 radians. It completes one full revolution in 3 seconds.
Object 2 is at a radius of 220 pts and is located at 0 radians. It completes one revolution in 5 seconds.
The objects are orbiting in the same direction.
What am I trying to figure out?
How can I, for example, determine the first 5 points when/where the two orbiting objects will cross paths. That is, each time a single straight line can be drawn from the common center point through the center points of both objects.
If any additional information is needed to calculate or if this isn't as straight forward as I'm imagining it to be, just let me know and I will do my best to provide additional info. Thanks ahead of time, really appreciate any help you guys can provide. :)

A: I am not sure I understand your question, but if it is as straightforward as it seems, then you might calculate the alignement time as follows. If the period of object 1 is $T_1$ and the period of object 2 is $T_ 2$, the time $t_n$ at which they are aligned is:
$$2 \pi \frac{t_n}{T_ 1} = 2 \pi \frac{t_n}{T_ 2} + 2 n \pi $$
$$ t_n = n\frac{T_1\, T_2}{T_2-T_1} $$
where n is any natural number.

A: Let $T_j$ and $T_k$ be the different periods of objects $j$ and $k$, with $T_k > T_j$.
If the objects are at different angles $\phi_j$ and $\phi_k$ at time $t=0$, they are aligned when:
$$
\frac{t}{T_j} - \frac{t}{T_k}  - \frac{\theta}{2 \pi} = n \in \mathbb{Z}
$$
with $\theta = \phi_j - \phi_k$. Note that there may be candidates for the solution for negative values of $n$.
The times $t$ at which $j$ and $k$ are aligned will be given by
$$
t = \frac{T_j T_k}{T_k - T_j} \left(n + \frac{\theta}{2 \pi} \right)
$$

(While I was writing this, I notice that Filipe Miguel posted a similar answer.)


text:
Q: How to count values in SQLITE in more then one column? I like to count the number of appearance of my users in more then one column. This is how I count the values in columns:
SELECT COUNT(col_01) FROM table_01 WHERE col_01 = 'John'     // result: 2
SELECT COUNT(col_02) FROM table_01 WHERE col_02 = 'John'     // result: 4

Is there any way to count John in one step in all columns I have and get the results 6?
Thank you in advance!

A: Try conditional aggregation
select
  sum(case when col_01='John' then 1 end) +
  sum(case when col_02='John' then 1 end)
from table_01;

A: First filter the table so that you get only the rows with 'John' in any of the 2 columns and then use aggregate function TOTAL() on each column:
SELECT TOTAL(col_01 = 'John') + TOTAL(col_02 = 'John') AS total
FROM table_01
WHERE 'John' IN (col_01, col_02);


text:
Q: RelativeLayout create button at a dynamic position
I am working on a project that involves painting on images.
To delete the unwanted lines or curves i have to draw a border and X button to delete it.
I have a relative layout where i have the freehand drawing canvas. on edit mode i should make them as u see in the pic, where i have to create button on a varying x,y positions.
i am confused how to achieve this.
Thanks in advance.
Jana.

A: I suggest doing this manually rather than using the Button widget. Override the onTouchEvent on the view holding your painting and use MotionEvent.getX and MotionEvent.getY in combination with MotionEvent.getAction to determine behaviour when the user touches the 'button'. Skipping widget creation will improve performance and open up doors to other types of functionality.

A: You could use the deprecated AbsoluteLayout container for this or keep the RelativeLayout and use layoutMargins to set the location of the buttons. The former is the route you should take despite the container being deprecated as the later breaks the layout paradigm by misusing margins...
You should keep in mind that there are a variety of devices with different screen sizes and setting explicit, pixel based locations is going to be awkward.


text:
Q: Chrono, c++, comparing dates I have Problem with comparing dates from chrono library.
For example, something should happen when the date_to_do_something is matched with the current date.
#include <iostream>
#include <chrono>
#include <typeinfo>
using namespace std;

int main(){
 end = chrono::system_clock::now();
 string date_to_do_something ="Tue Jul 27 17:13:17 2021";
 time_t end_time = chrono::system_clock::to_time_t(end);
 //gives some weird types:pc, pl
 cout<<typeid(ctime(&end_time)).name()<<endl;
 cout<<typeid(&end_time).name()<<endl;
 //Now how to compare?

}

A: First of all, pc and pl types are types char* and long*. If you want to print the full type name using typeid pipe your output to c++filt, something like ./prog | c++filt --types.
To compare these two dates, you should convert std::string to time_t. For that use tm structure. To convert string to time use strptime() function from time.h header. After that create time_point value using from_time_t() and mktime(). And at the end convert time_point_t type to time_t with to_time_t() function.
Your code should be something like this:
  auto end = chrono::system_clock::now();
  string date_to_do_something = "Mon Jul 27 17:13:17 2021";
  time_t end_time = chrono::system_clock::to_time_t(end);
  // gives some weird types:pc, pl
  cout << typeid(ctime(&end_time)).name() << endl;
  cout << typeid(&end_time).name() << endl;
  // Now how to compare?
  tm t = tm{};
  strptime(date_to_do_something.c_str(), "%a %b %d %H:%M:%S %Y", &t);
  chrono::system_clock::time_point tp =
      chrono::system_clock::from_time_t(mktime(&t));
  time_t time = chrono::system_clock::to_time_t(tp);
  if (time == end_time) {
    // do something
  } else {
    // do something else
  }