text:
Q: Discord.py Как я могу проверить содержимое сообщения? Я, с помощью discord.py, хочу сделать текстовый канал в своей гильдии, где будут одни картинки и ничего лишнего. Т.к. у меня не достаточно знаний в языке - прошу помощи! Так вот, как я могу проверять сообщение пользователя и если там будет текст - его удалять?
import discord
from discord.ext import commands
import config
import asyncio
from asyncio import sleep
from discord import utils
import random

bot = discord.ext.commands.Bot(command_prefix = ".", intents = discord.Intents.all())
client = commands.Bot(command_prefix =".", intents = discord.Intents.all())
client.remove_command("help")
only_pictures_channel_id = 853722060499845141
#Сообщение о том, что бот запущен.
@client.event
async def on_ready():
    print("Бот запущен")
    await client.get_user(363678879061377024).send("Бот запущен")
@client.event
async def om_command_error(ctx, error):
    pass
#.hello
@client.command()
async def hello(ctx):
    author = ctx.message.author
    await ctx.message.delete()
    await ctx.send(f"{author.mention}, привет. Кст, а ты знал, что я руиню жизнь своему создателю? ^..^")
#.clear
@client.command()
@commands.has_permissions(manage_messages=True)
async def clear(ctx, amount: int):
    amount = int(amount)
    await ctx.channel.purge(limit = amount+1)
    emb = discord.Embed(title = "Чат был очищен", colour = discord.Color.purple())
    await ctx.send(embed=emb, delete_after=10)
#.kikc
@client.command()
@commands.has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member,*,reason=None):
    await ctx.message.delete()
    await member.kick(reason=reason)
    emb = discord.Embed(title = f"Пользователь, под именем {member.name}, был кикнут, т.к. нёс херню.", colour = discord.Color.purple())
    await ctx.send(embed = emb)
    await client.get_user(363678879061377024).send(f"{member.name} - был кикнут!")
#.ban
@client.command()
@commands.has_permissions(ban_members=True)
async def ban(ctx, member: discord.Member,*,reason=None):
    await ctx.message.delete()
    await member.ban(reason=reason)
    emb = discord.Embed(title = f"Пользователь, под именем {member.name}, допизделся и был сослан в Dungeon навсегда по причине: *{reason}*.", color = discord.Color.purple())
    emb.set_thumbnail(url = "https://pics.me.me/thumb_deep-dark-fantasy-youtube-49022628.png")
    await ctx.send(embed = emb)
    await client.get_user(363678879061377024).send(f"{member.name} - был забанен!")
#.help
@client.command()
async def help(ctx):
    await ctx.message.delete()
    emb = discord.Embed(title = "Навигация по командам сервера", colour = discord.Color.purple())
    emb.set_author(name = client.user.name, icon_url = client.user.avatar_url)
    emb.add_field(name = "Команда *.hello* используется для вписания в хату.",value = ".hello")
    emb.add_field(name = "Команда *.clear* используется для очистки чата (Только для администраторов).",value = ".clear")
    emb.add_field(name = "Команда *.kick* - отвечает за гонения пользователя с сервера (Только для администраторов).",value = ".kick")
    emb.add_field(name = "Команда *.ban* - отвечает за запрет доступа пользователю к серверу (Только для администраторов).",value = ".ban")
    await ctx.send(embed=emb, delete_after=120)
#.TMute
@client.command()
@commands.has_permissions(mute_members = True)
async def tmute(ctx, member: discord.Member):
    await ctx.message.delete()
    TMute = discord.utils.get(ctx.message.guild.roles, name = "TMute")
    await member.add_roles(TMute)
    emb = discord.Embed(title = f"Пользователь, под именем {member.name}, потерял доступ к текстовому чату. D:", colour = discord.Color.purple())
    await ctx.send(embed = emb, delete_after=60)
    await asyncio.sleep(600)
    await member.remove_roles(TMute)
    emb = discord.Embed(title = f"Пользователь, под именем {member.name}, был прощён и преобрёл доступ к текстовому чату. :D", colour = discord.Color.purple())
    await ctx.send(embed = emb, delete_after=60)
    await client.get_user(363678879061377024).send(f"{member.name} - получил мут текстового чата!")
#.VMute
@client.command()
@commands.has_permissions(mute_members = True)
async def vmute(ctx, member: discord.Member):
    await ctx.message.delete()
    VMute = discord.utils.get(ctx.message.guild.roles, name = "VMute")
    await member.add_roles(VMute)
    await member.move_to(None)
    emb = discord.Embed(title = f"Пользователь, под именем {member.name}, потерял доступ к голосовому чату. D:", colour = discord.Color.purple())
    await ctx.send(embed = emb, delete_after=60)
    await asyncio.sleep(600)
    await member.remove_roles(VMute)
    emb = discord.Embed(title = f"Пользователь, под именем {member.name}, был прощён и преобрёл доступ к голосовому чату. <3", colour = discord.Color.purple())
    await ctx.send(embed = emb, delete_after=60)
    await client.get_user(363678879061377024).send(f"{member.name} - получил мут голосового чата!")
#.TunMute
@client.command()
@commands.has_permissions(administrator = True)
async def tunmute(ctx, member: discord.Member):
    await ctx.message.delete()
    TMute = discord.utils.get(ctx.message.guild.roles, name = "TMute")
    await member.remove_roles(TMute)
    emb = discord.Embed(title = f"Пользователь, под именем {member.name}, был прощён и преобрёл доступ к текстовому чату. :D", colour = discord.Color.purple())
    await ctx.send(embed = emb, delete_after=60)
#.VunMute
@client.command()
@commands.has_permissions(administrator = True)
async def vunmute(ctx, member: discord.Member):
    await ctx.message.delete()
    VMute = discord.utils.get(ctx.message.guild.roles, name = "VMute")
    await member.remove_roles(VMute)
    emb = discord.Embed(title = f"Пользователь, под именем {member.name}, был прощён и преобрёл доступ к голосовому чату. :D", colour = discord.Color.purple())
    await ctx.send(embed = emb, delete_after=60)
#Выдача роли
@client.event
async def on_member_join(member):
    channel = client.get_channel(850994154438787072)
    value = random.randint(1,3)
    if value == 1:
        role = discord.utils.get(member.guild.roles, id = 853266138380632075)
        await member.add_roles(role)
        emb = discord.Embed(title = f"Пользователь, под именем {member.name}, присоеденился и был распределён в команду розовых!", colour = discord.Color.pink())
    elif value == 2:
        role = discord.utils.get(member.guild.roles, id = 853266791256817684)
        await member.add_roles(role)
        emb = discord.Embed(title = f"Пользователь, под именем {member.name}, присоеденился и был распределён в команду синих!", colour = discord.Color.blu())
    elif value == 3:
        role = discord.utils.get(member.guild.roles, id = 853368542787534858)
        await member.add_roles(role)
        emb = discord.Embed(title = f"Пользователь, под именем {member.name}, присоеденился и был распределён в команду красных!", colour = discord.Color.red())
    await channel.send(embed = emb, delete_after=60)
    await client.get_user(363678879061377024).send(f"Пользователь, под именем {member.name}, присоеденился к гильдии!")
#Канал с пикчами
@bot.event
async def on_message(message):
    await bot.process_commands(message)
    if message.author.bot: return
    if message.channel.id == only_pictures_channel_id:
        if len(message.attachments) > 0 and message.content == '':
            if message.attachments[0].url.split('.')[-1].lower() not in ['png', 'jpg', 'gif', 'jpeg']:
                await message.delete()
        else:
            await message.delete()
#ошибки
@clear.error
async def clear_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send(f"{ctx.author.name}, обязательно укажите аргумент!", delete_after=15)
    elif isinstance(error, commands.MissingPermissions):
        await ctx.send("У вас недостаточно прав!", delete_after=15)
    elif isinstance(error, commands.CommandNotFound):
        await ctx.send("Такой команды не существует!", delete_after=15)
#Запуск
client.run(config.TOKEN)

A: Создадим объект бота, который будет управлять сообщениями:
import discord
from discord.ext import commands

bot = commands.Bot(command_prefix='!', intents = discord.Intents.all())

Создадим функцию обработки всех полученных сообщений:
@bot.event
async def on_message(message):

Дальше мы будем работать с объектом сообщения message, полученным в виде аргумента функции. Из объекта сообщения вы можете получить автора, канал, сервер и много чего еще.
Внутри функции, первым делом пропишем игнорирование сообщений от ботов:
if message.author.bot: return

Затем, проверим в какой канал пришло сообщение. Мы работаем с сообщениями только определенного канала. Добавим в функцию условие проверки по id:
only_pictures_channel_id = 920573476320590836 # здесь, вместо этого id вставьте id
                                              # вашего канала с картинками
if message.channel.id == only_pictures_channel_id:

Теперь, когда у нас есть функция проверки сообщений, и прописаны все необходимые условия, можем начать отбор "правильных" сообщений.
Из объекта message получаем текст сообщения: message.content
А также список (list) его вложений: message.attachments
В списке вложений могут быть не только изображения, но и звуковые, текстовые и прочие файлы. Нам нужно отсеять их.
Нам подходят условия, когда нет текста, то есть message.content == '' и когда количество вложений не равно нулю, то есть len(message.attachments) > 0. Если оба условия совпадают, то проверяем, чтобы расширение файла соответствовало расширению изображения:
if len(message.attachments) > 0 and message.content == '':
    if message.attachments[0].url.split('.')[-1].lower() not in ['png', 'jpg', 'gif', 'jpeg']:
        await message.delete()
else:
    await message.delete()

Таким образом, если не совпадает расширение или начальные условия, сообщение будет удалено.

Полный код:
import discord
from discord.ext import commands

bot = commands.Bot(command_prefix='!', intents = discord.Intents.all())

only_pictures_channel_id = 920573476320590836

@bot.event
async def on_message(message):
    if message.author.bot: return
    if message.channel.id == only_pictures_channel_id:
        if len(message.attachments) > 0 and message.content == '':
            if message.attachments[0].url.split('.')[-1].lower() not in ['png', 'jpg', 'gif', 'jpeg']:
                await message.delete()
        else:
            await message.delete()

bot.run('TOKEN')

Не забудьте указать токен, а также выдать боту права на "Управление сообщениями" на сервере

Подробнее о проверке расширения:
message.attachments[0].url.split('.')[-1].lower()

Здесь мы получаем объект вложения, из которого можем получить ссылку на него, через url. Затем, полученную ссылку мы разбиваем на 2 части по символу "." (точка), и забираем последний ([-1]) элемент списка, содержащий расширение файла. После чего, используя lower() меняем все его символы верхнего регистра на нижний, чтобы было меньше условия для проверки.


text:
Q: Finding records that exist in one table but not another (matching) table with no primary key I'm looking at changing a data load that is done using an external tool to generate a flat files based on several joins using that tool, and then loaded into a table using SQL*Loader.
I'd like to move away from using this program and use external tables, moving the table insert into the database instead. I'm uncertain about the validity of my joins versus what the program was doing though. When I compare what I have made using external tables, I have 14702052 total records and 14268891 distinct records. When I compare to the table loaded with the old tool with the same data I have 14669198 records, with 14268888 distinct. I'm not worried about the total number as duplicates are ok for this, it's updating some values and a duplicate should not matter.
I can't seem to figure out what the extra distinct values are though. I've tried minus, not in, not exists, and joining, maybe a few other tries I don't remember off the top of my head, but I get no records. There is no primary key for the table either to join on either which makes checking hard.
If it were less records I could compare using Kdiff3, but as it stands the output is way too large to run on my computer. I may try to break it down by rownum as a worst case attempt to find the extra records.
Anyone have any suggestions on an alternative?
Edit:
Here's the table structure, had to strip out some of the names
CREATE TABLE T (
ID varchar2(11 byte),
CLASS_CD varchar2(4 byte),
ITEM_NAME varchar2(60 byte),
UNIT_OF_ISSUE varchar2(2 byte),
PRICE number(15,2),
ITEM_CD varchar2(3 byte),
SERVICE_CD varchar2(2 byte));

Here's a sample record, though I've replaced most of the values for sensitivity.
ID         CLASS_CD ITEM_NAME      UOI     PRICE   ITEM_CD   SERVICE_CD
000000057  1111     NAME       FT      5.91    NULL      BC

A: Assuming you have both new and old table in the same structure, this should have given you at least 3 records
select * from new_table
minus
select * from old_table

In any case, use this query to find the differences
select      count(case when tab='O' then 1 end) as cnt_old
           ,count(case when tab='N' then 1 end) as cnt_new

           ,id,class_cd,item_name,uoi,price,item_cd,service_cd

from        (           select 'O' as tab,t.* from old_table t
            union all   select 'N'       ,t.* from new_table t
            ) t

group by    id,class_cd,item_name,uoi,price,item_cd,service_cd

having      count(case when tab='O' then 1 end) = 0
        or  count(case when tab='N' then 1 end) = 0
;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Casting struct to object for null comparison isn't causing boxing? I came across this while doing some benchmarking.
bool b;
MyStruct s;
for (int i = 0; i < 10000000; i++)
{
    b = (object)s == null;
}

Debug: 200 ms
Release: 5 ms

bool b;
MyStruct? s = null;
for (int i = 0; i < 10000000; i++)
{
    b = (object)s == null;
}

Debug: 800 ms
Release: 800 ms

I can understand this result since casting the nullable struct to object gives me a boxed type of that struct. But why isn't casting struct s to object for doing null comparison (as in the first method) result in the same performance? Is it that compiler is optimizing the call to return false always as a struct can't be null?

A: Yes, the compiler is optimising it.
It knows that a struct can never be null, so the result of casting it to an object can never be null - so it will just set b to false in the first sample. In fact, if you use Resharper, it will warn you that the expression is always false.
For the second of course, a nullable can be null so it has to do the check.
(You can also use Reflector to inspect the compiler-generated IL code to verify this.)
The original test code is not good because the compiler knows that the nullable struct will always be null and will therefore also optimize away that loop.  Not only that, but in a release build the compiler realises that b is not used and optimizes away the entire loop.
To prevent that, and to show what would happen in more realistic code, test it like so:
using System;
using System.Diagnostics;

namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            bool b = true;
            MyStruct? s1 = getNullableStruct();
            Stopwatch sw = Stopwatch.StartNew();

            for (int i = 0; i < 10000000; i++)
            {
                b &= (object)s1 == null; // Note: Redundant cast to object.
            }

            Console.WriteLine(sw.Elapsed);

            MyStruct s2 = getStruct();
            sw.Restart();

            for (int i = 0; i < 10000000; i++)
            {
                b &= (object)s2 == null;
            }

            Console.WriteLine(sw.Elapsed);
        }

        private static MyStruct? getNullableStruct()
        {
            return null;
        }

        private static MyStruct getStruct()
        {
            return new MyStruct();
        }
    }

    public struct MyStruct {}
}

A: in fact both loop will have an empty body when compiled!
to make the second loop behave, you will have to remove the (object) casting
this is what it look like when I compile your code,
public struct MyStruct
{
}

class Program
{
    static void Main(string[] args)
    {
        test1();
        test2();
    }

    public static void test1()
    {
        Stopwatch sw = new Stopwatch();
        bool b;
        MyStruct s;
        for (int i = 0; i < 100000000; i++)
        {
            b = (object)s == null;
        }
        sw.Stop();
        Console.WriteLine(sw.ElapsedMilliseconds);
        Console.ReadLine();
    }

    public static void test2()
    {
        Stopwatch sw = new Stopwatch();
        bool b;
        MyStruct? s = null;
        for (int i = 0; i < 100000000; i++)
        {
            b = (object)s == null;
        }
        sw.Stop();
        Console.WriteLine(sw.ElapsedMilliseconds);
        Console.ReadLine();
    }
}

IL:
the MyStruct (empty since you didn't provide any)
.class public sequential ansi sealed beforefieldinit ConsoleApplication1.MyStruct
extends [mscorlib]System.ValueType
{
    .pack 0
    .size 1

} // end of class ConsoleApplication1.MyStruct

the first loop in your example
.method public hidebysig static
void test1 () cil managed
{
// Method begins at RVA 0x2054
// Code size 17 (0x11)
.maxstack 2
.locals init (
    [0] valuetype ConsoleApplication1.MyStruct s,
    [1] int32 i
)

IL_0000: ldc.i4.0
IL_0001: stloc.1
IL_0002: br.s IL_0008
// loop start (head: IL_0008)
    IL_0004: ldloc.1
    IL_0005: ldc.i4.1
    IL_0006: add
    IL_0007: stloc.1

    IL_0008: ldloc.1
    IL_0009: ldc.i4 100000000
    IL_000e: blt.s IL_0004
// end loop

IL_0010: ret
} // end of method Program::test1

the second loop
.method public hidebysig static
void test2 () cil managed
{
// Method begins at RVA 0x2074
// Code size 25 (0x19)
.maxstack 2
.locals init (
    [0] valuetype [mscorlib]System.Nullable`1<valuetype ConsoleApplication1.MyStruct> s,
    [1] int32 i
)

IL_0000: ldloca.s s
IL_0002: initobj valuetype [mscorlib]System.Nullable`1<valuetype ConsoleApplication1.MyStruct>
IL_0008: ldc.i4.0
IL_0009: stloc.1
IL_000a: br.s IL_0010
// loop start (head: IL_0010)
    IL_000c: ldloc.1
    IL_000d: ldc.i4.1
    IL_000e: add
    IL_000f: stloc.1

    IL_0010: ldloc.1
    IL_0011: ldc.i4 100000000
    IL_0016: blt.s IL_000c
// end loop

IL_0018: ret
} // end of method Program::test2


text:
Q: Computer fails to sleep when booting from a NVMe SSD Whenever I'm trying to put my PC to sleep, the screen goes blank but a power indicator stays on and all fans keep on working.
I have a NVMe SSD installed on a PCIe card, and OS is installed on this disk. This problem is only happening when I put it to a PCIe 3.0 slot; when I move it to a PCIe 2.0 slot, the problem goes away but the disk works at half max speed.
Any ideas how to fix this problem?
UPD my motherboard is this one GA-Z97MX-Gaming 5
UPD2 after removing the video card, the results are the same for both PCIe 3.0 slot, i.e. PC shuts down incorrectly instead of sleeping.


text:
Q: How to generically instantiate a generic class in C#? Maybe it is pretty simple, but I'm not in use with the type Type and it's uses.
Say I want to create a List<T> either with T=Double or T=UInt32, depending on the result of some function, say public static Type CheckType(String input);
In code:
Type t = Program.CheckType(someInput); // it returns typeof(Double) or typeof(UInt32)
if (t == typeof(Double))
    List<Double> l = new List<Double>();
else
    List<UInt32> l = new List<UInt32>();

I know the above code won't compile because I'm letting l to have two different meanings (a list of double and a list of unsigned int)... So it leads to my question:

*

*Is there a way to avoid the if in the above code?

Something similar to this:
Type t = Program.CheckType(someInput);
List<t> l = new List<t>(); // I know this won't compile either...

I mean, that would generically instantiate a generic List...
Thank you in advance!
EDIT:
This is NOT a duplicate of the marked question for only one reason: Double and UInt32 are not Anonymous types! The question, here, is how to determine the type of some input data (which will be Type T=typeof(Double) or Type T=typeof(UInt32), for example) and, thus, create a generic SampleClass<T> based on that input data type, T!
In other words: determine some Type T in the runtime and, then, instantiate a generic type with the determined type T. Sorry if I didn't make that clear before...
PS: I used List<T> as an example for SampleClass<T>.

A: You can't type the list as generic, since you don't know the type parameter, but you can create a List instance at runtime.
Type t = Program.CheckType(someInput);
Type listType = typeof(List<>).MakeGenericType(t);
IList list = (IList) Activator.CreateInstance(listType);

If you try to add an object of the incorrect type, you will get an exception, so this approach has an advantage over using a collection like ArrayList, or List<object>

A: There's no real reason to use generics in such instances.  Since the generic argument isn't known at compile time the compiler can't verify whether or not the objects you're trying to add or remove are appropriate for that list.
If at all possible, it's best to avoid this situation entirely, possibly through making the method that this code is in generic itself.
If that's not possible, it's probably better to just use the non-generic ArrayList or a List<object>, because using a generic list in this context will add a lot of extra work for no extra help.

A: MakeGenricType might work
Using Reflection to set a Property with a type of List<CustomClass>
    Type type = Program.CheckType(someInput);
    IList list = (IList) Activator.CreateInstance(typeof(List<>).MakeGenericType(type));
    object obj = Activator.CreateInstance(type);
    list.Add(obj);

A: Type t = Program.CheckType(someInput);
var l = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(t));

A: I would go for a generic Histogram<T> but not try to hold both types in the same variable, unless you want to just have a IDictionary variable.
Here is an example with using the histogram with double types:
class Program
{

    static Random rnd=new Random();
    static void Main(string[] args)
    {
        Historgram<double> hist=new Historgram<double>();
        for(int i=0; i<1000; i++)
        {
            double x=Math.Round(rnd.NextDouble(), 1);
            hist.Add(x);
        }
        //double[] values=hist.Values;

        Console.WriteLine("Histogram");
        Console.WriteLine("{0,12} {1,12}", "Value", "Quantity");
        for(int i=0; i<=10; i++)
        {
            double x=(i/10d);
            Console.WriteLine("{0,12} {1,12}", x, hist[x]);
        }
        Console.ReadLine();
    }

with result
   Histogram
   Value     Quantity
       0           52
     0.1           97
     0.2          117
     0.3           98
     0.4           93
     0.5          110
     0.6           97
     0.7           94
     0.8           98
     0.9           93
       1           51

and the code:
public class Historgram<T>
{
    Dictionary<T, int> bins;
    public Historgram()
    {
        this.bins=new Dictionary<T, int>();
    }

    public void Add(T value)
    {
        if(bins.ContainsKey(value))
        {
            bins[value]++;
        }
        else
        {
            bins.Add(value, 1);
        }
    }
    public void Remove(T value)
    {
        if(bins.ContainsKey(value))
        {
            bins[value]--;
            if(bins[value]==0)
            {
                bins.Remove(value);
            }
        }
    }
    public int this[T x]
    {
        get
        {
            if(bins.ContainsKey(x))
            {
                return bins[x];
            }
            else
            {
                return 0;
            }
        }
        set
        {
            if(bins.ContainsKey(x))
            {
                bins[x]=value;
            }
            else
            {
                bins.Add(x, value);
            }
        }
    }
    public bool ContainsValue(T value) { return bins.ContainsKey(value); }
    public int Count { get { return bins.Count; } }
    public T[] Values { get { return bins.Keys.ToArray(); } }
    public int[] Quantities { get { return bins.Values.ToArray(); } }
}


text:
Q: qgis (segment (link) start node and end node id's extraction from shapefile ) I have been dealing with a lot of shape files editing tools last month..
I tried to get two dbf files from shape file (one for nodes and one for links) in an appropriate format (node_id,x,y for nodes and link_id,start_node_id,end_node_id,...for links)in order to create  an oracle spatial network.
I got the dbf for nodes..
I want now to get the attribute table from a loaded shape file containing polylines (roads) and I want to split each polyline to its segments containing their start and end node id's besides their geometry..
Every help accepted..

A: You might want to clarify your question slightly, but it sounds like you want to get the details of each point in a polyline from a shapefile so that you can define segments.
I wrote an example of how you can do this using Python here:
https://gis.stackexchange.com/questions/40798/how-to-split-shapefile-per-feature-in-python-using-gdal
Specifically, pay attention to the lines:
line = geom.asPolyline()
        # all points in the line
        for point in line:

You should be able to achieve your goal using a variation of this basic example.
Dan


text:
Q: Where can I find the nav-sections phtml file I want to customize the nav-section component, like changing data, adding more links, and customizing its styling on hover, but I cannot find its phtml or markup file in the Magento theme.
To my knowledge, to customize that component, I just need to find the file, copy it, paste it into my theme folder, and then customize it according to my design.
Is there any way to customize that component without creating it from scratch?
Please, any help would be appreciated.

A: In Magento 2, let call the nav-sections is a div or a section instead of component, component means UI component.
The template file responsible for the nav-sections is vendor/magento/module-theme/view/frontend/templates/html/sections.phtml.
To find the template file for the nav-sections in Magento codebase, you should find the word nav-sections in the vendor/magento directory. Here, you will see nav-sections CSS class declared in vendor/magento/module-theme/view/frontend/layout/default.xml which belongs to template Magento_Theme::html/sections.phtml.


text:
Q: "Exception calling 'GetFullPath'..." error when calling Scaffold-DbContext in Entity Framework Core I am using Visual Studio 2019 Professional to create an ASP.NET Core web site. I have a DLL that contains my Entity Framework Core models. I am using a Database First approach. Recently, when I try to call Scaffold-DbContext to update my models after adding a new database table, I get the following error:
Scaffold-DbContext : Exception calling "GetFullPath" with "1" argument(s): "The path is not of a legal form."
At line:1 char:1
+ Scaffold-DbContext "Server=[Server Name];Database=DB_TH_Cust ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Scaffold-DbContext], MethodInvocationException
    + FullyQualifiedErrorId : ArgumentException,Scaffold-DbContext

Here is the command I use:

Scaffold-DbContext "Server=[Server URL];Database=DB_TH_Custom_Apps_Dev_SQL;Trusted_Connection=True;Column Encryption Setting=enabled" Microsoft.EntityFrameworkCore.SqlServer -Project "Data Layer" -Force

I don't understand what this error message means; I'm not sure exactly what path it's referring to or why it's not of a legal form (or even what a "legal form" would be in this context).
This is at least somewhat intermittent, and I don't know what changed to start this happening.
Closing and re-opening Visual Studio sometimes seems to help, but I'm not sure exactly when or why it helps. Recently, I had opened it running it as an administrator and received the error. I closed Visual Studio and re-opened it as an administrator and got the same error message again. I tried closing it and re-opening it a second time, except not as an administrator that time, and it worked. I'm not sure if that was what made the difference, and I'm not sure why that would matter. (If that is, in fact, the problem, I'd definitely be interested to know why).
The only Stack Overflow question I've found so far that has the same error message seems to have occurred in an entirely different context, so I'm not sure how to apply it to my situation.
I also have a vague memory of reading an article that said that this could be caused by compilation errors in your solution, but I don't remember where. In any case, though, my solution compiles just fine.
Can someone explain what this error message means and why it's happening? Is there anything I can do to prevent it?

A: I was having the same issue. Very frustrating. I finally was able to resolve this issue by changing the "Startup Project" in Solution Properties.
I figured this out by going through the documentation here:
https://learn.microsoft.com/en-us/ef/core/cli/powershell
I noticed that in the command line I was using I was not defining -StartupProject. Hope this helps Josh, or future folks who come across this thread via Googling the error message, like I did.


text:
Q: Cannot subscript a value of type '[NSObject : Any]' with an index of type 'String' I found diverses on the Internet but nothing helped me further. I'm a newcomer and I m gonna help you.
I'll get the message:

Cannot subscript a value of type '[NSObject : Any]' with an index of type 'String'

private func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : Any]){
    let chosenImage = info[UIImagePickerControllerEditedImage] as UIImage
    let neuesBild = BildUndNotiz(bild: chosenImage, text: "")

    bildUndNotiz += [neuesBild]
    self.Spoonlist.reloadData()

    picker.dismissViewControllerAnimated(true, completion:
        {self.zeigeViewControllerFürBildUndNotiz(neuesBild)})

}

thank you very much

A: SWIFT 4 Solution:
 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

guard let image = info[UIImagePickerController.InfoKey.originalImage]
as? UIImage else {
  return
}

imagePicked.image = image
//dismiss(animated:true, completion: nil)
}

A: This code is out-of-date. The correct method signature is now:
func imagePickerController(_ picker: UIImagePickerController,
                           didFinishPickingMediaWithInfo info: [String : Any])

Because you have the wrong method signature, info has the wrong type and can't be subscripted by a string.

A: Explaining the error:
info is a [NSObject : Any] object. So it's a Dictionary which keys are NSObject object.
You do info[UIImagePickerControllerEditedImage], but UIImagePickerControllerEditedImage is a String, not a NSObject, so you can't do the subscript like this.
That's what is saying the error.
But that's not all, I suppose the Swift version you use is Swift 4, your method of UIImagePickerControllerDelegate shoudln't be called because it hasn't the good signature.
From the doc:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])

Not
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : Any])

Replace it with the one from the doc.

A: func imagePickerController(_ picker: UIImagePickerController,
      didFinishPickingMediaWithInfo info: [String : Any])

This method takes info as swift dictionary of type [String: Any], where the dictionary key is value type.
But you are passing the dictionary as [NSObject: Any], where the key is object or reference type. So basically you are passing wrong argument and also you can not change the delegate method signature of UIImagePickerControllerDelegate.


text:
Q: Displaying data from database in ListView I have this code in android that prints data from database to log.
List<Message> messages = db.getAllMessages();

for (Message mg : messages)
{
  String log = "Id: "+mg.getID()+", Message: " + mg.getMessage() + ", Time: " + mg.getDate();
  // display everything on log
  Log.d("", log);
}

How do I display it in a ListView instead of printing to log ?

A: First, create a list that you would store your values in if not already. For example:
private ArrayList<String> YOUR_LIST = new ArrayList<>();

Now, use this in an array adapter:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, YOUR_LIST);

Finally, set your adapter:
ListView listView = (ListView) findViewById(R.id.YOUR_LISTVIEW);
listView.setAdapter(adapter);

What you could do in your example, is something like this:
List<Message> messages = db.getAllMessages();
ArrayList<String> YOUR_LIST = new ArrayList<>();

for (Message mg : messages) {
    String log = "Id: " + mg.getID() + ", Message: " + mg.getMessage() + ", Time: " + mg.getDate();
    YOUR_LIST.add(log);
}

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, YOUR_LIST);

ListView listView = (ListView) findViewById(R.id.YOUR_LISTVIEW);
listView.setAdapter(adapter)


text:
Q: Parsing lines from a live streaming website in Python I'm trying to read in info that is constantly changing from a website.
For example, say I wanted to read in the artist name that is playing on an online radio site.
I can grab the current artist's name but when the song changes, the HTML updates itself and I've already opened the file via:
f = urllib.urlopen("SITE")
So I can't see the updated artist name for the new song.
Can I keep closing and opening the URL in a while(1) loop to get the updated HTML code or is there a better way to do this? Thanks!

A: You'll have to periodically re-download the website. Don't do it constantly because that will be too hard on the server.
This is because HTTP, by nature, is not a streaming protocol. Once you connect to the server, it expects you to throw an HTTP request at it, then it will throw an HTTP response back at you containing the page. If your initial request is keep-alive (default as of HTTP/1.1,) you can throw the same request again and get the page up to date.
What I'd recommend? Depending on your needs, get the page every n seconds, get the data you need. If the site provides an API, you can possibly capitalize on that. Also, if it's your own site, you might be able to implement comet-style Ajax over HTTP and get a true stream.
Also note if it's someone else's page, it's possible the site uses Ajax via Javascript to make it up to date; this means there's other requests causing the update and you may need to dissect the website to figure out what requests you need to make to get the data.

A: If you use urllib2 you can read the headers when you make the request. If the server sends back a "304 Not Modified" in the headers then the content hasn't changed.

A: Yes, this is correct approach. To get changes in web, you have to send new query each time. Live AJAX sites do exactly same internally.
Some sites provide additional API, including long polling. Look for documentation on the site or ask their developers whether there is some.


text:
Q: Finding which points are above or below threshold created with smooth.spline in R I'm working with a big dataset and had modelled the null distribution based on a subset of this big dataset. Now I have two thresholds, one upper and one lower thresholds, which are represented in a plot with smooth.lines function. I want to add all the points that are in original big dataset and pick up only those that falls above the upper threshold or the lower one.
I saw some questions that are related to this issue, but not really helped me.
The two smooth.splines are shown below with code used to generate it:
]
null=read.table('./FLK/FLK_missing25/envelope_missing25.txt',head=T)
attach(null)
plot(Ht,q0.005,xlim=c(0,0.5),ylim=c(0,80),type='l',col='gray',xlab='Heterozygosity',ylab='FLK statistic')
lines(smooth.spline(Ht,q0.995))
lines(smooth.spline(Ht,q0.005))
detach()

And after plotting all the original points to it:

points<-points(tests$Ht,tests$F.LK,pch=16, cex = 0.3)

So now I want to specifically choose those that are out of the bounds. In a previously, small dataset I manually did it using the identify() function, but now it's not viable.
Thank you for any help with this.
Sample of the data:
NULL DATA
    Ht q0.005 q0.995
0.00591439962121213 0.0470479532111184 2.50113629965976
0.0152043356973995 0.903847984179369 5.27712913495654
0.0247475329218107 1.10641288480299 8.38474123256296
0.0347981812865497 1.79379631237697 9.79551961929076
0.0447457820512821 1.50091253935435 13.5764489968702
0.0545112254521964 1.701442607667 14.716108081672
0.0647035527065527 1.8777834231014 19.7193011141249
0.0752057147315855 2.02703289299316 22.4056042334654
0.0853695647249191 2.55886670448224 26.3526825156905
0.0951034362745098 2.32581254159768 26.8590094714685
0.105249967013889 1.97512544742914 33.1975332778596
0.114477015605493 2.97238131961918 36.1521540009195
0.124979204031465 3.34075814389952 37.2515434121372
0.134785529320988 3.34714566225456 32.2932733505792
0.14490944879227 3.10226576305214 29.8338494464933
0.15506127420999 4.24950042259053 27.4185967884072
0.165180424133811 3.99191672611036 26.9666648107656
0.175250313459801 4.14044881633145 23.7361745813858
0.184953524875622 3.3261251322879 24.8595451578181
0.195661799033816 3.8585956628444 26.9607468892232
0.205136950292398 4.52812897956441 27.706304158175
0.21514489063867 4.47365964145688 28.3733660157821
0.224770744698897 3.46185120833234 23.3146767700615
0.235134508838384 4.20860691006497 25.2703736048277
0.245463810699588 5.25816733914855 24.4633123881128
0.254697365555556 5.01608789493179 22.436360164922
0.265263011937557 5.41045366008221 21.234603036848
0.274965869230769 4.57547849203251 22.123537129909
0.284762001736111 4.96960407757807 23.1453940270167
0.295016995780591 5.03463125959773 23.8167819631306
0.304919664888889 4.91088844199837 31.1948521499049
0.315003866394001 5.38422627088829 24.5116307178719
0.324648699845679 4.65914520212904 21.3910532375308
0.335376895143488 4.72500998773501 21.0712548679782
0.345309140503876 3.65292271944213 19.481764437033
0.355141738580247 4.87361431797648 19.7086186354089
0.36492435045045 3.3720338431453 21.1623708350575
0.374838788499025 4.42750819261774 22.4270755627995
0.384949760401371 6.32843488472143 19.4328206516264
0.394694700377562 6.13747955626477 21.0407091272595
0.405097673087661 5.92323768549744 20.0022002025301
0.415122219310036 7.04730509921557 19.838320586508
0.425285395264117 5.26585166530237 19.2312352201651
0.434997939814815 6.81458009465107 18.5690310892543
0.445171238970588 6.38590526021563 19.7545747503063
0.455201864718615 6.80826318124284 20.7346637551957
0.465409469306323 6.69008793893291 18.916645338847
0.475095361731458 6.82480379491385 19.2349327044628
0.485306814387211 6.4417087151098 19.1705016428993
0.496692359771218 6.50900360561522 18.5886408042256

SAMPLES OF 400 POINTS:
Ht F.LK
0.124444444444444 36.7500584428158
0.0349234567901235 7.68626952677946
0.095 13.9121809485979
0.0327777777777778 4.02670803483571
0.0327777777777778 4.02670803483571
0.316651234567901 18.1680720158939
0.0165277777777778 4.44427163440377
0.0165277777777778 2.40249815554879
0.0219753086419753 4.79410958577714
0.124444444444444 22.7267096656174
0.375 15.3610576981023
0.0165277777777778 4.64135741279412
0.0327777777777778 4.02670803483571
0.408027160493827 11.1592362583977
0.0327777777777778 4.82380608461891
0.0165277777777778 2.38147829746204
0.0165277777777778 2.38147829746204
0.0644444444444444 19.0408956498371
0 0
0.0176197530864198 4.04842613535931
0.04875 6.38514116317343
0.0644444444444444 9.08082795264823
0.0219753086419753 2.77731149495652
0.0165277777777778 4.64135741279412
0.095 12.4833417013004
0.0327777777777778 4.02670803483571
0.0165277777777778 4.69907933357134
0.0798611111111111 7.28613317182042
0.0219753086419753 2.96231029591765
0.21875 17.1896129695331
0.0165277777777778 2.07413566780096
0.0219753086419753 3.21314807835817
0.132108641975309 18.556113446321
0.18 14.2995388389357
0.424382716049383 14.8425335909128
0 0
0.0165277777777778 2.40211994735022
0.0327777777777778 4.85098786477187
0 0
0.0852997448979592 9.0349481226104
0.0373696145124717 3.50183528527322
0.0219753086419753 2.96231029591765
0.0327777777777778 4.4474073979159
0.124444444444444 16.9269546015968
0.235439231824417 13.7995627381987
0 0
0.0165277777777778 2.38147829746204
0.0592438271604938 5.21774915912316
0 0
0.0165277777777778 2.21267921892221
0.0165277777777778 2.40211994735022
0.293061111111111 16.517027637416
0.148132716049383 14.3827251495301
0.0219753086419753 2.96231029591765
0.0165277777777778 4.69907933357134
0.0849382716049383 19.6029386110943
0.39875 16.1698547005385
0.0132444444444444 3.3468904905399
0.0176197530864198 1.99690131691949
0.231111111111111 15.8361807587094
0.0434567901234568 6.40317107162842
0.258321995464853 16.1388383746647
0.0540123456790123 3.33523979403527
0.357777777777778 11.1009117328169
0.0644444444444444 9.72417962592817
0.0219753086419753 2.77731149495652
0.0327777777777778 4.8730619342236
0.0188662131519274 3.74952974929918
0.39875 19.6484754339051
0.339024417009602 16.3175265727668
0.124444444444444 23.3688865292886
0.0889777777777778 24.0226912089526
0.36995 14.8376551579362
0.0349234567901235 4.61414555275328
0.124444444444444 37.1525030700281
0 0
0.0849382716049383 24.0788597825384
0.0849382716049383 7.07229178174128
0.095 27.2056400197924
0.42 14.9657549617429
0.04875 7.32934570263806
0.0165277777777778 4.18793116296522
0.124444444444444 22.7267096656174
0.0165277777777778 2.38147829746204
0.455 16.2644703184679
0.0219753086419753 3.16274375984679
0.0165277777777778 2.40211994735022
0.406111111111111 14.9554868719022
0.0165277777777778 2.07413566780096
0.0219753086419753 3.63621960105724
0.0190458579881657 3.44986705436526
0.04875 6.804404278778
0.124444444444444 22.7267096656174
0.0798611111111111 11.6322074035758
0.0327777777777778 9.32483341411409
0.04875 7.4146254695531
0.0234227709190672 3.05975064289059
0.316426886145405 15.5636064013468
0.0165277777777778 4.64135741279412
0.0176197530864198 2.25323038510266
0.124444444444444 29.8469556711493
0.104938271604938 6.76940759330798
0.143456790123457 13.5781524622378
0.0747530864197531 5.37493552245388
0.0132444444444444 3.3468904905399
0.0219753086419753 2.96231029591765
0.483194444444444 15.0706194040885
0.0165277777777778 4.39209176720576
0.274058641975309 16.5756978747446
0.0327777777777778 4.85098786477187
0.295910493827161 13.6609425469527
0.0165277777777778 2.40249815554879
0.0132444444444444 3.3468904905399
0.04875 6.804404278778
0.0176197530864198 2.28360196351557
0.0349234567901235 3.1531925641648
0.0014803840877915 0.208488814916637
0.0219753086419753 6.27439399313949
0.0219753086419753 4.79410958577714
0.0349234567901235 4.2171295869503
0.0165277777777778 4.69907933357134
0.0327777777777778 9.43857115397289
0.132108641975309 21.5018400019892
0.0219753086419753 3.21831506149061
0.472777777777778 11.3832414981619
0.0165277777777778 2.40211994735022
0.0644444444444444 18.8204554463659
0.104938271604938 16.6202701829041
0.0219753086419753 3.16274375984679
0.124444444444444 19.3579825254014
0.0176197530864198 4.10328828108007
0.0219753086419753 3.21314807835817
0.0165277777777778 2.38147829746204
0.0462836762688615 10.8871162342715
0.0327777777777778 4.20181588220052
0.119808 28.0423119358955
0.141577777777778 10.3947265408058
0.0849382716049383 13.6388393237215
0.0219753086419753 3.63621960105724
0.0327777777777778 4.4474073979159
0.095 13.9121809485979
0.0798611111111111 22.7814003533669
0.0434567901234568 6.40317107162842
0 0
0 0
0.04875 7.4146254695531
0.0165277777777778 2.40211994735022
0.124444444444444 20.8970552010047
0.04875 13.3436423633028
0.0327777777777778 4.20181588220052
0.0165277777777778 4.44427163440377
0.451604938271605 14.2580434675109
0.0165277777777778 2.07413566780096
0.04875 6.38514116317343
0.0165277777777778 4.69907933357134
0.388503086419753 12.024032362231
0.0165277777777778 2.07413566780096
0.0165277777777778 2.21267921892221
0.104938271604938 17.3933460851521
0.489795918367347 2.6885312137628
0 0
0.449861111111111 17.8013216714898
0.0798611111111111 8.12520300770917
0.0165277777777778 4.39209176720576
0.143456790123457 9.55416885361777
0.0327777777777778 4.4474073979159
0.0165277777777778 2.40211994735022
0.49395 17.2286473899574
0.0165277777777778 4.69907933357134
0.0434567901234568 7.33110895561598
0.109861111111111 8.49079906480581
0.0219753086419753 2.96231029591765
0.0644444444444444 8.62632335592837
0.0165277777777778 2.21267921892221
0.487021604938272 13.2551758042932
0.0165277777777778 2.07413566780096
0.095 27.2056400197924
0.124444444444444 15.6712952124286
0.0165277777777778 2.21267921892221
0.309861111111111 16.0122904428983
0.0644444444444444 8.18561561753904
0.274058641975309 12.0694901513446
0.32 16.4164943866946
0.193194444444444 14.7250995621834
0.0219753086419753 2.96231029591765
0.0219753086419753 5.59353033970332
0.0327777777777778 8.94350852495432
0 0
0.124444444444444 20.2019151572928
0.277777777777778 13.4006745238862
0.464444444444444 11.0681987513934
0.0219753086419753 3.21831506149061
0.0165277777777778 4.44427163440377
0.495 11.7232625589786
0.0165277777777778 2.40249815554879
0 0
0.0327777777777778 4.02670803483571
0 0
0.124444444444444 16.9269546015968
0.0798611111111111 22.5255266189454
0.193194444444444 11.4014772624059
0.0132444444444444 3.3468904905399
0.0327777777777778 4.82380608461891
0.04875 3.56314021068146
0.0462836762688615 5.82756031662101
0.357777777777778 14.0247153884293
0.124444444444444 16.9269546015968
0 0
0.0219753086419753 6.27439399313949
0.0219753086419753 4.79410958577714
0.493194444444444 10.504634730485
0.0434567901234568 6.5593607362431
0.0219753086419753 3.16274375984679
0.0165277777777778 2.21267921892221
0.0327777777777778 4.82380608461891
0.0732879818594104 7.57979262928242
0.0165277777777778 2.40249815554879
0.255 11.6765957622922
0.0176197530864198 2.30009872451987
0.0327777777777778 4.02670803483571
0.0219753086419753 6.27439399313949
0.0644444444444444 9.89453455906778
0.266527777777778 13.6197851546911
0.0165277777777778 2.40211994735022
0.100977777777778 27.5711004179377
0.0644444444444444 18.8204554463659
0.0327777777777778 8.41931161938731
0.193194444444444 16.6198637338073
0.193194444444444 19.7385825307107
0.0434567901234568 7.33110895561598
0.0165277777777778 2.38147829746204
0.0434567901234568 6.5593607362431
0.0165277777777778 2.07413566780096
0.0392 10.1241813815794
0.0327777777777778 8.94350852495432
0.0219753086419753 3.16274375984679
0.206111111111111 10.7701153093882
0.0165277777777778 4.39209176720576
0.231111111111111 15.8361807587094
0.0219753086419753 6.27439399313949
0.0327777777777778 4.82380608461891
0.0219753086419753 4.79410958577714
0.095 27.2056400197924
0.0219753086419753 3.63621960105724
0.0165277777777778 4.64135741279412
0 0
0.0165277777777778 2.38147829746204
0 0
0.0219753086419753 5.86839006118109
0.0165277777777778 2.40249815554879
0.0165277777777778 2.38147829746204
0.13875 8.83478779181092
0.0165277777777778 4.64135741279412
0.0165277777777778 2.40249815554879
0.0165277777777778 4.69907933357134
0.0327777777777778 4.20181588220052
0.0219753086419753 3.18871230960838
0.0165277777777778 2.38147829746204
0.451604938271605 10.3016606110791
0.428641975308642 14.1709573991617
0.0798611111111111 22.7814003533669
0.04875 7.32934570263806
0.0519111111111111 7.18588289074698
0.0327777777777778 4.8730619342236
0 0
0.326604938271605 13.6925832569272
0.0644444444444444 10.0302939975709
0.0132444444444444 3.3468904905399
0 0
0.0327777777777778 4.48012764852979
0.0644444444444444 4.25757204398404
0.124444444444444 16.9269546015968
0 0
0.124444444444444 11.8966041620809
0.0176197530864198 2.24670145143038
0.302947530864198 15.647557284147
0.0165277777777778 2.38147829746204
0.0165277777777778 2.40211994735022
0.472777777777778 21.6545151604864
0.0219753086419753 2.96231029591765
0.0219753086419753 4.79410958577714
0.104938271604938 14.9037953666261
0.0165277777777778 2.40249815554879
0.0219753086419753 6.27439399313949
0.0165277777777778 2.40211994735022
0.124444444444444 38.7541517402647
0.095 14.140401856445
0.13875 22.2923964937516
0.458271604938272 11.4277070501224
0.0327777777777778 4.4474073979159
0.197530864197531 11.9942366204454
0.391111111111111 19.9433036596453
0.0644444444444444 8.62632335592837
0.0165277777777778 4.64135741279412
0.0014803840877915 0.19386782953831
0.0165277777777778 2.40249815554879
0.18 13.0718970161537
0.0327777777777778 4.02670803483571
0.0165277777777778 2.40249815554879
0.0644444444444444 10.0302939975709
0.0644444444444444 8.18561561753904
0.0219753086419753 4.79410958577714
0.0327777777777778 4.85098786477187
0.0644444444444444 17.9052407023711
0 0
0.0176197530864198 4.27297510503453
0.0219753086419753 3.16274375984679
0 0
0.0165277777777778 4.69907933357134
0.0219753086419753 3.16274375984679
0.0219753086419753 4.79410958577714
0.095 12.4833417013004
0.0849382716049383 14.9026698258922
0 0
0.18 14.1143183366686
0.0165277777777778 4.69907933357134
0.124444444444444 18.9544262421443
0.0165277777777778 2.38147829746204
0.124444444444444 19.3579825254014
0.095 13.9121809485979
0.095 28.8112723065338
0.109861111111111 11.6589142293783
0.0165277777777778 2.21267921892221
0.124444444444444 22.7267096656174
0.0644444444444444 9.90058337915599
0.0165277777777778 4.64135741279412
0.0165277777777778 4.64135741279412
0.095 7.61134574637366
0.406111111111111 11.774577707447
0.0519111111111111 6.99859311140469
0.04875 7.32934570263806
0.493194444444444 15.3312617641375
0 0
0.495 14.9338542232795
0.18 13.2478860417367
0.0165277777777778 4.44427163440377
0.0165277777777778 4.44427163440377
0.0219753086419753 6.27439399313949
0.124444444444444 18.2181906541074
0.0165277777777778 2.07413566780096
0.0798611111111111 11.6322074035758
0.0327777777777778 4.82380608461891
0.0462836762688615 6.18972392803396
0.0165277777777778 2.40249815554879
0 0
0.0165277777777778 2.40249815554879
0.0519111111111111 3.17830618816259
0.124444444444444 16.9269546015968
0.0219753086419753 3.18871230960838
0.0644444444444444 9.08082795264822
0 0
0.0327777777777778 4.02670803483571
0 0
0.24399012345679 17.8565540311217
0.095 15.1423376148871
0.499938271604938 16.1602588277824
0.35265306122449 13.7374609889186
0.0165277777777778 4.69907933357134
0.0327777777777778 4.48012764852979
0.0327777777777778 4.4474073979159
0.46141975308642 12.3837914568937
0.0219753086419753 3.16274375984679
0.277777777777778 13.9541603218533
0.118644444444444 8.51767581949589
0.0219753086419753 5.86839006118109
0.04875 7.4146254695531
0.0165277777777778 2.40211994735022
0 0
0.0327777777777778 4.4474073979159
0.0165277777777778 4.69907933357134
0.302249382716049 17.6464696415598
0.124444444444444 16.9269546015968
0 0
0.0176197530864198 4.27068975182888
0.0327777777777778 4.20181588220052
0.476527777777778 17.9889760853764
0.0327777777777778 4.85098786477187
0.0165277777777778 2.40211994735022
0.0327777777777778 4.20181588220052
0.04875 6.804404278778
0.0234227709190672 3.04032675868852
0.0165277777777778 2.07413566780096
0.0434567901234568 6.40317107162842
0.0165277777777778 2.07413566780096
0.494429012345679 11.7189833713657
0.0165277777777778 2.38147829746204
0.255 18.3064046174448
0.24399012345679 14.1721617969582
0.391111111111111 12.0438089335106
0.383194444444445 12.6438502507037
0.04875 7.4146254695531
0.124444444444444 22.7267096656174
0.496527777777778 13.1939316331812
0.366527777777778 19.4450595714789
0.124444444444444 37.1525030700281
0 0
0.0327777777777778 4.4474073979159
0.0327777777777778 4.48012764852979
0.0462836762688615 11.3471579553117
0.48875 17.0368364232462

PS.: I improved the null model and now it's much more accurate.
PS.2: Added the values of upper and lower bounds and a small sample of points as suggested. Sorry if it become too long.

A: smooth.spline saves a list you can merge with your data:
ssH <- smooth.spline(null$Ht, null$q0.995)
ssL <- smooth.spline(null$Ht, null$q0.005)
tests <- merge(tests, data.frame(Ht = ssH$x, F.LK0.995 = ssH$y), by = "Ht")
tests <- merge(tests, data.frame(Ht = ssL$x, F.LK0.005 = ssL$y), by = "Ht")

Then tests[tests$F.LK > tests$F.LK0.0995 | tests$F.LK < tests$F.LK0.005, ] are out of bounds
P.S. don't use attach - detach and null is a terrible data name


text:
Q: Instana monitoring inside docker swarm cluster? I'm trying to monitor a springboot microservice with instana on a docker swarm cluster. the Microservice has 2 replicas per node on a 3 nodes cluster. it is possible? do i need to run instana agent image with docker run? docker service? any help will be appreciate.
Thanks

A: Hey I know the post it's pretty old but I wondering if you have tried to installing instana on Docker if NOT please do follow this documentation : Instana Docker
I hope that will help achieve the above you already mentioned.


text:
Q: Bayes estimator with k-letter alphabet? I have a set of $n$ realizations $y_j \in \{a,b,c,...\}$ in an alphabet with $k$ symbols.
Each letter from this alphabet has an unknown prior probability $x_i$. The goal is to estimate $\mathbb{x}$ from the observations $\mathbb{y}$ so as to minimize the mean square error.
I assume the probabilities $x_i$ follow a uniform distribution, with the constraint that $\sum_{i}{x_i}=1$.
I already know that the case where the alphabet has only two letters is called the bayes estimator with beta prior, which has well-known solutions. However, I'm at loss for the more general case with $k$ letters.
Any insight?

A: Turns out @jerad was right: the problem works out very nicely with a Dirichlet prior distribution. This pdf answers the question in-depth.
In the end, with a uniform prior distribution, the minimum mean square estimator is:
$p_i = \frac{n_j+1}{n+k}$
Where $n_j$ is the number of times the j-eth symbol has been observed.


text:
Q: Persist javascript variables across pages? Is there a way we can persist javascript variables across various pages? Suppose in Page A I am setting window.someVar = 5. Then I move to Page B, via clicking a hyperlink in A, and do something like alert(window.someVar) -- I should get a message box displaying 5. Is there a technique to persist someVar as such...?

A: You can persist values using HTML5 storage, Flash Storage, or Gears. The dojo storage library provides a nice wrapper for this.

A: I recommend web storage. Example:
// Storing the data:
localStorage.setItem("variableName","Text");
// Receiving the data:
localStorage.getItem("variableName");
Just replace variable with your variable name and text with what you want to store. According to W3Schools, it's better than cookies.

A: For completeness, also look into the local storage capabilities & sessionStorage of HTML5. These are supported in the latest versions of all modern browsers, and are much easier to use and less fiddly than cookies.
http://www.w3.org/TR/2009/WD-webstorage-20091222/
https://www.w3.org/TR/webstorage/. (second edition)
Here are some sample code for setting and getting the values using sessionStorage and localStorage :
 // HTML5 session Storage
 sessionStorage.setItem("variableName","test");
 sessionStorage.getItem("variableName");

//HTML5 local storage
localStorage.setItem("variableName","Text");
// Receiving the data:
localStorage.getItem("variableName");

A: I would recommend you to give a look to this library:

*

*PersistJS
I really like it, it supports a variety of storage backends (from cookies to HTML5 storage, Gears, Flash, and more...), its usage is really transparent, you don't have to know or care which backend is used the library will choose the right storage backend depending on the browser capabilities.

A: Yes, using Cookies. But be careful, don't put too much in them (I think there is a limit at 4kb). But a few variables are ok.
If you need to store considerably more than that, check out @Annie's great tips in the other answer. For small time data storage, I would say Cookies are the easiest thing.
Note that cookies are stored client side.

A: You could use the window's name window.name to store the information. This is known as JavaScript session. But it only works as long as the same window/tab is used.


text:
Q: Determine if undirected graph is connected I came across this posting from a while back:
Best algorithm to determine if an undirected graph is a tree
It says that to determine if an undirected graph is a tree, you just have to check if it has a cycle.  However, don't you have to make sure the graph is connected? I was taught that a tree is connected and acyclic.  How is checking only for acyclicity sufficient?
Thanks.

A: You're right. If the graph is acyclic, then it's a forest. In addition, if it only has one component, then it's a tree.
What the algorithm mentioned does is look for back edges. If it finds one, then the graph is not a tree. If it doesn't find one and the algorithm visited n-1 edges before running out of edges, then it IS a tree, because having visited n-1 edges means that the graph is indeed connected (a tree with n vertices has n-1 edges). If the algorithm ran out of edges but didn't reach n-1 visited edges, then it means the graph is not connected, hence it is not a tree.


text:
Q: How to import specs library How do I import specs library? I get the following error:
scala> import org.specs._
<console>:11: error: object specs is not a member of packa
ge org
       import org.specs._
              ^

I think it has to do with classpath, but I don't know how to fix it because I am new to scala.
In fact, I am actually trying to run tests in sbt, so it would be helpful if you could tell me how to import specs in sbt.

A: Your build.sbt should include
libraryDependencies ++= {
  Seq(
    "org.specs2"        %% "specs2"             % "2.3.12"             %    "test"
 )
}

and in your test.scala
import org.specs2.mutable.Specification

class PlayerTest extends Specification {

   // test code here
}

A: Just add the dependency in build.sbt and compile it again then you can import spec2.


text:
Q: Proper way to "spawn" game objects. (I want to spawn projectiles) Hey all I made the following class to act as "bullets" in my game and I don't know how to construct these bullet objects with the params that I want (determined at runtime) and spawn them in the game.
My first attempt looked like this:
 if (canShoot())
        {
            shotCoolDown = FRAMES_BETWEEN_SHOTS;
            Bullet bullet = new Bullet().setLoft(LOFT).setWobble(WOBBLE).setInitialVel(INITIAL_VEL).setDirectionOffset(internalRecoil.getRecoil());
        }

but i get the following warnign from the unity editor:
You are trying to create a MonoBehaviour using the 'new' keyword.  This is not allowed.  MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all
What is the proper way to spawn these bullets and to set the fields as I want them?
For more info here is the bullet class
 public class Bullet : MonoBehaviour
{
    private Rigidbody rigidbody;
    private float wobble;
    private float loft;
    private float initialVel;
    private Vector2 initialDirectionOffset;
    private bool wobbleDirection = false;

    private void Awake()
    {
        this.rigidbody = this.GetComponent<Rigidbody>();
    }

    private void Start()
    {
        transform.Rotate(initialDirectionOffset);
        rigidbody.AddForce(initialVel*transform.forward);
        rigidbody.AddForce(loft*transform.up);
    }

    private void FixedUpdate()
    {
        if (wobbleDirection)
        {
            rigidbody.AddForce(transform.right * wobble);
            wobbleDirection = false;
        }
        else
        {
            rigidbody.AddForce(-transform.right * wobble);
            wobbleDirection = true;
        }
    }

    public Bullet setWobble(float wobble)
    {
        this.wobble = wobble;
        return this;
    }

    public Bullet setLoft(float loft)
    {
        this.loft = loft;
        return this;
    }

    public Bullet setInitialVel(float initialVel)
    {
        this.initialVel = initialVel;
        return this;
    }

    public Bullet setDirectionOffset(Vector2 offset)
    {
        this.initialDirectionOffset = offset;
        return this;
    }
}

For more info here is the full "gun" class that spawns the bullets.
public class Gun : MonoBehaviour
{
    private int FRAMES_BETWEEN_SHOTS = 10;
    private int shotCoolDown = 0;
    private const float LOFT = 100F;
    private const float WOBBLE = 100F;
    private const float INITIAL_VEL = 100F;
    private Vector3 directionOffset;
    private Recoil internalRecoil;

    private void Awake()
    {
        internalRecoil = this.GetComponent<Recoil>();
        if (internalRecoil == null)
        {
            throw new Exception("Could not find recoil component");
        }
    }

    private void FixedUpdate()
    {
        if (shotCoolDown > 0)
        {
            shotCoolDown--;
        }
    }

    private bool canShoot()
    {
        return shotCoolDown == 0;
    }

    public void performShoot()
    {
        if (canShoot())
        {
            //need to have a recoil component that reacts to bullet fire. then adjusts back to 0,0,0
            shotCoolDown = FRAMES_BETWEEN_SHOTS;
            Bullet bullet = new Bullet().setLoft(LOFT).setWobble(WOBBLE).setInitialVel(INITIAL_VEL).setDirectionOffset(internalRecoil.getRecoil());
        }
    }
}

My second attempt looks like:
 GameObject.Instantiate(new Bullet().setLoft(LOFT).setWobble(WOBBLE).setInitialVel(INITIAL_VEL)
                .setDirectionOffset(internalRecoil.getRecoil()));

is this the right way to do it???

A: As 3Dave mentioned, the best way to do this would be to instantiate a prefab. Assuming you will be dealing with multiple projectiles, I like to separate this into a utility function for instantiating prefabs at a given position.
public static class UnityUtil {

    public static GameObject instantiatePrefab(
        Object prefab,
        Vector3 position,
        Transform? parent = null
    ){
        // Create an instance of the prefab
        GameObject instance = Object.Instantiate(prefab, position, Quaternion.identity) as GameObject;

        // Set the parent
       if(parent != null){
          instance.transform.parent = parent;
       }

       return instance;
    }

}

Then you could have code like
Transform projectileHolder;
GameObject myBulletPrefab;
Vector3 bulletPosition;

...setup variables...

var BulletGameObj = UnityUtil.instantiatePrefab(myBulletPrefab, bulletPosition, projectileHolder);
Bullet bullet = BulletGameObj.GetComponent<Bullet>();

I keep some other functions in my util for dealing with generic gameobject cases, you can see my full UnityUtil class here


text:
Q: mod_fcgid: stderr: PHP Warning: simplexml_load_string() Can someone tell me what is the reason I get this warnings all the time?
simplexml_load_string(): Entity: line 3: parser error :  xmlParseEntityRef: no name in /var/www/..line 50

mod_fcgid: stderr: PHP Warning:  simplexml_load_string(): <titel>Shiatsu ..on line 50

mod_fcgid: stderr: PHP Warning: simplexml_load_string():                          ^ in ... on line 50

mod_fcgid: stderr: PHP Notice:  Trying to get property of non-object in .. on
I do a simple:
$var= simplexml_load_string($xml);

on that line..


text:
Q: How to use a DN containing commas as the attribute value in an LDAP search filter? Was attempting to search our directory based on an attribute whose value is a DN. However, our user RDNs are of the form CN=Surname, GivenName, which requires that the comma be quoted in the full DN. But given an attribute like manager whose value is the DN of another user, I was unable to search for all users having specific manager. I tried (manager=CN=Surname\, GivenName,CN=users,DC=mydomain,DC=com), but got a syntax error "Bad search filter". I tried various options for quoting the DN, but all either gave me a syntax error or failed to match any objects. What am I doing wrong?
(Note that if I were looking for user objects directly, I could search for simply (CN=Surname, GivenName), with no quoting required, but I was searching for users having a specific manager. The comma-containing attribute value only becomes a problem when part of a Distinguished Name.)

A: The problem is that quoting the comma in the Common Name is not for the benefit of the filter parser, but for the benefit of the DN parser; the attribute value passed to that by the filter has to literally contain the backslash character. Unfortunately, the backslash is also (differently) special in LDAP filters, thus the syntax errors.
The solution is simple, but it isn't as obvious as doubling the backslash; backslash in LDAP filters works like % in URIs, so you have to use a literal backslash followed by the 2-digit hexadecimal code point for a backslash:
(manager=CN=Surname\5c, Givenname,OU=org,DC=mydomain,DC=com)

It turns out there's an example of this specific use case at the very bottom of https://docs.oracle.com/cd/E19424-01/820-4811/gdxpo/index.html#6ng8i269q.


text:
Q: Calculated Columns in MySQL I have a table that has two fields (latitude and longitude).
I also have a script that gets the users current latitude and longitude.
I want to get all the rows from the table that are <= 50Km from the users location.
Calculating the distance is not a problem.
My question is how do I restrict unwanted rows in my search result using mysql?
$currentLatitude = 10.999;
$currentLongitude = 23.354;

MYSQL
$this->db->select('latitude, longitude');
$this->db->from('table');
//This is where I have a problem
$this->db->where('distance <=',  50km);

$result = $this->db->get()


text:
Q: Applying and Creating Multiple Views For GridViewLayout Im attempting to add two different views to the GridviewLayoutManager using a custom adapter.
However, I cant seem to reference the headerview correctly. When the onbindViewHolder is called it is expecting a "ViewHolder" response, however i really want to reference the HeaderView i crated
Because I cant access the correct view, I also cant reference the TextView within the XML layout I am calling.
here is my customer adaptor class:
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import java.util.ArrayList;

public class ElementsAdapter extends RecyclerView.Adapter<ElementsAdapter.ViewHolder> {
    private ArrayList<String> mDataset;
    private ArrayList<Integer> mDatamap;

public Context context;

    private static final int VIEW_HEADER = 0;
    private static final int VIEW_NORMAL = 1;

    private View headerView;
    private int datasetSize;

    public class HeaderHolder extends RecyclerView.ViewHolder {
        // each data item is just a string in this case
        public TextView headertext;

        public HeaderHolder(View v) {
            super(v);
            headertext = (TextView) v.findViewById(R.id.headertext);
        }
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        // each data item is just a string in this case
        public TextView txtHeader;
        public TextView txtFooter;
        public ImageView imgImage;

        public ViewHolder(View v) {
            super(v);
            txtHeader = (TextView) v.findViewById(R.id.firstLine);
            txtFooter = (TextView) v.findViewById(R.id.secondLine);
            imgImage = (ImageView) v.findViewById(R.id.icon);
        }

    }

    public ElementsAdapter(ArrayList<String> myDataset, ArrayList<Integer> myDatamap) {
        mDataset = myDataset;
        myDatamap = mDatamap;
    }

      @Override
    public int getItemViewType(int position) {
        return isHeader(position) == 1 ? VIEW_HEADER : VIEW_NORMAL;
    }

    @Override
    public int getItemCount() {
        return mDataset.size();
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == VIEW_HEADER) {
            // create a new view
            View sub_view = LayoutInflater.from(parent.getContext()).inflate(R.layout.header, parent, false);

            Context context = sub_view.getContext();

            // set the view's size, margins, paddings and layout parameters
            ViewHolder vh = new ViewHolder(sub_view);

            return vh;

//            return new HeaderViewHolder(headerView);

        } else {
            // create a new view
            View sub_view = LayoutInflater.from(parent.getContext()).inflate(R.layout.sub_layout, parent, false);

            context = sub_view.getContext();

            // set the view's size, margins, paddings and layout parameters
            ViewHolder vh = new ViewHolder(sub_view);

            return vh;

        }
    }

    @Override
    public void onBindViewHolder(ViewHolder viewHolder, int position) {
        if (isHeader(position) == 1) {

            // - get element from your dataset at this position
            // - replace the contents of the view with that element
            final String name = mDataset.get(position);

//        holder.txtHeader.setText(mDataset.get(position));
            viewHolder.headertext.setText(name);

        } else {

    // - get element from your dataset at this position
    // - replace the contents of the view with that element
    final String name = mDataset.get(position);

    Picasso.with(context).load("http://www.500kgiveaway.co.uk/"+name).resize(200,200).into(viewHolder.imgImage);

//        holder.txtHeader.setText(mDataset.get(position));
    viewHolder.txtHeader.setText(name);

    viewHolder.txtHeader.setOnClickListener(new View.OnClickListener()

    {
        @Override
        public void onClick (View v){
        //remove(name);
    }
    }

    );

    viewHolder.txtFooter.setText("Footer: "+mDataset.get(position));
}

        //ViewHolder holder = (ViewHolder) viewHolder;
        //holder.textView.setText("Position " + (position - 1));
    }

    public int isHeader(int position) {
        return mDatamap.get(position) ==1 ? 1:0;}
}

A: It seems to me that the isHeader() method will always return 0, since you compare a String with a integer. I assume you would like want to check the position of the current item to be 1.
Try this code instead:
public boolean isHeader(int position) {
    return position == 1;
}

Then replace
if (isHeader(position) == 1)...

with
if (isHeader(position))...

I hope this helps.
Edit
The above was intended. Sorry.
In the class definition ElementsAdapter.ViewHolder is inserted as the ViewHolder type. This works for the normal
ElementsAdapter.ViewHolder extends RecyclerView.ViewHolder

but not for
ElementsAdapter.HeaderHolder extends RecyclerView.ViewHolder

since it doesn't extend ElementsAdapter.ViewHolder.
You should therfore specify RecyclerView.ViewHolder instead as a generic type to support both of your types.


text:
Q: No wireless connection on new install Okay guys. I know that these problems can get super specific and I've looked around at questions with similar problems and I'm just not finding it.
I am brand spanking new to Linux. Keep that in mind.
I have a dual boot MacBook Pro that I just got done with yesterday. At first, the wireless connection was fine, but today I started having problems. I know it's not a hardware issue with the laptop itself as I am typing this and asking this using OS X right now. Anywho, the trouble is that whenever I boot Ubuntu (14.04), the wireless connection works for probably five or ten minutes. It gets super slow. And then it dies all together. The icon indicator for the wireless connection still says that I'm connected this whole time, but nothing loads and I'm at a loss.
Help?
Thanks in advance.


text:
Q: What is the most efficient way to subtract/add the "zone diff time" from/to the LocalDateTime in java 8 My client is sitting in other Zone. On UI there is way to search by DateRange (start and end date).
Client sends start and end date in String form. eg -> startDate = "DD/MM/YYYY", endDate = "DD/MM/YYYY".
Server converts dates to searchStartDate = "DD/MM/YYYY 00:00:01" and searchEndDate = "DD/MM/YYYY 23:59:59". But before searching in DB I need to add "zone time difference" in these searchStartDate and searchEndDate.
Different clients are sitting in different zones. How do we add/subtract the zone diff time using java 8 APIs?
eg - my server is running in UTC. and Client sitting in IST. I will subtract 5H:30M from both searchStartDate and searchEndDate before searching into DB.
What I have - LocalDateTime searchStartDate and searchEndDate. What I want searchStartDate = searchStartDate.plus(<UtcIstTimeZoneDiff>).
Edit - Server knows the timeZone of every client.

A:     DateTimeFormatter searchDateFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");
    ZoneId clientZone = ZoneId.of("Asia/Colombo");
    String startDate = "29/01/2018";
    String endDate = "04/02/2018";

    Instant searchStartTime = LocalDate.parse(startDate, searchDateFormatter)
            .atStartOfDay(clientZone)
            .toInstant();
    Instant searchEndTime = LocalDate.parse(endDate, searchDateFormatter)
            .plusDays(1)
            .atStartOfDay(clientZone)
            .toInstant();

    System.out.println("" + searchStartTime + " inclusive to "
                        + searchEndTime + " exclusive");

This example prints
2018-01-28T18:30:00Z inclusive to 2018-02-04T18:30:00Z exclusive

Use a half-open interval: Instead of trying to decide the last clock hour in a day and consider whether you want how many decimals on the seconds, it's better to set the search end time to the first moment of the following day and then just only retrieve records that come strictly before that time.
I am giving you start and end times as Instants. Most JDBC drivers are happy to use them, and I consider it an advantage that they inherently represent points on the timeline, which is what you need them for. If for your search you do need LocalDateTime, here's a way to obtain one:
    LocalDateTime searchStartTime = LocalDate.parse(startDate, searchDateFormatter)
            .atStartOfDay(clientZone)
            .toOffsetDateTime()
            .withOffsetSameInstant(ZoneOffset.UTC)
            .toLocalDateTime();

The search end time case is similar.

A: There's not much to do since you are already storing all date/time entries in UTC, and you know the client's time zone. All you need to do is convert UTC date/time to/from the client's time zone. Use ZonedDateTime.withZoneSameInstant() for that:

Returns a copy of this date-time with a different time-zone, retaining
  the instant. This method changes the time-zone and retains the
  instant. This normally results in a change to the local date-time.

Here's some sample code for converting from UTC to IST:
public class Main {

    public static void main(String[] args) {

        // Get some arbitrary UTC value for the search start date (regardless of caller's time zone).
        // Note that the zone ID for UTC is "Z".
        ZonedDateTime utcSearchStartDate = ZonedDateTime.now(ZoneOffset.UTC);

        // Convert the UTC date/time to the target time zone.
        ZoneId clientZone = Main.getClientZoneId();
        ZonedDateTime adjustedSearchStartDate = utcSearchStartDate.withZoneSameInstant(clientZone);

        System.out.println("Current date/time for " + utcSearchStartDate.getZone().getId() +  " = " + utcSearchStartDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss")));
        System.out.println("Current date/time for " + adjustedSearchStartDate.getZone().getId() +  " = " + adjustedSearchStartDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss")));
    }

    // Your logic to get the actual ZoneID of the client goes in this method.
    static ZoneId getClientZoneId() {

        return ZoneId.of("Asia/Kolkata"); // For example...
    }
}

The output from running that code is shown below, where the date/time for IST has been adjusted by +5:30:
Current date/time for Z = 2018-02-21 06:09:19
Current date/time for Asia/Kolkata = 2018-02-21 11:39:19


text:
Q: Firma SOAP en PHP con certificado digital Al final, antes de tirar la toalla o de volverme definitivamente loca recurro a vosotros para ver si algún alma caritativa me puede echar un cable.
Antes de que se me pase trato de hacer la conexión desde PHP y decir que llevo googleando y probando desde hace un par de meses y no consigo sacar nada en claro, hay alguna pregunta parecida a esta pero sin respuesta, traté con varias rutinas pero sin éxito.
El tema en cuestión es comunicar a al Ministerio de Fomento de España los traslados (viajes) que está previsto realizar en los próximos días por medio de un procedimiento SOAP.
Para poder operar con ellos hay que enviarles un correo a la dirección registrovtc@fomento.es, indicando en el asunto "ALTA REGISTRO VTC" con la siguiente información:

*

*NIF de la entidad (persona jurídica) que va a realizar las comunicaciones

*Razón social de la entidad que va a realizar las comunicaciones

*Número de serie ("SERIALNUMBER") del certificado utilizado para las comunicaciones

*Entorno en el que se solicita el alta (INTEGRACIÓN y/o PRODUCCIÓN)

*Dirección (o rango) IP desde la que se realiza la conexión (sólo en caso de solicitar alta en el entorno de integración)

*Adjuntar  al correo una copia de la parte pública del certificado que se utilizará para la comunicación de servicios, de forma que se pueda comprobar que la información suministrada es correcta y comprobar que es reconocido correctamente por el Registro.

La información que facilitan para la especificación de la firma electrónica es la siguiente:
Las llamadas al servicio web deberán implementar el estándar "Web Services Security" (WS-Security), garantizando la autenticidad e integridad de los datos remitidos. La confidencialidad se garantizará al utilizarse HTTPS como protocolo de transporte.
Los mensajes deberán firmarse con un certificado de entidad único para cada entidad (persona jurídica) autorizada.
El mensaje SOAP se enviará junto con los datos de firma digital XML y un BinarySecurityToken que contenga la parte pública del certificado utilizado.
Se muestra a continuación un ejemplo de petición SOAP, con el nodo de firma WS-Security:
    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:vtc="http://mfom.com/vtc">
    <soapenv:Header>
   <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
    <wsse:BinarySecurityToken EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3" wsu:Id="X509-8E8323448EEC46F5B41559339975629101">MIIGoDCC……………..……UNAD/Mif8A=</wsse:BinarySecurityToken>
<ds:Signature Id="SIG-8E8323448EEC46F5B41559339975632105" xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<ds:SignedInfo>
<ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"><ec:InclusiveNamespaces PrefixList="soapenv vtc" xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#"/></ds:CanonicalizationMethod><ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/><ds:Reference URI="#id-8E8323448EEC46F5B41559339975630104"><ds:Transforms><ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"><ec:InclusiveNamespaces PrefixList="vtc" xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#"/></ds:Transform></ds:Transforms><ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/><ds:DigestValue>cf2SHSHaZhYkbe6ypSbJAT+FsLM=</ds:DigestValue></ds:Reference></ds:SignedInfo><ds:SignatureValue>dvxXH………………...ctviyCg==</ds:SignatureValue><ds:KeyInfo Id="KI-8E8323448EEC46F5B41559339975629102"><wsse:SecurityTokenReference wsu:Id="STR-8E8323448EEC46F5B41559339975629103"><wsse:Reference URI="#X509-8E8323448EEC46F5B41559339975629101" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3"/></wsse:SecurityTokenReference></ds:KeyInfo></ds:Signature></wsse:Security></soapenv:Header>
    <soapenv:Body wsu:Id="id-8E8323448EEC46F5B41559339975630104" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
    <vtc:qaltavtc>
    <header fecha="2019-01-01T12:29:00" version="1.0" versionsender="1.0"/>
    <body>
    <vtcservicio cgmunicontrato="079" cgmunifin="079" cgmuniinicio="079" cgmunilejano="079" cgprovcontrato="28" cgprovfin="28" cgprovinicio="28" cgprovlejano="28" direccionfin="destino" direccioninicio="origen" direccionlejano="lejano" fcontrato="2019-01-01" ffin="2019-12-31" fprevistainicio="2019-12-31T15:00:00" matricula="9999-ZZZ" nifarrendador="99999999R" nifarrendatario="123456789" niftitular="11111111H" nombarrendador="ARRENDADOR" nombarrendatario="ARRENDATARIO" nombtitular="TITULAR"/>
    </body>
    </vtc:qaltavtc>
    </soapenv:Body>
    </soapenv:Envelope>

El código anterior es para la comunicación de un nuevo traslado (Alta de servicio), las otras funciones que existen son:
[0] => rconsultavtc ConsultaDeServicio(qconsultavtc $pqconsultavtc)
[1] => raltavtc AltaDeServicio(qaltavtc $pqaltavtc)
[2] => ranulacionvtc AnulacionDeServicio(qanulacionvtc $pqiniciovtc)
[3] => rmodificacionvtc ModificacionDeServicio(qmodificacionvtc $pqmodificacionvtc)
[4] => riniciovtc InicioDeServicio(qiniciovtc $pqiniciovtc)

Posiblemente la función más sencilla de llamar sea la primera (ConsultaDeServicio) dado que sólo hay que pasarle la información de fecha="2019-01-01T12:29:00" version="1.0" versionsender="1.0" en la cabecera y el idservicio="xxxxxxx", donde xxxxxx es un número único que se asigna a cada servicio al darlo de alta.
He probado desde SOAP UI la función de Consulta de servicio y no da ningún problema.
El acceso se realiza mediante el certificado digital, no existe un par usuario contraseña, que es lo más extendido por la Web.
Probé sin éxito (supongo que definiría algo mal) soap-wsse, nusoap-0.9.5, xmlseclibs y no se cuantas otras cosas mas.
Si alguien tiene una idea de por donde pueden ir los tiros le quedaría eternamente agradecida si comparte su sabiduría.
Haciendo caso a las sugerencias edito (lo siento es la primera vez que pregunto y estoy un poco pez), ahora que no se si podre borrar el comentario para evitar duplicidades.
Las direcciones de acceso al servicio web en los entornos de Integración y Producción son:
Entorno de Integración
https://presede.fomento.gob.es/MFOM.Services.VTC.Server/VTCPort?wsdl
Puerto de conexión:  443
Entorno de Producción
https://sede.fomento.gob.es/MFOM.Services.VTC.Server/VTCPort?wsdl
Puerto de conexión: 443
Lo que pretendo hacer es una página web programada en PHP en la cual introduciendo el id del servicio me muestre la información asociada al mismo (función ConsultaDeServicio) y otra que permita indicar el inicio del mismo (InicioDeServicio), a las dos le pasaría por POST el id del servicio y recuperaria la respuesta obtenida.
Me estrello, una y otra vez con la llamada con la petición de datos creo que por el certificado digital, he probado con otros métodos SOAP sacados por Internet (como la conversión de grados centigrados a farenhait) y no había problemas, pero claro tampoco había certificados por el medio.
Muchas gracias a todos, estoy abierta a cualquier sugerencia.


text:
Q: How can I delete time-stamped folders if one has already been created that day? Folders are created every time I (re)boot.
They have the format below: (the time will always vary)
.mozilla_2019_01_08_08:02
.mozilla_2019_01_09_20:16
.mozilla_2019_01_10_01:16
.mozilla_2019_01_10_18:12

Here, I want to be able to delete the folder .mozilla_2019_01_10_18:12 when it is created as an earlier one already exists on ..._2019_01_10. Better would be to stop it being created, i.e. if one has already been created that day.
I can't use cron @daily or specific times as I never know how often or when the computer will be (re)booted.
How can I do this in an existing script please?
Here is my script:
##!/bin/bash
##
# COPY .mozilla FOLDER AND LEAVE LAST 10 COPIES (1 per day?)
#
sleep 30
#
if [ -e /home/david/nas-backups/mozilla/ ]
  then
    cp -a /home/david/.mozilla /home/david/nas-backups/mozilla/
    mv /home/david/nas-backups/mozilla/.mozilla /home/david/nas-backups
    /mozilla/backups/.mozilla_$(date +%Y_%m_%d_%H:%M)

# Show result of copy message
    export DISPLAY=:0 && zenity --info --title "Backup Information Box"
    --text=".mozilla Backup Finished

    Backed up to:
    /nas-backups/mozilla/backups/" --width=600 --height=200

## Working on how to keep only first copy per day ##

# Limit to last 10 alphabetical copies (courtesy of @Vijay)
    cd ~/nas-backups/mozilla/backups
    total=$(ls -1A|wc -l); remove=$((total - 10)); rm -rv $(ls -1vA|head
   -n $remove)

# Show folder so I can manually delete extra daily copies
    nautilus /home/david/nas-backups/mozilla/backups

else

    export DISPLAY=:0 && zenity --info --title "Backup Information Box"
    --text=".mozilla backup FAILED

    - nas-backups either not mounted or not availeble" --width=450
    --height=150
fi

A: One backup per day: Don't create more backups if one exists for today
Add a condition that checks if a backup folder for today does not exist. If there is no folder for today then only the cp and mv will be executed.
Note the * at the end of the second folder check. This allows for the time stamp at the end of the folder name, as you have done.
Here is the code fragment:
##!/bin/bash
if [ -d /home/david/nas-backups/mozilla/ ]
  then
  if [ ! -d /home/david/nas-backups/mozilla/backups/.mozilla_"$(date +%Y_%m_%d)"* ]
    then
      echo "No backups found for today: Making one"
      cp -a /home/david/.mozilla ~/nas-backups/mozilla/
      mv /home/david/nas-backups/mozilla/.mozilla ~/nas-backups/mozilla/backups/.mozilla_$(date +%Y_%m_%d_%H:%M)
    else
      echo "Backup folder for today exists. No backups will be made today"
  fi
fi

Hope this helps


text:
Q: How to use the Ruby map method to limit the parameters sent via an API Consider the follow:
@posts = Post.all
render json: { success: true, data: @posts }

Now, each post will have parameters that are not required to be sent in this particular scenario (although it'll be in others), so I'd like to restrict the parameters sent and I thought maybe I could use map like so:
@posts = Post.all.map { |user| [user.email, user.first_name, user.last_name] }
render json: { success: true, data: @posts }

As you can imagine that doesn't work. Its very likely I'm using - or intending to use - map in a completely incorrect way and I'd appreciate your comments on how to achieve the above.
Thanks in advance!

A: You can make use of Hash#slice method to do something like:
@posts = Post.all.map { |user| user.as_json.slice("email", "first_name", "last_name") }

The @posts will be an array of Hash in this case, with each hash containing three key-value pairs.

A: It may be more appropriate to use a serializer.
You'll have to install the active_model_serializers gem first.
An example serializer for your Post controller would be:
class PostSerializer < ActiveModel::Serializer
  attributes :email,
             :first_name,
             :last_name,

end

You'll use the serializer in this manner (I'm assuming you'd call it in the index method):
def index
    posts = Mentor.all

    render(
      json: ActiveModel::ArraySerializer.new(
        posts,
        each_serializer: PostSerializer,
        root: 'posts'
      )
    )
  end


text:
Q: Keras Model Accuracy differs after loading the same saved model I trained a Keras Sequential Model and Loaded the same later. Both the model are giving different accuracy.
I have came across a similar question but was not able solve the problem.
Sample Code :
Loading and Traing the model
model = gensim.models.FastText.load('abc.simple')
X,y = load_data()
Vectors = np.array(vectors(X))
X_train, X_test, y_train, y_test = train_test_split(Vectors, np.array(y),
test_size = 0.3, random_state = 0)
X_train = X_train.reshape(X_train.shape[0],100,max_tokens,1)

X_test = X_test.reshape(X_test.shape[0],100,max_tokens,1)
data for input to our model
print(X_train.shape)
model2 = train()

score = model2.evaluate(X_test, y_test, verbose=0)
print(score)

Training Accuracy is 90%.
Saved the Model
# Saving Model
model_json = model2.to_json()
with open("model_architecture.json", "w") as json_file:
  json_file.write(model_json)
model2.save_weights("model_weights.h5")
print("Saved model to disk")

But after I restarted the kernel and just loaded the saved model and runned it on same set of data, accuracy got reduced.
#load json and create model
json_file = open('model_architecture.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)

#load weights into new model
loaded_model.load_weights("model_weights.h5")
print("Loaded model from disk")

# evaluate loaded model on test data
loaded_model.compile(loss='binary_crossentropy', optimizer='rmsprop',
metrics=['accuracy'])

score = loaded_model.evaluate(X_test, y_test, verbose=0)
print(score)

Accuracy got reduced to 75% on the same set of data.
How to make it consistent ?
I have tried the following but of no help :
from keras.backend import manual_variable_initialization
manual_variable_initialization(True)

Even , I saved the whole model at once( weights and architecture) but was not able to solve this issue

A: Not sure, if your issue has been solved but for future comers.
I had exactly the same problem with saving and loading the weights. So on loading the model the accuracy and loss were changed greatly from 68% accuracy to 2 %. In my experiment, I am using Tensorflow as backend with Keras model layers Embedding, LSTM and Dense. My issue got solved by fixing the seed for keras which uses NumPy random generator and since I am using Tensorflow as backend, I also fixed the seed for it.
These are the lines I added at the top of my file where the model is also defined.
from numpy.random import seed
seed(42)# keras seed fixing
import tensorflow as tf
tf.random.set_seed(42)# tensorflow seed fixing

I hope this helps.
For more information have a look at this- https://machinelearningmastery.com/reproducible-results-neural-networks-keras/

A: I had the same problem due to a silly mistake of mine - after loading the model I had in my data generator the shuffle option (useful for the training) turned to True instead of False. After changing it to False the model predicted as expected. It would be nice if keras could take care of this automatically. This is my critical code part:
pred_generator = pred_datagen.flow_from_directory(
    directory='./ims_dir',
    target_size=(100, 100),
    color_mode="rgb",
    batch_size=1,
    class_mode="categorical",
    shuffle=False,
)

model = load_model(logpath_ms)

pred=model.predict_generator(pred_generator, steps = N, verbose=1)

A: My code worked when I scaled my dataset before reevaluating the model. I did this treatment before saving the model and had forgotten to repeat this procedure when I opened the model and wanted to evaluate it again. After I did that, the accuracy value appeared as it should \o/
model_saved = keras.models.load_model('tuned_cnn_1D_HAR_example.h5')

trainX, trainy, testX, testy = load_dataset()
trainX, testX = scale_data(trainX, testX, True)
score = model_saved.evaluate(testX, testy, verbose=0)
print("%s: %.2f%%" % (model_saved.metrics_names[1], score[1]*100))

inside of my function scale_data I used StandardScaler()


text:
Q: Django UpdateView returns a blank rendered template I am using django allauth for user authentication, in my adapter I have modified the get_login_redirect_url to redirect
new users to an ONBOARD_URL so they can complete registration process while regular users get the expected LOGIN_REDIRECT_URL
class UserAccountAdapter(DefaultAccountAdapter):
    def get_login_redirect_url(self, request):
        if request.user.is_authenticated and (not request.user.name or not request.user.avatar
                                              or not request.user.mobile):
            url = settings.ONBOARD_URL
        else:
            url = settings.LOGIN_REDIRECT_URL
        return resolve_url(url)

I have two functions handling the view and they both inherit from UpdateView and DetailView respectively.
class UpdateUserAfterSignupView(LoginRequiredMixin, UpdateView):
    model = User
    form_class = UpdateUserAfterSignupForm
    template_name = 'users/user_form.html'
    context_object_name = 'user'
    success_url = reverse_lazy('users:detail')

class UserDetailView(LoginRequiredMixin, DetailView):
    model = User
    slug_field = 'username'
    slug_url_kwarg = 'username'
    template_name = 'users/user_detail.html'
    context_object_name = 'user'

    def get_object(self, queryset=None):
        return get_object_or_404(self.model, username=self.request.user.username)

In my DetailView, if i leave out the get_object it returns a PageNotFound 404, but when its present as is, I get a blank page
in the rendered template. This is the template:
{% extends 'base.html' %}
{% block content %}

welcome {{user}}

<form action="" method="post" enctype="multipart/form-data">{% csrf_token %}
    {{ form.as_p }}
    <button type="submit" value="submit">submit</button>
</form>
{% endblock %}

and my url conf looks like this
[
    path('<str:username>/', views.UserDetailView.as_view(), name='detail'),
    path('complete-signup/', views.UpdateUserAfterSignupView.as_view(), name='complete_signup'),
]

Again, all of these results in a blank rendered template, nothing at all. Could you please suggest things I should do
differently, or add. I can provide more information as required. Thank you
EDIT
DetailView template looks like this:
{% extends 'base.html' %}
{% block content %}

{{user.name}}

{% if user.avatar %}

{% endif %}

{{ user.mobile }}

{% endblock %}

and my base template looks like this:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

    {% block content %}
    {% endblock %}

EDIT 2
My template dir settings looks like this:
'DIRS': [
            os.path.join(BASE_DIR / 'templates'),
            os.path.join(BASE_DIR / 'auth_templates'),
        ],

A: Got it to work finally, these are my changes:
Adapter
class UserAccountAdapter(DefaultAccountAdapter):
    def get_login_redirect_url(self, request):
        if request.user.is_authenticated and (not request.user.name and not request.user.avatar and
                                              not request.user.mobile):
            return reverse('users:complete_signup', kwargs={'username': request.user.username})

        else:
            return resolve_url(settings.LOGIN_REDIRECT_URL)

DetailView
class UserDetailView(LoginRequiredMixin, DetailView):
    model = User
    slug_field = 'username'
    slug_url_kwarg = 'username'
    template_name = 'users/user_detail.html'
    context_object_name = 'user'

    def get_object(self, queryset=None):
        return get_object_or_404(self.model, username=self.request.user.username)

UpdateView
class UpdateUserAfterSignupView(LoginRequiredMixin, UpdateView):
    model = User
    slug_field = 'username'
    slug_url_kwarg = 'username'
    form_class = UpdateUserAfterSignupForm
    template_name = 'users/user_update.html'
    context_object_name = 'user'

URLs
urlpatterns = [
    path('<str:username>/', views.UserDetailView.as_view(), name='detail'),
    path('<str:username>/complete-signup/', views.UpdateUserAfterSignupView.as_view(), name='complete_signup'),
]

My detail URL matched anything, complete_signup URL inclusive. These changes helped fixed that, the template now displays the expected form and not an empty page it did previously.


text:
Q: Existence of certain subgroup of non-abelian group of order $p^3$ Let $G$ be a group of order $p^3$, where $p$ is prime, and $G$ is not abelian.  Let $Z$ be its center. Suppose $x^p=1$ for all $x\in G$. Show that $G$ contains a normal subgroup $H\cong \mathbb{Z}_p\times \mathbb{Z}_p$.
Remark: I have tried but many different approaches to this problem but I failed. Also we are not allow to use any structure theorem. Here it is one of my approaches.
Since $x^p=1$ for all $x\in G$ then all non-identity elements in $G$ has order $p$. Take some $x\neq e\in G$ and consider the subgroup $\langle x\rangle_p$ of $G$. Let's take $y\in G-\langle x\rangle_p$ then we see that $\langle x\rangle_p\cap \langle y\rangle_p=\{e\}$ and $\langle x\rangle_p, \langle y\rangle_p\cong \mathbb{Z}_p$. I was trying to show that these subgroups are normal but no results.
So I would be very grateful if anyone can show how to solve this problem?

A: The comment of user10354138 gives the correct idea.
$Z(G)$ is non-trivial because $G$ is a $p$-group, so it has order $p$ or $p^2$ ($G$ is not abelian). If it has order $p^2$, then $G/Z(G)$ would have order $p$, and so would be cyclic. It is a standard fact that this implies that $G$ is cyclic, which we excluded. Hence $Z(G)$ has order $p$, call $x$ a generator. Now take any element $y$ not in the center. If $y$ has order $p$ then $<x,y>\cong \mathbb Z/p\times\mathbb Z/p$, otherwise $y$ has order $p^2$, and $<x,y^p>$ does the trick.
To make this problem more concrete, let me tell you that there is in fact only one group (for any odd prime $p$) with those characteristics.
First of all, if $p=2$ then $x^2=1$ for every $x$, so $G$ is abelian, so assume $p$ odd.
The group $G$ is the so-called Heisenberg group. It consists of upper triangular $3\times 3$ matrices with diagonal entries all equal to $1$.