text:
Q: JWT token validation process in AdonisJs / Laravel I am using AdonisJs which is very similar to Laravel except syntax. I have generated JWT token with User Model providing uid as email and password as password as below;
jwt: {
    serializer: 'lucid',
    model: 'App/Models/User',
    scheme: 'jwt',
    uid: 'email',
    password: 'password',
    options: {
      secret: Env.get('APP_KEY'),
      expiresIn: 1000000000,
    }
  }

I was able to get user by validating that token through API call with postman.
Now I have changed the email id from database manually which was uid while generating token previously, I am still able to validate previous token and get user details through postman api call.
My question is, Adonis  auth object should be validating that token when await.auth.getUser() is called. but instead of invaliding, this returning data with updated email which was changed manually from database. How does this process work? I guess this will be same in Laravel.

A: Answer on forum.adonisjs.com
Adonis uses only the user ID for authentication.
Basic Adonis token :

full token
uid = user ID
You can encode the User object into the token with jwtPayload and then manually check User data:
Add User instance in Payload
Enable jwtPayload when create token:
const user = await User.find(1)

// generate(user, [jwtPayload], [jwtOptions])
const token = await auth.generate(user, true)

Token example:

full token
Get Payload data
const data = auth.jwtPayload; // Get full Playload

const user = auth.jwtPayload.data; // Get user

Output (full Payload) :
{
  "uid": 2,
  "data": {
    "email": "test@crbast.ch",
    "role": "admin",
    "created_at": "2020-05-06 11:26:36",
    "updated_at": "2020-05-06 11:26:36",
    "id": 2
  },
  "iat": 1588757196
}

Now you can validate email


text:
Q: Is it safe to not use the constructor when push_back the Iterator of vector to vector? First of all, both are code with no errors.
1.
std::vector<HttpConfigLocation> m_postLocation;
std::vector<HttpConfigLocation> location_block = this->m_server_block.get_m_location_block();
std::vector<HttpConfigLocation>::const_iterator location_iter = location_block.begin();

this->m_postLocation.push_back(*location_iter);

*

std::vector<HttpConfigLocation> m_postLocation;
std::vector<HttpConfigLocation> location_block = this->m_server_block.get_m_location_block();
std::vector<HttpConfigLocation>::const_iterator location_iter = location_block.begin();

this->m_postLocation.push_back(HttpConfigLocation(*location_iter));

In the motion of the vector's push_back, the pointers could not be moved, so I encountered the background of emplace. So, I had to create it with a constructor, but I had a question. If I just put the iterator as push_back, is the value maintained safe?

redpajama_set_name: RedPajamaStackExchange


text:
Q: 18.04 - Disk says "read only", and then reboot goes into initramfs I was trying to work on some files on my Ubuntu machine, and when I tried to save them, it told me that the disk was read only. I then rebooted the machine, but upon rebooting into Ubuntu it displayed an initramfs command prompt with all my files gone. How do I restore my desktop environment and my files?

A: Probably a disk error(s) caused your disk to become ro.
First, lets check out the file system...

*

*boot to a Ubuntu Live DVD/USB

*open a terminal window

*type sudo fdisk -l

*identify the /dev/XXXX device name for your "Linux Filesystem"

*type sudo fsck -f /dev/XXXX # replacing XXXX with the number you found earlier

*repeat the fsck command if there were errors

*type reboot
Then lets check the SMART Data...

*

*open the Disks application

*select SMART Data & Tests from the hamburger icon

*review the data, looking for parameters with "sector" in the name

*take a screenshot and edit it into your question

*run the SMART Tests


text:
Q: Android ActionBar Tab Navigation I am following http://www.youtube.com/watch?v=gMu8XhxUBl8 example. Setting up the tabs is working fine. On each tab, I am using a cursor to get the data from SQLite and display it. where should I write that code ? In TabActivity ? In AFragmentTab ?

A: In your AFragmentTab
Im sure this is where your work if any will take place.


text:
Q: Using tooltip in emberJs Problem
I want to show a tooltip on click of a link.
When I click on a link it will open a tooltip on that link.
Here i will add data to form then hit save.
Now i want to save this data using ember data.
I dont understand what should I use to achieve this.
What I have done
Till now I am loading all tooltips in a view at the end of body tag.
As the view loaded i do this to init the tooltip
//initiate the popup for adding new task as the view loaded
didInsertElement : function(){

    //Ember current object
    var self = this;

    //element we need to attach qtip on to
    var trigger_elm = $("#trigger-add-task");

    //if element is loaded then attach
    if(trigger_elm.length > 0){
        trigger_elm.qtip({
            content : {
                text : $("#popups #popup-add-task").remove(),
                title: 'Add New Task',
                button : 'Close'
            },
            style : {
                classes : 'font-lucida qtip-light qtip-bootstrap'
            },
             position: {
                my: 'center left',
                at: 'center right',
            },
            show: {
                event: 'click',
                solo: true
            },
            hide: {
                event: 'click',
            },
        })
    }

},
actions : {
    saveTask : function(){
        console.log('Ember running');
    }
},

Now everything is working but I dont know how can i add other js functionality in the form loaded in view. Like adding new rows on click. handling a few events. where should i do that
What should I use to achieve something like this.

A: Events (called actions in Ember.js) can be handled in a number of different places, depending on what you are trying to do:

*

*The view or component

*The controller

*The route

In your template, use an {{action}} to specify this:
<button {{action 'addRow'}}>Add Row</button>

The controller will handle this first, the addRow action is implemented:
export default Ember.ArrayController.extend({
  actions: {
    addRow: function() {
      // Do something here
    }
  }
});

If you return true from the controller action, the route action (if it exists) will be triggered also. If you want to target the view, change the template like this:
<button {{action 'addRow' target='view'}}>Add Row</button>

Now, which should you choose?
If you are going to be doing something which doesn't affect the data, and you are changing the DOM only, then target the view. Otherwise, target the controller or route. If you are altering the model, e.g adding a record to the model array, then do this in the controller. If you need to communicate with the server, then do it in the route. There are no hard and fast rules though.


text:
Q: How to do insert and update in a single query in mysql This is my table :
CREATE TABLE 'jobseeker_text_approval' (
    'id' Int( 11 ) AUTO_INCREMENT NOT NULL,
    'js_id' Int( 11 ) NULL,
    'first_name' VarChar( 200 ) NULL,
    'last_name' VarChar( 200 ) NULL,
    'address_line1' VarChar( 150 ) NULL,
    'address_line2' VarChar( 150 ) NULL,
    'about_me' Text NULL,
    'accomplishments' Text NULL,
    'awards' Text NULL,
    'created_on' Timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY ( 'id' ),
    CONSTRAINT 'js_id' UNIQUE( 'js_id' ) )
    ENGINE = InnoDB
    AUTO_INCREMENT = 272;
 )

I want to do insert and update in a single query
I have tried this one :
INSERT INTO jobseeker_text_approval (created_on)
VALUES('2017-02-26T00:00') ON DUPLICATE KEY UPDATE js_id= 216;

But it is adding a new row instead of updating the row if js_id exists.
I want to update  the table if there a row with the given js_id . otherwise insert. I also tried the REPLACE INTO function . But it  replace
the given values .But making existing fields  in the row to null.


text:
Q: Best way to create a vpn between two windows machines? I'm looking for way to create a VPN between two windows machines. I want the installed software to behave as if the two computers are connected through a LAN.
What's the best (free) way to do it?
Thanks,
Udi

A: If you're using Windows machines, client OSs can accept up to 10 incoming PPTP VPN connections (EDIT: only in the Professional or Business editions of Windows accept up to 10 connections; Home editions only accept 1 incoming connection) as per these instructions. Of course, Windows has built-in PPTP VPN client capabilities so there is no software needed. You'll need to edit the router that the receiving computer is behind to forward PPTP ports to the newly created VPN "server". The real question is: does the router that the receiving computer is behind pass GRE through?

A: Hamachi (http://hamachi.cc/download) provides a very easy setup for a VPN, after setting up your server, you'll just need to configure your router to open up the applicable ports.
Check out http://www.itsatechworld.com/2006/01/17/hamachi-vpn-solution/ for a quick setup guide.

A: openvpn - free & open source. works fine not only under linux but also for windows.
To note the opensource/community edition is free, there is a commercial version too.


text:
Q: Как установить модуль prettytable Запускаю cmd - Enter - pip install -  -U prettytable.
Получаю: «pip» не является исполняемой командой

A: У вас не установлен сам pip для Python через который вы скачиваете модуль. Для его установки вы можете переустановить язык поставив в инсталляторе галочку на Add to Patch или Pip.


text:
Q: How to setup nginx config .well-known/acme-challenge with a proxy to Django? I am very confused with the Nginx .well-known/acme-challenge configuration and how it works with a proxy for Django.
Here is my frontend config with is working:
server {
     listen 80;
     server_name myserve.com;
     root /var/www/html/myapp_frontend/myapp/;
     index index.html;
     location / {
          try_files $uri$args $uri$args/ /index.html;
     }
     location /.well-known/acme-challenge {
          allow all;
          root /var/www/html/myapp_frontend/myapp/;
     }

     return 301 https://myserver.com$request_uri;
 }

So, on the frontend I have no problem to define: root /var/www/html/myapp_frontend/myapp/;
Now I can run the acme script like this:
/root/.acme.sh/acme.sh --issue -d myserver.com -w /var/www/html/myapp_frontend/myapp/

It is working fine.
But I have issues with my Django backend because the nginx config uses a proxy:
upstream myapp {
     server backend:8000;
}

server {

     listen 80;
     server_name api.myserver.com;

     location / {
          proxy_pass http://myapp;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header Host $host;
          proxy_redirect off;
     }

     return 301 https://api.myserver.com$request_uri;
 }

Notice that I do not really have a configuration for the folder "/var/www/html/myapp_backend/myapp/" as I have on the frontend config, because now I'm using a proxy.
Now I can't run acme script like this:
/root/.acme.sh/acme.sh --issue -d myserver.com -w /var/www/html/myapp_backend/myapp/

How do I configure the folder for the SSL provider to be able to check my backend?

A: I don't know if it's possible to do it only in Nginx configuration, but I came to the conclusion that using a proxy it was Django who should create a url to /.well-known/acme-challenge/
I basically set a URL like this:
urlpatterns = [
    re_path(r'^acme-challenge/(?P<file_name>[\w\-]+)$', get_challenge),
]

and
urlpatterns = [
   ...
   path('.well-known/', include('myapp.wellknonw.urls')),
]

Notice that to accept multiple file names I use this: (?P<file_name>[\w-]+)$
And my views are like this:
@require_GET
def get_challenge(request, file_name=None):
    lines = []
    if file_name:
        path = f'{BASE_DIR}/myapp/.well-known/acme-challenge/{file_name}'
    try:
        with open(path) as f:
            lines = f.readlines()
            f.close()
    except:
        return HttpResponse("File not found!",
                            status=status.HTTP_404_NOT_FOUND)

    return HttpResponse("".join(lines), content_type="text/plain")

In docker my volume to: /myapp/.well-known/acme-challenge/
is mounted to: /var/www/html/myapp_backend/myapp/


text:
Q: Sum of ideals in polynomial rings Let $ I = \lbrace g(X) \in \mathbb{Z} \;| \; g(0)\in 5\mathbb{Z}\rbrace$
Show that $I$ is an ideal in $\mathbb{Z}[X]$, and that $I = \langle  5\rangle + \langle X\rangle $.
From previous parts of the exercise, I've proved the following statements:
$5 \in \langle f(X)\rangle \Rightarrow n = 0\wedge a_0 \;|\; 5$
$X \in \langle f(X)\rangle \Rightarrow n \leq 1 \wedge (\;\langle X \rangle = \langle  f(X)\rangle \vee \langle X\rangle = \mathbb{Z}[X]\;)$
I have proven the first part by checking that I is a subgroup of $\mathbb{Z}[X]$ and checking that $I$ is an ideal.
How do I go from here? I figure I can use the previously proven statements, but I'm not sure how. I know that the sum of ideals is the set containing the sum of one element from each ideal.

A: $\mathbb{Z}[X]$ is not a principal ideal domain, so not every ideal is of the form $\langle f(X)\rangle$. To see that $I\subseteq \langle 5\rangle +\langle X\rangle$, note that every element $g(X)$ of $I$ can be written as $h(X)+5n$ where $n\in\mathbb{Z}$ and $h(0)=0$. Then $h\in\langle X\rangle$ and $5n\in\langle 5\rangle$, so $g\in \langle 5\rangle +\langle X\rangle$. To see that $\langle 5\rangle + \langle X\rangle\subseteq I$, note that every element $g(X)$ of $\langle 5\rangle+\langle X\rangle$ is a sum of the form $h(X)+5n$ where $n\in\mathbb{Z}$ and $h\in\langle X\rangle$, meaning that $h(0)=0$. Thus $g(0)=h(0)+5n=5n\in 5\mathbb{Z}$, so $g\in I$.

A: Hint $\,\ g \in (x,5)\iff  \overbrace{g\ {\rm mod}\ x}^{\Large g(0)}\in (x,5)\iff 5\mid g(0)$


text:
Q: changed the entity mapping name from "/index" to "/indexemploye" and got this error I have saved both errors logs from the browser and IDE console into these 2 pdf files below:
browser error log
IDE console error log

https://imgur.com/a/3IYsVlE

codebase (source code link): https://github.com/ismailalabou/service-mvc.git

A: Caused by: org.attoparser.ParseException: Exception evaluating SpringEL expression: "currentPage==status.indexemploye" (template: "employes" - line 44, col 11)

Looks like a find and replace gone wrong.

A: I think you don't have any problem in DB or spring-data-jpa.
Thymeleaf is causing it. I seem you havn't added any indexemploye object in model which you want to use in thymeleaf.
You can add object in model like:
    @GetMapping("/showPost/{id}")
    public String showPost(@PathVariable(value = "id") long id, Model model) {
        Post post = postService.getPostById(id);
        postService.generateTagsString(post);
        model.addAttribute("post", post); // Now object Post can accessed in thyemeaf with name post
        return "show_post";
    }


text:
Q: Dynamically Generate Tarball and send through PHP? I have a directory listing script that I made, and I would like to know what direction I need to go in to make an option for a specific directory to be downloaded as a tarball.  A cronjob would not be acceptable because I would like this to be on demand so CPU cycles aren't wasted on unwanted content, but I would also like caching for content that has been requested.  An ideal solution, which would exclude caching, would be to output the tar command to stdout, but how would I send that through PHP without having to wait for the command to finish?  Some direction on this would be helpful.

A: To send it without waiting you could execute the gz command while using "ob_implicit_flush()", not sure if the command will read while still running but you can run it in the background and read from it while outputing into a file or something. You could also check the date on the dir/files and then run the gzip script


text:
Q: mysql_connect() works PDO doesn't I'm trying to connect to my database using PDO but i can't get it working. I get a 500 server error
MySQL version 5.0.83

'PDOException' with message 'SQLSTATE[HY000] [2002]
  php_network_getaddresses: getaddrinfo failed: nodename nor servname
  provided, or not known' inerror: Fatal error: Uncaught exception

Other error i get:

Fatal error: Uncaught exception 'PDOException' with message
  'SQLSTATE[HY000] [2002] Operation timed out'

I changed the values in this example obviously. And yes they are the correct credentials. I can connect with Sequel Pro or other methods.
connection.php:
<?php

//Our MySQL user account.
define('MYSQL_USER', 'user');

//Our MySQL password.
define('MYSQL_PASSWORD', 'pass');

//The server that MySQL is located on.
define('MYSQL_HOST', 'host');

//The name of our database.
define('MYSQL_DATABASE', 'database');

/**
 * PDO options / configuration details.
 * I'm going to set the error mode to "Exceptions".
 * I'm also going to turn off emulated prepared statements.
 */
$pdoOptions = array(
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_EMULATE_PREPARES => false
);

/**
 * Connect to MySQL and instantiate the PDO object.
 */
$pdo = new PDO(
    "mysql:host=" . MYSQL_HOST . ";dbname=" . MYSQL_DATABASE, //DSN
    MYSQL_USER, //Username
    MYSQL_PASSWORD, //Password
    $pdoOptions //Options
);

Registration.php
<?php

require 'connection.php';

The strange thing is that on an older page of this website mysql_connect() is used.

$db = mysql_connect($hostname, $db_user, $db_password);
  mysql_select_db($database,$db);

This works perfect with the exact same credentials.
It's hosted on a shared hosting and PDO is enabled on the server.
Shared Hosting: Blacknight
I tried:

*

*Not using $pdoOptions

*Not using define()

*Not using require and putting the new pdo code straight into the registration.php file

*running the script in the answers and now my mysql_connect() does a time-out and on my hosting i get a whitescreen.

now: Fri, 15 Jan 2016 08:54:21 +0100 last changed:Fri, 15 Jan 2016
  08:53:01 +0100 Deprecated: mysql_connect(): The mysql extension is
  deprecated and will be removed in the future: use mysqli or PDO
  instead in connection.php on line 14
Warning: mysql_connect(): Operation timed out in connectie.php on line
  14 connection failed. Operation timed out

A: You said using the mysql_* functions the connection can be established, yet with he exact same parameters the PDO connection fails.
And it fails with SQLSTATE[HY000] [2002] php_network_getaddresses....
So, abusing the "answers" section once again, I would like you to run the following script (only adjusting the defines) which will try both APIs.
It will also display the filemtime of the script; wouldn't be the first time some caching problem on a shared host caused the trouble ;-)
<?php
error_reporting(E_ALL|E_STRICT);
ini_set('display_errors', true);
// for testing purposes keep everything in one file
define('MYSQL_USER', 'localonly');
define('MYSQL_PASSWORD', 'localonly');
define('MYSQL_HOST', 'localhost');
define('MYSQL_DATABASE', 'test');

echo 'now: ', date('r'), ' last changed:', date('r', filemtime(__FILE__));

$db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD);
if ( !$db ) {
    die( 'connect failed. '.mysql_error() );
}
if ( !mysql_select_db(MYSQL_DATABASE, $db) ) {
    die( 'select_db failed. '.mysql_error($db) );
}
echo 'mysql: ', mysql_get_server_info($db), "
\r\n";

$pdoOptions = array(
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_EMULATE_PREPARES => false
);

try {
    $dsn = "mysql:host=" . MYSQL_HOST . ";dbname=" . MYSQL_DATABASE;

    $pdo = new PDO(
        $dsn,
        MYSQL_USER, //Username
        MYSQL_PASSWORD, //Password
        $pdoOptions //Options
    );
    echo 'pdo: ', $pdo->getAttribute(PDO::ATTR_SERVER_INFO), "
\r\n";
}
catch(Exception $ex) {
    echo 'PDO failed.', $ex->getMessage();
    var_dump($dsn);
    die;
}

Does the mysql_* part of the script get executed (printing the server version) while the PDO part fails again?

A: It appears to be the hosting. I put the exact same script on a different shared hosting : 'Combell' , i made a database on that hosting , i changed the credentials and the script works like a charm. So the problem is 'Blacknight'. Thanks for the help everybody.


text:
Q: How to check Multiple values at list in one condition with linq? I can check with 2 conditions like below, but in aspect of performance , is there any better way to do this? I want it to return true when list includes  records whose StudentName is John and  Ram. If there is just John, it needs to return false
studentList.Any(o => o.StudentName.Equals("John"))
                     && studentList.Any(o => o.StudentName.Equals("Ram"));

will cause getting Students list 2 times, may I check if multiple values exist in list in one condition?
using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        // Student collection
        IList<Student> studentList = new List<Student>() {
                new Student() { StudentID = 1, StudentName = "John", Age = 13} ,
                new Student() { StudentID = 2, StudentName = "Moin",  Age = 21 } ,
                new Student() { StudentID = 3, StudentName = "Bill",  Age = 18 } ,
                new Student() { StudentID = 4, StudentName = "Ram" , Age = 20} ,
                new Student() { StudentID = 5, StudentName = "Ron" , Age = 15 }
            };

        // LINQ Query Syntax to find out teenager students

        var bool_check = studentList.Any(o => o.StudentName.Equals("John"))
            && studentList.Any(o => o.StudentName.Equals("Ram"));

        Console.WriteLine(bool_check);
    }
}

public class Student
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }
    public int Age { get; set; }
}

A: The current condition would search the list twice if "John" was found. If you want to avoid this, you could filter for both "John" and "Ram" and check this smaller list, e.g.:
var shortList = studentList
                  .Where(x => x.StudentName == "John"
                              || x.StudenName == "Ram")
                  .ToHashSet();
var bool_check = shortList.Contains("John") && shortList.Contains("Ram);

However, as long as you have the list in memory and the size is not too big, the difference will be subtle.

A: List<string> DesireNames = new List<string>(){"John", "Ram"};
var YourFilteredStudents = ShortList.Where(o=> DesireNames.Contains(o.StudentName ));

A: In performance there is nothing that makes a big difference but in syntax you can use multiple conditions like this:
IList<Student> studentList = new List<Student>() {
                new Student() { StudentID = 1, StudentName = "John", Age = 13} ,
                new Student() { StudentID = 2, StudentName = "Moin",  Age = 21 } ,
                new Student() { StudentID = 3, StudentName = "Bill",  Age = 18 } ,
                new Student() { StudentID = 4, StudentName = "Ram" , Age = 20} ,
                new Student() { StudentID = 5, StudentName = "Ron" , Age = 15 }
            };

var test = from s in studentList
           where (s.StudentName!=null && s.StudentName!="") && (s.StudentName.Contains("John") || s.StudentName.Contains("Ram"))
           select s;

foreach (var item in test)
{
    Console.WriteLine($"id: {item.StudentID} name : {item.StudentName}");
}

Console.ReadKey();

This way in the "where" you can apply all the necessary filters as if it were a single condition


text:
Q: Can brandId be retrieved for an envelope using REST API? We are using the API to retrieve data from envelopes, mainly text tabs, but one of the fields we need is the brand.  I've seen where brandId can be set when creating an envelope but is this data available when doing a GET on an envelope?

A: I'm not aware of any way to retrieve brandId for an existing Envelope, and there is no mention of this possibility in the DocuSign REST API Guide.
A work-around would be to use a "Custom Envelope Field" (type = Text) to store brandId as a piece of metadata associated with the Envelope when the Envelope is created. For example, to set a (text) custom Envelope field in the Create Envelope API request to store the Brand Id, you could simply include this structure as part of the Create Envelope API request:
"customFields":{
     "textCustomFields":[
         {
             "name":"envBrandId",
             "required":"false",
             "show":"false",
             "value":"XXXX-XX-XXXX-XX-XXXX"
         }
     ]
 }

See the DocuSign REST API Guide (https://10226ec94e53f4ca538f-0035e62ac0d194a46695a3b225d72cc8.ssl.cf2.rackcdn.com/rest-api-guide-v2.pdf) for more details.
Then, once the Envelope has been created, you can retrieve the value(s) of Custom Envelope Field(s) by using this request:
GET /accounts/{accountId}/envelopes/{envelopeId}/custom_fields

Once again, the REST API Guide contains details about this operation.


text:
Q: How to get redirect from HttpWebResponse? I am trying to get a redirect from Google Maps using a project that is currently only at .Net Framework 4.0.
Take Microsoft's mailing address as an example:

1 Microsoft Way, Redmond, WA

Format a string that replaces Spaces  , Commas , with Plus + signs:
https://www.google.com/maps?daddr=1+microsoft+way+redmond+wa
By the time Google finishes processing the page, the final URL has the Latitude and Longitude:
https://www.google.com/maps/dir//1+Microsoft+Way,+Redmond,+WA+98052/@47.6393095,-122.1327333,16z/data=!3m1!4b1!4m8!4m7!1m0!1m5!1m1!1s0x54906d73f7de150b:0x922499d19305e9a0!2m2!1d-122.1283559!2d47.6393096
I need the Latitude and Longitude from this URL.
I found this article already on SO:
Get a collection of redirected URLs from HttpWebResponse
Using the solution there, I created this very similar looking method:
private String latitude, longitude;

private void GetLatLongFromAddress(String p_street_name, String p_city, String p_state, String p_postal_code)
{
    var street_name = String.Format("{0}", p_street_name.Replace(' ', '+')).Trim();
    var city = String.Format("{0}", p_city).Trim();
    var state = String.Format("{0}", p_state).Trim();
    var postal_code = String.Format("{0}", p_postal_code).Trim();
    var mapUrl = String.Format("http://maps.google.com/?daddr={0}+{1}+{2}+{3}",
                               street_name, city, state, postal_code);
    var location = String.Copy(mapUrl);
    while (!String.IsNullOrEmpty(location))
    {
        var req1 = (HttpWebRequest)HttpWebRequest.Create(location);
        req1.AllowAutoRedirect = false;
        // give page time to redirect?
        // System.Threading.Thread.Sleep(5000);
        using (var resp = (HttpWebResponse)req1.GetResponse())
        {
            location = resp.GetResponseHeader("Location");
            if (!String.IsNullOrEmpty(location))
            {
                var postalIndex = location.IndexOf(postal_code);
                var slashAtIndex = location.IndexOf("/@") + 1;
                if ((postalIndex < slashAtIndex) && (slashAtIndex < location.Length))
                {
                    var split = location.Substring(slashAtIndex).Split(',');
                    latitude = split[0];
                    longitude = split[1];
                }
            }
        }
    }
}

You can see where I format the original URL with this line:
var mapUrl = String.Format("http://maps.google.com/?daddr={0}+{1}+{2}+{3}",
                          street_name, city, state, postal_code);

The problem is with this line:
location = resp.GetResponseHeader("Location");

Every time I get the response, the returned location value is the same as the mapUrl value that I started with because Google does not redirect it immediately.
I tried adding a Sleep(5000) call, but that did not change anything.
How would I go about getting the final redirect?


text:
Q: How to read contents in a exe file of a game created using sdl 2? I was recently playing a game called Into the breach, i was fascinated by the game mechanics and wanted to learn more about the game, so i thought what better way to learn about the game by read through it's code. Fortunately the game developer has made the scripts view able directly through text editor all the script files had a .lua extension and showed how the game worked.
Files inside the game folder
But not everything was accessible for viewing like the code for the main menu.
So i tried different methods for reading the exe files, like opening the exe with Visual studio, but no dropdown would appear under the exe file, when i started to debug it the game ran perfectly well.
Also I was able extract files from the exe file using 7zip, but none of them could be read using a normal text editor.Files found inside the exe file after extracting it using 7zip
Is there any way to read these files through a third party program ?


text:
Q: ¿Cómo desplegó una aplicación en el ROOT Context para que se pueda acceder a través de la URL: 192.168.1.n:8080? hasta ahora he desplegado una aplicación JSP (.WAR) y se escucha desde localhost(de forma local), necesito cambiar esa ip (127.0.0.1/localhost) por la ip de mi ordenador.

Lo he desplegado con un servidor de Apache Tomcat!


text:
Q: how to find code for model no of iphone model no of iphone through code

A: UIDevice *myCurrentDevice = [UIDevice currentDevice];

NSLog(@"%@", [myCurrentDevice model]);
NSLog(@"%@", [myCurrentDevice systemName]);
NSLog(@"%@", [myCurrentDevice systemVersion]);

// result
iPhone
iPhone OS
3.1.2


text:
Q: How to configure Streaming on Starbound In Starbound, when you click on F6 you can open a menu to start a streming on Twitch.

And how it says, you have to configure the "streamingvideo.config" file. This file contains this code inside:
{
  "startAtLoad" : false,
  "kind" : "twitch",
  "targetFps" : 30,
  "verticalFlip" : true,
  "caCertPath" : ".\\curl-ca-bundle.crt",
  "dllLoadPath" : ".",
  "username" : "",
  "password" : "",
  "audioEnabled" : true,
  "tracing" : false,
  "traceFile" : ".\\twitch.log",
  "refreshTimer" : 30.0
}

But i don't know how to configure it. the "only" fields that I changed are "username" and "password" that I put my account on twitch.
Then I push the Start button, but doesn't works given the error that can be seen on image.
How can I Configure it to make it work?

A: The in-game streaming option are being developed at the current stage of the game. However, programs such as OBS (Open Broadcaster Software) are effective for recording such things quite well, with a much wider assortment of options.

A: If the streaming implementation worked, you would also need your streaming key, which you can find at
http://www.twitch.tv/*/dashboard/streamkey
replace the asterisk with whatever username you're logged in with, and wish to stream on. Looking at that config type file, I'm not sure where you'd input it, but I do know that you need the key.


text:
Q: Cruise Control error - unversioned file of the same name already exists Cruise Control couldn't compile a *.sln (or *.vbproj) file because of the error below.  Has anyone ever seen this error before?
Error:
unversioned file of the same name already exists
Cruise Control console error:
ThoughtWorks.CruiseControl.Core.CruiseControlException: Source control operation failed: svn: Failed to add file '\\dev-web-02\web\lims\dev\docs\UI.Web\web.config': an unversioned file of the same name already exists
. Process command: svn update \\dev-web-02\web\lims\dev\docs --username ccserver --password ccserver --non-interactive --no-auth-cache
   at ThoughtWorks.CruiseControl.Core.Sourcecontrol.ProcessSourceControl.Execute(ProcessInfo processInfo)
   at ThoughtWorks.CruiseControl.Core.Sourcecontrol.Svn.UpdateSource(IIntegrationResult result)
   at ThoughtWorks.CruiseControl.Core.IntegrationRunner.Build(IIntegrationResult result)
   at ThoughtWorks.CruiseControl.Core.IntegrationRunner.Integrate(IntegrationRequest request)

A: Yes, it's probably because someone has deleted the file from subversion and then re-added it, or this file "was" auto-generated (or manually added) on the CC server and now has been added to version control. svn is trying to create that file because it's been added to subversion, but it's erroring because the file is already there.
To fix it, just delete the file at \\dev-web-02\web\lims\dev\docs\UI.Web\web.config. The next svn update will get the latest version from the repository.


text:
Q: RightFax Server Setting I am currently doing integration to rightfax which using visual basic. There are some basic settings in order to establish connection.
I would like to ask the server name it is limited to servername only or IP address also acceptable?
Because currently I am using IP but it return me an error "The system cannot find the file specified" Anyone can kindly advise me? Appreciate for any reply.
gl_MyFaxServer = New RFCOMAPILib.FaxServer()
        gl_MyFaxServer.ServerName = "172.17.80.167"
        gl_MyFaxServer.Protocol = RFCOMAPILib.CommunicationProtocolType.cpNamedPipes
        gl_MyFaxServer.AuthorizationUserID = "ADMINISTRATOR"
        gl_MyFaxServer.AuthorizationUserPassword = "password01"
        gl_MyFaxServer.UseNTAuthentication = RFCOMAPILib.BoolType.False

        gl_MyFaxServer.OpenServer()

A: Have you installed the FaxUtil client to install the dll files needed?

A: This error caused because of authentication failure.
Make sure from the provided details by using them to connect to the right fax server via "RightFax FaxUtil".
One more thing, the "Administrator" account set without password for RightFax Server. So try to comment "gl_MyFaxServer.AuthorizationUserPassword = "password01" " line. Don't pass empty string, just remove the password assignment.


text:
Q: How to split list of strings into sublists where len("".join(sublist)) <= N? I'm given a list of strings and a length limit N.  I have to write a function to accumulate consecutive strings in the list until the next string would exceed the N limit.  I have to return a list of lists, where each list is the largest consecutive substring not to exceed N characters total.
See the test case below for an example.  Also, if any single string in the list is longer than N, I have to print a useful message and return.
def break_lst(lst, size):
    def len_lst(l):
        return len("".join(l))

    result = []
    sublst = []

    for i, v in enumerate(lst):
        sublst.append(v)
        ls = len_lst(sublst)

        if ls == size:
            result.append(sublst)
            sublst = []
        elif ls > size:
            prev_sublst = sublst[:-1]
            if not prev_sublst or len_lst(prev_sublst) > size:
                raise Exception("Error: use a bigger size than " + str(size))
            else:
                result.append(prev_sublst)
                sublst = []

    return result

if __name__ == "__main__":
    lst = ["1", "22", "333", "4444", "55555", "666666", "7777777", "88888888"]

    for i in range(17):
        try:
            print(i, break_lst(lst, size=i))
        except Exception as e:
            print(e)

The above code it's not only ugly but also buggy, it's giving me this output:
Error: use a bigger size than 0
Error: use a bigger size than 1
Error: use a bigger size than 2
Error: use a bigger size than 3
Error: use a bigger size than 4
Error: use a bigger size than 5
Error: use a bigger size than 6
Error: use a bigger size than 7
8 [['1', '22', '333'], ['55555'], ['7777777']]
9 [['1', '22', '333'], ['55555'], ['7777777']]
10 [['1', '22', '333', '4444'], ['55555'], ['7777777']]
11 [['1', '22', '333', '4444'], ['666666']]
12 [['1', '22', '333', '4444'], ['666666']]
13 [['1', '22', '333', '4444'], ['666666', '7777777']]
14 [['1', '22', '333', '4444'], ['666666', '7777777']]
15 [['1', '22', '333', '4444', '55555'], ['666666', '7777777']]
16 [['1', '22', '333', '4444', '55555']]

When the expected output should be:
Error: use a bigger size than 0
Error: use a bigger size than 1
Error: use a bigger size than 2
Error: use a bigger size than 3
Error: use a bigger size than 4
Error: use a bigger size than 5
Error: use a bigger size than 6
Error: use a bigger size than 7
8 [['1', '22', '333'], ['4444'], ['55555'], ['666666'], ['7777777'], ['88888888']]
9 [['1', '22', '333'], ['4444', '55555'], ['666666'], ['7777777'], ['88888888']]
10 [['1', '22', '333', '4444'], ['55555'], ['666666'], ['7777777'], ['88888888']]
11 [['1', '22', '333', '4444'], ['55555', '666666'], ['7777777'], ['88888888']]
12 [['1', '22', '333', '4444'], ['55555', '666666'], ['7777777'], ['88888888']]
13 [['1', '22', '333', '4444'], ['55555', '666666'], ['7777777'], ['88888888']]
14 [['1', '22', '333', '4444'], ['55555', '666666'], ['7777777'], ['88888888']]
15 [['1', '22', '333', '4444', '55555'], ['666666', '7777777'], ['88888888']]
16 [['1', '22', '333', '4444', '55555'], ['666666', '7777777'], ['88888888']]

Any suggestion?

A: The problem is in this section:
    elif ls > size:
        prev_sublst = sublst[:-1]
        if not prev_sublst or len_lst(prev_sublst) > size:
            raise Exception("Error: use a bigger size than " + str(size))
        else:
            result.append(prev_sublst)
            sublst = []

You've determined that the next list exceeds the given length.  You've properly backed up one element and recorded the maxed-out sublist.  However, you have not found a home for the v element that just blew your size limit.
For starters, try putting it into your new sublist:
        else:
            result.append(prev_sublst)
            sublst = [v]     # <=== the change is here.

Now, check your logic -- you'll want to validate this one-item list before you iterate to the next one.
One small comment on
for i, v in enumerate(lst):

Why did you go to the trouble of enumerate when you never use i?


text:
Q: How to integrate the following integral for all $q$? How to integrate
$$
\int^{\infty}_{-\infty}\frac{1}{4} \lambda _1 \lambda _2 e^{-\lambda _1 |x|^q-\lambda _2 |x|}\,dx
$$
where $0<q<1$?
If it can't be solved for $0<q<1$ then can it be solve for just $q=\frac{1}{2}$?

A: For $q=\frac 12 :$
$I=\frac 12 \lambda_1 \lambda_2 \int_{0}^{+\infty}e^{-\lambda_1x^{1/2}-\lambda_2x}dx$
Setting $u^2=\lambda_2x$,  $2udu=\lambda_2dx$, and :
$I=\lambda_1\int_0^{+\infty}u\times e^{-u^2-\frac{\lambda_1}{\sqrt{\lambda_2}}u}du=-\frac 12\lambda_1\int_0^{+\infty}(-2u-\frac{\lambda_1}{\sqrt{\lambda_2}}+\frac{\lambda_1}{\sqrt{\lambda_2}})\times e^{-u^2-\frac{\lambda_1}{\sqrt{\lambda_2}}u}du=-\frac 12\lambda_1([e^{-u^2-\frac{\lambda_1}{\sqrt{\lambda_2}}u}]_0^{+\infty}+\frac{\lambda_1}{\sqrt{\lambda_2}}\int_0^{+\infty}e^{-u^2-\frac{\lambda_1}{\sqrt{\lambda_2}}u}du)=\frac 12\lambda_1-\frac 12 \frac{\lambda_1^2}{\sqrt{\lambda_2}}\int_0^{+\infty}e^{-(u+\frac{\lambda_1}{2\sqrt{\lambda_2}})^2+\frac{\lambda_1^2}{4\lambda_2}}du=\frac 12\lambda_1(1-\frac{\lambda_1}{\sqrt{\lambda_2}}e^{\frac{\lambda_1^2}{4\lambda_2}}\int_{\frac{\lambda_1}{2\sqrt{\lambda_2}}}^{+\infty}e^{-w^2}dw) $
The last integral can be expressed with the help of the erfc function :
$\int_{\frac{\lambda_1}{2\sqrt{\lambda_2}}}^{+\infty}e^{-w^2}dw=\frac 12 \sqrt{\pi}erfc(\frac{\lambda_1}{2\sqrt{\lambda_2}})$
Therefore,
$$I_{1/2}=\frac 12\lambda_1(1-\frac{\lambda_1}{2\sqrt{\lambda_2}}\sqrt{\pi}e^{\frac{\lambda_1^2}{4\lambda_2}}erfc(\frac{\lambda_1}{2\sqrt{\lambda_2}}))$$


text:
Q: inline-block isn't working as expected with divs I trying to build a Simon game but I'm messing with CSS.

(source: walmartimages.com)
I don't know my mistakes but inline-block isn't working as expected:

    body {
        text-align: center;
    }

    #box {
        width: 500px;
        height: 500px;
        border-radius: 100%;
        position: relative;
        margin: auto;
        background-color: #333;
        top: 10vh;
        box-shadow: 0px 0px 12px #222;
    }

    #box .pad {
        width: 240px;
        height: 240px;
        float: left;
        left: 0px;
        border: 5px solid #333;
        box-shadow: 0px 0px 2px #222;
        display: inline-block;
        position: absolute;
    }

    #topLeft {
        background-color: green;
        border-top-left-radius: 100%;
    }

    #topRight {
        background-color: red;
        border-top-right-radius: 100%;
        /*right: 0;*/
    }

    #bottomLeft {
        background-color: yellow;
        border-bottom-left-radius: 100%;
    }

    #bottomRight {
        background-color: blue;
        border-bottom-right-radius: 100%;
    }

freeCodeCamp JS Simon Game

https://jsfiddle.net/gbs4320m/
I tried to mix things up with different settings and consulted online resources but i couldn't figure out the problem.
Please help!!
Thanks in advance.

A: Remove the position absolute:

body {
  text-align: center;
}

#box {
  width: 500px;
  height: 500px;
  border-radius: 100%;
  position: relative;
  margin: auto;
  background-color: #333;
  top: 10vh;
  box-shadow: 0px 0px 12px #222;
}

#box .pad {
  width: 240px;
  height: 240px;
  float: left;
  left: 0px;
  border: 5px solid #333;
  box-shadow: 0px 0px 2px #222;
  display: inline-block;
}

#topLeft {
  background-color: green;
  border-top-left-radius: 100%;
}

#topRight {
  background-color: red;
  border-top-right-radius: 100%;
  /*right: 0;*/
}

#bottomLeft {
  background-color: yellow;
  border-bottom-left-radius: 100%;
}

#bottomRight {
  background-color: blue;
  border-bottom-right-radius: 100%;
}

freeCodeCamp JS Simon Game

A: Firstly, you are setting various unnecessary float:left, position:absolute, left:0px; which conflicts with inline-block or just don't do anything in this scenario.
So let's remove those and get the #box .pad definition much simpler:
#box .pad {
    width: 240px;
    height: 240px;
    border: 5px solid #333;
    box-shadow: 0px 0px 2px #222;
    display: inline-block;
}

body {
    text-align: center;
}

#box {
    width: 500px;
    height: 500px;
    border-radius: 100%;
    position: relative;
    margin: auto;
    background-color: #333;
    top: 10vh;
    box-shadow: 0px 0px 12px #222;
}

#box .pad {
    width: 240px;
    height: 240px;
    border: 5px solid #333;
    box-shadow: 0px 0px 2px #222;
    display: inline-block;
}

#topLeft {
    background-color: green;
    border-top-left-radius: 100%;
}

#topRight {
    background-color: red;
    border-top-right-radius: 100%;
    /*right: 0;*/
}

#bottomLeft {
    background-color: yellow;
    border-bottom-left-radius: 100%;
}

#bottomRight {
    background-color: blue;
    border-bottom-right-radius: 100%;
}

freeCodeCamp JS Simon Game

That gets things in the right order but the segments are showing underneath each other. Why? Because of the way that spaces between inline-block elements is handled - see this question.
There are various ways around this as described in the answers to that question but the simplest solution in your case is probably just to float:left instead of display:inline-block. This will show the elements next to each other and overflow them onto the next "line" in a similar way to display:inline-block, but without the spacing issue:
#box .pad {
    width: 240px;
    height: 240px;
    border: 5px solid #333;
    box-shadow: 0px 0px 2px #222;
    float:left;
}

body {
    text-align: center;
}

#box {
    width: 500px;
    height: 500px;
    border-radius: 100%;
    position: relative;
    margin: auto;
    background-color: #333;
    top: 10vh;
    box-shadow: 0px 0px 12px #222;
}

#box .pad {
    width: 240px;
    height: 240px;
    border: 5px solid #333;
    box-shadow: 0px 0px 2px #222;
    float:left;
}

#topLeft {
    background-color: green;
    border-top-left-radius: 100%;
}

#topRight {
    background-color: red;
    border-top-right-radius: 100%;
    /*right: 0;*/
}

#bottomLeft {
    background-color: yellow;
    border-bottom-left-radius: 100%;
}

#bottomRight {
    background-color: blue;
    border-bottom-right-radius: 100%;
}

freeCodeCamp JS Simon Game

A: You should use position:relative for your #box pad in CSS.
Here is the updated link https://jsfiddle.net/gbs4320m/2/

A: Simply remove position absolute:and it works just fine.


text:
Q: Visial Studio - MS Teams - Auto Email Changes to Spreadsheet - Is this possible? Visual Studio 2017
Microsoft Teams
Scenario:
Within Teams we have a team with a tab that contains a spreadsheet. Users can enter information w/ a new number and the name of the person responsible etc.
Is it possible that when this item is entered that an email can automatically be sent to the person responsible from within Teams?
I have done some initial research and so far I do see where you can create apps BUT I just would like to know if what I am proposing is possible and if so would it be a monumental undertaking or shouldn't be too difficult.
Any thoughts/feedback appreciated,
Thank you

A: There are actually two problems to solve here. One, how to detect that something happened in Excel. Two, to take action on that event and send email.
For both of these, you can create Excel macros using VBA (transforming the file from xlsx to xslm). XSLM files require the full Excel client though and don't run well on the web version of Excel. I can't think of another way to do it using Excel.


text:
Q: How to correctly Min-Cut this network? I'm trying to understand the right procedure for making cuts in max-flow min-cut problems.
In this network here https://i.stack.imgur.com/SornO.png with the dashed cut through the middle, when working out the capacity of this cut, you would not include the capacity 9 of the $v_3$ to $v_2$ edge, because it is going backwards towards S (though, if you would count the -4 if you were working out how much actual flow you were interrupting). This I understand.
But, I was told that if you were to make a cut say across edges $(v_3,t), (v_4,v_3), (v_2, v_4)$ you in fact don't count the capacity - and I think not even the flow, though please correct me if I'm wrong - of edge $(v_4, v_3)$ - why? How am I supposed to know which edges that I cut across to exclude from the calculations?
Is it because, if I were to cut all 3 of those edges, because all the edges supplying $v_4$ have been cut (namely $(v_2,v_4)$ ) then all edges leaving v4 are now defacto 'empty'?
If I'm right, then if I were to make a cut along $(s, v_2), (v_2,v_1)$ and $(v_1,v_3)$ then I wouldn't count $(v_2,v_1)$, since all edges supplying $v_2$ are already, so any capacity potentially leaving $v_2$ is already accounted for with another cut? Is this right - if not, what's the understanding behind this/procedure to follow?
Thanks very much, indeed!
Edit for future readers: it was the insightful comments supporting the accepted answer that brought it together for me, so check those out for the full explanation.

A: A cut in a network isn't a line drawn through the picture. It is a partition of the vertices into two sets, $S$ and $T$, such that the source is in $S$ and the sink is in $T$. Then the capacity of a cut is the sum of the capacities of all the edges that go from a vertex in $S$ to a vertex in $T$.


text:
Q: MQ V7.5.3 can anyone please advise on taking dump of subscriptions which are created by MQ API Thanks for going thru this question.
We have installed ITCAM agent on MQ V7.5.0.3. Currently we had a scenario to clean out all the MQ objects and recreate it. While configuring ITCAM agent on MQ, there were few auto-created Subscriptions on Qmgr.
While taking dmpmqcfg -m  these subscriptions are not captured ( as per info center "The dmpmqcfg utility dumps only subscriptions of type MQSUBTYPE_ADMIN, that is, only subscriptions that are created using the MQSC command DEFINE SUB or its PCF equivalent. Subscriptions that are created by applications using the MQSUB MQI call of type MQSUBTYPE_API are not part of the queue manager configuration, even if durable, and so are not dumped by dmpmqcfg")
Can anyone please advise how to take dump of all the subscriptions irrespective of created by DEFINE SUB or by some API's.
Thank you

A: You can issue the command DISPLAY SUB(*) TYPE(API) ALL to see them all.
dmpmqcfg does not dump them out because replaying them as DEFINE SUB commands would create TYPE(ADMIN) subscriptions.


text:
Q: Image, Pdf download not working in Java Rest Api Im trying to download the image and pdf with the below code
        File createdFile = new File("logs/decryptedDocs"+filename);
        Path path = Paths.get(createdFile.getAbsolutePath());
        logger.info("Path is..{}",path.toUri());
        Resource resource = new UrlResource(path.toUri());
        headers.add("Content-Disposition", "attachment;filename="+resource.getFilename());

        // Try to determine file's content type
        String contentType = null;
        try {
            contentType = httpServletRequest.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException ex) {
            logger.info("Could not determine file type.");
        }

        // Fallback to the default content type if type could not be determined
        if(contentType == null) {
            contentType = "application/octet-stream";
        }
        logger.info("ContentType is..{}",contentType);
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(createdFile.length())
                .contentType(MediaType.parseMediaType(contentType))
                .body(resource);

In my local it is working and in postman when I checked image was visible but couldn't download directly in postman also but when I try to hit the API from front end, the image is visible in the preview section but getting some error in the response like json parser exception. front end technology used is AngularJs.
please help me on this.


text:
Q: Connect via SSH to a Raspberry Pi while using a VPN I have a Raspberry Pi connected to my local network via ethernet cable, I access it with putty through my laptop connected to the same network, at the local address 192.168.x.x port 22.
Now I would like to connect my Raspberry Pi to a VPN (in this case NordVPN) but obviously after having given the command nordvpn connect the connection with putty to the Raspberry Pi is lost, I think because the packets coming out of the Raspberry Pi at this point are forwarded to the servers of NordVPN and not to my computer.
So is there a way to properly connect to my Raspberry Pi in my network while a VPN is active on the Raspberry?

A: The same question is asked here: https://unix.stackexchange.com/questions/365285/how-to-allow-ssh-into-terminal-after-connecting-to-vpn-server-using-nordvpn-serv. The solution was to run there command to allow the ssh packets to bypass the vpn connection.
ip rule add from x.x.x.x table 128
ip route add table 128 to y.y.y.y/y dev eth0
ip route add table 128 default via z.z.z.z

Where x.x.x.x is your Server public IP, y.y.y.y/y should be the subnet of your Server public IP address, eth0 should be your Server public Ethernet interface, and z.z.z.z should be the default gateway.


text:
Q: Natural numbers that are square sums of four different nonzero integers It's known that any natural number can be expressed as a sum of four squares.
Conjecture:

A natural number can be written as a square sum of four different
  nonzero integers if and only if it not is a potency of two and not is
  a member of the set:
{3,5,6,7,9,10,11,12,13,14,15,17,18,19,20,21,22,23,24,25,26,27,28,29,31,33,34,35,36,38,40,41,43,44,47,48,49,52,53,56,59,68,73,76,80,83,88,96,104,112,128,144,160,192,208,224,304,320,384,416,448,640,768,832,896,1280,1536,1664,1792,2560,3072,3328,3584,5120,6144,6656,7168,10240,12288,13312,14336,20480,24576,26624,28672}.

So far tested up to $2^{16}$.

A: The OEIS entry for the positive integers that are not the sum of four distinct non-zero perfect squares says that your conjecture is wrong. Specifically, their list of the first $1000$ numbers shows a lot of numbers that are not powers of $2$ even after your $28\,672$. Here are the numbers from that list between $2^{15}$ and $2^{16}$ in the sequence:
$$
\begin{array}{}
31744\\
32768\\
33792\\
34816\\
36864\\
37888\\
38912\\
40960\\
43008\\
44032\\
45056\\
48128\\
49152\\
53248\\
56320\\
57344\\
59392\\
61440
\end{array}
$$


text:
Q: Are snaps limiting ubuntu product? Since loop devices are limited, and based on  of my ubuntu 18.04 (with cinnamon), one must assume that at some point ubuntu will be useless. There will be so many loop devices for the snaps that will pass the max limit (not mentioning that some apps, like gnome-calculator, are already using more than one). Is that correct?
EDIT (after commented):
I am running a default Ubuntu installation, which means that snaps are default for Ubuntu. (I am not sure, but I don't remember installing all these snaps)
The idea of proposing to desktop users to change the hard coded loop limit is out of (any) discussion.


text:
Q: Toggling Flash on AVCaptureDevice requires Stopping and Starting AVCaptureSEssion In iOS 7 when changing the flash state for AVCaptureDevice using:
if ([self.avCaptureDevice isFlashModeSupported:self.avCaptureFlashMode])
{
    NSError *error = nil;
    [self.avCaptureDevice lockForConfiguration:&error];
    if (!error) [self.avCaptureDevice setFlashMode:self.avCaptureFlashMode];
    [self.avCaptureDevice unlockForConfiguration];
}

The device won't use the flash unless the AVCaptureSessions is stopped and started with:
[self.avCaptureSession stopRunning];
[self.avCaptureSession startRunning];

This causes the camera to flash to black briefly. Is it possible to toggle the flash without stopping/starting the session?

A: I had a similar flash related problem in iOS7 where still capture would fail if the session had multiple outputs (still and videodata) and the flash was used. Found a workaround in https://devforums.apple.com/message/894764 (removing the second output before calling captureStillImageAsynchronouslyFromConnection:completion). Obviously this will also pause the video, but it may be more suitable if you have a shutter animation anyway.


text:
Q: Hyperledger Fabric - Error while Instantiating chaincode (error trying to connect to local peer: context deadline exceeded) I am using Hyperledger Fabric v 1.3.0 and trying to deploy using swarm network on multiple hosts. I am facing an issue when trying to instantiate the chaincode. The error i get is below in the image
Chaincode Instantiate Error :

I keep getting "Error trying to connect to local peer: context deadline exceeded"
From some discussions, i added these 2 environment variables in the peer yaml
CORE_PEER_ADDRESSAUTODETECT=true
CORE_PEER_CHAINCODELISTENADDRESS=0.0.0.0:7052

But still i get the same error.
Any pointers regarding the same?

A: I've seen this issue before when the peer is trying to stand up a chaincode container on a different docker network to which the peer is on- I'd recommend that you check the network(s) that all the containers are running on across your hosts and ensure the peer/chaincode networks are aligned


text: Q: How to get the gamma value of QImage In QImageWriter there is an option for setting the gamma value if the image but i want to know how to get the present gamma value so i can represent it in my histogram of the image .


text:
Q: Can't connect Android Studio with SQL Server I am trying to connect my android studio application with my database to save the "Log in" that are made on the page.
The problem is that when you press "Register" the app freezes for a few seconds and stops. I would appreciate any help.
package com.example.trainer;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.StrictMode;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class MainActivity extends AppCompatActivity {

EditText edtNombres,edtCorreo;
Button btnAgrgar;

String ip="192.168.1.137",port="51896",db="Trainer",username="IVAN",password="ivanlo";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    edtNombres = findViewById(R.id.edtNombres);
    edtCorreo = findViewById(R.id.edtCorreo);
    btnAgrgar = findViewById(R.id.btnAgregarUsuario);

    btnAgrgar.setOnClickListener(View -> agregarUsuario());

}

public Connection conexionBD(){
    Connection conexion=null;
    String ConnectURL=null;
    try {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
        ConnectURL = "jdbc:jtds:sqlserver://"+ip+":"+port+";"+"databasename="+db+";user"+username+";"+"password="+password+";";
        conexion = DriverManager.getConnection(ConnectURL);
    }catch (Exception e){
        Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
    }
    return conexion;
}

public void agregarUsuario() {
    try {
        PreparedStatement pat = conexionBD().prepareStatement("insert into usuarios values (?,?)");
        pat.setString(1,edtNombres.getText().toString());
        pat.setString(2,edtCorreo.getText().toString());
        pat.executeUpdate();

        Toast.makeText(getApplicationContext(),"REGISTRO AGREGADO",Toast.LENGTH_SHORT).show();
    }catch (Exception e){
        Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
    }
}

}
for the connection I use my IP and the credentials that I have created in SQL server.
when I press the button, these errors appear in the Log:
2021-08-31 12:54:53.812 7595-7595/com.example.trainer E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.trainer, PID: 7595
java.lang.NoClassDefFoundError: Failed resolution of: Lorg/ietf/jgss/GSSManager;
    at net.sourceforge.jtds.jdbc.TdsCore.createGssToken(TdsCore.java:4400)
    at net.sourceforge.jtds.jdbc.TdsCore.sendMSLoginPkt(TdsCore.java:1971)
    at net.sourceforge.jtds.jdbc.TdsCore.login(TdsCore.java:617)
    at net.sourceforge.jtds.jdbc.JtdsConnection.<init>(JtdsConnection.java:371)
    at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184)
    at java.sql.DriverManager.getConnection(DriverManager.java:580)
    at java.sql.DriverManager.getConnection(DriverManager.java:236)
    at com.example.trainer.MainActivity.conexionBD(MainActivity.java:43)
    at com.example.trainer.MainActivity.agregarUsuario(MainActivity.java:52)
    at com.example.trainer.MainActivity.lambda$onCreate$0$MainActivity(MainActivity.java:31)
    at com.example.trainer.MainActivity$$ExternalSyntheticLambda0.onClick(Unknown Source:2)
    at android.view.View.performClick(View.java:7448)
    at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
    at android.view.View.performClickInternal(View.java:7425)
    at android.view.View.access$3600(View.java:810)
    at android.view.View$PerformClick.run(View.java:28305)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:223)
    at android.app.ActivityThread.main(ActivityThread.java:7656)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
 Caused by: java.lang.ClassNotFoundException: Didn't find class "org.ietf.jgss.GSSManager" on path: DexPathList[[zip file "/data/app/~~tRgfQFqCq4697lIpnn8MFQ==/com.example.trainer-H6Semqa_egRWQ15HhPsALw==/base.apk"],nativeLibraryDirectories=[/data/app/~~tRgfQFqCq4697lIpnn8MFQ==/com.example.trainer-H6Semqa_egRWQ15HhPsALw==/lib/x86, /system/lib, /system_ext/lib]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:207)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
    at net.sourceforge.jtds.jdbc.TdsCore.createGssToken(TdsCore.java:4400)
    at net.sourceforge.jtds.jdbc.TdsCore.sendMSLoginPkt(TdsCore.java:1971)
    at net.sourceforge.jtds.jdbc.TdsCore.login(TdsCore.java:617)
    at net.sourceforge.jtds.jdbc.JtdsConnection.<init>(JtdsConnection.java:371)
    at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184)
    at java.sql.DriverManager.getConnection(DriverManager.java:580)
    at java.sql.DriverManager.getConnection(DriverManager.java:236)
    at com.example.trainer.MainActivity.conexionBD(MainActivity.java:43)
    at com.example.trainer.MainActivity.agregarUsuario(MainActivity.java:52)
    at com.example.trainer.MainActivity.lambda$onCreate$0$MainActivity(MainActivity.java:31)
    at com.example.trainer.MainActivity$$ExternalSyntheticLambda0.onClick(Unknown Source:2)
    at android.view.View.performClick(View.java:7448)
    at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
    at android.view.View.performClickInternal(View.java:7425)
    at android.view.View.access$3600(View.java:810)
    at android.view.View$PerformClick.run(View.java:28305)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:223)
    at android.app.ActivityThread.main(ActivityThread.java:7656)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)


text:
Q: Implicit conversion from data type datetime to tinyint is not allowed. Use the CONVERT function to run this query I understand the error and its meaning.  What I don't understand is why I'm receiving the error since the table I'm inserting into (Table B) is a replica of the table where the data is coming from (Table A).  Can you please help explain why I'm receiving the error.  Here are the data types for each column of the tables in question.
Table A                                    Table B

ID_TYPE:int                            int
ID_TYPE:int                            int
ID_TYPE:int                            int
ID_TYPE:int                            int
ID_TYPE:int                            int
ID_TYPE:int                            int
ID_TYPE:int                            int
ID_TYPE:int                            int
ID_TYPE:int                            int
ID_TYPE:int                            int
ID_TYPE:int                            int
ID_TYPE:int                            int
numeric(19, 4)                         numeric(19, 4)
ID_TYPE:int                            int
numeric(19, 4)                         numeric(19, 4)
ID_TYPE:int                            int
varchar(10)                            varchar(10)
varchar(128)                           varchar(128)
varchar(1000)                          varchar(1000)
ADDRESS_TYPE:varchar(40)               varchar(40)
ADDRESS_TYPE:varchar(40)               varchar(40)
CITY_TYPE:varchar(28)                  varchar(28)
STATE_TYPE:char(2)                     char(2)
POSTALCODE_TYPE:varchar(11)            varchar(11)
NPA_TYPE:varchar(3)                    varchar(3)
NXX_TYPE:varchar(3)                    varchar(3)
LINE_TYPE:varchar(12)                  varchar(12)
smallint                               smallint
varchar(11)                            varchar(11)
datetime                               datetime
datetime                               datetime
varchar(128)                           varchar(128)
varchar(32)                            varchar(32)
BOOLEAN_TYPE:tinyint                   tinyint
BOOLEAN_TYPE:tinyint                   tinyint
varchar(256)                           varchar(256)
varchar(256)                           varchar(256)
varchar(256)                           varchar(256)
datetime                               datetime
BOOLEAN_TYPE:tinyint                   tinyint
ABANO_TYPE:varchar(9)                  varchar(9)
BANKACCTNO_TYPE:varchar(17)            varchar(17)
QBID_TYPE:varchar(36)                  varchar(36)
QBID_TYPE:varchar(36)                  varchar(36)
BOOLEAN_TYPE:tinyint                   tinyint
int                                    int
USERID_TYPE:int                        int
SYSTEMDATE_TYPE:datetime               datetime
USERID_TYPE:int                        int
SYSTEMDATE_TYPE:datetime               datetime
SWORKSTATIONID_TYPE:varchar(256)       varchar(256)
APPLICATIONID_TYPE:smallint            smallint
ID_TYPE:int                            int
ID_TYPE:int                            int
ID_TYPE:int                            int
varchar(128)                           varchar(128)
varchar(128)                           varchar(128)
char(2)                                char(2)
BOOLEAN_TYPE:tinyint                   tinyint
ID_TYPE:int                            int
BOOLEAN_TYPE:tinyint                   tinyint
ID_TYPE:int                            int
BOOLEAN_TYPE:tinyint                   tinyint
varchar(25)                            varchar(25)
                                       nvarchar(50)

Query
 insert into cogent_firm_specific.dbo.client_grouping

 select MAIN.dbo.client.[NCLIENTID]
      ,main.dbo.client.[NFIRMID]
      ,main.dbo.client.[NCLIENTLIASONID]
      ,main.dbo.client.[NPARENTID]
      ,main.dbo.client.[NCLNTCOSTCODEID]
      ,main.dbo.client.[NFEEAGREEMENTID]
      ,main.dbo.client.[NREMITMETHODCODEID]
      ,main.dbo.client.[NCLIENTSTATUSCODEID]
      ,main.dbo.client.[NTRANSACTSTCODEID]
      ,main.dbo.client.[NEXPORTCODEID]
      ,main.dbo.client.[NARCODEID]
      ,main.dbo.client.[NCOLLECTIONCHRGCODEID]
      ,main.dbo.client.[NCOLLCHRG]
      ,main.dbo.client.[NATTYFEECODEID]
      ,main.dbo.client.[NATTYFEE]
      ,main.dbo.client.[NCOUNTRYCODEID]
      ,main.dbo.client.[SCLIENTNO]
      ,main.dbo.client.[SCLIENTNAME]
      ,main.dbo.client.[SCLIENTLEGALNAME]
      ,main.dbo.client.[SADDR1]
      ,main.dbo.client.[SADDR2]
      ,main.dbo.client.[SCITY]
      ,main.dbo.client.[SSTPROV]
      ,main.dbo.client.[SPOSTALCODE]
      ,main.dbo.client.[SCLNTNPA]
      ,main.dbo.client.[SCLNTNXX]
      ,main.dbo.client.[SCLNTLINE]
      ,main.dbo.client.[NPRIORITY]
      ,main.dbo.client.[STIN]
      ,main.dbo.client.[DTLASTPLCMNT]
      ,main.dbo.client.[DTFIRSTPLCMNT]
      ,main.dbo.client.[SWEBSITE]
      ,main.dbo.client.[SWEBLOGIN]
      ,main.dbo.client.[BRPTASFAMILY]
      ,main.dbo.client.[BBILLASFAMILY]
      ,main.dbo.client.[SFTPSITE]
      ,main.dbo.client.[SFTPLOGIN]
      ,main.dbo.client.[SFTPPWD]
      ,main.dbo.client.[DTLASTSTMT]
      ,main.dbo.client.[BNOPOST]
      ,main.dbo.client.[SCLIENTBANKABANO]
      ,main.dbo.client.[SCLIENTBANKACCTNO]
      ,main.dbo.client.[SQBID]
      ,main.dbo.client.[SQBDEBTORID]
      ,main.dbo.client.[BACTIVE]
      ,main.dbo.client.[NCONCURRENCYID]
      ,main.dbo.client.[NCREATEDBY]
      ,main.dbo.client.[DTCREATEDON]
      ,main.dbo.client.[NCHANGEDBY]
      ,main.dbo.client.[DTCHANGEDON]
      ,main.dbo.client.[SWORKSTATIONID]
      ,main.dbo.client.[NAPPLICATIONID]
      ,main.dbo.client.[NCLIENTCODEID]
      ,main.dbo.client.[NENTITYTYPEID]
      ,main.dbo.client.[NPLAINTIFFID]
      ,main.dbo.client.[SDBA]
      ,main.dbo.client.[SFRIENDLYNAME]
      ,main.dbo.client.[SSTINCORPORATEDIN]
      ,main.dbo.client.[BINVOICENSF]
      ,main.dbo.client.[NAUDITORLOGINID]
      ,main.dbo.client.[BALLOWNEGREMIT]
      ,main.dbo.client.[NCREDITORCLASSIFICATIONID]
      ,main.dbo.client.[BRECOVERCOSTSFIRST]
      ,main.dbo.client.[SCOUNTY]
 FROM main.[dbo].CLIENT
  join COGENT_FIRM_SPECIFIC.dbo.Client_Grouping on Client_Grouping.NCLIENTID = client.NCLIENTID
 where main.dbo.CLIENT.NCLIENTID is null

A: Thanks Aaron. I'm still not sure what caused the issue, but wrapping the INSERT INTO column list in () did the trick. Thanks again! Aaron, please submit as the answer and I'll accept it.


text:
Q: angular mulitiple ng-hide using same variable I'm stuck with something, that should  be quite ordinary. I'm about to write a factory to solve this problem, but was thinking, that there must be a clever way out of this.
I have a ng-repeat in my directive templateUrl:

{{item.$value}}

   <input ng-model="item.$value" ng-show="display">
   <button ng-show="display" ng-click="changeText(item)">finish</button>

My toggle function looks like this:
$scope.toggle = function (){
      $scope.display = !$scope.display;
    };

That means, when I click on one
 element, all input-fields are being displayed. Since they all are using the same variable. I can't wrap my head around making a proper angular solution to this problem, so that only the one within this item is being toggled. Does such a solution even exist?

A: One simple way to make it is to use item.display instead of display and pass item in toggle(). Something like this:

{{item.$value}}

    <input ng-model="item.$value" ng-show="item.display">
    <button ng-show="item.display" ng-click="changeText(item)">finish</button>

JS:
$scope.toggle = function (item) {
    item.display = !item.display;
};

A: Try this:

{{item.$value}}

     <input ng-model="item.$value" ng-show="item.display">
     <button ng-show="item.display" ng-click="changeText(item)">finish</button>

$scope.toggle = function (item){
  item.display = item.display || false;
  item.display = !item.display;
};

If you keep the "display" flag inside the item, you can toggle it for each one individually. If "item.display" is not defined, it will be treated as "false".
At least that's how I usually do it, there may be better solutions though.


text:
Q: Best way to determine the direction my UIPageViewController was swiped? I have set up a UIPageViewController that has five view controllers the user can swipe between in a loop.
I use these two methods two either increase or decrease an int variable called swipeTotal that I use to determine the index of an array so I can display for example 200 different strings from an array in order using five view controllers that loop.
-(UIViewController *)pageViewController:(UIPageViewController *)pageViewController
         viewControllerBeforeViewController:(UIViewController *)viewController {

    swipeTotal = swipeTotal - 1;
}

-(UIViewController *)pageViewController:(UIPageViewController *)pageViewController
          viewControllerAfterViewController:(UIViewController *)viewController
    {

    swipeTotal = swipeTotal + 1;
}

This seems to work to determine if the user swiped forwards or backwards, however these two methods seem to be called twice every time the swipe direction changes causing the swipeTotal to be out of sync for 1 swipe everytime the user changes direction.
I can't use this method because I want the swipeTotal int variable to increase if the user swiped forward and decrease if the swiped backward everytime and not be canceled out by the methods both occasionally being called.
So what is the best way to determine what direction the user has swiped so I can increase or decrease an int variable accordingly? I have tried to find a way but have had no luck, there must be a simple enough way to do this?
Any help would be greatly appreciated.

A: Use willTransitionTo to determine nextIndex and then assign real value at
didFinishAnimating
func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]){

                guard let viewController = pendingViewControllers.first else { return }
                guard let index = viewControllers.index(of: viewController) else { return }

                nextPage = index
            }
    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {

                if completed {

                   currentPage = nextPage

                }

            }


text:
Q: Is it possible to write "isa"/"match" function Is it possible to write "isa" or "match" function on Haskell without TH? It must get constructor and values and to match value with this constructor, but constructor can have multiple arguments. Example:
data X = X a b|Y {age::Int, name::String}
isa c v = ???
goal_of_exercise x y|iff all (isa X) x y = 1
                    |iff any (isa Y) x y = 2
  where iff agg c a b = agg c [a, b]

Or may be exists another solution of goal-of-exercise... ?

A: The function you're asking for is not just impossible to write - it's absolutely nonsensical in the context of Haskell.
In Haskell all (most of) your data types are indeed, as you've observed, tagged unions carrying type information in runtime. This allows pattern matching to work:
data D = A | B

whichD :: D -> String
whichD A = "it's an A"
whichD B = "it's a B"

This works for constructors of one particular type, though. The signature of whichD specifically says it takes a D, which can be constructed using one of its constructors. If you wanted to extend it to, say, take an analogous D', you could use a sum type for that:
data OneOf = OneD D | OneD' D'

Now, there are cases where this is not the case, namely parametrized contexts:
specialShow :: Show a => a -> String
specialShow a = "it's a special " ++ show a

So now, is it possible to change the behavior of specialShow for some particular as? Yes in principle, but not under that signature. Typically you'd introduce your own type class and provide specific instances for the types you want, and use generic code for all other types you want to bring in. This can pose some problems with overlapping instances, but that's solvable.

What if you insisted on doing the runtime check? I don't think that would even work in all cases, but possibly using some compiler intrinsics you'd be able to force it to tell you more about the actual value. I am pretty sure there's no standard Haskell way to do that, as it's essentially breaking the type system abstraction.


text:
Q: NLog with Autofac in MassTransit 6.0? My Consumers fail to instantiate from Autofac due to the following:

Cannot resolve parameter 'Microsoft.Extensions.Logging.Logger1[MyConsumer] logger' of constructor 'Void .ctor(MyService, Microsoft.Extensions.Logging.Logger1[MyConsumer])'.

The ILoggers resolve fine in every other class except the MassTransit Consumers; I believe it's an issue with LogContext.ConfigureCurrentLogContext(); and order of operations. Below is the code, edited for brevity:
ContainerBuilder builder = new ContainerBuilder(); // Autofac

builder.RegisterType<LoggerFactory>()
                         .As<ILoggerFactory>()
                         .SingleInstance();

builder.RegisterGeneric(typeof(Logger<>))
                         .As(typeof(ILogger<>))
                         .SingleInstance();

builder.RegisterAssemblyTypes() // load up all services, yada yada

// what to pass here? I'm inside an unbuilt Autofac Container at this point. There is no ILoggerFactory until the Container is built!
LogContext.ConfigureCurrentLogContext(); // configure MassTransit logging

builder.AddMassTransit(x =>
            {
                x.AddConsumers(Assembly.GetEntryAssembly());

                x.AddBus(bus => MassTransit.Bus.Factory.CreateUsingRabbitMq(config =>
                {
                    config.ConfigureEndpoints(bus); // wire-up consumers discovered by the AddConsumers() call above
                }));
            });

Container = builder.Build(); // now build the container

// add NLog
IServiceProvider serviceProvider = new AutofacServiceProvider(Container); // this requires a built Container!
ILoggerFactory loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
loggerFactory.AddNLog();

I should note that logging within MassTransit is actually working; I see all kind of debug output regarding the queues and messages. But the Consumer will not instantiate for whatever reason. If I try to manually Resolve<ILogger<MyConsumer>>() I'll get an ILogger but MassTransit seems to have trouble with it.
Edit: full error message via VS Output:

None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'MyConsumer' can be invoked with the available services and parameters:
  Cannot resolve parameter 'Microsoft.Extensions.Logging.Logger 1[MyConsumer] logger' of constructor 'Void .ctor(MyService, Microsoft.Extensions.Logging.Logger`1[MyConsumer])'.*

Package versions:

*

*Autofac.Extensions.DependencyInjection 5.0.1

*MassTransit 6.0

*MassTransit.Autofac 6.0

*NLog.Extensions.Logging 1.6.1

A:
Cannot resolve parameter Microsoft.Extensions.Logging.Logger 1[MyConsumer] logger

This error message means that Autofac can't find a registered Logger<MyConsumer>. If you look at your registration you register ILogger<> and not Logger<>. You should change the dependency to the interface version in MyConsumer and autofac will find it.


text:
Q: Postgresql 13 Change WAL segment size On my Ubuntu 20 server, I installed PostgreSQL 13 using the apt manager. I read some articles on performance tuning of PostgreSQL [1] and thought of increasing the WAL segment size (from default of 16MB). I see the following instruction, however, I don't know where to run this.
initdb -D ./data --wal-segment=1024
I guess the documentation refers to installing from PostgreSQL source code, which I don't intend to do. How do I go about change the WAL segment size?
[1] https://software.intel.com/content/dam/develop/external/us/en/documents/Open-Source-Database-Tuning-Guide-on-3rd-Generation-Intel-Xeon-Scalable-Processors.pdf

Following Daniel's answer, I did the following steps
$ pg_lsclusters
$ sudo pg_dropcluster --stop 13 main
$ sudo pg_createcluster 13 main -- --wal-segsize=256
$ sudo pg_ctlcluster 13 main start

You can verify the size of the WAL segments as
# du -hcs /var/lib/postgresql/13/main/pg_wal/*

A: If you want to change the WAL segment size of an existing cluster, you can use pg_resetwal.
Warning: for that, run pg_resetwal only on a cluster that has been shut down cleanly. Running pg_resetwal on a crashed cluster will cause potential data loss.
The command would look somewhat like this:
/usr/lib/postgresql/13/bin/pg_resetwal -D /var/lib/postgresql/13/main --wal-segsize 64

You may need to increase min_wal_size if you increase the WAL segment size.

A: Ubuntu/Debian packages for Postgres have their own layer on top of initdb and pg_ctl to control multiple instances and the integration with systemd.
The command that may be used to create an instance with specific options in Debian/Ubuntu is:
pg_createcluster [options] version name [-- initdb options]

use pg_lsclusters to see the list of already existing clusters. Possibly you want to drop the existing default cluster named main using the default segment size that you don't want, in order to have one single Postgres instance with the desired wal segment size.


text:
Q: How do you compile c++0x code using Eclipse? As I've decided to dive enthusiastically into the open-source world, I downloaded the Eclipse IDE for C/C++ Developers (Kepler Service Release 1) and installed minGW.
I created a new project using minGW as the toolchain, and I can create the hello world program using <iostream>, but if I try to create a tuple, smart pointer, or any other c++0x thingy I get a "symbol not found" error:
#include <tuple>
int main(int in)
{
    std::tuple<int> lameTuple; // symbol "tuple" could not be resolved
    return 0;
}

I tried adding -std=c++0x to the Other flags in the GCC C++ Compiler tool settings but this didn't seem to help. Any ideas?

A: I've run into this problem as well. Using Eclipse + Mingw GCC on windows is an incredibly.... egregious setup because of random issues like this. For example, I have one C++11 project in my workspace that requires no workarounds except for the std=c++11 or gnu flag, while others completely die regardless of this.
Unfortunately, the only answer is what I'd consider a hack. If you take a look in the Tuple header, you'll see:
#if __cplusplus < 201103L
# include <bits/c++0x_warning.h>
#else

So here the answer (solution) becomes evident. Somewhere, either a compiler flag or as a define in a .cpp file, you're going to want to define __cplusplus as greater than 201103L. How I did this was to go into

Project Properties->C/C++ General->Paths And Symbols

Then, under the "Symbols" tab, I added a new symbol. For the symbol name I used __cplusplus and for the value I used 201303L. This will force the indexer to re-run, at which time Eclipse will use the C++11 includes correctly.
On a side note, I think it's long over due for someone to create an Eclipse CDT + Mingw GCC installer which sets everything up properly. This issue is just scratching the surface of the incredible amount of issues you run into with this IDE and Toolchain, from bugged out versions of Mingw to poor indexing and parsing in the IDE. On that note always make sure that you're not using a buggy distribution of Mingw. This can also cause these issues.
Edit #1
Note also that you should include --std=X flag as a compiler flag under "miscellaneous", even when using this symbol. This symbol is just for the IDE to parse the headers with correct C++11 support.


text:
Q: Registering Nested Open Generic Types in Unity I am using Unity.   I am able to register normal open generic types.  But in this case the interface has the open generic nested one step inside.
Is there any way to register this kind of thing with Unity?
class DoSomethingCommandHandler<TModel> : ICommandHandler<DoSomethingCommand<TModel>>
{
    public void Handle(DoSomethingCommand<TModel> cmd)
    {
        var model = cmd.Model;
        //do thing with model
    }
}

class QuickTest
{
    static void Go()
    {
        var container = new UnityContainer();
        container.RegisterType(
            typeof(ICommandHandler<>).MakeGenericType(typeof(DoSomethingCommand<>)),
            typeof(DoSomethingCommandHandler<>));

        //This blows up:
        var res = container.Resolve<ICommandHandler<DoSomethingCommand<object>>>();
    }
}

A: Shot answer - it's impossible :)
I spent a couple of hours exploring this problem and didn't find a way to tell Unity how to do this.
You need implement another interface:
internal interface IDoSomethingCommandCommandHandler<out T> { }

class DoSomethingCommandHandler<TModel> : ICommandHandler<DoSomethingCommand<TModel>>, IDoSomethingCommandCommandHandler<TModel>

And register by this interface:
container.RegisterType(
    typeof(IDoSomethingCommandCommandHandler<>),
    typeof(DoSomethingCommandHandler<>));
var res = container.Resolve<IDoSomethingCommandCommandHandler<object>>();

Or explicitly register for every nested type:
var container = new UnityContainer();
container.RegisterType(
            typeof(ICommandHandler<>).MakeGenericType(typeof(DoSomethingCommand<object>)),
            typeof(DoSomethingCommandHandler<object>));
var res = container.Resolve<ICommandHandler<DoSomethingCommand<object>>>();


text:
Q: What was Euler's misconception about functions and infinite series? I just read this on Strichartz' The way of Analysis:

[...] Euler - the leading mathematician of the eighteenth - developed all techniques needed for the study of Fourier series, but he never carried out the project. On the contrary, he argued in print against the possibility of representing functions as Fourier series, when this proposal was put forth by Daniel Bernoulli, and his argument was based on fundamental  misconceptions concerning the nature of functions and infinite series.

What were these misconceptions?


text:
Q: Why do protocol_* methods do not work with Clang + modern GCC-Runtime on Linux? I tried to switch some of my Objective-C projects from GCC to Clang on Linux.
I used the GCC 4.6.2 runtime because the Clang compiler does not ship with one.
The compiling and linking works, but when using the protocol_* methods they do not work.
The following example works fine with GCC but not as expected with Clang:
#include <objc/runtime.h>
#include <stdio.h>

@protocol MyProtocol
+ aClassMethod;
- anInstanceMethod;
@end

void doIt(Protocol *p, SEL sel)
{
    printf("the protocol: %p\n", p);
    if (!p) return;
    printf("the protocol's name: %s\n", protocol_getName(p));
    struct objc_method_description d = protocol_getMethodDescription(p, sel, YES, YES);
    printf("required: YES instance: YES → %p\n", d.name);
    d = protocol_getMethodDescription(p, sel, YES, NO);
    printf("required: YES instance: NO → %p\n", d.name);
    d = protocol_getMethodDescription(p, sel, NO, YES);
    printf("required: NO instance: YES → %p\n", d.name);
    d = protocol_getMethodDescription(p, sel, NO, NO);
    printf("required: NO instance: NO → %p\n", d.name);
}

int main(int argc, char **argv)
{
    Protocol *p1 = @protocol(MyProtocol);
    printf("P1\n");
    printf("class method first:\n");
    doIt(p1, @selector(aClassMethod));
    printf("instance method follows:\n");
    doIt(p1, @selector(anInstanceMethod));

    Protocol *p2 = objc_getProtocol("MyProtocol");
    printf("P2\n");
    printf("class method first:\n");
    doIt(p2, @selector(aClassMethod));
    printf("instance method follows:\n");
    doIt(p2, @selector(anInstanceMethod));

    printf("done\n");
    return 0;
}

The expected output of the GCC compiled program:
P1
class method first:
the protocol: 0x804a06c
the protocol's name: MyProtocol
required: YES instance: YES → (nil)
required: YES instance: NO → 0x804b530
required: NO instance: YES → (nil)
required: NO instance: NO → (nil)
instance method follows:
the protocol: 0x804a06c
the protocol's name: MyProtocol
required: YES instance: YES → 0x804b528
required: YES instance: NO → (nil)
required: NO instance: YES → (nil)
required: NO instance: NO → (nil)
P2
class method first:
the protocol: 0x804a06c
the protocol's name: MyProtocol
required: YES instance: YES → (nil)
required: YES instance: NO → 0x804b530
required: NO instance: YES → (nil)
required: NO instance: NO → (nil)
instance method follows:
the protocol: 0x804a06c
the protocol's name: MyProtocol
required: YES instance: YES → 0x804b528
required: YES instance: NO → (nil)
required: NO instance: YES → (nil)
required: NO instance: NO → (nil)
done

The unexpected output of the Clang compiled program:
P1
class method first:
the protocol: 0x804a050
the protocol's name: (null)
required: YES instance: YES → (nil)
required: YES instance: NO → (nil)
required: NO instance: YES → (nil)
required: NO instance: NO → (nil)
instance method follows:
the protocol: 0x804a050
the protocol's name: (null)
required: YES instance: YES → (nil)
required: YES instance: NO → (nil)
required: NO instance: YES → (nil)
required: NO instance: NO → (nil)
P2
class method first:
the protocol: (nil)
instance method follows:
the protocol: (nil)
done

What's wrong here?
Is there some magical initialization code which will not be called when using Clang?
[Update]
When adding an implementation of the protocol like the following the objc_getProtocol() method works but the protocol_* methods still do not.
@interface MyInstance <MyProtocol>
@end

@implementation MyInstance

+ aClassMethod
{
    return nil;
}

- anInstanceMethod
{
    return nil;
}

@end

A: In my tests, GCC works well with its included GNU libobjc, but Clang works better with GNUstep libobjc2.
GCC 4.6 w/ included GNU libobjc: PASS

P1
class method first:
the protocol: 0x602120
the protocol's name: MyProtocol
required: YES instance: YES → (nil)
required: YES instance: NO → 0x10eda50
required: NO instance: YES → (nil)
required: NO instance: NO → (nil)
instance method follows:
the protocol: 0x602120
the protocol's name: MyProtocol
required: YES instance: YES → 0x10eda40
required: YES instance: NO → (nil)
required: NO instance: YES → (nil)
required: NO instance: NO → (nil)
P2
class method first:
the protocol: 0x602120
the protocol's name: MyProtocol
required: YES instance: YES → (nil)
required: YES instance: NO → 0x10eda50
required: NO instance: YES → (nil)
required: NO instance: NO → (nil)
instance method follows:
the protocol: 0x602120
the protocol's name: MyProtocol
required: YES instance: YES → 0x10eda40
required: YES instance: NO → (nil)
required: NO instance: YES → (nil)
required: NO instance: NO → (nil)
done

GCC 4.6 w/ libobjc2 1.6: FAIL

P1
class method first:
the protocol: 0x602120
the protocol's name: MyProtocol
required: YES instance: YES → (nil)
required: YES instance: NO → 0x6020a0
required: NO instance: YES → (nil)
required: NO instance: NO → (nil)
instance method follows:
the protocol: 0x602120
the protocol's name: MyProtocol
required: YES instance: YES → 0x6020b0
required: YES instance: NO → (nil)
required: NO instance: YES → (nil)
required: NO instance: NO → (nil)
P2
class method first:
the protocol: (nil)
instance method follows:
the protocol: (nil)
done

Clang 3.1 w/ GCC 4.6 GNU libobjc: FAIL

P1
class method first:
the protocol: 0x602080
the protocol's name: (null)
required: YES instance: YES → (nil)
required: YES instance: NO → (nil)
required: NO instance: YES → (nil)
required: NO instance: NO → (nil)
instance method follows:
the protocol: 0x602080
the protocol's name: (null)
required: YES instance: YES → (nil)
required: YES instance: NO → (nil)
required: NO instance: YES → (nil)
required: NO instance: NO → (nil)
P2
class method first:
the protocol: (nil)
instance method follows:
the protocol: (nil)
done

Clang 3.1 w/ libobjc2 1.6: PASS

P1
class method first:
the protocol: 0x602080
the protocol's name: MyProtocol
required: YES instance: YES → (nil)
required: YES instance: NO → (nil)
required: NO instance: YES → (nil)
required: NO instance: NO → (nil)
instance method follows:
the protocol: 0x602080
the protocol's name: MyProtocol
required: YES instance: YES → (nil)
required: YES instance: NO → (nil)
required: NO instance: YES → (nil)
required: NO instance: NO → (nil)
P2
class method first:
the protocol: 0x602080
the protocol's name: MyProtocol
required: YES instance: YES → (nil)
required: YES instance: NO → (nil)
required: NO instance: YES → (nil)
required: NO instance: NO → (nil)
instance method follows:
the protocol: 0x602080
the protocol's name: MyProtocol
required: YES instance: YES → (nil)
required: YES instance: NO → (nil)
required: NO instance: YES → (nil)
required: NO instance: NO → (nil)
done


text:
Q: StateFlow Observer is being triggered Two Times - Is this a good solution? Okay so I've been using StateFlow with Room database for a while. Now I have one common case. At the start of my app I have a logic that if ROOM database is empty I should show an EmptyContent(), otherwise I will show the ListContent() from ROOM database.
Now every time I launch the app, I'm always getting that EmptyContent() shown for a HALF a second maybe, and then the ListContent() is displayed. After that when I'm using the app everything works normal. But at that app launch time, while ROOM database is working I guess, that EmptyContent() is shown for just a small amount of period (Because my StateFlow default value is an empty list), and after that the actual LIST from Database is displayed.
Now I have one solution for that, to just use delay() function inside a Coroutine, to wait for example 200MS and then trigger the function for reading the DATABASE, because those 200MS are enough for ROOM database to actually get the value and update my STATE FLOW variable with the actual data instead of using that StateFlow default value for a half second at the beginning.
Is that a good solution, I must ask? Because I'm using coroutine, the thread is not blocked, and I'm just waiting until ROOM database updates my STATE FLOW variable the second time.
@Composable
fun displayContent(
    tasks: List<ToDoTask>,
    ListContent: @Composable () -> Unit
) {
    val scope = rememberCoroutineScope()
    var counter by remember { mutableStateOf(0)}
    LaunchedEffect(Unit){
        scope.launch {
            delay(200)
            counter = 1
        }
    }
    if(counter == 1){
        if (tasks.isNotEmpty()) {
            ListContent()
        } else {
            EmptyContent()
        }
    }
}

A: My suggestion would be map your expected states.
For instance:
sealed class RequestState<out T> {

    object Idle : RequestState<Nothing>()

    object Loading : RequestState<Nothing>()

    data class Success<T>(val data: T) : RequestState<T>()

    data class Error(
        val t: Throwable,
        var consumed: Boolean = false
    ) : RequestState<Nothing>()
}

And your function would be something like:
@Composable
fun YourScreen() {
   val requestState = viewModel.screenData.collectAsState()
   when (requestState) {
       is Idle ->
           // This is the default state, do nothing
       is Loading ->
           // Display some progress indicator
       is Success ->
           YourListScreen(requestState.data) // Show the list
       is Error ->
           // Display an error.
   }
   LaunchedEffect(Unit) {
      viewModel.loadData()
   }
}

Of course, in your view model you must emit these values properly...
class YourView: ViewModel() {
    private val _screenData =
        MutableStateFlow<RequestState<List<ToDoTask>>>(RequestState.Idle)
    val screenDatae: StateFlow<RequestState<List<ToDoTask>>> = _screenData

    fun loadData() {
       _screenData.value = Loading
       try {
           // load the data from database
           _screenData.value = Success(yourLoadedData)
       } catch (e: Exception) {
           _screenData.value = Error(e)
       }
    }
}


text:
Q: Why vector in C++ doesn't utilize move semantics when its capacity grows? Recently, when I am testing the implement of std::vector, I found that when the capacity of an vector grows, it uses copy construction to initialize the objects in the newly-allocated memory, rather than move construction.
In my point of view, when the capacity of an vector grows, the old objects in the old memory become useless. Therefore, I think they should be moved to the new memory, but not copied. If the objects are costly to copy but easy to move (e.g. std::string) , then the current implement of std::vector is rather slow!
Can somebody explain for me why vector in C++ doesn't utilize move semantics when its capacity grows? Thanks so much!
Here's my code for test. (Windows 64bit,-std=c++11)
// Testing the implement of C++ standard template library.
#include <iostream>
#include <vector>

// Custom object for test use.
struct object {
    void * ptr;
    size_t val;
    object() {std::cout << "Construction.\n";}
    object(object &&) {std::cout << "Move Construction.\n";}
    object(const object &) {std::cout << "Copy Construction.\n";}
    object &operator = (object &&) {
        std::cout << "Move Assignment.\n";
        return *this;
    }
    object &operator = (const object &) {
        std::cout << "Copy Assignment.\n";
        return *this;
    }
};

inline void printline() {std::cout << "----------------------\n";}

signed main() {
    std::vector <object> test(2); // size = capacity = 2
    printline();
    test.resize(3); // now the capacity must grow
    printline();
    return 0;
}

Output:
Construction.
Construction.
----------------------
Construction.
Copy Construction.
Copy Construction.
----------------------

What I think it should output:
Construction.
Construction.
----------------------
Construction.
Move Construction.
Move Construction.
----------------------


text:
Q: Powershell ErrorAction not silent I've got a PS script that looks for the Office15 folder on computers on our network. For the most part, the script works as intended. In fact, this is just me being picky. I set -ErrorAction SilentlyContinue, but the error messages when the Office15 folder is not found still appear on screen. I'm wondering if I'm doing something wrong or just don't really understand what my script is doing.
$filePath = "\\"+$computer+"\c$\Program Files (x86)\Microsoft Office\"
$listing = Get-ChildItem $filePath | where-object { $_.name -eq "Office15" } | Select-Object Name -ErrorAction SilentlyContinue

With this script as-is, I get errors like the following:
Get-ChildItem : Cannot find path '\\COMPNAME\c$\Program Files (x86)\Microsoft Office\' because it does not exist.
At C:\Users\someGuy\bootTime\checkOffice.ps1:16 char:20
+ $listing = Get-ChildItem $filePath | where-object { $_.name -eq "Office1 ...
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : ObjectNotFound: (\\COMPNAME\c$\Pr...crosoft Office\:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

I pump all of the valid results into a text file, so the other parts of the script work just fine, and I get the expected results otherwise. I'm only really interested in learning what I might be doing wrong here.

A: You need to pass the error action to gci:
$listing = Get-ChildItem $filePath -ErrorAction SilentlyContinue | where-object { $_.name -eq "Office15" } | Select-Object Name


text:
Q: Can I get the image and load via ajax into div I have the code below and what I need to do is load the image from the href into a div via ajax... Any help appreciated. I believe that load() can't load images like this?

Image 1

Image 2

Image 3

Image 4

Many thanks,
C

A: This would be the first thing I would try, I'm also a bit of a beginner as well though:
var image = $('');
image.attr('src', 'images/image1.jpg');
$('#image-holder').append(image);

A: You have to also remove the currently appended image. Here it is with a click event and Image instead of appending markup.
$('#list li a').click(function () {
    var url = $(this).attr('href'),
    image = new Image();
    image.src = url;
    image.onload = function () {
        $('#image-holder').empty().append(image);
    };
    image.onerror = function () {
        $('#image-holder').empty().html('That image is not available.');
    }

    $('#image-holder').empty().html('Loading...');

    return false;
});

A: Okay. Messy but it works perfectly. A few tweak like adding the images as background images. Here it is and I hope it helps someone else! Thanks so much everyone.

A: If you want to change image dynamically use dom
What you need to do is change the img src attribute
say img_div is your parent element then
var im = document.createElement('img');
im.src = 'image_path1';
img_div.appendChild(im);

on some event if you want to change this image
im.src = 'image_path2'


text:
Q: How to automatically update the IBM cognos Framework manager metadata? I am new to IBM Cognos, I have created a project using DB2 as a data source. When I added some extra rows to my table it's not reflecting into my project. Is there any way to automatically update the database data into Cognos Report studio.
Please tell me the solution.

A: If its rows you are adding to your Query subject, they will automatically update in your framework manager metadata. You can check it by using Test tab.


text:
Q: Can't Source vimrc file I am trying to learn vim right now and I was trying to source vimrc for the first time. After editing the file I used the command:
:so %

But I got the error:
Can't open file /c/Users/Name/.vimrc
I also tried using:
:so $HOME/.vimrc

But got the same error. How do I source my .vimrc file

A: have you saved the file before trying to source it(:w)?