text:
Q: For each country find product's category which were the most popular - subqueries The tables are given:
1) Categories: id, name
2) Countries: id, name
3) Producers: id, name, country_id
4) Products: id, name, price, category_id, producer_id
5) Customers: id, name, surname, age, country_id
6) Customer_orders: id, customer_id, product_id, quantity, discount, order_date

I want to find the most popular product's category for each country (most popular products category - products were produced by producers from specified country)
My current apporach:
select countries.name, categories.name, sum(cs.quantity) from countries
join producers on producers.country_id = countries.id
join products on products.producer_id = producers.id
join categories on categories.id = products.category_id
join customerorders as cs on cs.product_id = products.id
group by countries.name

That's not actually the good solution. Not sure how to do it, I suppose I should group all prodcts by country, and then for each country count the number of products for each product's category (products produced by producers from specified country) and finally find the category with most products bought.

A: You need to fix your group by and then use window functions:
select c.*
from (select co.name as country_name, c.name as category_name, sum(co.quantity) as total_qty,
             row_number() over (partition by co.name order by sum(co.quantity) desc) as seqnum
      from countries co join
           producers pr
           on pr.country_id = co.id join
           products p
           on p.producer_id = pr.id join
           categories c
           on c.id = p.category_id join
           customerorders co
           on co.product_id = p.id
      group by co.name, c.name
     ) c
where seqnum = 1;

This should work in MySQL 8+.  It is possible to express this in earlier versions but a bit of a pain.


text:
Q: Copying database tables to new database am trying to migrate my old site to a new site, by only copying database tables. the reason doing this way is the old site is out of date with plugins etc and i have WooCommerce installed which i dont have translated only post/pages are in 2 languages.
After iv copied over the tables when i went to pages/post it shows 0, yet WooCommerce shows all. iv ran through your WPML troubleshooting to fix any errors etc… this seems to work! but it now shows all pages but not under any lang!
How can i can copy this correctly ?

A: Export your tables using phpmyadmin interface. Just select those tables only that you want to export from the old database and import those tables in the new database
or you can run the command(query) in mysql to copy one table
create table newdbname.newtablename like olddbname.oldtablename;
INSERT INTO  newdbname.newtablename SELECT * FROM olddbname.oldtablename;

Repeat the same command to copy other tables

redpajama_set_name: RedPajamaStackExchange


text:
Q: Hosting CLR in native - COM interfaces, unresolved external symbol _CStdStubBuffer_Release@4 I'm experimenting with hosting CLR (not trying to use mono for now, though I will probably try). Basically, I'm following this:
http://www.lenholgate.com/blog/2010/07/clr-hosting---a-flexible-managed-plugin-system-part-1.html
However, I've got some troubles with COM itself, as it's not so thoroughly explained in that article, and I'm learning as I go (haven't been playing with COM before).
I've defined an interface:
import "unknwn.idl";
[
    object,
    uuid(55d96f88-9633-4ad7-b9de-1a546ea73307),
    helpstring("INative interface"),
    pointer_default(unique)
]
interface INative : IUnknown
{
    HRESULT Write(BSTR s);
}
[
   object,
   uuid(74eeeaaa-d73c-436e-b52d-5c8a972ce60a),
   helpstring("ITestManager Interface"),
   pointer_default(unique)
]
interface IManagedHost : IUnknown
{
    HRESULT Init(INative* native);
}

And included generated files in my native project. However, I can't build the executable, because linker cannot resolve: _CStdStubBuffer_Release@4. The RpcRT4.lib is linked, but I've run dumpbin rpcrt4.lib /all | grep _CStdStubBuffer_Release and there is nothing like that exported by that library, there is CStdStubBuffer_DebugServerRelease. So, question is what exactly references that method, if it supposedly should not exist?
Did some more investigation, and I've found out that this method is referenced via the .c file that is generated by IDL tool:
const CInterfaceStubVtbl _INativeStubVtbl =
{
    &IID_INative,
    &INative_ServerInfo,
    4,
    0, /* pure interpreted */
    CStdStubBuffer_METHODS
};

and CStdStubBuffer_METHODS are defined in RpcProxy.h of windows SDK v7.0A:
#define CStdStubBuffer_METHODS \
    CStdStubBuffer_QueryInterface,\
    CStdStubBuffer_AddRef, \
    CStdStubBuffer_Release, \
    CStdStubBuffer_Connect, \
    CStdStubBuffer_Disconnect, \
    CStdStubBuffer_Invoke, \
    CStdStubBuffer_IsIIDSupported, \
    CStdStubBuffer_CountRefs, \
    CStdStubBuffer_DebugServerQueryInterface, \
    CStdStubBuffer_DebugServerRelease

which indeed wants that CStdStubBuffer_Release method, though it's a bit different than: http://msdn.microsoft.com/en-us/library/windows/desktop/ms764247%28v=VS.85%29.aspx.
What other library should I link then?

A: CStdStubBuffer_Release() is implemented by another file that's auto-generated by midl.exe, dlldata.c.  The DLLDATA_ROUTINES macro generates it.
This problem is pointing to a project configuration mistake, sounds like you added the proxy .c file to your main project instead of using it in the proxy/stub project.  Which also consumes the dlldata.c.  I'm pretty sure there is no need for the proxy/stub in a custom CLR host, so simply remove the .c file.


text:
Q: Can not get the timepicker value using Angular.js and Jquery I need one help. I am implementing jquery.timepicker.js to get the time interval in my Angular application but i am not getting any value like that.I am explaining my code below.

      From Time :
      <input type="text" name="time" id="time" class="form-control oditek-form" placeholder="E.G-9.00AM" ng-model="time" ng-change="clearField('time');" maxlength="30" time-picker="" />

      To Time :
      <input type="text" name="time1" id="time1" class="form-control oditek-form" placeholder="E.G-9.00AM" ng-model="time1" ng-change="clearField('time1');" maxlength="30" time-picker="" />

    <input type="button" class="btn btn-success" ng-click="addTimeDetails();" id="saveData" value="Add" style="margin-right:20px;" />

my controller side code is given below.
var app=angular.module('spesh',[]);
app.controller('formController',function($scope,$http){
  $scope.addTimeDetails=function(){
    console.log('time',$scope.time,$scope.time1);
  }
})
app.directive('timePicker', [function () {
        return {
        restrict: 'A',
        require: 'ngModel',
        scope: {
            model: '=ngModel'
        },
        link: function ($scope, element, attrs, ngModelCtrl) {
            element.timepicker();
            element.on('changeTime', function () {
              $scope.$apply(function () {
                $scope.model = element.val();
              });
            });

        }
    }
}]);

Here i need when user will click on text field the time drop down will come and click on add button the selected time will show in console.MY complete code is here in plunkr.Please help me.

A: Change  to
Here is better solution: https://plnkr.co/edit/A0sSqXzx73XYn0f7UVGD?p=preview
When you require ngModel, you can use it's methods or read value. You don't need to read ngModel attribute.

$setViewValue(value, trigger); Update the view value.
This method should be called when a control wants to change the view
  value; typically, this is done from within a DOM event handler. For
  example, the input directive calls it when the value of the input
  changes and select calls it when an option is selected.


text:
Q: How do I write a MySQL LIKE clause using qmark syntax with the oursql Python library? I'm using the oursql Python library to talk to a MySQL database.  I want to write code to search for users by name or email address.  This is the code I have currently:
query = get_query()
cursor.execute("""
    SELECT *
      FROM users
     WHERE full_name LIKE '%?%'
        OR email LIKE '%?%';""", (query, query))

This code throws an exception:
ProgrammingError: 0 parameters expected, 2 given
Apparently the parser thinks the question mark is apart of the single-quoted string, and therefore isn't doing the substitution.  Any ideas on how to fix this?

A: The %'s in the argument to LIKE are part of the data you want to pass to the DB-API module's execute method, so they need to be part of the argument you pass for the placeholder, not part of the SQL query itself. For example:
query = '%%%s%%' % (get_query(),)
cursor.execute("""
    SELECT *
      FROM users
     WHERE full_name LIKE ?
        OR email LIKE ?;""", (query, query))

A: I think this would work, too:
query = get_query()
cursor.execute("""
    SELECT *
      FROM users
     WHERE full_name LIKE '%' || ? || '%'
        OR email LIKE '%' || ? || '%';""", (query, query))


text:
Q: Como reeordenar uma ViewBag, dentro da View? Estou tentando fazer com que uma ViewBag que recebeu uma lista na controladora, ser reordenada após a alteração em uma combobox sem que a página seja recarregada.
Passando a Lista para a ViewBag:
public ActionResult Answers(int id)
        {
            List<Respostas> Respostas = _Control.ViewRespostas(id);
            Respostas = Respostas.OrderBy(p => p.DataResposta).ToList();
            Pergunta aPergunta = _Control.SelecionarPergunta(id);
            Usuario oUsuario = _Control.SelecionarUsuario(aPergunta.Per_IDUsuario);
            ViewBag.Usuario = oUsuario.Usu_UserName;
            ViewBag.Quantidade = Respostas.Count();
            ViewBag.Respostas = Respostas;
            ViewBag.LDPergunta = _Control.ViewLikesDeslikesPergunta(id);
            return View(aPergunta);
        }

E na Página Answers estou usando essa ViewBag pra popular as respostas da Pergunta em Questão:
foreach (var x in ViewBag.Respostas)
                    {

@x.Usu_Name

@x.DataResposta

                                @x.QuantidadeLikes
                                @x.QuantidadeDeslikes

                                @Html.Raw(@x.Res_Message)

                    }

O resultado ficou o seguinte:

Agora quando o usuário alterasse o valor na combobox deveria reordenar essas respostas sem recarregar a página, consigo mandar uma requisição em ajax e estou recebendo a resposta com os objetos ordenados, mas não sei oque teria que fazer
para que esse foreach recarregue com as respostas ordenadas:
requisição em Ajax:
 $("#Filtro").change(function () {
                var Url = "@Url.Action("OrdenaRespostas", "Questions")";
                var Valor = $(this).val();
                $.post(Url, { id: @Model.Per_ID, Filtro: Valor }, AtualizaRespostas);
            });

Controladora que recebe a requisição:
   public ActionResult OrdenaRespostas(int id,string Filtro)
        {
            if(Filtro!="")
            {
                List<Respostas> Respostas = _Control.ViewRespostas(id);
                if(Filtro=="recentes")
                {
                    Respostas = Respostas.OrderBy(p => p.DataResposta).ToList();
                }

                else if(Filtro=="antigas")
                {
                    Respostas = Respostas.OrderByDescending(p => p.DataResposta).ToList();
                }

                else if(Filtro=="like")
                {
                    Respostas = Respostas.OrderBy(p => p.QuantidadeLikes).ToList();
                }

                else if(Filtro=="deslike")
                {
                    Respostas = Respostas.OrderBy(p => p.QuantidadeDeslikes).ToList();
                }
                return Json(Respostas);
            }
            return View("Index");
        }

Função que está recebendo a resposta:
function AtualizaRespostas(resposta) {
                $("@ViewBag.Respostas").html(resposta);
            }

esse parâmetro resposta está pegando a resposta em json da controladora, mas agr não sei oque fazer para que aquele foreach, seja reordenado...

A: Você deve limpar sua ComboBox e colocar os itens ordenados após isto
Limpar ComboBox
$("#IdDaSuaComboBox").empty();

Adicionar novos itens
$.each(resposta, function (i, obj) {
    $("#IdDaSuaComboBox").append('<option value="' + obj.Value + '">' + obj.Text + '</option>');
});

Você ira fazer isto na sua função AtualizaRespostas


text:
Q: Manejar error al deserializar un string a bigdecimal espero que anden muy bien.
¿Cuál seria la forma de poder manejar las siguientes dos excepciones?
Es decir, quiero que cuando se me presenten los siguientes dos errores poder responder con un mensaje personalidad, dado que actualmente solo recibo un 400 y el body vacío, en Postman.
Actualmente tengo un endpoint que recibe un body compuesto por dos propiedades, ambas del tipo BigDecimal. Cada uno tiene la validacion que acepte como maximo 3 digitos y 0 decimal, y cuando no se cumple cualquiera de esas dos condiciones, me devuelve el mensaje que le puse en @Digits.
La clase del request es el siguiente:
@Getter
@Setter
@Builder
public class OperationBodyRequest {

    @Digits(integer = 3, fraction = 0, message = "More than 3 digits and decimals are not accepted")
    private BigDecimal a;

    @Digits(integer = 3, fraction = 0, message = "More than 3 digits and decimals are not accepted")
    private BigDecimal b;
}

Es decir, estos casos andan bien
{
    "a": "211",
    "b": "21"
}

{
    "a": 211,
    "b": 21
}

Pero estos fallan
{
    "a": "211",
    "b": "21a"
}

{
    "a": 211,
    "b": 21a
}

Los logs que obtengo son,
Primer caso
JSON parse error: Cannot deserialize value of type `java.math.BigDecimal` from String "21a": not a valid representation; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.math.BigDecimal` from String "21a": not a valid representation
 at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream);
.m.m.a.ExceptionHandlerExceptionResolver : Using @ExceptionHandler o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Using 'application/octet-stream', given [*/*] and supported [*/*]
.m.m.a.ExceptionHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.math.BigDecimal` from String "21a": not a valid representation; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.math.BigDecimal` from String "21a": not a valid representation<EOL> at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 3, column: 10]

Segundo caso
JSON parse error: Unexpected character ('a' (code 97)): was expecting comma to separate Object entries; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('a' (code 97)): was expecting comma to separate Object entries
 at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 3, column: 13]
.m.m.a.ExceptionHandlerExceptionResolver : Using @ExceptionHandler AppErrorExceptionHandler#handleException(Exception, WebRequest)
o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Using 'application/octet-stream', given [*/*] and supported [*/*]
.m.m.a.ExceptionHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unexpected character ('a' (code 97)): was expecting comma to separate Object entries; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('a' (code 97)): was expecting comma to separate Object entries<EOL> at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 3, column: 13]]

Intente agregando
@Pattern(regexp = "[^0-9]", message = "Some error message")

Pero me dice que @Pattern pero no funciona.
También intente, donde tengo mi @RestControllerAdvice, manejar las dos excepciones que salen en los logs pero pareciera que no llega ahí. Con la excepción HttpMessageNotReadableException directamente no me inicia la aplicación.
@ExceptionHandler({InvalidFormatException.class, JsonParseException.class})
public final ResponseEntity<Object> handleOperationException() {

    return new ResponseEntity("Invalid exception", HttpStatus.BAD_REQUEST);
}

El controller tiene lo siguiente
public ResponseEntity<?> create(@Valid @RequestBody OperationBodyRequest operationBodyRequest,
                                BindingResult errors)

Agradeceria cualquiera ayuda.


text:
Q: Rails has many and belongs to between two times with same models I am wondering how to do something so If someone knows I will be glad to hear. I have the following models
User
Usertype
Course

I have two types of users - student and teacher.
What I want to have is two tables
CourseTeacher - course_id, teacher_id
CourseStudent - course_id, student_id

My User model has usertype_id column. So I am wondering how to use has_many_and_belongs_to in that case because everything depends on usertype_id column in User model.

A: I think class inheritance is a cleaner way to model your domain logic:
class User < ActiveRecord::Base
end

class Student < User
end

class Teacher < User
end

Then the table would have an id and type column, greatly simplifying what you're trying to accomplish. Read the API docs to learn more: Single Table Inheritance

A: If you don't have ability to refactor, you can try using this approach:
Instead of 2 tables create one:
class CoursesUsers
  belongs_to :course
  belongs_to :user
end

And the decide yourself logic inside the user model (It seems like polymorphic to me)


text:
Q: Better way to save array / objects in PHP Laravel MySQL What is the better practice for example I have a table of Posts and the post might contain many comments, is it better to create a Comments table and use a foreign ID or create a column of comments in the Posts table and save it as an array and cast it in the Model? It would be like an array of objects
[{"username":"user1","date":"25 February 2022 01:01PM","comment":"qwer"}]

    protected $casts = [
        'comments' => 'array',
    ];

A: depend on how you're gonna use the comments.
For example if you want to retrieve a post with only the count of the comments instead of their content, then you will need to put them in another table to make retrieving that info faster and effortless.
// for example
Post::withCount('comments')->get();

If every time you need a post, you also need its comments, then there is no reason to put them in another table. But you will be limiting yourself for future evolution without a heavy cost on performance because it would go against database normalization.

A: It's better to create a comments table and Comment Model with relation between your existing Post model and Comment model.
In case comment will only be attached to Post you can define a one to many relationship
Here is the definition of the Post Model
class Post extends Model
{
    /**
     * Get the comments for the blog post.
     */
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

And here is the definition of Comment
class Comment extends Model
{
    /**
     * Get the comments for the blog post.
     */
    public function post()
    {
        return $this->belongsTo(Post::class);
    }
}

with this you must have a foreign key on the comments table named post_id which reference the id in the posts table.
With this relationship established you can get all comment for a given post by simple calling $post->comments or access post from comment by calling $comment->post You can learn more here Eloquent: Relationship - One to Many


text:
Q: Twitter API 1.1, OAuth and PHP (for use in a Content Management System) for Many Websites and Relative Beginners At the moment we query a Twitter user's timeline using file_get_contents to get a JSON feed which we cache for a minute at a time and life was good. However, after some of our hundreds of sites started to break (when Twitter helpfully started removing the old XML urls), I noticed they were going to be changing to API 1.1 next year and we'd need to authenticate requests.
So, I'm basically looking for a simple pointer in the right direction. So far I assume the following:

*

*The new GET resource seems quite similar, bonus!

*Since we're only ever displaying that user's tweets, we're going to need only a  dev.twitter.com token

*It seems like we're going to need to create a new token on that user's account for every website we do.

*We probably have to install a library similar to twitteroauth as found https://dev.twitter.com/docs/auth/oauth/single-user-with-examples#php
As I say, we're simply displaying the user's tweets who owns the website we're building. People don't log in or post or anything like that.
I know there are embedded timelines, but these afford almost no customisation and I already hate Facebook's 'Like Box' for the same reason. (but I also know Twitter's 'Display Requirements' offer little to no flexibility other than probably colours...
So, taking that into account, is this the easiest way to do it? It seems relatively straight forward (I mean twitteroauth does the get request in 7 lines or less once set up), the biggest pain sounds like having to talk each user through getting an access key.
Thanks.

A: Twitteroauth is certainly going to give you a head start on this.  Remember though in the twitter documentation you are only allowed to do 180 timeline request in 15 minutes and if you go above that they will limit you for about an hour I think (it could be less). You should also read the bit about timelines if you want to be able to show every tweet you most not what the last ID you got was. Of course if you do all of this in realtime then your website will slow down as it makes the request to twitter.
I wouldn't use file_get_contents, mostly because it is slightly slower than curl and twitteroauth provides a much nicer interface IMO, less coding for you and it's forkable in git.
So, yes cache your results and keep an eye on how many requests you make within the 15 minutes allocated in 1.1. If you go over you will regret it for an hour, and that applies to every app using your key.
Hope that helps


text:
Q: Discord.net Problem with announcing new users joining I used C# and Discord.net to make my own Discord bot, but something doesn't work when announcing a new user.
When someone joins, it sends the message, and all is good, but right after, the bot crashes with the error
    System.NullReferenceException: 'Object reference not set to an instance of an object.'

at line
    var context = new SocketCommandContext(_client, message);

Any ideas as to why?
Here is the full code:
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using Microsoft.Extensions.DependencyInjection;
using System.Net.Sockets;
using System.Reflection;
using System.Threading;
using System.IO;
using Discord.Rest;

namespace DiscordBot2
{
    class Program
    {
        static void Main()
        {
            Thread t = new Thread(new ThreadStart(input));
            t.Start();
            new Program().RunBotAsync().GetAwaiter().GetResult();
        }

        private DiscordSocketClient _client;
        private CommandService _commands;
        private IServiceProvider _services;

        public async Task RunBotAsync()
        {
            _client = new DiscordSocketClient();
            _commands = new CommandService();

            _services = new ServiceCollection()
                .AddSingleton(_client)
                .AddSingleton(_commands)
                .BuildServiceProvider();

            string token = "lol you wish";
            _client.Log += _client_Log;

            await HandleNewUser();

            await RegisterCommandsAsync();

            await _client.LoginAsync(TokenType.Bot, token);

            await _client.StartAsync();

            await _client.SetGameAsync("with the flock!");

            await _client.SetStatusAsync(UserStatus.Online);

            await Task.Delay(-1);
        }

        private Task _client_Log(LogMessage arg)
        {
            Console.WriteLine(arg);
            return Task.CompletedTask;
        }

        public async Task RegisterCommandsAsync()
        {
            _client.MessageReceived += HandleCommandAsync; //Handle incoming commands
            await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services);
        }

        public async Task HandleNewUser()
        {
            _client.UserJoined += AnnounceJoinedUser;
            await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services);
        }

        public async Task AnnounceJoinedUser(SocketGuildUser user)
        {
            var channel = _client.GetChannel(743578569476931626) as SocketTextChannel; // Gets the channel to send the message in
            await channel.SendMessageAsync($"Welcome {user.Mention} to {channel.Guild.Name}"); //Welcomes the new user
            return;
        }

        private async Task HandleCommandAsync(SocketMessage arg)
        {
            var message = arg as SocketUserMessage;
            var context = new SocketCommandContext(_client, message);
            //Prevent looping
            if (message.Author.IsBot) return;

            //Check for prefix
            int argPos = 0;
            await BadWordsWarn(message);
            if (message.HasStringPrefix("c!", ref argPos))
            {
                //Execute command
                var result = await _commands.ExecuteAsync(context, argPos, _services);
                //If it failed, log the error
                if (!result.IsSuccess)
                {
                    Console.WriteLine(@"'" + message.Content + @"' has thrown an error: " + result.ErrorReason);
                    //Handle errors in commands
                    result = await _commands.ExecuteAsync(context, argPos, _services);
                    if (result.ErrorReason != null)
                        switch (result.ErrorReason)
                        {
                            //Not enough paramaters
                            case "The input text has too few parameters.":
                                await context.Channel.SendMessageAsync(
                                    "This command lacks parameters. Check the command description for more details.");
                                break;
                            //Bad command
                            case "Unknown command.":
                                await context.Channel.SendMessageAsync(
                                    "I don't understand this command. :frowning: You can type **c!list** to see the list of avaliable commands.");
                                break;
                            //Some other shenanigans
                            default:
                                await context.Channel.SendMessageAsync(
                                    $"{result.ErrorReason}");
                                break;
                        }
                }
            }
        }
        private async Task BadWordsWarn(SocketMessage message)
        {
            string[] badWords = File.ReadAllLines("Banned.txt");

            if (badWords.Any(word => message.Content.IndexOf(word, 0, message.Content.Length, StringComparison.OrdinalIgnoreCase) >= 0))
            {
                var m = (RestUserMessage)await message.Channel.GetMessageAsync(message.Id);
                await m.DeleteAsync();
            }
        }

A: I'm not sure where the variable input is coming from in Main(), but the way I start my bot is as follows:
static void Main() => new Program().RunBotAsync().GetAwaiter().GetResult();

You only need to call AddModulesAsync() once. You were calling it in RegisterCommandsAsync() and HandleNewUser(). Calling it more than once may cause problems, so I've moved it to the RunBotAsync() method and removed it from the other two methods. I've also moved the lines _client.MessageReceived += HandleCommandAsync; and _client.UserJoined += AnnounceJoinedUser; into theRunBotAsync() method as I was left with two separate methods each running a single line of code which only ever need to be called once, and I don't feel the extra methods are necessary for this. The RegisterCommandsAsync() and HandleNewUser() methods can be deleted.
public async Task RunBotAsync()
{
    _client = new DiscordSocketClient();
    _commands = new CommandService();

    _services = new ServiceCollection()
        .AddSingleton(_client)
        .AddSingleton(_commands)
        .BuildServiceProvider();

    await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services); // This should only be called once. You were calling it in RegisterCommandsAsync() and RegisterCommandsAsync()

    string token = "lol you wish";
    _client.Log += _client_Log;

    _client.UserJoined += AnnounceJoinedUser;

    _client.MessageReceived += HandleCommandAsync; //Handle incoming commands

    await _client.LoginAsync(TokenType.Bot, token);

    await _client.StartAsync();

    await _client.SetGameAsync("with the flock!");

    await _client.SetStatusAsync(UserStatus.Online);

    await Task.Delay(-1);
}

The line var message = arg as SocketUserMessage; in your HandleCommandAsync() method can result in null, which looks like the cause of your problem. To handle this I've replaced that line with if (arg is SocketUserMessage message) and wrapped all of your code inside it. This way you are checking for null before executing the rest of your code. Alternatively you could keep the original line and add if (message == null) return; underneath it.
You are also executing your commands with _commands.ExecuteAsync and then if they fail, you're executing them again before sending an error response to the Discord channel. If a command failed the first time, then chances are it's also going to fail the second time so I'm not sure why your're executing them again. I've commented the second line so it now only executes them once.
private async Task HandleCommandAsync(SocketMessage arg)
{
    if (arg is SocketUserMessage message)
    {
        var context = new SocketCommandContext(_client, message);
        //Prevent looping
        if (message.Author.IsBot) return;

        //Check for prefix
        int argPos = 0;
        await BadWordsWarn(message);
        if (message.HasStringPrefix("c!", ref argPos))
        {
            //Execute command
            var result = await _commands.ExecuteAsync(context, argPos, _services);
            //If it failed, log the error
            if (!result.IsSuccess)
            {
                Console.WriteLine(@"'" + message.Content + @"' has thrown an error: " + result.ErrorReason);
                //Handle errors in commands
                //result = await _commands.ExecuteAsync(context, argPos, _services); // Why are you executing the command again after it failed?
                if (result.ErrorReason != null)
                    switch (result.ErrorReason)
                    {
                        //Not enough paramaters
                        case "The input text has too few parameters.":
                            await context.Channel.SendMessageAsync(
                                "This command lacks parameters. Check the command description for more details.");
                            break;
                        //Bad command
                        case "Unknown command.":
                            await context.Channel.SendMessageAsync(
                                "I don't understand this command. :frowning: You can type **c!list** to see the list of avaliable commands.");
                            break;
                        //Some other shenanigans
                        default:
                            await context.Channel.SendMessageAsync(
                                $"{result.ErrorReason}");
                            break;
                    }
            }
        }
    }
}

This YouTube video helped me to get started with Discord.Net. Maybe it will help you too: https://www.youtube.com/watch?v=ccsf5Rcu9mM


text:
Q: Send a command to a process Using bash, is it possibile to send the equivalent of a space bar stroke to a process? If so, how can that be done?
Edit to clarify a bit what I want to achieve: let's say I've got an mplayer process running and I want to pause the execution of the current song, how would I achieve this?

A: You can direct standard I/O to it. If you are using Bash, then you probably have other GNU tools. GNU Coreutils has an echo command that can output pretty much anything. For example:
$ echo -n ' ' | some_command

However if you need an actual TTY (terminal) and you have more sophisticated requirements, look into expect, which can do nearly anything a human can (except think).

*

*Expect

*Perl expect

*Python expect

A: You can send a signal to a process using kill command. Try man kill for more info.


text:
Q: Custom Facebook feed - Like buttons I've written out a custom facebook feed that uses the PHP SDK initially to get the data and then loops through the feed and prints it all out. Works fine with no problems.
I now need to add a like button to each feed, so I've done the below:
Within PHP Foreach Loop:
$ids = explode('_', $value['id']);
$like_it = "https://www.facebook.com/". $ids[0] ."/posts/". $ids[1] ?>

...

<fb:like href="<?php echo $like_it; ?>" layout="button_count"
    show_faces="true" width="160" height="40"
    action="like" colorscheme="light"></fb:like>

I am loading the JS SDK asynchronously with correct App ID and XFBML enabled
js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=xxxxxxxxxxxxxxxx";

Now the like buttons display and do link to the news feed item they are assigned to as you would expect, though none of them pick up on the number of likes that are actually already attributed to the feed item. Strangely, one does... and I cant quite get my head round it.
Is there anything I am doing blatently wrong here?
Here is the page in question The like buttons have not been positioned properly yet as I'd rather get them working first!
Any help would be appreciated,
Cheers,
DB

A: I found out that this is not possible to do with Facebook any longer. There are other SO answers that go into detail on this topic and why this is not possible.


text:
Q: CSS seclect element by id containing query string I'm theming a website http://www.complementchic.com
so in my css, I've set css for the body to resize images at
http://www.complementchic.com/modules/vente_flash/flashSale.php
 #module-vente_flash-flashSale

but when I have the page switching language through
php post the url becomes:
http://www.complementchic.com/modules/vente_flash/flashSale.php?&id_lang=2
and as a result my body id in css is changing to
 #module-vente_flash-flashSale?&id_lang=2

and I'm unable to use this ID in my css stylesheet -
So, a) is there a way for me to use this ID in my stylesheet or fix this issue,

A: Try using CSS attribute selector:
HTML:
<body id="module-vente_flash-flashSale?&id_lang=2">
This is a text here
</body>

CSS:
body[id="module-vente_flash-flashSale?&id_lang=2"] {
  background-color: red; /* for example */
}

jsBin demo

A: you can use PHP explode function for this ex:
$idetails = explode("?&", 'flashSale?&id_lang=2');

$id=$idetails[0];

value of $id is flashSale


text:
Q: Distinguish between two VPC Endpoints calling my VPC Endpoint Service I have a VPC Endpoint Service exposing a MicroService deployed in a private VPC. There are multiple VPC Endpoints created in other AWS accounts and private VPCs that connect to my VPC Endpoint Service.
Is there a way to tell from with in the MicroSevice which VPC Endpoint called it?

A: You can use VPC flow log to check traffic flowing through your VPC or subnet level. These VPC flow logs while creating them has to be configured to be send logs to either S3 or CloudWatch logs.


text:
Q: Resizing large image dataset with dlib I have a large face dataset (10k training, 5k validation images) with an image size of 5184x3456 and two XML files describing the training and validations sets (in dlib format, see below). I would like to train a deep neural network on this dataset for face detection using dlib. With the current image size, the training takes too much memory and time. Therefore, I would like to rescale the whole dataset.
Rescaling the images are easily achieved by using ImageMagick convert; however, of course I also need to change the pixel coordinates of the ground truth face boxes in my training and validation XML files appropriately so that the face boxes still fall on faces on the new, rescaled images. Those files have the following structure:
<image file="00056475158675a7f26160c17b6643bb.jpg">
  <box width="294" top="1245" height="354" left="753"/>
  <box width="210" top="639" height="366" left="309"/>
  <box width="222" top="9" height="228" left="4365"/>
</image>
<image file="0013609d9d3189887f659e1c0354ac3d.jpg">
  <box width="282" top="1029" height="402" left="225"/>
</image>

Is there a way to quickly rescale the box attributes (width, height, top, left) using dlib, or perhaps imglab? Thanks.


text:
Q: Xamarin bug happens when linker is set to "Link All". Can't use DependencyService Right now, I have to have my linker set to "Link All" in order to submit to the App Store because of the deprecated UIWebView. While doing this, I had to add [Preserve(AllMembers = true)] to my DataStores to make them work this way, but then I ran into this issue.
The following line will return null:
var dp = DependencyService.Get<ITextMeter>();

After looking into the solution, it seemed the best answer would be to add the following line into the AppDelegate:
DependencyService.Register<ITextMeter, TextMeterImplementation>();

Once I did that, I started receiving this exception:
DependencyService: System.MissingMethodException: Default constructor not found for [Interface]
https://forums.xamarin.com/discussion/71072/dependencyservice-system-missingmethodexception-default-constructor-not-found-for-interface
I just want to find a working solution that will allow everything to work with the linker set to "Link All". Thanks in advance.
ITextMeter:
using System;
using Xamarin.Forms.Internals;

namespace RedSwipe.Services
{
    public interface ITextMeter
    {
        double MeasureTextSize(string text, double width, double fontSize, string fontName = null);
    }
}

TextMeterImplementation:
using System.Drawing;
using Foundation;
using RedSwipe.iOS.Services;
using RedSwipe.Services;
using UIKit;

[assembly: Xamarin.Forms.Dependency(typeof(TextMeterImplementation))]
namespace RedSwipe.iOS.Services
{
    public class TextMeterImplementation : ITextMeter
    {

        public double MeasureTextSize(string text, double width, double fontSize, string fontName = null)
        {
            var nsText = new NSString(text);
            var boundSize = new SizeF((float)width, float.MaxValue);
            var options = NSStringDrawingOptions.UsesFontLeading | NSStringDrawingOptions.UsesLineFragmentOrigin;

            if (fontName == null)
            {
                fontName = "HelveticaNeue";
            }

            var attributes = new UIStringAttributes
            {
                Font = UIFont.FromName(fontName, (float)fontSize)
            };

            var sizeF = nsText.GetBoundingRect(boundSize, options, attributes, null).Size;

            //return new Xamarin.Forms.Size((double)sizeF.Width, (double)sizeF.Height);
            return (double)sizeF.Height;
        }

    }
}

A: Add this [Preserve (AllMembers = true)] in your TextMeterImplementation before class implementation.
Your code would be like:
using System.Drawing;
using Foundation;
using RedSwipe.iOS.Services;
using RedSwipe.Services;
using UIKit;
using Xamarin.Forms.Internals; // Add This import

[assembly: Xamarin.Forms.Dependency(typeof(TextMeterImplementation))]
namespace RedSwipe.iOS.Services
{
    [Preserve (AllMembers = true)]
    public class TextMeterImplementation : ITextMeter
    {

        public double MeasureTextSize(string text, double width, double fontSize, string fontName = null)
        {
            var nsText = new NSString(text);
            var boundSize = new SizeF((float)width, float.MaxValue);
            var options = NSStringDrawingOptions.UsesFontLeading | NSStringDrawingOptions.UsesLineFragmentOrigin;

            if (fontName == null)
            {
                fontName = "HelveticaNeue";
            }

            var attributes = new UIStringAttributes
            {
                Font = UIFont.FromName(fontName, (float)fontSize)
            };

            var sizeF = nsText.GetBoundingRect(boundSize, options, attributes, null).Size;

            //return new Xamarin.Forms.Size((double)sizeF.Width, (double)sizeF.Height);
            return (double)sizeF.Height;
        }

    }
}


text:
Q: IBM WESB/WAS JCA security configuration I'm working with IBM tools. I have a Websphere ESB (WESB) and a CICS transaction gateway (CTG). The basic set-up is as follows:
A SOAP service needs data from CICS. The SOAP-service is connecting to service bus (WESB) to handle data and protocol transformation and then WESB calls the CTG which in turn calls CICS and the reply is handled vice verse (synchronously). WESB calls the CTG using Resource Adapter and JCA connector (or CICS adapter as it is called in WESB). Now, I have all the pieces in place and working.
My question is about the security, and even though I'm working with WESB, the answer is probably the same as in Websphere Application Server (WAS). The Resource Adaper is secured using JAAS - J2C authentication data. I have configured the security using J2C authentication data entry, so basically I have a reference in the application I'm running and at runtime the application does a lookup for the security attributes from the server. So basically I'm always accessing the CICS adapter with the same security reference.

My problem is that I need to access the resource in more dynamic way
  in the future. The security cannot be welded into the application
  anymore but instead given as a parameter.

Could some WESB or WAS guru help me out, how this could be done in WESB/WAS exactly?

A: Can you elaborate a bit further? I don't work with CTG but I believe it is no different from other resources such as JDBC or JMS resource.
On the CTG resource adapter, you have identified credentials that are used for all calls to the CICS.
This is similar to what we do when we work with a Data Source and this approach is agreeable to most people.
I do not see how the J2C credential is welded to the application. The configuration is done @ WAS/WESB. The application would simply work with the JNDI resources on the server to which the J2C aliases are configured.
If you elaborate on the dynamic requirement folks can help out.
HTH
Manglu


text:
Q: classic asp use capicom for md5 hashing - result differs from .net System.Security.Cryptography When using CAPICOM in Classic ASP (VBScript) to perform MD5 hashing like so:
With server.CreateObject("CAPICOM.HashedData")
    .Algorithm = 3                  ' CAPICOM_HASH_ALGORITHM_MD5
    .Hash "password"

    md5Pwd = .Value
End With

I get this result: B081DBE85E1EC3FFC3D4E7D0227400CD
When I use .NET, I get this result: 5f4dcc3b5aa765d61d8327deb882cf99
Why are the MD5 strings different? What am I doing wrong?
Here is my C# function:
MD5 md5Hasher = MD5.Create();
byte[] data = md5Hasher.ComputeHash( Encoding.Default.GetBytes( val ) );

StringBuilder sBuilder = new StringBuilder();

// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for( int i = 0; i < data.Length; i++ ) {
    sBuilder.Append( data[i].ToString( "x2" ) );
}

// Return the hexadecimal string.
return sBuilder.ToString();

A: The problem is that you are using Encoding.Default encoding which represents 7 bit ASCII characters. At the same time, "CAPICOM manipulates only Unicode strings while validating and generating digital signatures".
So, Encoding.Default.GetBytes deals with one-byte characters (losing any non-ASCII data by the way), while CAPICOM.HashedData treats them as 2-byte Unicode characters.
Replace Encoding.Default with Encoding.Unicode to make your .NET implementation to be compatible with CAPICOM.
One more note, use data[i].ToString("X2") to produce upper-case result, as you have in CAPICOM implementation.


text:
Q: Lookup table or similar within the Arduino IDE? Good day,
I am receiving userIds as integer on an ESP32, I would like to convert them to the corresponding name. Currently I solve this with the switch statement as shown below. Is there a more elegant solution?
   String ReturnName(int userId) {
      Switch(userId) {
      case 20:
        {
          return "John";
        }
        break;
      case 44:
        {
          return "Maria";
        }
        break;
      case 4:
        {
          return "Herrensen";
        }
        break;
      }
    }

A: First of all having a break after a return doesn't make sense. Remove them.
  Switch(userId) {
  case 4:  return "Herrensen";
  case 20: return "John";
  case 44: return "Maria";
  }

Isn't to bad imho.
Alternatively you could use an array.
const char* lut[45];
lut[20] = "John";
lut[44] = "Maria";
lut[4] = "Herrensen";

But this is not very memory efficient if you don't have consecutive user ids. At the moment you have reserved memory for 45 pointers but only used 3 so most of the memory is wasted. and you have to make sure that you only index valid elements within the array.
You could use a hash table but that is usually not a good idea on Arduino due to limited memory.

A: For an ESP32 target, you might consider a std::map
#include <map>
std::map<byte, const char*> list;

void setup() {
  list[4] = "Anna";
  list[20]= "John";
  Serial.begin(115200);

  for (auto const & n : list) {
    Serial.print(n.first); Serial.print(":"); Serial.println(n.second);
  }
}

An ESP is not as restricted in RAM and c++ stdlib as a real Arduino


text:
Q: add country id from json to dorling map I am working with this map where I am trying to get the id numbers from the world-110m.json file to be displayed in the circles of the dorling map. The structure of the json file looks like this:
{
"type": "Topology",
"transform": {
    "scale": [0.0036000360003600037, 0.0016925586033320111],
    "translate": [ - 180, - 85.60903777459777]
},
"objects": {
    "land": {
        "type": "MultiPolygon",
        "arcs": [[[0]], [[1]], [[2]], [[3]], [[4]], [[5]], [[6]], [[7, 8, 9]], [[10, 11]], [[12]], [[13]], [[14]], [[15]], [[16]], [[17]], [[18]], [[19]], [[20]], [[21]], [[22]], [[23]], [[24]], [[25]], [[26]], [[27]], [[28]], [[29, 30]], [[31]], [[32]], [[33]], [[34]], [[35]], [[36]], [[37]], [[38]], [[39]], [[40]], [[41]], [[42, 43]], [[44]], [[45]], [[46]], [[47, 48, 49, 50]], [[51]], [[52]], [[53]], [[54]], [[55]], [[56]], [[57]], [[58]], [[59]], [[60]], [[61]], [[62, 63]], [[64]], [[65]], [[66]], [[67]], [[68]], [[69]], [[70]], [[71]], [[72]], [[73]], [[74]], [[75]], [[76, 77]], [[78]], [[79]], [[80]], [[81]], [[82]], [[83]], [[84]], [[85]], [[86]], [[87]], [[88]], [[89]], [[90, 91]], [[92]], [[93]], [[94]], [[95]], [[96]], [[97]], [[98]], [[99]], [[100]], [[101]], [[102]], [[103]], [[104]], [[105]], [[106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221]], [[222, 223]], [[224]], [[225]], [[226]], [[227]], [[228]], [[229]], [[230, 231, 232, 233]], [[234]], [[235]], [[236]], [[237]], [[238]], [[239]], [[240]], [[241]], [[242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 460, 461, 462, 463, 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477], [478, 479, 480, 481, 482, 483, 484]], [[485]], [[486]], [[487]], [[488]], [[489]], [[490]], [[491]], [[492]], [[493]], [[494]], [[495]], [[496]], [[497]], [[498]]]
    },
    "countries": {
        "type": "GeometryCollection",
        "geometries": [{
            "type": "Polygon",
            "arcs": [[499, 500, 501, 502, 503, 504]],
            "id": 4
        }, {
            "type": "MultiPolygon",
            "arcs": [[[505, 506, 352, 507]], [[354, 508, 509]]],
            "id": 24
        }, {
            "type": "Polygon",
            "arcs": [[510, 511, 414, 512, 513, 514]],
            "id": 8
        }, {
            "type": "Polygon",
            "arcs": [[312, 515, 314, 516, 517]],
            "id": 784
        }, {
            "type": "MultiPolygon",
            "arcs": [[[518, 11]], [[519, 520, 521, 166, 522, 168, 523, 524]]],
            "id": 32
        }, {
            "type": "Polygon",
            "arcs": [[525, 526, 527, 528, 529]],
            "id": 51
        }, {
            "type": "MultiPolygon",
            "arcs": [[[0]], [[1]], [[2]], [[3]], [[4]], [[5]], [[6]], [[530, 531]]],
            "id": 10
        }, {
            "type": "Polygon",
            "arcs": [[13]],
            "id": 260
        }, {
            "type": "MultiPolygon",
            "arcs": [[[14]], [[24]]],
            "id": 36
        }, {
            "type": "Polygon",
            "arcs": [[532, 533, 534, 535, 536, 537, 538]],
            "id": 40
        }, etc.

I know that I can access the id like that:
var nbr = "unknown";
    try {
        nbr = land.geometries[parseInt(d.id)-1].parent.id;
    } catch(e) {
        console.log("no nbr found for "+d.id);
    }

And then return it with all the other variables taken from the world-110m.jsonfile:
return {
  nbr:nbr,
  x: centroid[0],
  y: centroid[1],
  ox: centroid[0],
  oy: centroid[1],
  geometry: d.geometry,
  dorling: dorling(d.geometry)
};

But now I don't understand how I can access this variable and draw it into the circles of the dorling map (preferably, only when the circles have a big enough size to "carry" the id number). I have seen this question and this post about how to add country names to a d3 map, but I don't understand how to do this with the map I'm working with. Everything I have tried so far did not work. Could anyone please help me with this? I have added the html file with my additions to this pen. I am sorry it doesn't display anything (I didn't know how to add the required json files to the pen; I simply downloaded them from the source of the map I'm working with and ran everything locally).

A: Duh, silly me, I forgot to add a svg text element. The below code did it:
svg.selectAll("text")
  .data(nodes).enter()
  .append("text")
  .attr("x", function (d) { return d.x; })
  .attr("y", function (d) { return d.y; })
  .text(function (d) { return d.nbr; });

The display doesn't look very nice yet, though, but that's going to be another problem...


text:
Q: Simple explanation for number of solutions of system of linear equations So a system of linear equations can be represented as:
$$Ax=d$$
where
$A$ is a $n\times n$ matrix and
$x$ and $d$ are $ n\times 1$ vectors.
Now in my notes it says the number of solutions are either:
$$0, 1 \text{ or } \infty$$
I understand if $\det(A) \neq 0$ then there is a unique one-to-one solution but could someone explain simply the other two cases in a easily understandable fashion?
Thank you.

A: 0:
For simplicity let's assume 2x2 matrix. Assume that after multiplication you get system of equations:
$x_1 + x_2 = 5$
$x_1 + x_2 = 10$
infinity:
Assume that after multiplication you get system of equations:
$x_1 + x_2 = 5$
$2x_1 + 2x_2 = 10$

To extend this on any $n$ x $n$ matrix:

*

*if the determinant of the non-homogeneous is zero, then

*

*the system has infinite number of solution if it is not conflicted

*the system has $0$ solutions if it is conflicted

*if the determinant of the non-homogeneous is different from zero, then the system has unique solution

A: The statement remains true even when $A$ is a matrix with different numbers of rows and columns.  Say that $A$ has $m$ rows and $n$ columns.  This corresponds to a system of $m$ equations in $n$ variables.
If $n=2$ then all of the equations represent lines.  If all $m$ lines cross in a single point, then there's a unique solution.   If all $m$ equations represent the same line, then every point on that line is a solution to the system, so there are infinitely many solutions.  If there is no point common to all $m$ lines, then there is no solution.
Could there be any other cases?  Could there, for example, be $2$ solutions?  If there were two equations, this would correspond to a pair of lines that intersect twice, but not infinitely many times, a clear impossibility.  In the case of $m$ lines, all $m$ of the lines would have to pass through the same $2$ points, but couldn't all be the same line.  Again, this is geometrically impossible.
If $n=3$, the equations represent planes.  It becomes harder to visualize all cases.  If all of the planes have a point in common, then there is a unique solution.  Two non-parallel planes will intersect in a line.  A third plane not parallel to that line will cross the line in a unique point—the unique solution.  One can think of many configurations where a set of planes have no point common to all planes—the no solution case.  There are essentially two ways to have infinitely many solutions: (1) have all of the equations represent the same plane, so that all points on that plane are solutions; (2) have all of the planes intersect in a common line, so that all points on that line are solutions.  In case (1), we have a $2$-parameter family of solutions; in case (2), we have a $1$-parameter family of solutions.  You can think about why, geometrically, it is impossible for a set of plane to have some other number of points in common.
Geometry, of course, only takes you so far.  The better way to understand why there are $0,$ $1,$ or infinitely many solutions is to understand row-reduction thoroughly.  If an inconsistency arises in the process of row-reduction, then there are no solutions; otherwise there are $1$ or infinitely many solutions.  Which one it is depends on whether there remain any undetermined parameters after row-reduction is complete.


text:
Q: How can I change default list style? \documentclass{article}
\begin{document}
\begin{itemize}
\item Item 1
\item Item 2
\end{itemize}
\end{document}

This generates list like:
• Item 1
• Item 2
Changing article to mwrep generates:
— Item 1
— Item 2
I want to use mwrep but witharticle list style.

A: Redefine \labelitemi locally (inside itemize) or globally in your document preamble:

\documentclass{article}
\begin{document}
\begin{itemize}
  \let\labelitemi\labelitemii
  \item Item 1
  \item Item 2
\end{itemize}
\begin{itemize}
  \item Item 3
  \item Item 4
\end{itemize}
\end{document}

Using \renewcommand{\labelitemi}{\normalfont\bfseries\textendash} would also work.
Defaults lists in LaTeX are managed as \lists, where each item is either numbered (in enumerate) or bulleted (in itemize). These item constructions are based on the following definitions:
% Labels for items in (nested) enumerate (uses counters)
\newcommand\labelenumi{\theenumi.}% Default is arabic: 1.
\newcommand\labelenumii{(\theenumii)}% Default is alph: (a)
\newcommand\labelenumiii{\theenumiii.}% Default is roman: i.
\newcommand\labelenumiv{\theenumiv.}% Default is Alph: A.
% Labels for items in (nested) itemize (uses bullets/characters)
\newcommand\labelitemi{\textbullet}% bullet
\newcommand\labelitemii{\normalfont\bfseries \textendash}% --
\newcommand\labelitemiii{\textasteriskcentered}% *
\newcommand\labelitemiv{\textperiodcentered}% .

Note that there are four definitions for each list environment, corresponding to the (maximum) four levels of nested lists (this is for the standard document classes article, book and report). Redefining any of these modifies the list item representation at that level.
mwrep uses a similar definition for enumerate, but the following for itemize:
\newcommand\labelitemi{\textemdash}
\newcommand\labelitemii{\textemdash}
\newcommand\labelitemiii{\textemdash}
\newcommand\labelitemiv{\textemdash}

enumitem allows to extend this in a more general way and also to have more levels if needed.

A: I think the enumitem package could be helpful here:
\documentclass{mwrep}
\usepackage{enumitem}
\begin{document}
\begin{itemize}[label=\textbullet]
 \item Item 1
 \item Item 2
\end{itemize}
\end{document}

If you'd like to make the change globally, you can use the \setlist feature provided by enumitem
\documentclass{mwrep}
\usepackage{enumitem}

\setlist[itemize]{label=\textbullet}
\begin{document}
\begin{itemize}
 \item Item 1
 \item Item 2
\end{itemize}
\end{document}


text:
Q: How do you flush the contents of `std::cin` before an additional read from it? I am trying to read a single character multiple times. The catch is that I need to prevent user errors. So for example:
char arr[10];
for(int i = 0; i < 10; i++)
{
    cin.get(arr[i]);
}

Where the inputs should be something like a, b, c, d, .... But if someone were to enter ab for the first entry I want to capture the a and then ignore the b. I know about cin.ignore however I don't know how I would go about ignoring an arbitrary number of alphanumeric characters or symbols considering that I want to ignore a potentially unlimited number of characters and then stop ignoring and read again.
How can I either ignore an arbitrary number of characters and then stop ignoring or how can I actually flush the buffer for cin.

A: Most input is line feed so if you want to ignore all characters in the input stream until you hit a newline then you could use:
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')

Since we ignore up to the streamsize there should not be an extra content in the input buffer.

A: If you want user to hit enter after each symbol, then code could be as simple as this:
char arr[10];
for(int i = 0; i < 10; )
{
    std::string line;
    std::getline( std::cin, line );
    // check that line is not empty
    if( line.empty() ) {
         std::cout << "missing input" << std::endl;
         continue;
    }
    arr[i++] = line[0]; // get only first symbol and ignore the rest
}

if you have something else in mind, I am afraid that will not work with std::cin - you do not see any input until user presses enter. In that case you would have to use OS specific functions to get unbuffered input.

A: The following is the code that you want, if your inputing like this a 'enter' b 'enter' c 'enter' etc...
#include <iostream>
#include <string>

using namespace std;

int main() {

    char arr[10];
    string line;

    for (int i = 0; i < 10; i++)
    {
        getline(cin, line);
        arr[i] = line[0];

        cout << endl << "Here is the Char: " << arr[i] << endl;
    }

    return 0;
}

BUT if you enter input like this in one line: a,b,c,d,e,f,g,h,i,j 'enter' then you want the following code:
#include <iostream>
#include <string>

using namespace std;

int main() {

    char arr[10];
    string line;
    int i = 0;
    size_t  end;

        getline(cin, line);

        end = 0;
        int counter = 0;

            if (line != "") {

                while (end != string::npos && counter < 10) {

                    if (counter == 0) {
                        arr[counter] = line[0];
                    }
                    else {
                        end = line.find(",", end + 1);
                        arr[counter] = line[end + 1];
                    }

                    counter++;

                }
            }

            for (int i = 0; i < 10; i++) {
            cout << endl << "Here is the Char: " << arr[i] << endl;
        }

    return 0;
    }


text:
Q: How do I retrive a certificate and view it's subject in Ruby 1.9.3 with OpenSSL In Bash I'd just:
$ openssl s_client -connect www.example.com:443 </dev/null 2>/dev/null | grep 'subject'

But I want to do it elegantly in ruby.
Thanks,

A: You can accomplish what you are trying to do with the built-in OpenSSL Ruby module.
Specifically you can use the SSLSocket class to retrieve the certificate as a X509:Certificate object, which has an accessor for subject.
The example code found here is very close to what you are trying to do.


text:
Q: Setting up Github Pages My question is about how to create git pages when there is no "launch automatic page generator" in my GitHub account. I tried adding index.html file to master branch. how do i add a theme for that page and it does not displays in the page form instead it just shows the code

A: First step is to create new repository for your github page.
Core feature is a name of github page.
To make your github page works you need to name it like this:
your_project_name.github.io
Start file of your github page will be index.html.
Create a new repository

Upoad index.html to your repository.

Code of index.html file:
<html>
<head>
<title>hello github!</title>
</head>
<body>
hello github!
</body>
</html>

Result:

https://github.com/fonjeekay/fonjeekay.github.io
https://fonjeekay.github.io/
After operations you need to wait some time to make your github.io page added to the github.io server.


text:
Q: How can we generate multiple output file in benthos? Input Data:
{ "name": "Coffee", "price": "$1.00" }
{ "name": "Tea", "price": "$2.00" }
{ "name": "Coke", "price": "$3.00" }
{ "name": "Water", "price": "$4.00" }

extension.yaml
input:
  label: ""
  file:
    paths: [./input/*]
    codec: lines
    max_buffer: 1000000
    delete_on_finish: false
pipeline:
  processors:
    - bloblang: |
        root.name = this.name.uppercase()
        root.price = this.price
output:
  file:
    path: "result/file1.log"
    codec: lines

I want to create an output file based on the input and defined processor for our need.

A: extension.yaml
input:
  label: ""
  file:
    paths: [./input/*]
    codec: lines
    max_buffer: 1000000
    delete_on_finish: false
pipeline:
  processors:
    - bloblang: |
        root.name = this.name.uppercase()
        root.price = this.price
output:
  broker:
    pattern: fan_out
    outputs:
    - file:
        path: "result/file1.log"
        codec: lines
    - file:
        path: "result/file2.log"
        codec: lines
      processors:
        - bloblang: |
            root.name = this.name.lowercase()

It will generate two output files "file1.log" & file2.log".
file1.log
{"name":"COFFEE","price":"$1.00"}
{"name":"TEA","price":"$2.00"}
{"name":"COKE","price":"$3.00"}
{"name":"WATER","price":"$4.00"}

file2.log
{"name":"coffee"}
{"name":"tea"}
{"name":"coke"}
{"name":"water"}

Here we can use something called 'Broker' in Benthos as shown in the above example.
It allows you to route messages to multiple child outputs using a range of brokering patterns.
You can refer to this link for more information: Broker


text:
Q: Excel Lookup with multiple criteria with greter than date I am working on a process where I have data in two tables. First table consist of material no. and the date of delivery for these materials. The second table consist of materials and the document validity in which they are valid. There are multiple contracts with the date of validity. I have to get the document no. in the first table but when I select vlookup it will show simply if it is true or false and will not check the next valid document no. for the material.
The requirement is that I want valid document no. for the materials. The validity depends on the delivery date in Table 1 and Table 2 consist of document details. At the end I want a value and not 'False' statement.

A: There is no lookup formula for multiple criteria. But if there is only one valid time span each material then you can use SUMIFS:
=SUMIFS(F:F,E:E,A:A,G:G,">="&B:B,H:H,"<="&B:B)

Make sure to remove the = sign if the date itself is not included in beeing considered valid.
Note that somehow it looks like start and end dates are mixed up. Start should be lower than end? Also 31.09.2022 is not a date as september has only 30 days. You need to make sure to use real numeric dates or it won't work.

//Edit
If you want to be sure that the SUMIF function only shows the exact doc number and never a sum, you can use the following formula instead:
=IF(IFERROR(MATCH(SUMIFS(F:F,E:E,A:A,G:G,">="&B:B,H:H,"<="&B:B),F:F,0),0)<>0,SUMIFS(F:F,E:E,A:A,G:G,">="&B:B,H:H,"<="&B:B),"double doc found")


text:
Q: How do I pass the recordId from Aura to my Apex controller? I have access to recordId in Aura and I want to access it in my Apex Controller.  I am following the docs here.
I keep getting an error that it can't find the serverEcho controller file.  (See doInit js file -> var action = component.get("c.serverEcho");).
But in all the examples in the docs, there is no such file - it is just a reference to the apex controller function's name.  What am I missing?  Thank you.
//.cmp file
<aura:component implements="force:hasRecordId,flexipage:availableForAllPageTypes" access="global" >
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
     <lightning:card title="Lightning Aura Component">

            Current Record ID in Lightning Aura Component: {!v.recordId}

    </lightning:card>
    <lightning:container src="{!$Resource.demo_salesforce_hello + '/index.html?recordid=' + v.recordId}"
                          onerror="{!c.handleError}"/>
</aura:component>

//.js file
({
    doInit : function(component, event, helper) {
        var recordId = component.get('v.recordId');
        var action = component.get("c.serverEcho");
        action.setParams({ recordId : recordId });
        //adding this doesn't work either nor does adding a callback
        //$A.enqueueAction(action);
    }
})

//apex controller
global with sharing class ContactController {
@AuraEnabled
public static String serverEcho(String recordId) {
    return ('Hello from the server, ' + recordId);
}

}

A: You need to add the controller attribute to your aura:component header :
Something like this :  controller="ContactController"
<aura:component controller="ContactController " implements="force:hasRecordId,flexipage:availableForAllPageTypes" access="global" >
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
 <lightning:card title="Lightning Aura Component">

        Current Record ID in Lightning Aura Component: {!v.recordId}

</lightning:card>
<lightning:container src="{!$Resource.demo_salesforce_hello + '/index.html?recordid=' + v.recordId}"
                      onerror="{!c.handleError}"/>
</aura:component>

Hope this will help


text: Q: How to change Lifelines CoxPHFitter summary's reported p-value? I have been using Lifelines for some of the research I have been doing with clinical data and it seems that the p-value reporting from the CoxPHFitter summary doesn't go below p<0.005. Is it possible to have p-values below this reported (for instance, p<0.001)?


text:
Q: Why are some (but not all) Python iterators summable after being exhausted? In Python, iterators are intended for one-time use.  Once an iterator has raised StopIteration, it shouldn't return any more values.  Yet if I define a custom iterator, it seems that I can still sum the values after they're exhausted!
Example code (Python 3.6.5, or replace __next__(self) with next(self) to see the same behaviour in Python 2.7.15):
class CustomIterator:
  def __iter__(self):
    self.n=0
    return self

  def __next__(self):
    self.n += 1
    if self.n > 3:
      raise StopIteration
    return self.n

i1 = iter([1,2,3])
i2 = iter(CustomIterator())

print('Sum of i1 is {}'.format(sum(i1))) # returns 6 as expected
print('Sum of i1 is {}'.format(sum(i1))) # returns 0 because i1 is now exhausted
try:
  print(next(i1))
except StopIteration:
  print("i1 has raised StopIteration") # this exception happens
print('Sum of i1 is {}'.format(sum(i1))) # 0 again

print('Sum of i2 is {}'.format(sum(i2))) # returns 6 as expected
print('Sum of i2 is {}'.format(sum(i2))) # returns 6 again!
try:
  print(next(i2))
except StopIteration:
  print("i2 has raised StopIteration") # still get an exception
print('Sum of i2 is {}'.format(sum(i2))) # and yet we get 6 again

Why do i1 and i2 behave differently?  Is it some trick in how sum is implemented?  I've checked https://docs.python.org/3/library/functions.html#sum and it doesn't give me a lot to go on.
Related questions:

*

*Summing values in an Iterator

*Why can't I iterate twice over the same data?

*Python iterator is empty after performing some action on it
These describe the expected behaviour for built-in iterators, but don't explain why my custom iterator behaves differently.

A: The problem is that the custom iterator is initialising inside the __iter__ method.  Even though i2 = iter(CustomIterator()) includes an explicit call to iter, the sum function (and also min, max, for, etc) will still call i2.__iter__() again and reset i2.
There's a bunch of tutorials out there on "how to make Python iterators", and about half of them say something like "to make an iterator, you just have to define iter and next methods".  While this is technically correct as per the documentation, it will get you into trouble sometimes.  In many cases you'll also want a separate __init__ method to initialise the iterator.
So to fix this problem, redefine CustomIterator as:
class CustomIterator:
  def __init__(self):
    self.n=0

  def __iter__(self):
    return self

  def __next__(self):
    self.n += 1
    if self.n > 3:
      raise StopIteration
    return self.n

i1 = iter([1,2,3])
i2 = CustomIterator() ### iter(...) is not needed here (but won't do any harm either)

Then init is called once and once only on creating a new iterator, and repeated calls to iter won't reset the iterator.


text:
Q: by-group calculation, limited to first N rows of each group I asked a question before and received a good answer but I needed to apply it to a more specific problem. The DT needs to be divided into 16 sectors based on X and Y values. The X and Y variables represent the coordinates to loop through and divide the data table. I have successfully divided this data table into 16 different 'sectors' and I need to apply the sCalc function on each sector and output a number. I'm looking for a faster way to do this.
Refer to this link for clarification if needed: Faster way to subset data table instead of a for loop R.
library(data.table)
DT <- data.table(X = rep(1:2000, times = 1600), Y = rep(1:1600, each =   2000), Norm =rnorm(1600*2000), Unif = runif(1600*2000))

sCalc <- function(DT) {
    setkey(DT, Norm)
    cells <- DT[1:(nrow(DT)*0.02)]
    nCells <- nrow(DT)
    sumCell <- sum(cells[,Norm/sqrt(Unif)])
    return(sumCell/nCells)
}

startstop <- function(width, y = FALSE) {
    startend <- width - (width/4 - 1)
    start <- round(seq(0, startend, length.out = 4))
    stop <- round(seq(width/4, width, length.out = 4))
    if  (length(c(start,stop)[anyDuplicated(c(start,stop))]) != 0) {
        dup <- anyDuplicated(c(start,stop))
        stop[which(stop == c(start,stop)[dup])] <- stop[which(stop == c(start,stop)[dup])] - 1
}
    if (y == TRUE) {
        coord <- list(rep(start, each = 4), rep(stop, each = 4))
  } else if (y == FALSE) {
        coord <- list(rep(start, times = 4), rep(stop, times = 4))
  }
  return(coord)
}

sectorCalc <- function(x,y,DT) {
    sector <- numeric(length = 16)
    for (i in 1:length(sector)) {
        sect <- DT[X %between% c(x[[1]][i],x[[2]][i]) & Y %between% c(y[[1]][i],y[[2]][i])]
        sector[i] <- sCalc(sect)
    }
    return(sector)
}

x <- startstop(2000)
y <- startstop(1600, y = TRUE)

sectorLoop <- sectorCalc(x,y,DT)

sectorLoop returns:
-4.729271 -4.769156 -4.974996 -4.931120 -4.777013 -4.644919 -4.958968 -4.663221
-4.771545 -4.909868 -4.821098 -4.795526 -4.846709 -4.931514 -4.875148 -4.847105
One solution was using the cut function.
DT[, x.sect := cut(DT[, X], seq(0, 2000, by = 500), dig.lab=10)]
DT[, y.sect := cut(DT[, Y], seq(0, 1600, by = 400), dig.lab=10)]
sectorRef <- DT[order(Norm), .(sCalc = sum(Norm[1:(0.02*.N)] / sqrt(Unif[1:(0.02*.N)])  )/(0.02*.N)), by = .(x.sect, y.sect)]
sectorRef <- sectorRef[[3]]

The above solution returns a data table with the values:
-4.919447 -4.778576 -4.757455 -4.779086 -4.739814 -4.836497 -4.776635 -4.656748
-4.939441 -4.707901 -4.751791 -4.864481 -4.839134 -4.973294 -4.663360 -5.055344
cor(sectorRef, sectorLoop)

The above returns: 0.0726904

A: As far as I can understand the question, the first thing I would explain is that you can use .N to tell you how many rows there are in each by=.(...)group.  I think that is analogous to your nCells.
And where your cells takes the top 2% of rows in each group, this can be accomplished at the vector level by indexing [1:(0.02*.N)].  Assuming you want the top 2% in order of increasing Norm (which is the order you would get from setkey(DT, Norm), although setting a key does more than just sorting), you could call setkey(DT, Norm) before the calculation, as in the example, or to make it clearer what you are doing, you could use order(Norm) inside your calculation.
The sum() part doesn't change, so the equivalent third line is:
DT[order(Norm),
   .(sCalc = sum( Norm[1:(0.02*.N)] / sqrt(Unif[1:(0.02*.N)]) )/.N),
   by = .(x.sect, y.sect)]

Which returns the operation for the 16 groups:
         x.sect      y.sect       sCalc
 1: (1500,2000]  (800,1200] -0.09380209
 2:  (499,1000]   (399,800] -0.09833151
 3:  (499,1000] (1200,1600] -0.09606350
 4:     (0,499]   (399,800] -0.09623751
 5:     (0,499]  (800,1200] -0.09598717
 6: (1500,2000]     (0,399] -0.09306580
 7: (1000,1500]   (399,800] -0.09669593
 8: (1500,2000]   (399,800] -0.09606388
 9: (1500,2000] (1200,1600] -0.09368166
10:  (499,1000]     (0,399] -0.09611643
11: (1000,1500]     (0,399] -0.09404482
12:     (0,499] (1200,1600] -0.09387951
13: (1000,1500] (1200,1600] -0.10069461
14: (1000,1500]  (800,1200] -0.09825285
15:     (0,499]     (0,399] -0.09890184
16:  (499,1000]  (800,1200] -0.09756506


text:
Q: Is it better to archive/move mail based on mtime or ctime? I have been using a perl script to archive mail found here
The script uses ctime to process and decide which month sub folder to place mail. In most cases this is fine since the ctime = mtime and therefore the mails are archived by the month that they were sent or received.
But I have found occasions when it is not good to run the script.
Say for example a user moves mail back into the inbox or mail has been recovered from a backup into the inbox. If the script processes the touched mail it will move mail into a month it was touched not the time it was sent/received.
Is it not better to process mails by mtime ?
In other words what is the better POSIX qw I should use ?

A: I work with procmail and Dovecot, but the maildir structure is fairly standardized.
If you are trying to archive by date you may want to verify the Date from the headers.  Reading from the top of the headers the first date you find should be very accurate.  My messages have three fields which can be used Delivery-Date:, the Received: headers, and the Date: header.  For received messages, the Delivery-Date: or first Received: header will have the appropriate date.  For sent messages, you are likely to have only the Date: header, which may reflect the time of the system that created it, not your mail server.  You may want to flag messages which don't have a usable date in the headers.
ctime should usually be the date of the message, but there are cases where a new copy of the message is created when it is moved or copied.  Normally these actions take place by relinking the file to the correct directory.
EDIT:  This script will print a list of messages with the first date in the file.  It matches on the RFC date format. The regex may not be the best.
#!/usr/bin/perl

%months = ( 'Jan'=>'01', 'Feb'=>'02', 'Mar'=>'03', 'Apr'=>'04',
            'May'=>'05', 'Jun'=>'06', 'Jul'=>'07', 'Aug'=>'08',
            'Sep'=>'09', 'Oct'=>'10', 'Nov'=>'11', 'Dec'=>'12' );

foreach $filename (@ARGV) {
    open( MESSAGE, $filename);

    while (<MESSAGE>) {
        if ( m/[A-Z][a-z][a-z], ([1230][0-9]) ([A-Z][a-z][a-z]) ([12][0-9][0-9][0-9])/ ) {
            print "$3-$months{$2}-$1 $filename\n";
            last
        }

        if ( m/^$/ ) {                     # End of header
            print "-No--Date- $filename\n";
            last
        }
    }
    close MESSAGE;
}

# EOF

A: As I read from here,the difference between ctime and mtime is explained here http://cerebro.freeshell.org/log/unix-mtime-vs-ctime/ . I can tell you small idea, just attach timestamp to every mail you store so that when you retrieve back you have the exact date it was sent or received, this we use to do for our backups.


text:
Q: use class methods in class variable python How can I use my format_date function for my class variable?
class DailyAggregator(Aggregator):
    time_dirty_data = self.format_date(datetime.datetime.now())

    @staticmethod
    def format_date(date):
        return date.replace(hour=0, minute=0, second=0, microsecond=0)

A: You need to use @classmethod decorator and use with reference Daily, like
class Daily(Aggregator):

    time_dirty_data = None

    def __init__(self):
        Daily.time_dirty_data = Daily.format_date(datetime.datetime.now())

    @classmethod
    def format_date(cls, date):
        return date.replace(hour=0, minute=0, second=0, microsecond=0)

print(Daily.time_dirty_data)
d = Daily()
print(Daily.time_dirty_data)

A: You need to instanciate your class.
Like this:
daily = Daily()
daily.format_date(your_date)

I think it's what you want ?

A: You can the method static and use like this:
@staticmethod
def format_date(date):
    return date.replace(hour=0, minute=0, second=0, microsecond=0)

time_dirty_data = format_date.__func__(datetime.datetime.now())


text:
Q: preg_replace for replacing everything of a variable I actually got a problem, in my situation i select
information from a MYSQL Database saved into $data.
and i have 2 arrays for preg_replace.
this is an example :
$repl();
$repl[0] = '/bull/';
$repl[1] = '/found/';
$repl[2] = '/search/';

$replto();
$replto[0] = 'This is not a ballon';
$replto[1] = 'This has been found';
$replto[2] = 'Im looking for it';

$data = array();
$data[0] = '/mynickname/search';
$data[1] = '/somebulls/search';
$data[2] = '/mcdo/found';
$data[3] = '/bump/search';
$data[4] = '/blood/bull';

echo preg_replace($repl,$replto,$data);

Ok, but the output of preg_replace is this :
/mynickname/Im looking for it
/somebulls/Im looking for it
/mcdo/This has been found
/bump/Im looking for it
/blood/This is not a ballon

... but I want this output :
Im looking for it
Im looking for it
This has been found
Im looking for it
This is not a ballon

I'm new in php, i solved a lot of problem but this is a problem that i haven't found solution.
Can you help me please?

A: Great thanks it work perfectly.
put like
$repl();
$repl[0] = '/.*bull/';
$repl[1] = '/.*found/';
$repl[2] = '/.*search/';

Sorry for the late answer, can't come earlier.
Great thanks again.

A: Based on the result you want, it looks like you want to do something like:
$repl();
$repl[0] = '/.*bull/';
$repl[1] = '/.*found/';
$repl[2] = '/.*search/';


text:
Q: PHP timeout error handling I'm triyng to catch timeout error to output some clear text to the user (like "Sorry, timeout").
So why does this example:
function shutdown() {
    $a=error_get_last();
    if($a==null)
        echo "No errors";
    else
         print_r($a);

}
register_shutdown_function('shutdown');
ini_set('max_execution_time',1 );
sleep(3);

output no errors?? I'm confused about it.
Here this example looks helpful.
Thanks

A: Try not using sleep(), seems to work if the reason for timeout is real work:
Example
function isPrime($num) {
    if($num == 1)
        return false;
    if($num == 2)
        return true;
    if($num % 2 == 0) {
        return false;
    }
    for($i = 3; $i <= ceil(sqrt($num)); $i = $i + 2) {
        if($num % $i == 0)
            return false;
    }
    return true;
}
function shutdown()
{
     $a=error_get_last();
     if($a==null)
         echo "No errors";
     else
          print_r($a);
}
register_shutdown_function('shutdown');
ini_set('max_execution_time',1 );
$ps = 0;
for ($i = 0; $i < 1000000; $i++) {
    if (isPrime($i)){
        $ps++;
    }
}
echo $ps;


text:
Q: Issue with a socket program in python I'm trying to write a code that prompts the user to enter a URL but I can't figure out how to send the entered URL in the get request in the 10th line of this code.
import socket

inp = input('Enter a URL: ')
ipt = inp.split('/')
inu = ipt[2]

mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect((inu, 80))
cmd = 'GET  HTTP/1.0\r\n\r\n'.encode()
mysock.send(cmd)

while True:
    data = mysock.recv(512)
    if len(data) < 1:
        break
    print(data.decode(),end='')

mysock.close()

UPDATE:
I was going through my old questions here and found this silly question I asked in my early programming days. If anyone's having the same roadblock just use String.format() method.

A: Use urllib library.
import urllib

url = input("Enter url: ")
url_parsed = urllib.parse.urlparse(url)
domain = url_parsed.netloc
if not domain:
    raise Exception("Invalid URL")

# Use this domain to connect


text:
Q: How to receive data instantly with Architecture Compoenents? I'm trying to implement the recommended architecture by Google and in a tutorial they show this diagram:

So I have a MainActivity and when the app starts it should go and fetch some data from the internet. I do those network operations in the Repository. Now my problem is that I don't know how to communicate properly between activities and Repository. For example MainActivity starts and immediately display a circular progress bar while Repository fetches the data. How can I stop the animation in MainActivity as soon as the data is inserted to the database? I guess I could call observe() on the LiveData and wait for onChanged(). Is there a better approach? What if there is no new data? Then onChanged() wouldn't be called...
Maybe I could send intent from Repository to MainActivity when there is no data so MainActivity knows it should stop the animation and if it doesn't receive the intent it just waits for onChanged()?
I guess I just don't feel confortable with the onChanged() method because I will never be sure of the operation it corresponds to. Maybe before the data from the network arrived there was some other data inserted which trigged onChanged() which would then stop the loading animation before it was supposed to.

A: Regarding your issue in the comments, which I believe to answer your main question also.
You need to observe from your UI (Activity / Fragment) to a progress LiveData in your ViewModel. That could be working with a Boolean (LiveData<Boolean>). To represent the progress view being visible or not.
That in turn needs to take an identical LiveData from the Repository (declared in the Repository as a MutableLiveData). You then post updates to the progress MutableLiveData in the Repository.
Now, whenever the MutableLiveData receives a change, that exists in your ViewModel as it shares the variable reference, and it will pass to the observer in your UI.
-
Alternatively, you could return a LiveData<Boolean> from the method in your Repository that pulls data. That would then be observable in your UI.
Instead of Boolean, you could also use a more complicated structure containing more information. A message, error code, etc.


text:
Q: Passing data from VC to VC segue I am using this code to pass a object to another view controller.
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if([segue.identifier isEqualToString:@"Detail"]){
        UINavigationController *navController = (UINavigationController *)segue.destinationViewController;
        DetailedViewController *controller = (DetailedViewController *)navController.topViewController;
        controller.clipping = [pasteBoardArray objectAtIndex:_row];
    }
}

On the line of:
DetailedViewController *controller = (DetailedViewController *)navController.topViewController;

I get a lengthy exception
2014-05-20 18:46:39.752 SWTableViewCell[8370:60b] -[DetailedViewController topViewController]: unrecognized selector sent to instance 0x10c7169e0
2014-05-20 18:46:39.756 SWTableViewCell[8370:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[DetailedViewController topViewController]: unrecognized selector sent to instance 0x10c7169e0'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000102667495 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x00000001016c699e objc_exception_throw + 43
    2   CoreFoundation                      0x00000001026f865d -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
    3   CoreFoundation                      0x0000000102658d8d ___forwarding___ + 973
    4   CoreFoundation                      0x0000000102658938 _CF_forwarding_prep_0 + 120
    5   SWTableViewCell                     0x000000010000d91c -[ViewController prepareForSegue:sender:] + 204
    6   UIKit                               0x00000001004f4c73 -[UIStoryboardSegueTemplate _perform:] + 134
    7   SWTableViewCell                     0x000000010000c4be -[ViewController tableView:didSelectRowAtIndexPath:] + 350
    8   SWTableViewCell                     0x00000001000089ae -[SWTableViewCell selectCell] + 798
    9   SWTableViewCell                     0x000000010000864b -[SWTableViewCell scrollViewTapped:] + 171
    10  UIKit                               0x0000000100362fc2 _UIGestureRecognizerSendActions + 188
    11  UIKit                               0x0000000100361f28 -[UIGestureRecognizer _updateGestureWithEvent:buttonEvent:] + 357
    12  UIKit                               0x00000001003662d9 ___UIGestureRecognizerUpdate_block_invoke + 53
    13  UIKit                               0x0000000100366261 _UIGestureRecognizerRemoveObjectsFromArrayAndApplyBlocks + 257
    14  UIKit                               0x000000010035e337 _UIGestureRecognizerUpdate + 93
    15  UIKit                               0x0000000100072a15 -[UIWindow _sendGesturesForEvent:] + 928
    16  UIKit                               0x00000001000736d4 -[UIWindow sendEvent:] + 909
    17  UIKit                               0x000000010004b29a -[UIApplication sendEvent:] + 211
    18  UIKit                               0x0000000100038aed _UIApplicationHandleEventQueue + 9579
    19  CoreFoundation                      0x00000001025f6d21 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    20  CoreFoundation                      0x00000001025f65f2 __CFRunLoopDoSources0 + 242
    21  CoreFoundation                      0x000000010261246f __CFRunLoopRun + 767
    22  CoreFoundation                      0x0000000102611d83 CFRunLoopRunSpecific + 467
    23  GraphicsServices                    0x00000001025c6f04 GSEventRunModal + 161
    24  UIKit                               0x000000010003ae33 UIApplicationMain + 1010
    25  SWTableViewCell                     0x0000000100002763 main + 115
    26  libdyld.dylib                       0x000000010607f5fd start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

As a side note I am doing this all within a UINavigationBarController. All I need to do is pass objectAtIndex:_row to the _clipping property in the DetailedViewController.

A: Use the following code if there is NO navigation controller BETWEEN your two view controllers:
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if([segue.identifier isEqualToString:@"Detail"]){
        DetailedViewController *controller = (DetailedViewController *)[segue destinationViewController];
        controller.clipping = [pasteBoardArray objectAtIndex:_row];
        /* ... */
    }
}

Use the following code only if there is ONE navigation controller BETWEEN your two view controllers:
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if([segue.identifier isEqualToString:@"Detail"]){
        UINavigationController *navController = (UINavigationController *)segue.destinationViewController;
        DetailedViewController *controller = (DetailedViewController *)navController.topViewController;
        controller.clipping = [pasteBoardArray objectAtIndex:_row];
        /* ... */
    }
}

A: The error message you posted suggests that the destination view controller of your segue is not a navigation controller as you think it is. You should log the class of the destination view controller to see what it is.


text:
Q: How can $\sin(n \pi x)$ be a complete ONB of $L^2([0,1])$ when $-\Delta$ is positive on them As done in this question one can prove that $\sin(n\pi \cdot), n \ge 1$ is a orthonormal basis of $L^2([0,1])$.
We also have that $(-\Delta)( \sin(n\pi\cdot) )= (n\pi)^2 \sin(n\pi \cdot)$, which means that we can diagonalize $-\Delta$ w.r.t. $\sin(n \pi x)$ and have only positive eigenvalues.
From this I now conclude that $-\Delta$ is strictly positive on $L^2([0,1])$. This is a contradiction to the constants and the linear functions being in the kernel of $-\Delta$ and also in $L^2([0,1])$

A: The operator domain comes with endpoint conditions $f(0)=f(1)=0$. That eliminates constants from being in the domain of the operator, unless those constants are $0$. If you choose endpoint conditions $f'(0)=f'(1)=0$, then you end up with a new basis of eigenfunctions $\{1,\cos(\pi x),\cos(2\pi x),\cdots\}$.

A: This would be a contradiction if $-\Delta$ were a bounded operator, but it's not (it's not even defined on all of $L^2([0,1])$.).
Write out the proof that it's a contradiction in detail, and you'll see there's a point where you use the non-fact that the operator is continuous.

A:
From this I now conclude that $-\Delta$ is strictly positive on $L^2([0,1])$.

This is not true, because the representation of some element with respect to the mentioned ONB and the operator $-\Delta$ do not commute, because $-\Delta$ is not continuous operator!
As an example, let $f= 1_{[0,1]}$ be the indicator function of $[0,1]$, then
\begin{equation}
\int_0^1 \sin(\pi nx) \, \mathrm{d} x = \frac{1-(-1)^n}{\pi n}.
\end{equation}
Thus
$$1_{[0,1]}(x) = \sum_{n=1}^\infty \frac{1-(-1)^n}{\pi n} \sin(\pi nx)$$
in $L^2$-sense. Now, you cannot apply the operator 'coordinatewise'! The resulting sum is not convergent.


text:
Q: Are dynamic libraries loaded on startup or only when required by executable Take a C application running on Linux for example which is dynamically linked with a required shared library.
I know that the .so file should be found in the paths defined in the environment variable LD_LIBRARY_PATH .
Does the dynamic linker load this library on startup of the application regardless? Or can it load it only when a function call from that library is required? If the latter, how would it actually know which function belongs to which library?

A: On Linux libraries are loaded at program startup. Some systems (e.g. Windows or Solaris) support the lazy loading feature which delays library load until one of its functions is called (in this case the static linker will embed information which function belongs to which library into the executable).
Lazy loading can be emulated on Linux using tools like Implib.so.


text:
Q: copy THEN paste FILES in terminal Is there any package that I can use to copy one (or more) file/folder THEN paste into another directory?
I am using Ubuntu, and I have the standard terminal + Terminator.
For example, I am looking for a functionality like:
Folder1$ COPY a.txt
Folder1$ cd ../Folder2
Folder2$ PASTE (a.txt -- optional)

Thank you! I just hate to keep referring to the whole path every time!

A: Here's my dumb way to do this, you can add them to your rcfile:
copy(){
    test -z $1 && echo "No file input!" && return
    test ! -e $1 && echo "File not exist!" && return
    export orig_path="$PWD/$1"
    export orig_name="$1"
}
paste(){
    test -z $orig_path && echo "No copied file!" && return
    if [ "$#" -lt 1 ];then
        dist_name="$PWD/$orig_name"
        if [ -d $orig_path ];then
            cp -r $orig_path $dist_name
        else
            cp $orig_path $dist_name
        fi
        echo "$orig_name pasted."
    else
        dist_name="$PWD/$1"
        if [ -d $orig_path ];then
            cp -r $orig_path $dist_name
        else
            cp $orig_path $dist_name
        fi
        echo "\"$1\" pasted."
    fi
}

This doesn't copy any data to the clipboard, since you want to do this only for not referencing folders, and this works for copying folder as well.

A: Take a look at clipboard-files here: https://github.com/larspontoppidan/clipboard-files
It uses xclip to interface the desktop environment clipboard and provides handy commands like ccopy and cpaste that does exactly what was asked for here. As the desktop environment clipboard is used, the commands interact with the copy/pasting in file managers and other programs that use the clipboard for files. At least it works on Gnome-like desktops.
Full disclosure, I wrote the script after giving up finding something like it out there :)

A: This terminal command should work for files:
cp a.txt ../Folder2/a.txt

And for folders:
cp -R myFolder ../Folder2/myFolder

A: I just created a tool that can do this.
https://github.com/FynnSu/savepath
Use the sap command followed by a list of file paths (either relative or absolute) to add paths.
To use one of the saved paths just write pap followed by the command you want to use the path in and hit enter. You will then be prompted to confirm the command, and can use the arrow keys to modify the command: left/right moves the path insert location and up/down switches between different saved paths.


text:
Q: When does a hypergraph represent maximal independent sets? Let $G = (V,E)$ be a simple graph. Then, we can view the set of maximal independent sets (or the set of maximal cliques) as a hypergraph $H = (V, E')$. This is quite a useful device when connecting the (fractional) packing/covering numbers of $H$ with the (fractional) clique/chromatic numbers of $G$ (cf. Scheinerman and Ullman, Fractional Graph Theory).
When is the converse true, namely, when does a hypergraph correspond to a set of maximal independent sets?
As an example, $H = ([3], \{ \{1,2\}, \{2,3\} \})$ corresponds to the maximal independent sets of the graph
$1 \text{------}3~~~~~~~~2$,
or equivalently, to the maximal cliques of the complementary graph
$1 \text{------} 2 \text{------} 3$.
But another hypergraph with hyperedges $\{ \{1,2\}, \{2,3\}, \{3,1\} \}$ does not correspond to the maximal independent sets of any graph.
Is there any sufficient and necessary condition that can be captured by the incidence matrix of $H$?

A: Clearly, if $E'=\{X_1,X_2,\dots,X_n\}$ is the set of all maximal cliques of a simple graph $(V,E)$, then
$$E=\binom{X_1}2\cup\binom{X_2}2\cup\cdots\cup\binom{X_n}2.$$
Hence, a necessary and sufficient condition for an antichain $E'$ of subsets of $V$ to be the set of all maximal cliques of a simple graph on the vertex set $V$ is that, for every set $S\subseteq V$, if each $2$-element subset of $S$ is contained in an element of $E'$, then $S$ is contained in an element of $E'$.