text:
Q: SQL Server joining two tables counting I want to join table 1 and table 2 by counting the people in table two who visited the combo in table 1, so the result would look like
table 1
City1  City2

Rome   Berlin
Moscow Berlin

....many more rows  (to be clear- this was just an excerpt)
table 2
Person City

Peter Rome
Peter Paris
Peter Berlin
Peter Moscow
Paul  Rome
Paul  Moscow
Mary  London
Mary  Moscow
Mary  Berlin

... many more rows
What I want it to look like:
Rome   Berlin 0
Moscow Berlin 3
London Berlin 1

Any help appreciated.
Here is what I have done so far:
select a.city1
     , a.city2
     , count(case when city=a.city1 and city=a.city2 THEN city ELSE NULL END)
from table1 a join table2 b

A: Sample data is incorrect, no London-Berlin combination in table1 and result should be
Rome    Berlin  1
Moscow  Berlin  2
London  Berlin  1

However it can be achieved: you want the combinations of the cities of table2 so join table2 to itself based on person.
You also want to mach the combinations in table1 so join table1 to the previous result.
You need a counter so group on the last resultset:
select t2.city, t3.city, count(t1.city1) as counter
from table2 as t2
inner join table2 as t3 on t2.person = t3.person and t2.city <> t3.city
inner join table1 as t1 on t1.city1 = t2.city and t1.city2 = t3.city
group by t2.city, t3.city

The result will be as requested but you have to enter correct data in table1, otherwise you can get wrong result.

A: One way you can do this is by joining to each of the cities and then aggregating, counting up when there is a match in both tables.  This form of the query assumes there are no duplicates in the second table:
select t1.city1, t2.city2,
       sum(case when t21.person is not null and t22.person is not null then 1 else 0 end) as cnt
from table1 t1 left outer join
     table2 t21
     on t1.city1 = t21.city left outer join
     table2 t22
     on t1.city1 = t22.city and t22.person = t21.person
group by t1.city1, t2.city2;

EDIT:
You can also do this with two levels of aggregation and one join.  This is pretty easy to explain.  The inner query counts the number of cities that a person matches for each pair of cities.  The cnt is 0, 1, or 2.  The outer query then counts the number where cnt = 2, because these are the ones that match both cities.
select city1, city2, sum(case when cnt = 2 then 1 else 0 end) as cnt
from (select t1.city1, t2.city2, person, count(t2.person) as cnt
      from table1 t1 left outer join
           table2 t2
           on t2.city in (t1.city1, t1.city2);

The advantage of this approach is that adding new cities is easy, as well as getting more information, such as how many people match exactly one of the cities.


text:
Q: Min-Height, Max-Height for Image container I am trying to fit my image into a container but it is overflowing. For the image, I gave height 100% to the container; for the container, I specified min-max height. I thought this could work but it is not. This error happens on the phone screen, not on the full screen. When I give height:200px that solves the problem but that is not what I want.
CSS
.adminAddDeleteEdit__img {
  height: auto;
  min-height: 200px;
  max-height: 400px;
  width: auto;
  min-width: 200px;
  max-width: 600px;
  border: 3px solid var(--main-color);
  border-radius: var(--admin-borderRadius);
  /* overflow: hidden; */
}
.adminAddDeleteEdit__img img {
  width: auto;
  max-width: 100%;
  height: auto;
  max-height: 100%;
  object-fit: contain;
  border-radius: var(--admin-borderRadius);
}

HTML

      <Swiper
        modules={[Navigation, A11y, EffectFade, Mousewheel]}
        slidesPerView={1}
        loop

        effect={"fade"}
        navigation
        className="carousel__swiper"
      >
        {selectedItem.images?.map((img) => (
          <SwiperSlide key={img.name + uuidv4()}>

          </SwiperSlide>
        ))}
      </Swiper>

A: How I solve this problem was by adding display flex to adminAddDeleteEdit__img.
 .adminAddDeleteEdit__img {
  height: auto;
  min-height: 200px;
  max-height: 400px;
  width: auto;
  min-width: 200px;
  max-width: 600px;
  border: 3px solid var(--main-color);
  border-radius: var(--admin-borderRadius);
  display: flex;
  justify-content: center;
}

@Damzaky thank you. Your display block idea led me to this solution.

A: Add display: block to the .adminAddDeleteEdit__img img rule:
.adminAddDeleteEdit__img img {
  width: auto;
  max-width: 100%;
  height: auto;
  max-height: 100%;
  object-fit: contain;
  border-radius: var(--admin-borderRadius);
  display: block;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: highlighting by div behind text I'd like to do text highlighting by hovering a div behind the text via z-index*.  If the element containing the text doesn't have a background, it works fine:

However, if the element has a background or background-color, it doesn't work as the background blocks the view of the div that's behind it:

Of course I can make the div be on top, but that looks terrible, as it colors the text itself:

You can see this problem in action with jsfiddle here.  My question is: how can I have a div go behind the text but above the background?

* Why am I not using a span like everyone else?  Because with div I can animate the highlighting's movement from word to word.  That's in the jsfiddle also.

A: http://jsfiddle.net/V3Kae/9/
you could do it like this. setting the z-index of the container to be lower then the highlight, an the z-index of the text to be higher then the highlight.


text:
Q: Explicit type conversion in c language if my c code is
#include<stdio.h>
int main()
{
    int c;
    while((c=getchar())!=EOF)
    {
       putchar(c);
    }
getch();
return 0;
}

I want to know whether int c woud be converted into char , or the input character would be converted into int and then be stored in c.

A: getchar returns an int and putchar expects an int so there is no need of conversion. char in name may be confusing for you. But type int also allows to accommodate some special values for ex: EOF

A: From the man page of getchar()
int getchar(void);

So, why'd think of conversion, anyway? The return type of getchar() is int, being stored into an int variable.
Same goes for putchar() also.
int putchar(int c);

A: The return type of getchar is int, so no type conversion takes place in the assignment.


text:
Q: What controls the visibility of the "Share your answer" section? As the title states, I've noticed that after answering a question I can share my answer on Facebook/Twitter, yet this option disappears when looking at answers I've posted previously elsewhere.
Is there a way to access these links when revisiting a question?

A: I believe Jeff has said the popup is random.  You can get it anytime you like using the "link" link just under the tags, next to edit, close, flag, etc.
Edit:
Or did you mean this one: Please ditch all of the share icons - they give me nightmares?  If so, see that post for Jeff's answer.


text:
Q: Python - Writing parsed JSON to an CSV I am working on a script to read JSON from a file and then to extract a certain content to a different table. I am able to read from the file and parse the list of books out(in the example). The issue is since I am writing to a table, not every list has the same fields. I want to send default values in the JSON.So this is the JSON I have. I want to end up writing the JSON
{
    "books": [
        {
            "field1": "value",
            "field2": "value",
            "field3": "value"
        },
        {
            "field1": "value",
            "field2": [
                "value"
            ],
            "field3": "value",
            "field4": "value"
        },
        {
            "field1": "value",
            "field2": "value",
            "field3": "value",
            "field4": "value",
            "field5": "value"
        }
    ]
}

I am trying to write these values to a csv. I thought the next intermediate step might be to have a flattened structure like the following. So basically empty strings and then I could write this to an CSV. I am not clear how to do this if anyone has suggestions. Thanks!
[
    {
        "field1": "value",
        "field2": "value",
        "field3": "value",
        "field4": "",
        "field5": ""
    },
    {
        "field1": "value",
        "field2": [
            "value"
        ],
        "field3": "value",
        "field4": "value",
        "field5": ""
    },
    {
        "field1": "value",
        "field2": "value",
        "field3": "value",
        "field4": "value",
        "field5": "value"
    }
]

A: Easier to do it using Pandas library. Sample code below
import numpy as np
import pandas as pd

d = {
    "books": [
        {
            "field1": "value",
            "field2": "value",
            "field3": "value"
        },
        {
            "field1": "value",
            "field2": [
                "value"
            ],
            "field3": "value",
            "field4": "value"
        },
        {
            "field1": "value",
            "field2": "value",
            "field3": "value",
            "field4": "value",
            "field5": "value"
        }
    ]
}

df = pd.DataFrame.from_dict(d['books'])
df.fillna("", inplace = True)
csv = df.to_csv(index = False)
print(csv)

A: You can merge a default valued dictionary with your data dictionary, to generate default values. See an example approach below:
books: list = {
    "books": [
        {
            "field1": "value",
            "field2": "value",
            "field3": "value"
        },
        {
            "field1": "value",
            "field2": [
                "value"
            ],
            "field3": "value",
            "field4": "value"
        },
        {
            "field1": "value",
            "field2": "value",
            "field3": "value",
            "field4": "value",
            "field5": "value"
        }
    ]
}.get("books")

# find all keys and get a unique set
keys_list = []
[keys_list.extend(book.keys()) for book in books]
all_keys = set(keys_list)

# Generate a default dict
default = {key: "" for key in all_keys}

# Generate a list dicts with default merged values
flattened_list =[{**default, **book} for book in books]

#Write a CSV file
import csv
with open("books.csv", 'w') as csv_file:
    writer = csv.DictWriter(csv_file, fieldnames=all_keys)
    writer.writeheader()
    writer.writerows(flattened_list)


text:
Q: Perl (or C printf) back one tab, possible? We all know how to print a string one tab further with \t
printf ("Hello\tthere!\n");

which outputs:
Hello    there!

What about printing one tab backwards? I know we can just use \r to start back from the beginning of the line, but there are situation when indentation is more complex than that, I am looking for something like \bt (if it existed) such that I could write:
printf ("Hello\tthere! \n\tHow\n\btare you?\n");

to get in output:
Hello    there!
             How
         are you?

Edit
I am surprised by the amount and speed of replies here, and sometimes even by the uselessness of some comments, but only a few. What I am trying to achieve is of course more complex than this, it's properly formatting an XML file to be easily readable. I wanted to be sure there wasn't an easier way, the response confirmed there wasn't thanks.
Edit 2
Sorry guys, you are right to vote down this question, first because I didn't specify I was writing to a text file, secondly because I was assuming tabs could be "remembered" by the file handler. Sorry for wasting your time.

A: With printf you control how much tabbing is taking place explicitly.  To back tab you would just use fewer tabs.  From the example you provided it looks like you are expecting the tab level to be remembering, and have How indented farther than it really will be when printed.  It would appear at the same tab stop as there! and are you?
Assuming with:
printf ("Hello\tthere! \n\tHow\n\btare you?\n");

You are expecting to see:

Hello   there!
    How
are you?

Then just don't add the tab before are you? and you will get what you want.  To get fewer tabs, just add fewer \t symbols to your printf.  printf doesn't have any memory of what tabbing has occurred before.
printf ("Hello\tthere! \n\tHow\nare you?\n");

A: No, there is no special character to do what you want. Even the behavior of \b is dependent on the platform.
\bt is simple the backspace character followed by the letter t. So that syntax is supported but there's no special behavior.
But why do you need that here? Why not just use:
printf("Hello\tthere!\r\n\tHow\r\nare you?\n");

A: There's no way to "back tab", but there are other options:
As you noted, \t gives you a tab forward.
\b can give you a backspace, so you can "back up" with that.
There are also some less-frequently-used ones:
\f is a form feed/new page (eject page from printer)
\v is a vertical tab (move down one line, on the same column)
So using the other options you can simulate what you want.
printf("Hello, this is\n\t\tjust a test.\n");
printf("Hello, this is\v\b\bjust a test.\n");

Ends up looking like:
Hello, this is
        just a test.
Hello, this is
    just a test.

You could then simplify your code with something like:
#define BACKTAB "\v\b\b"

printf("Hello, this is%sjust a test.\n", BACKTAB);

I think that's the best you can do


text:
Q: Customize JSON parsing (Gson) How can I customize serialization/deserialization of a specific field?
Here's my json:
[{
"Short Name": "X",
"Address": "X Address",
"Latitude": 40.739982,
"Longitude": -73.978053,
"Type": "A, B"
},
{
"Short Name": "Y",
"Address": "Y Address",
"Latitude": 40.852856,
"Longitude": -73.938098,
"Type": "A, B, C, D"
}]

Using Gson, now I can parse the json and get a JAVA object with
String type; but I want to split the Type string and get a type String[].
public class MyClass {
    @SerializedName("Short Name")
    @Expose
    private String ShortName;

    @Expose
    private String Address;

    @Expose
    private Double Latitude;

    @Expose
    private Double Longitude;

    @Expose
    private String Type;
    // how can I split the string
    // and get private String[] Type;
    // when deserializing
}

A: You need to implement a custom Type Adapter.
You can do in this way:
JsonDeserializer<String[]> deserializer = new JsonDeserializer<String[]>() {

    @Override
    public String[] deserialize(JsonElement jsonElem, Type type,
            JsonDeserializationContext context) throws JsonParseException {

        if(jsonElem == null) {
            return null;
        }

        return jsonElem.getAsString().split(", ");
    }

};

Gson gson = new GsonBuilder()
                    .registerTypeAdapter(String[].class, deserializer)
                    .create();

Type listType = new TypeToken<ArrayList<MyClass>>() {}.getType();
List<MyClass> t = gson.fromJson(json, listType);

And modify your MyClass bean from:
@Expose
private String Type;

to:
@Expose
private String[] Type;

In the same way you can add a serializer if you need to serialize MyClass object in order to convert the "Type" array to String comma separed!

A: Easy. Json allows you to use Numbers(Int/Long/Double), Strings, Lists or Objects. What you need is a list.
JSON:

"Type" : {
                   "type": "array",
                   "items" : {"type": "string"}
                   }

e.g. "Type" : ["A","B","C","D"]
JAVA:
List<String> Type;

Later on you can use any Java List implementation such as ArrayList.
e.g. Type = new ArrayList();

A: You can use JsonAdapter for that.
Here is example from ducumentation.
Here is an example of how this annotation is used:
   @JsonAdapter(UserJsonAdapter.class)
   public class User {
     public final String firstName, lastName;
     private User(String firstName, String lastName) {
       this.firstName = firstName;
       this.lastName = lastName;
     }
   }
   public class UserJsonAdapter extends TypeAdapter<User> {
     @Override public void write(JsonWriter out, User user) throws IOException {
       // implement write: combine firstName and lastName into name
       out.beginObject();
       out.name("name");
       out.value(user.firstName + " " + user.lastName);
       out.endObject();
       // implement the write method
     }
     @Override public User read(JsonReader in) throws IOException {
       // implement read: split name into firstName and lastName
       in.beginObject();
       in.nextName();
       String[] nameParts = in.nextString().split(" ");
       in.endObject();
       return new User(nameParts[0], nameParts[1]);
     }
   }

Since User class specified UserJsonAdapter.class in @JsonAdapter annotation, it will automatically be invoked to serialize/deserialize User instances.
Here is an example of how to apply this annotation to a field.
   private static final class Gadget {
     @JsonAdapter(UserJsonAdapter2.class)
     final User user;
     Gadget(User user) {
       this.user = user;
     }
   }

It's possible to specify different type adapters on a field, that field's type, and in the com.google.gson.GsonBuilder. Field annotations take precedence over GsonBuilder-registered type adapters, which in turn take precedence over annotated types.
The class referenced by this annotation must be either a TypeAdapter or a TypeAdapterFactory, or must implement one or both of JsonDeserializer or JsonSerializer. Using TypeAdapterFactory makes it possible to delegate to the enclosing Gson instance.


text:
Q: Can not save form with CreateView (Django, Python) I am trying to save data that fill out with form to database but it doesn't work as well. when i click on Submit button nothing change, the webpage just refresh!
These are my codes.
Views.py
class HotelAdCreate(AuthorsAccessMixin,CreateView):
    model = HotelBookingAd
    form_class = HotelBookingAdForm
    template_name = "account/article-create-update.html"

    def form_valid(self,form):
        form.save()
        return super(HotelAdCreate).form_valid(form)

Forms.py
class HotelBookingAdForm(forms.ModelForm):

    class Meta:
        model = HotelBookingAd
        fields = '__all__'

    def clean_sales_price(self):
        sales_price = self.cleaned_data["sales_price"]
        purchase_price = self.cleaned_data["purchase_price"]
        if sales_price > purchase_price:
            raise forms.ValidationError("error.")
            print("error")

        return sales_price

Edit :
i just added template file codes to debaug clearly.
Template File
{% extends 'account/base.html' %}
{% load crispy_forms_tags %}

{% block title %}{% endblock %}
{% block title-meta %} آگهی{% endblock %}
{% block main %}

ایجاد آگهی

        <form method="post" enctype="multipart/form-data">{% csrf_token %}

                    {{form.title|as_crispy_field}}

                    {{form.hotel_name|as_crispy_field}}

                    {{form.sale_reason|as_crispy_field}}

                    {{form.check_in_date|as_crispy_field}}

                {{form.check_out_date|as_crispy_field}}

                    {{form.purchase_price|as_crispy_field}}

                    {{form.sales_price|as_crispy_field}}

                    {{form.city_name|as_crispy_field}}

                    {{form.room_type|as_crispy_field}}

                    {{form.confirm|as_crispy_field}}

                {% if user.is_superuser %}

                    {{form.slug_generator|as_crispy_field}}

                {% endif %}

            <button class="btn btn-success">ارسال مقاله</button>
            {% if user.is_superuser and request.resolver_match.kwargs.pk %}

            حذف مقاله

            پیش نمایش

            {% endif %}
        </form>

{% endblock %}

I've tried different options, but I don't have enough skills to handle this problem.
Can anyone help me?
UPDATE (FIXED)
I found problem by my self, here it is :
As you see in forms.py, i am using __all__ for fields but in template i am not using all the fields, so form will not be valid.
To fix the bug completely i just added Exclude option and added the fields that i didn't use in template. finally everything works fine :)


text:
Q: Saving data with NSMutableDictionary I had a method to save a dic to the disk:
+(BOOL) writeApplicationData:(NSDictionary *)data
              bwriteFileName:(NSString *)fileName
{
    NSLog(@"writeApplicationData");
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    if (!documentsDirectory) {
        NSLog(@"Documents directory not found!");
        return NO;
    }
    NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
    return ([data writeToFile:appFile atomically:YES]);
}

And I tested it with:
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
        NSMutableDictionary *d1 = [[NSMutableDictionary alloc] init];
        NSMutableDictionary *d2 = [[NSMutableDictionary alloc] init];

        [d1 setObject:@"d11"
               forKey:@"d11"];
        [d1 setObject:@"d12"
               forKey:@"d12"];
        [d1 setObject:@"d13"
               forKey:@"d13"];

        [d2 setObject:@"d21"
               forKey:@"d21"];
        [d2 setObject:@"d22"
               forKey:@"d22"];
        [d2 setObject:@"d23"
               forKey:@"d23"];

        [dic setObject:d1
                forKey:@"d1"];
        [dic setObject:d2
                forKey:@"d2"];

        [self writeApplicationData:dic
                    bwriteFileName:@"testSave"];

And the data is saved correctly.
Then I tried to save d1 with class obj in it:
LevelInfoData *levelInfoData = [[LevelInfoData alloc] init];

[levelInfoDictionary setObject:levelInfoData
            forKey:@"test"];

[dic setObject:levelInfoDictionary
        forKey:@"LevelInfoDictionary"];

But this time, even no plist file was generated in the disk.
Here is the LevelInfoData class:
@interface LevelInfoData : NSObject {

    int levelNum;
}

@property (nonatomic) int levelNum;

@end

@implementation LevelInfoData
@synthesize levelNum;
@synthesize isLevelLocked;
@synthesize isLevelCleared;
@synthesize levelHighScore;

-(id)init
{
    if( (self = [super init]) ) {

        levelNum = 0;
    }

    return self;
}

@end

I'm really confused, hope somebody could help me out, thanks.

A: The contents of the dictionary need to be property list type objects.
From the NSDictionary Class Reference:
This method recursively validates that all the contained objects are property list objects (instances of NSData, NSDate, NSNumber, NSString, NSArray, or NSDictionary) before writing out the file, and returns NO if all the objects are not property list objects, since the resultant file would not be a valid property list.
https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/Reference/Reference.html
You may want to try making your custom class a subclass of NSData rather than NSObject.

A: I'm not sure how attached you are to NSDictionary, but this may be a situation where NSCoder will better serve you.
See nscoder vs nsdictionary when do you use what
More details here:

*

*NSCoder Class Reference

*Some code snippets

*A tutorial


text:
Q: Is it possible to store nested dict in Redis as hash structure? I am trying to store a nested dictionary as hash with HSET, but that does not seem to be possible.
An example that does not work:
from redis import StrictRedis
foo = {
    "host_data": {
        "hostname": "some_host",
        "mac_address": "82:fa:8e:63:40:05",
        "root_password": {
            "is_crypted": True,
            "password": "sha512_password"
        },
        "network": {
            "ip_address": "192.168.0.10/24",
            "default_gateway": "192.168.0.1",
            "vmnic": "vmnic3",
            "vlan": 20
        },
        "dns_servers": [
            "dns01.local",
            "dns02.local"
        ]
    },
    "installation_type": "esxi",
    "image_data": {
        "type": "vCenter_contentlib",
        "host": "vcenter01",
        "credential": {
            "username": "some_user",
            "password": "some_password"
        },
        "content_library": "the_content_lib_name",
        "image_name": "some_image"
    },
    "host_short_name": "esxi021"
}

redis_connection = StrictRedis(host='localhost', port=6379, charset="utf-8", decode_responses=True)
redis_connection.hset("test", mapping=foo)

Throws the following error:
Traceback (most recent call last):
  File "/Users/project/dummy.py", line 36, in <module>
    redis_connection.hset("test", mapping=thing)
  File "/Users/project/venv/lib/python3.9/site-packages/redis/client.py", line 3050, in hset
    return self.execute_command('HSET', name, *items)
  File "/Users/project/venv/lib/python3.9/site-packages/redis/client.py", line 900, in execute_command
    conn.send_command(*args)
  File "/Users/project/venv/lib/python3.9/site-packages/redis/connection.py", line 725, in send_command
    self.send_packed_command(self.pack_command(*args),
  File "/Users/project/venv/lib/python3.9/site-packages/redis/connection.py", line 775, in pack_command
    for arg in imap(self.encoder.encode, args):
  File "/Users/project/venv/lib/python3.9/site-packages/redis/connection.py", line 119, in encode
    raise DataError("Invalid input of type: '%s'. Convert to a "
redis.exceptions.DataError: Invalid input of type: 'dict'. Convert to a bytes, string, int or float first.

An example that works:
from redis import StrictRedis
foo = {
    "installation_type": "esxi",
    "host_short_name": "esxi021"
}

redis_connection = StrictRedis(host='localhost', port=6379, charset="utf-8", decode_responses=True)
redis_connection.hset("test", mapping=foo)

In summary, my question is:
Is it possible to store nested dict as hash structure in Redis?
NOTE: I am aware it can be stored as string and then loaded as json, but I am really trying to avoid it.
EDIT: Reids version is 6.2.5

A: Redis alone doesn't store nested structures in hashes. There is a good answer for how to work around here.
However, there is a module RedisJSON that supports this and the python redis client includes support for this module.
Load the module in the redis server:
redis-server --loadmodule ../RedisJSON/target/release/librejson.dylib

In python you can then set and retrieve nested dicts or portions of the path.
import redis
from redis.commands.json.path import Path

redis_connection = StrictRedis(host='localhost', port=6379, charset="utf-8", decode_responses=True)

foo = {
    "host_data": {
        "hostname": "some_host",
        "mac_address": "82:fa:8e:63:40:05",
        "root_password": {
            "is_crypted": True,
            "password": "sha512_password"
        },
        "network": {
            "ip_address": "192.168.0.10/24",
            "default_gateway": "192.168.0.1",
            "vmnic": "vmnic3",
            "vlan": 20
        },
        "dns_servers": [
            "dns01.local",
            "dns02.local"
        ]
    },
    "installation_type": "esxi",
    "image_data": {
        "type": "vCenter_contentlib",
        "host": "vcenter01",
        "credential": {
            "username": "some_user",
            "password": "some_password"
        },
        "content_library": "the_content_lib_name",
        "image_name": "some_image"
    },
    "host_short_name": "esxi021"
}

redis_connection.json().set("test", Path.rootPath(), foo)
print(redis_connection.json().get("test", '.host_data.hostname'))

A: Nevermind the question, obviously Redis can only use flat structures according to: https://redis.com/redis-best-practices/data-storage-patterns/object-hash-storage/


text:
Q: C substring two equal characters not matching am writing a program to find a substring in a string. For some strange reason, during comparison of one character to another, two similar characters do not match. I'm not sure if this is some sort of bug.
Here's the code:
#include <stdio.h>
int first_char_compare(char *str,char a);

int main()
{
    int i,j, char_exists,substring;
    char string1[] = "jrsfahamfsf";
    char string2[] = "ham";

    char_exists = first_char_compare(string1,string2[0]);

    if(!(char_exists<0))
    {
        j=char_exists;

        for(i=0;string2[i]!='\0';i++)
        {
            for(;string1[j]!='\0';j++)
            {
                printf("%c\t%c\n",string2[i],string1[j]);
                if(string1[i]==string2[j])
                {
                    substring = 1;
                    printf("matches\n");
                    break;
                }
                else
                {
                    printf("doesn't match\n");
                    substring = 0;
                }
            }

            if(substring==0)
                break;

            j++;
        }

    }

    if(substring)
        printf("Is a substring\n");
    else
        printf("Not a substring\n");

    return 0;
}

int first_char_compare(char *str,char a)
{
/* Checks if the first character of the substring is in the main string.
 * If the character exists, it's index is returned. If it doesn't exist
 * -1 is returned.
 */
    int i;
    for(i=0;str[i]!='\0';i++)
    {
        if(a==str[i])
            return i;
    }
    return -1;
}

A: In your loops, string2 is indexed by i, and string1 by j:
for (i = 0; string2[i] != '\0'; i++)
{
  for( ; string1[j] != '\0'; j++)
  {

But in your comparison, the indices are backwards:
if (string1[i] == string2[j])

correct that to:
if (string1[j] == string2[i])


text:
Q: Auto Suggest not working in Xcode 9.4.1 AM using Xcode 9.4.1.
The auto suggest is not working.
I ahem tried almost all possible suggestions like:
1. Cleaning the code
2. Deleting the derived data
3. Checking and unchecking the auto suggestion option in the Xcode preferences.
Please help me in fixing this issue.


text:
Q: Why would I get a PHP/PDOException complaining that it can't make a Postgres connection because it can't find an app-local certificate file? I've got a PHP app with Postgresql for the datastore, and just migrated the db to a new managed offering provider. Now when I try and run the app on my local development machine (macOS 10.12.6), I encounter the following error trying to connect to the newly situated db:

PDOException: SQLSTATE[08006] [7] could not open certificate file
"/var/root/.postgresql/postgresql.crt": Permission denied

There's a couple of interesting things about this:

*

*If I try to connect to the same remote database via the psql client, I have no problem, it drops me straight into a psql prompt where I can query away at the DB to my heart's content.

*I can execute PHP cli scripts that connect to the remote DB and query it without problem. PDO only throws an exception if I'm calling the connection code through a script invoked via an http request through a local Apache 2.4 server.

*I am not at all shocked that permission is denied to access resources in /var/root, but  I am shocked that anything expected to run in userland would ever be checking there. It seems like permission should be denied by default for its contents, even if there was a .postgresql/ subdirectory there (which there isn't).
#1 suggests this is not a pg_hba.conf or other client whitelist or network issue. #3 probably suggests perhaps I should have Apache switch to a non-root user, I'd guess, but beyond that I'm not sure what to make of it, and at any rate I have not placed a ~/.postgresql or postgresql.crt anywhere.
#2 suggests Apache2+libphp7.so doesn't know where to look for postgresql client certs... but the php binary does? This feels like the big clue, but I have no idea why it would be the case or how to fix it.
What are some next steps I could take to figure out how to get the web app connecting?
EDIT:
Prompted by the comment by @jjanes below, it occurred to me to try two things:
a) changing the apache config so that it was running as my personal user to see if the connection worked
b) trying to make a psql connection as root to see if that worked
When both did, that suggested to me that maybe the error message isn't complaining that it can't find a certificate for root (but somehow knows where to look for my personal account), it's that it's freaked out that it couldn't even muster permissions to check under /var/root.
So I did chmod /var/root o+x and mkdir /var/root/.postgresql/ and... it's fine. It didn't need the cert, just needed to have permission to look for it.
This feels like a bug for the sslmode=require level of things, but I'm happy to have a workaround. And I'd still be interested to hear suggestions of other ways to address situations like it.


text: Q: Woocommerce - Change Message for variant not available in Woocommerce (woodmart template), I would like to change the text of the message that appears at the bottom of the product page when an unavailable variable is selected. The photo is below:


text:
Q: Suitetalk journal entry approval status I'm creating a journal entry via Suitetalk but this journal entries gets created in a "Pending Approval" status, I need it to be approved.
I'm sending the fields approved and approvedSpecified as true but the journal entry doesn't get approved this way.
Anyone knows how I can achieve this?
Thank you.

A: Setting approved = true and approvedSpecified = true are enough to create an approved journal entry via SuiteTalk.  In testing this, I did have to disable an existing workflow that forced new JE's to go into a Pending Approval state.  Perhaps you have some other customization that is preventing the creation of a JE in an approved state.
The following code worked for me.

var journal = new JournalEntry
{
    tranDate = DateTime.Now,
    approved = true,
    approvedSpecified = true,
    subsidiary = 2.ToRecordRef(),
    memo = "test",
    lineList = new JournalEntryLineList
    {
        line = new List<JournalEntryLine>
        {
            new JournalEntryLine
            {
                account = 122.ToRecordRef(),
                credit = 100F,
                creditSpecified = true
            },
            new JournalEntryLine
            {
                account = 122.ToRecordRef(),
                debit = 100F,
                debitSpecified = true
            }
        }.ToArray()
    },
};

var response = ns.add(journal);


text:
Q: Startup Security Utility Admin Permission I have a company mac with admn privileges. There are also other hidden admin accounts installed. Wanted to boot windows from external disk to play some Indi coop games
To boot from external Disk I need to allow it in Startup Security Utility in Secure Boot with cmd + R
I can select my Admin user to authenticate. However my password is not accepted. There is no error message at all.
For example If go to terminal and type 'resetpassword' I can authenticate with this user and would be able to change others users passwords.
Is there some specific authorization policy for Startup Security Utility which needs to be granted ? Or is something broken for this user ?

A: You have a Mac with a T2 chip, which requires an Administrator account with both a signed certificate and a SecureToken linked to that account, and the account that tries to change any of those settings in Recovery has to have the same matching SecureToken, a copy of which is held by the BridgeOS running the T2 chip.
Your IT folk have (quite rightly) locked that kind of thing away good & proper. Sorry, but no coop today :)


text:
Q: What's the best way to ensure security in multi-network? I have the following setup:
I have a server using XEN to run several virtual machines. All of them are connected to various (virtual or physical) networks. I have the internet (bad guys), a DMZ network and a internal network (only good guys). I separate the networks by (virtual) routers that prevent unauthorized traffic to be stopped.
Now I want to be able to access to all machines via SSH from both inside the LAN and the internet if needed to do some remote repair. From the internet all SSH acces is redirected to a machine in the DMZ. Now I could do two differnet things from there on:

*

*Have the keys to all machines on my laptop (somewhere in the internet) and then connecting to the SSH machine. I build a tunnel to the internal router and through that I can access the internal network.

*Have the key to my SSH machine on the laptop and go from machine to machine through the virtual net. So the key for the router is on the SSH machine and so on.

My own suggestion was to use option 1 plus the possibility to build a tunnel from there to every PC in DMZ/LAN/VPN (iptables is active at moment).
How would you do it? What is your suggestions? Is there even a better solution?

A: Note: This is my personal opinion as someone interested in security. I am not an expert, nor have any qualification under my name.
Possible security Risk:
I believe by you having a DMZ-ed SSH server is a security risk as DMZ-ed server means firewall will simply pass any unknown / not explicitly blocked connection attempt to that server, which mean that server is prone to probing, and worst case, attack.
Recommendation #1
Have you considered having VPN server within your LAN? This way you can remove the DMZ, and still access behind your LAN via a secure tunnel with VPN.
Pro: VPN allows secure, encrypted connection from internet to your LAN. If you have VPN, you won't need DMZ - which means hopefully it will be more secure for you.
Con: VPN server can be difficult to set up, or require money to set up, and adding another layer of complexity for IT management.
And having all your eggs in 1 basket (all your secure SSH keys in your laptop) is not exactly the best way (Scenario: If you lose your laptop) - but you can always have a full disk encryption with TrueCrypt or other software so if your laptop ever leave your hand, at least your data will be fully encrypted and no bad guys can attempt to abuse those data.
If you don't have the resources / time to invest on VPN - If you have some existing NAS box (Synology, QNAP, or other brand) they may have VPN server as a module that you can download for very easy installation and set up (this is true for Synology that I owned and personally tested).
Recommendation #2
Or if VPN is truly not possible (due to whatever reason) - then perhaps consider a remote support software? (GotoAssist, TeamViewer, Logmein to name a few).
Install the client on a machine you trust inside your LAN, and simply connect to that machine from the internet. And then using that machine as your jumping point, you can SSH everywhere, as if you are sitting in front of the machine inside your LAN.
Pro: You can keep your SSH keys in a PC INSIDE your LAN. Secured behind your corporate firewall.
Con: A 3rd party software is required to allow the connection from Internet into your LAN. And the software may cost money.
Personal experience: TeamViewer is definitely very easy to use, and free for personal use. And also TeamViewer has an option to connect via VPN (Unfortunately I have not personally tested this, but I have seen the option to install VPN driver) - added benefit of securing your connection.
Hope this helps.


text:
Q: Как в Битрикс добавить модуль в меню По инструкции

http://dev.1c-bitrix.ru/api_help/main/general/admin.section/rubric_admin.php

Создал файлы

bitrix\modules\subscribe\admin\insert_admin.php
bitrix\modules\subscribe\lang\ru\admin\insert_admin.php
bitrix\bitrix\admin\insert_admin.php

В инструкции написано

Теперь наш файл доступен по ссылке
  http://mysite.ru/bitrix/admin/rubric_admin.php.

Собственно он и открывается по ссылке

домен/bitrix/admin/insert_admin.php

А как его в меню то добавить?

A: Чтобы добавить свой пункт меню в административном разделе, нужно зайти в админку - контент - файлы и папки. выбрать /bitrix/admin/. нажимаете "добавить" - "добавить меню". тип меню - "left". добавляете пункты, сохраняете.
новые пункты меню появятся в разделе "сервисы".


text:
Q: e.preventDefault does load empty page without Ajax data I used e.preventDefault() in Jquery to load an html page into a . The html page has some Ajax action that will get the data from the server. I got it works to display the page but not the Ajax data that it got. It seems to me that the page display in  happen before the ajax call back data. But with out the e.preventDefault, when click on the link, the page open a new page and it works with all the data it got back from ajax page. Any solution or help to delay the load page.
$(document).ready(function() {
    $('a').click(function (e) {
        $("#content").load($(this).attr("href"));
        e.preventDefault();
    });
});

A: The most likely cause is that the page you are loading fires of the ajax requests as part of an event handler. E.g.
$(document).ready(function(){
   fetchDataByAjax();
}

however that event won't befired when you load it through ajax. the document ready event already happened and it will only happen once.
To make it work you will therefor need to extra the javascript to a common place and include it in both pages. In one you would still execute the method(s) in the document.ready or what ever you use) while in the other you will execute it when you've inserted the html into #content


text:
Q: Grouping array elements in Rx I'm want to clean-up the following implementation into a more declarative approach, hopefully there is an Rx operator I'm missing.
I have an array of data published on a stream, something like this:
var data = new[] { 'A', 'A', 'C', 'A', 'A', 'A', 'A', 'B', 'C', 'C' };

And I want to group items in the data into a array until the change, so you the result would be:
var result = new[] { { 'A', 'A' },  {'C' }, { 'A', 'A', 'A', 'A' }, { 'B' }, { 'C', 'C' } };

I have the following, and I want to clean-up the 'Select' implementation. Ideally using an Rx operator (e.g. GroupByUntil).
How can this be improved?
 Observable.Return(data)
           .Select(items =>
           {
               var groupedItems = new List<List<char>>();

               var currentItems = new List<char>();
               var previousItem = items.FirstOrDefault();
               foreach (var currentItem in items)
               {
                   if (previousItem != currentItem)
                   {
                       groupedItems.Add(currentItems);
                        currentItems = new List<char>();
                   }

                   currentItems.Add(currentItem);
                   previousItem = currentItem;
               }
                groupedItems.Add(currentItems);
                return (IEnumerable<IEnumerable<char>>)groupedItems;
            })
            .Subscribe(groupedItems =>
            {
               foreach (var groupedItem in groupedItems)
               {
                   Console.WriteLine("{0} - {1}", groupedItem.First(), groupedItem.Count());
               }
            });

A: When the input stream is converted to a stream of characters with .ToObservable. The following implementation is possible:
    var data = new[] { 'A', 'A', 'C', 'A', 'A', 'A', 'A', 'B', 'C', 'C' };

    var publishedData = data
        .ToObservable()
        .Publish()
        .RefCount();

    publishedData
        .GroupByUntil(e => e, e => e, g => publishedData.Where(i => i != g.Key))
        .Select(g => g.ToArray())
        .Merge()
        .Subscribe(groupedItems =>
        {
            Console.WriteLine("{0} - {1}", groupedItems.First(), groupedItems.Count());
        });

The .Publish().RefCount() is needed for the closing sequence in the .GroupByUntil operator.


text:
Q: Trying to build a queue using linked list in c++ but got this error: I just started learning c++ and I am working on an assignment asking us to build queue using linked list, but when I tried my "display function" I got an Thread 1: EXC_BAD_ACCESS (code=EXC_I386_GPFLT) error, my logic behind this function is that little arrow(->) is to dereference pointers, so in theory it should be able to print out the data inside the node. Could anyone tell me what is the issue with my code?
#include <iostream>
using namespace std;

struct node{
    int data;
    node *next;
};

node *front, *last, *use;

bool isempty(){
    if(front == NULL)
        return false;
    else
        return true;
}
void add(int a){
    node *t = new node;
    t->data = a;
    if(isempty()==false){
        front = t;
        last = t;
    }else{
        front = front->next;
        t->next = front;
        front = t;
    }

}

void goaway(){
    if(isempty()==true){
        use = front;
        do{
            last = use;
            use = use->next;
        }while(use->next!=NULL);
        if(use->next == NULL)
            cout<<"You just delete: "<<use->data<<endl;
            delete use;
    }
    else{
    cout<<"Nothing in here. "<<endl;
    }
}

void display(){
    cout<<"Your stored element: "<<endl;
    for (use = front; use!=NULL; use = use->next) {
        cout<<use->data;
    }
    cout<<"\n";
}

int main(){
    front= NULL;
    last = NULL;
    int flag = 1;
    while(flag == 1){
        int choice;
        cout<<"1 add 2 remove 3 display 4 exit"<<endl;
        cin>>choice;
    switch (choice) {
        case 1:
            int a;
            cout<<"Input element!"<<endl;
            cin>>a;
            add(a);
            break;
        case 2:
            goaway();
            break;
        case 3:
            display();
            break;
        case 4:
            flag = 2;
        default:
            cout<<"wrong choice!!"<<endl;
            flag = 3;
            break;
        }
    }
}

A: First of all, In else block of add function, I don't understand why are you incrementing front while adding new Node. By doing front = front->next your front pointer always points to second node in the list whenever you call add function and your first node get waste every time which results no nodes in the list.
Secondly, In your add function, after t->data = a; you did not initialize t->next = NULL that's why you are facing undefined behavior.
Your add function should be like this:
void add(int a) {
    node* t = new node;
    t->data = a;
    t->next = NULL;
    if (isempty() == false) {
        front = t;
        last = t;
    }
    else {
        t->next = front;
        front = t;
    }
}


text:
Q: Expand div with floating children to their full height UPDATE: The problem has been solved using the code provided by Pradeep, specifically the "clearfix" code. I asked this question in search of a way of keeping my wrapper
 behind all of my content, i.e. extend its height to the full height of all its children, and considered using a moving
 where in reality my problem was fully discussed in "What is a clearfix?" and in CSS clearfix demystified.
Essentialy my container
 had floating elements within that were expanding past the bottom of my wrapper. I wanted the wrapper to be behind all of my content so that users could read the text that was on top. Applying this new CSS class clearfix to my wrapper
 the problem was solved but a new one created. I lost the ability to center the
 on the page, which I did not state in my original question below. The solution to being able to center it again without losing the "clearfix" solution was to use a parent
 that has margin-left: auto and margin-right: auto set. See CSS clearfix how to over come the inability to center an element using it
The Origional Question:
http://jsfiddle.net/L7TKx/
I want my
 to move with the page as the user scrolls down the page.
I have seen answers on this site as well as others stating that you need to add the postion:fixed property but when I do this, my div which was centered on the page is now left aligned and the scroll bar disappears, so you cannot view the rest of the content.  I'm looking for a fix that keeps the scroll bar and as the user scrolls, the
 follows.
See http://www.rustdome.hfbsite.com/ I want that off white background to follow behind the text as the user scrolls.
I have the following and have experimented with position:fixed but that disables the scroll bar.
#wrapper {
    min-width: 740px;
    max-width: 1000px;
    width: 100%;
    margin-left: auto;
    margin-right: auto;
    background-color: hsla(30,100%,97%,0.69);
    height: 100%;
}

html {
    min-height: 100%;
    position: relative;
}

body {
    height: 100%;
}

A: Instead of using position:fixed you'll probably want to use background-attachment:fixed. This will just make the background fixed while the text keeps being scrollable.
Regarding Pradeep's code you could also have used a simpler approach. You just needed to add this rule to your CSS:
#wrapper::after {
   content: "";
   display: block;
   clear: both;
   height: 0;
}

A: You can try below code:
.clearfix:after {
   content: ".";
   display: block;
   clear: both;
   visibility: hidden;
   line-height: 0;
   height: 0;
}

.clearfix {
   display: inline-block;
}

Above css add in your css file..and Add "clearfix" class in your main div(wrapper).
Good luck...

A: You will probably want it to be a separate div entirely from the one that houses your content. I am assuming the #wrapper is the off-white thing you want to move around, and I'd try something like bellow.
HTML:

        Your Content

CSS:
#wrapper {
    min-width: 740px;
    max-width: 1000px;
    width: 100%;
    position: fixed;
    left: 50%;
    margin-left: 500;
    background-color: hsla(30,100%,97%,0.69);
    height: 100%;
    z-index: -1;
}
#background {
    z-index:-2;
}


text:
Q: Identifying which tracks are too close together? I have a point shape (yield logging data) and I want to find the tracks that are too close to another track. Usually the combine drives always with the same distance (e.g. 10m). I want to find the tracks that are closer then 10m (e.g. 5m). Could this work with the voronoi polygons?
The picture below showes the problem. The red market distance between the points is ok. The blue marked point distance is not ok. These points I want to find/select.

A: It's clear from the image that the points are sequentially numbered. This means you can easily connect them together into lines using the Points to Path tool. Use the "ID" field as the Order field.

This will give you a single line that looks something like this:

(You didn't show the full data extent, so I'm just guessing at what the ends of the lines would look like.)
Now use the Split features tool (Advanced Digitizing Toolbar) to manually split this long line apart so that each "pass" of the combine is a separate line feature. Split it about where the red lines are in this image:

Select the "not OK" line, the one that's too close to the nearby passes of the combine.

*

*If you only have a few lines like in the example, use the Select Features tool (Attributes toolbar) to manually select it.

*If you have many (tens or hundreds) of lines, use the Select by Expression tool (Processing toolbox) to select all lines that are closer together than 10m. Use this expression:
intersects( $geometry, buffer(difference( $geometry, collect( $geometry)), 5))

Note: You might want to substitute a smaller buffer distance than 5m, to account for some variation in the data. Eg, if lines that are actually 9m apart instead of 10m apart are acceptable, use a buffer distance of 4.5m.

Notice that in addition to the "not OK" line, this method also selects the two "OK" lines that that line is close to. You'll have to manually remove all the "OK" lines from the selection, by using the Select Features tool while holding down the Ctrl key.

Use the Select by location tool (Processing toolbox) to select the points that intersect the "not OK" line you just selected.

The safest method (in terms of preserving your source data) is to invert the selection (open the attribute table and click the invert selection button, or hit Ctrl+R) and export the selected features to a separate layer. The faster method is to delete the selected points from the point layer if you're absolutely certain you won't need them later.


text:
Q: adding httpSecurity.csrf().disable() to spring security configuration is allowing unauthenticated endpoint calls I have the following security configuration for my springboot project
@Override
   public void configure(WebSecurity web) throws Exception {
       web.ignoring().antMatchers("/test_url_1");
   }

   @Override
   public void configure(HttpSecurity httpSecurity) throws Exception {

       httpSecurity.csrf().disable()
               .authorizeRequests()
               .anyRequest().authenticated()
               .and()
               .logout()
               .invalidateHttpSession(true)
               .clearAuthentication(true)
               .logoutSuccessUrl("/");
       httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
   }

now I have another endpoint /test_url_2. Calling which should be redirected to error page for an unauthorized user. If am removing csrf().disable() its working fine and the request is going to default /error page. but on adding csrf().disable() ,I am noticing a very unusual behaviour. once another endpoint ex. /test_url_3 is being called with an jwt header for authorization, next time onwards the endpoint(/test_url_2) is blocked even for unauthorized user, i.e. instead of going to the error page its calling the end point.
I am still new to spring security and spring, and not sure if I am writing some configuration wrong, please help me with the issue.

A: I didn't get exact meaning of the following sentences:
I am noticing a very unusual behaviour. once another endpoint ex. /test_url_3 is being called with an jwt header for authorization, next time onwards the endpoint(/test_url_2) is blocked even for unauthorized user, i.e. instead of going to the error page its calling the end point.
If you didn't get what exactly CSRF I recommend watching this video: https://youtu.be/uzZzlar-iQI from 1:08:00. If you want to authenticate url1 and don't want to authenticate url2 try the following code instead of using anyRequest().
 httpSecurity.csrf().disable()
           .authorizeRequests()
           .antMatchers('/ur1')
           .authenticated()

follow through this URL for more info on CSRF: https://www.baeldung.com/spring-security-csrf


text:
Q: Spring boot + redis I am working demo Spring boot application with integration of Redis.
I have referred various site reference but lastly I preferred to follow this: http://www.baeldung.com/spring-data-redis-tutorial
My code is almost same as given in above link. Only change is that I have autowired StudentRepository in my RestController class.
Now when I try to do maven-install at that time it gives me error that
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'studentController': Unsatisfied dependency expressed through field 'studentRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'studentRepositoryImpl' defined in file [/home/klevu/work/Nimesh/Spring Boot Workspace/bootDemo/target/classes/com/example/demo/redis/repository/StudentRepositoryImpl.class]: Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class com.example.demo.redis.repository.StudentRepositoryImpl]: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: No visible constructors in class com.example.demo.redis.repository.StudentRepositoryImpl

When I tried to keep constructor public, it creates build successfully. But I don't know I should do it or not here. I was thinking that rather than Autowiring constructor, I should be able to do setter injection. I also tried below:
@Autowired
private RedisTemplate<String, Student> redisTemplate;

But it is also not working.
package com.example.demo.redis.repository;

import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import com.example.demo.redis.bean.Student;

@Repository
public class StudentRepositoryImpl implements StudentRepository {

    private static final String KEY = "Student";

    //@Autowired
    private RedisTemplate<String, Student> redisTemplate;

    private HashOperations<String, String, Student> hashOps;

    @Autowired
    private StudentRepositoryImpl(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @PostConstruct
    private void init() {
        hashOps = redisTemplate.opsForHash();
    }

    @Override
    public void saveStudent(Student person) {
        hashOps.put(KEY, person.getId(), person);
    }

    @Override
    public void updateStudent(Student person) {
        hashOps.put(KEY, person.getId(), person);
    }

    @Override
    public Student findStudent(String id) {
        return hashOps.get(KEY, id);
    }

    @Override
    public Map<String, Student> findAllStudents() {
        return hashOps.entries(KEY);
    }

    @Override
    public void deleteStudent(String id) {
        hashOps.delete(KEY, id);
    }
}

RedisConfiguration are default and code as below:
package com.example.demo.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

@Configuration
public class RedisConfiguration {

    @Bean
    JedisConnectionFactory jedisConnectionFactory() {
        return new JedisConnectionFactory();
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(){
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(jedisConnectionFactory());
        return template;
    }

}

Spring boot main entry point is declared as below:
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;

@SpringBootApplication
@EnableMongoRepositories(basePackages = {"com.example.demo.mongo.repository"} )
@EnableRedisRepositories(basePackages = {"com.example.demo.redis.repository"})
public class BootDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(BootDemoApplication.class, args);
    }
}

Demo controller to test redis is as below:
package com.example.demo.controller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.redis.bean.Student;
import com.example.demo.redis.repository.StudentRepository;

@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentRepository studentRepository;

    @GetMapping
    public ResponseEntity<Map<String, Student>> index() {
        Map<String, Student> students = studentRepository.findAllStudents();
        return new ResponseEntity<Map<String, Student>>(students, HttpStatus.OK);
    }

    @RequestMapping(method = RequestMethod.GET, value = "/{id}")
    public ResponseEntity<Student> getStudentById(@PathVariable("id") String id) {
        Student student = studentRepository.findStudent(id);
        return new ResponseEntity<Student>(student, HttpStatus.OK);
    }

    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<Student> saveStudent(@RequestBody Student student) {
        studentRepository.saveStudent(student);
        return new ResponseEntity<Student>(student, HttpStatus.CREATED);
    }

    @RequestMapping(method = RequestMethod.PUT, value = "/{id}")
    public ResponseEntity<Student> updateStudent(@RequestBody Student student) {
        studentRepository.updateStudent(student);
        return new ResponseEntity<Student>(student, HttpStatus.OK);
    }

    @RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
    public ResponseEntity<Student> deleteMessage(@PathVariable("id") String id) {
        studentRepository.deleteStudent(id);
        return new ResponseEntity<Student>(HttpStatus.OK);
    }
}

A: You set the constructor as private... change it to public
@Autowired
public StudentRepositoryImpl(RedisTemplate redisTemplate) {
    this.redisTemplate = redisTemplate;
}

A: Change the following redis configuration:
Your original:
@Bean
public RedisTemplate<String, Object> redisTemplate() {
   ...
}

Change it to:
@Bean
public RedisTemplate<String, ?> redisTemplate(){
    ...
}

It should work now for you.

A: You could use Spring Data Redis
Add dependencies:
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

Enable Caching
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class RedisDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(RedisDemoApplication.class, args);
    }

}

Add Cacheable annotation at method to cache in redis
   @Cacheable(value = "employee", key = "#id")
    public Employee getEmployee(Integer id) {
        log.info("Get Employee By Id: {}", id);
        Optional<Employee> employeeOptional = employeeRepository.findById(id);
        if (!employeeOptional.isPresent()) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Id Not foud");
        }
        return employeeOptional.get();
    }


text:
Q: How can I define Option Partial in typescript? export type PartialOption<T,K extends string[]> = {[P in K]?: T[P]}
type Student = PartialOption<People, ['age', 'type']>
// So Student will like this
{
 age?: number,
 type?: string,
 name: string
...
}

My typescript version: "typescript": "^3.1.2",
How can I define PartialOption?

A: You just need to use a union type instead of a tuple type.
 export type PartialOption<T,K extends keyof T> = {[P in K]?: T[P]}
 type Student = PartialOption<People, 'age' | 'type'>

In fact this is actually equivalent to the bultin Partial type used with Pick<T, K>.
If you want to make just some properties optional you can use Partial to mark the optional properties and Pick to extract the rest of the properties without changing their optinality
 export type PartialOption<T,K extends keyof T> = Partial<Pick<T, K>> & Pick<T, Exclude<keyof T, K>>
 type Student = PartialOption<People, 'age' | 'type'>


text:
Q: Best practices for pointer validation? So, when I discovered the shared_ptr class (and its weak_ptr brother), I loved it. But then, one of our guys said it was too heavy and expensive. So now we just have raw pointers hanging out, and a fairly heavy multithreaded pipeline. Because bugs, we have a number of crashes that can't be null-guarded, because the pointers aren't actually null (but they are garbage). I've thought of the following constructs:
template<class T>
class GoodPtr {
public:
    GoodPtr() {
        std::lock_guard<std::mutex> lock(mux);
        goodPtrs.emplace((T*)this);
    }

    virtual ~GoodPtr() {
        std::lock_guard<std::mutex> lock(mux);
        goodPtrs.erase((T*)this);
    }

    static bool isGoodPtr(T* ptr) {
        // would love to use shared_mutex, but apparently it's not in c++11, so...
        std::lock_guard<std::mutex> lock(mux);
        return goodPtrs.find((T*)ptr) != goodPtrs.end();
    }

private:
    static std::unordered_set<T*> goodPtrs;
    static std::mutex mux;
};

template<class T> std::unordered_set<T*> GoodPtr<T>::goodPtrs;
template<class T> std::mutex GoodPtr<T>::mux;

template <class T>
class GoodPtrHolder {
public:
    GoodPtrHolder(){}
    GoodPtrHolder(T* ptr) : _ptr(ptr) {}
    void setPtr(T* ptr) {
        _ptr = ptr;
    }

    T* operator->() {
        if (_ptr && GoodPtr<T>::isGoodPtr(_ptr)) {
            return _ptr;
        } else {
            static T dummy;
            return &dummy;
        }
    }

private:
    T* _ptr = nullptr;
};

Given the following example:
class testo : public GoodPtr<testo> {
public:
    testo() {}
    virtual ~testo(){}
    void doSomething() {
        printf("sup %d\n", x);
    }
    void setX(int val) { x = val; }

private:
    int x;
};

and:
auto *test = new testo;
GoodPtrHolder<testo> testHolder(test);
testHolder->setX(5);
testHolder->doSomething();
delete test;
testHolder->doSomething();

Is this better or worse than shared_ptr, considering I have to keep a static table of pointers? Is there a better approach to the problem?

A: Apart from everything else, your code has undefined behavior here:
delete test;
testHolder->doSomething();
// ends up here:
        if (_ptr && GoodPtr<T>::isGoodPtr(_ptr)) {
//          ^^^^

The problem is that _ptr is a copy of test, and deleting test invalidates the pointer value.
In C++98 [expr.delete] says:

*The cast-expression in a delete-expression shall be evaluated exactly once. If the delete-expression calls the implementation deallocation function (3.7.3.2), and if the operand of the delete expression is not the null pointer constant, the deallocation function will deallocate the storage referenced by the pointer thus rendering the pointer invalid. [Note: the value of a pointer that refers to deallocated storage is indeterminate. ]

Or in this C++11 draft, [basic.stc.dynamic.deallocation]:

*If the argument given to a deallocation function in the standard library is a pointer that is not the null pointer value (4.10), the deallocation function shall deallocate the storage referenced by the pointer, rendering invalid all pointers referring to any part of the deallocated storage. The effect of using an invalid pointer value (including passing it to a deallocation function) is undefined.

(All emphasis mine.)
After delete test, just looking at the pointer value invokes undefined behavior.


text:
Q: Is there a C# method overload parameter ordering convention? Is there any sort of convention in C# (or any object oriented language that supports method overloading) for the following situation?
Lets say I have a method foo:
public void Foo(int a){//does stuff}

But actually I have 3 methods foo:
public void Foo(int a){}
public void Foo(int a, double b){}
public void Foo(float c, int a, double b){}

Is there a convention that states whether or not the order of parameters matters in an overloaded method? Notice how the 3rd method doesn't an obvious logical progression (a,b,c).

A: Yes there is. Have a look at https://msdn.microsoft.com/en-us/library/ms229029(v=vs.110).aspx

Do be consistent in the ordering of parameters in overloaded members. Parameters with the same name should appear in the same position in all overloads.

A: While it is not required to maintain a specific order, it is generally a good idea to do so, for the sake of readability. The order of the parameters does matter for the method signature however. For example,
public void DoStuff(int a, bool b, string c)
{

}

public void DoStuff(bool b, string c, int a)
{

}

is valid and compiles just fine, even though the number of parameters, and even their names are the same.
Update: I wouldn't recommend doing it this way. It could lead to confusion. I was just stating that it is technically valid.


text:
Q: Perl module to parse clean URL I know how to create slugs for my website, so instead of URLs like this:
www.site.com/index.cgi?article=12

I create URLs like this:
www.site.com/article/12

My question is what Perl modules exist, if any, to parse these?  I've done this with WSGI in Python but have no idea where to begin in Perl.

A: What you refer to as a slug is really a clean URL. The slug is the part of the URL that identifies the resource - in this case article/12 or perhaps just 12.
A clean URL is just a URL, and rewrite rules on the HTTP server are usually used to translate it into a form that includes the necessary resource and query.
URLs can be parsed using the URI module, but I am not clear what it is that you want to do. In this case you may as well just split the URL string on slashes. There is no general way of producing a clean URL from an unclean one, as the transformation depends entirely on the rewrite rules in place on the server.

A: You're asking about parsing these URLs, but what I think you really mean is, "How do I create a web application that uses this style of URL, and easily dispatches URL calls to function calls with the right arguments?".
If you're using one of the popular web frameworks, this will be one of the core functionalities that the framework provides:

*

*Mojolicious routing

*Catalyst chained actions

*Dancer named matching
If you're not already using a framework, well, picking one, or even deciding if you need one at all, is a whole other question.  Still, you could do worse that working through, say, the Mojolicious tutorial to see if it seems like something that would make your project easier to develop.


text:
Q: Problema ao usar CancelEdit() do BindingSource C# Estou criando um CRUD e estou utilizando o componente BindingSource com o DataSource Tipado com minha classe Pais.
No formulario coloquei um textbox ligado ao meu bindingSource na propriedade Nome do meu objeto Pais. Também foi colocado um 2 botões, o novo, onde insiro um novo Pais para cadastro no BindingSource, e o cancelar que cancela a edição.
A minha dúvida é, como faço para o bindingSource cancelar uma edição que realizo? por exemplo, clico no Botão novo, escrevo algo no textBox que é ligado ao BindingSource e quando clicado em cancelar ele voltar ao estado anterior, ou seja, desafazer o que  acabei escrevendo no meu textoBox.
Porque ao clicar no botão novo estou criando uma nova Instância do meu objeto Pais, ou seja, todos os campos null, e quando digito no textoBox(Nome) um texto e clico em cancelar, o bindingSource colocar esse texto escrito no meu campo Nome, então quando clico em cancelar e é executado o CancelEdit() do BindingSource o estado anterior do meu objeto não deveria voltar ao que era antes?

public partial class Pais : EntityBase
{
    public Pais() : base() { }
    public override string TableName { get { return "PAIS"; } }
    public override int Handle { get; set; }
    public string Nome { get; set; }
    public string Sigla { get; set; }
    public virtual ICollection<Estado> Estados { get; set; }
    public override DateTime DataCadastro { get; set; }
    public override string UsuarioCadastro { get; set; }
    public override DateTime? DataAlteracao { get; set; }
    public override string UsuarioAlteracao { get; set; }
}

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        this.bindingSource1.DataSource = typeof(App.Erp.Data.Entities.Pais);
    }

    private void btnNovo_Click(object sender, EventArgs e)
    {
        bindingSource1.Add(new Pais());
    }

    private void btnCancelar_Click(object sender, EventArgs e)
    {
        bindingSource1.CancelEdit();
    }
}

A: O que deu pra entender é que quando você clica no botão novo, o c# cria uma nova instancia. Tenta destruir a instancia manualmente. Faz assim:
private void btnCancelar_Click(object sender, EventArgs e)
{
    ~NomeDaClasse
    bindingSource1.CancelEdit();
}


text:
Q: How to print all words in an array and split them in the same function I have a program like this to print all the words in
the word_array, with delimit separating the words, and a \n after the
last word.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<ctype.h>
#include<assert.h>
void capitalize(char * lowercase) {
    while (*lowercase) {
        *lowercase = toupper(*lowercase) ;
        lowercase++ ;
    }
    return ;
}

void capitalize_all(char ** string) {
    while (*string) {
        capitalize(*string) ;
        string++ ;
    }
    return ;
}
void print_everything(char ** string, char * delimiter) {
    scanf("string =",string) ;
    for(int i=0; sp[i]!='\0'; i++)
   {
      printf("%c", string[i]);

      if(*string[i]==' ')
      {
         printf("\n");
      }
   }
    return ;
}
int main(int argc, char * argv[]) {
    int char ;
    char ** the_word_array ;
    char ** pp ;
    int i ;
    while ((char = getopt(argc, argv, "")) != -1) {
        switch(char) {
            break ;
        default:
                printf("%s\n", USAGE_MESSAGE) ;
                return 0 ;
        }
    }
    argc -= optind; // these are globals defined in the getopt code
    argv += optind;

    the_word_array = (char **) malloc((sizeof(void *)*(argc+1))) ;
    for (i=0;i<argc;i++) {
        the_word_array[i] = argv[i] ;
    }
    the_word_array[argc] = NULL ;
    pp = the_word_array ;
    capitalize_all(pp) ;
    print_all(word_array," ") ;
    return 0 ;
}

and I want to print everything words in the array + using delimiter to separate the words, and a \n after the last word in the print_everything function. How to do that?


text:
Q: How to draw a line between two buttons in android? I have two buttons in my xml layout as shown bellow.

I used an activity for this button click. I want to draw a line between these buttons as shown. Could someone please help me to draw the line between this by using code or XML..

A: You can use an custom view to draw the line such as LineView and override the onDraw.
@Override
protected void onDraw(Canvas canvas)
{
    canvas.drawLine(0, 0, getWidth(), getHeight(), m_paint);
}

Then use the XML to achieve the layout you want.
<com.android.drawable.LineView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@id/leftButton"
    android:layout_toLeftOf="@id/rightButton"
    android:layout_below="@id/leftButton"
    android:layout_above="@id/rightButton"
    />


text:
Q: Python function to approximate mathematical value of e I am writing a function to approximate the mathematical value of e.
We are told to use the factorial function and the inverse function above. It is also suggested to use map.
I have this so far, but it gives me an error saying: ValueError: factorial() only accepts integral values.
def inverse(n):
    """Returns the inverse of n"""
    return 1 / n

def e(n):
    """Approximates the mathematical value e"""
    lst = range(1, n+1)
    lst2 = map(inverse, lst)
    lst3 = map(math.factorial, lst2)
    return sum(lst3)

Could someone point me in the right direction please?

A: This is now working for me. I needed to change the range from (1, n+1) to (0, n+1) and reverse the order of doing the factorial first and then doing the inverse.
def inverse(n):
    """Returns the inverse of n"""
    return 1 / n

def e(n):
    """Approximates the mathematical value e"""
    lst = map(math.factorial, range(0, n+1))
    return sum(map(inverse, lst))

A: e can be defined by Σ(1/k!), where k = 0 .. ∞.
So, for each k,

*

*compute k!

*invert

*add to total

It looks like you're doing the inversion before the factorial instead of after, and starting from 1 instead of 0.
Note that this is not the most efficient way of doing this computation, as the factorial is unnecessarily being computed from scratch for each k.

A: As everyone else pointed out:

*

*You are missing the first term in the series which is 1.

*In python, the division gives you an integer value if both numbers are integers. i.e. 1/2 == 0.

You need something like this:
def inverse(n):
    """Returns the inverse of n"""
    # Using 1 as a float makes the division return a float value.
    return 1. / n

def e(n):
    """Approximates the mathematical value e"""
    lst = range(1, n+1) # k=1...n
    lst2 = map(math.factorial, lst)
    return 1 + sum(map(inverse, lst2))

You can compare your approximation against math.exp:
>>> abs(math.exp(1) - e(20)) < 1e-10
True

A: I has some fun with that question, using generators and decorators. First, you can create a generator to yield consecutively more precise values of e:
def compute_e():
    currentFactorial = 1
    currentSum = 1
    for i in itertools.count(start=1):
        currentFactorial *= i
        currentSum += 1/currentFactorial
        yield currentSum

And, after that, I create a decorator to find a fixed point (with a maximum number of iterations, and wanted precision) :
def getFixedPoint(gen, maxiter=10000, precision=0):
    def mywrap(*args, **kwargs):
        instanceGen = gen(*args, **kwargs)
        prevValue = next(instanceGen)
        for n, value in enumerate(instanceGen):
            if (value - prevValue < precision) or (n > maxiter):
                return value
            else:
                prevValue = value
    return mywrap

which gives me stuff like this:
In [83]: getFixedPoint(compute_e)()
Out[83]: 2.7182818284590455

In [84]: getFixedPoint(compute_e, maxiter=5)()
Out[84]: 2.71827876984127

In [85]: getFixedPoint(compute_e, precision = 0.001)()
Out[85]: 2.7182539682539684

Of cours, now I can change my way of computing each successive value of e, for example by using from decimal import Decimal:
@getFixedPoint
def compute_e():
    currentFactorial = Decimal(1)
    currentSum = Decimal(1)
    for i in itertools.count(start=1):
        currentFactorial *= i
        currentSum += 1/currentFactorial
        yield currentSum

compute_e()
Out[95]: Decimal('2.718281828459045235360287474')


text:
Q: Express res.json({}) not sending data to angular application I am trying to pass res.json after reading folder size. I am not receiving data in angular front-end. Below is the code for reference-
 const items = fs.readdirSync('//prod_storage1/shared/Computer_Ops/public/Users/');

      for(let folderperm of items){
       fs.access('//prod_storage1/shared/Computer_Ops/public/Users/'+folderperm,fs.constants.R_OK , (err) => {
         if (!err) {
           countFiles++
         }
       });
      }
    let prom = new Promise((resolve,reject) =>{
      items.forEach(function(folder){
        try {

          getSize('//prod_storage1/shared/Computer_Ops/public/Users/'+folder,async (err, size) => {
            c++
            //&& size > 314572800
            if (!err ) {
              try {
                  fullName = await ad.user(folder).get()
              } catch (error) {
                  console.log(error)
              }
              counter++
              folderArr.push({fullName:fullName.cn,folderName:folder,size:(size / 1024 /1024 /1024 ).toFixed(2)})

              console.log(counter+'- '+fullName.cn+'~ '+folder+' : '+size);
              if(folderArr.length == countFiles){
                console.log('done')
                let folderSize = folderArr;
                folderSize.sort(function(a, b){return b.size-a.size});
                resolve(folderSize)

              }
            }else{
              console.log(countFiles)
              console.log(c+'...'+folder)
            }
          })
        } catch (error) {

        console.log(error)
        }
      })
    })
    let finalRes = await prom;
    console.log(finalRes)
    res.status(204).send({'size':finalRes})
    console.log(res.headersSent)

A: If you change the status to 200 it should work. Status 204 is "No content", so it does not send back the JSON.
res.status(204).send({value: something})

becomes
res.status(200).send({value: something})

which is the same as
res.send({value: something})


text:
Q: how to read the dependencies conflicting report most resources in the internet and answers in stackoverflow just mention to add --force to npm install
I want to be able to determine which peerDependency conflicts with which one.
this is an example that I recently encountered, but if you have another conflicting report, it is welcome
npm ERR!
npm ERR! While resolving: @engineers/ngx-content-core@1.1.2
npm ERR! Found: @engineers/ngx-utils@1.1.1
npm ERR! node_modules/@engineers/ngx-utils
npm ERR!   workspace packages\ngx-utils from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! @engineers/ngx-utils@"1.1.0" from @engineers/ngx-content-core@1.1.2
npm ERR! packages/ngx-content-core
npm ERR!   @engineers/ngx-content-core@1.1.2
npm ERR!   node_modules/@engineers/ngx-content-core
npm ERR!     workspace packages\ngx-content-core from the root project
npm ERR!
npm ERR! Conflicting peer dependency: @angular/core@14.2.2
npm ERR! node_modules/@angular/core
npm ERR!   peer @angular/core@"14.2.2" from @angular/common@14.2.2
npm ERR!   node_modules/@angular/common
npm ERR!     peer @angular/common@"^14.0.6" from @engineers/ngx-utils@1.1.0
npm ERR!     node_modules/@engineers/ngx-utils
npm ERR!       @engineers/ngx-utils@"1.1.0" from @engineers/ngx-content-core@1.1.2
npm ERR!       packages/ngx-content-core
npm ERR!         @engineers/ngx-content-core@1.1.2
npm ERR!         node_modules/@engineers/ngx-content-core
npm ERR!     peer @angular/common@"14.2.2" from @angular/platform-browser@14.2.2
npm ERR!     node_modules/@angular/platform-browser
npm ERR!       peer @angular/platform-browser@"^14.0.6" from @engineers/ngx-content-core@1.1.2
npm ERR!       packages/ngx-content-core
npm ERR!         @engineers/ngx-content-core@1.1.2
npm ERR!         node_modules/@engineers/ngx-content-core


text:
Q: Vlans and subinterfaces I've inherited a moderate size network that I'm trying to bring some sanity to. Basically, its 8 public class Cs and a slew of private ranges all on one vlan (vlan1, of course). Most of the network is located throughout dark sites.
I need to start separating some of the network. I've changed the ports from the main cisco switch (3560) to the cisco router (3825) and the other remote switches to trunking with dot1q encapsulation. I'd like to start moving a few select subnets to different vlans.
To get some of the different services provided on our address space (and to separate customers) on to different vlans, do I need to create a subinterface on the router for each vlan and, if so, how do I get the switch port to work on a specific vlan? Keep in mind, these are dark sites and geting console access is difficult if not impossible at the moment. I was planning on creating a subinterface on the router for each vlan then setting the ports with services I want to move to a different vlan to allow only that vlan.  Example of vlan3:
3825:
interface GigabitEthernet0/1.3
description Vlan-3
encapsulation dot1Q 3
ip address 192.168.0.81 255.255.255.240

the connection between the switch and router:
interface GigabitEthernet0/48
description Core-router
switchport trunk encapsulation dot1q
switchport mode trunk

show interfaces gi0/48 switchport
Name: Gi0/48
Switchport: Enabled
Administrative Mode: trunk
Operational Mode: trunk
Administrative Trunking Encapsulation: dot1q
Operational Trunking Encapsulation: dot1q
Negotiation of Trunking: On
Access Mode VLAN: 1 (default)
Trunking Native Mode VLAN: 1 (default)
Administrative Native VLAN tagging: enabled
Voice VLAN: none
Administrative private-vlan host-association: none
Administrative private-vlan mapping: none
Administrative private-vlan trunk native VLAN: none
Administrative private-vlan trunk Native VLAN tagging: enabled
Administrative private-vlan trunk encapsulation: dot1q
Administrative private-vlan trunk normal VLANs: none
Administrative private-vlan trunk private VLANs: none
Operational private-vlan: none
Trunking VLANs Enabled: ALL
Pruning VLANs Enabled: 2-1001
Capture Mode Disabled
Capture VLANs Allowed: ALL

Protected: false
Unknown unicast blocked: disabled
Unknown multicast blocked: disabled
Appliance trust: none

So, if the boxen hanging off of gi0/18 on the 3560 are on an unmanaged layer2 switch and all within the 192.168.0.82-95 range and are using 192.168.0.81 as their gateway, what is left to do, especially to gi0/18, to get this working on vlan3? Are there any recommendations for a better setup without taking everything offline?

A: Pardon, in your cut and pasted configs, you appear to be describing Gi0/48 - your uplink to your router, but in your question refer specifically to hosts connected to Gi0/18. I'm going to assume you're describing two different ports here. Further, I'm assuming from details in your config statements and question, that vlan 3 is being used for the 192.168.0.80/28 traffic. I'm going to assume that the vlan has already been declared on your 3560. (Check sh vlan)
First of all, your port Gi0/18 should be configured for access mode on vlan 3. Likely, something like this:
interface GigabitEthernet 0/18
switchport access vlan 3
switchport mode access

As far as for other recommendations. Will all/most of your traffic from your IP subnets be to and from the internet. Basically, If you have enough traffic between subnets, it may suit you to have the 3560 act as your internal router and then dedicate your 3825 to be your border router. The problem is that if your router is baring the entire load for all routing, then a packet from one subnet will arrive at your switch, then be forwarded via the dot1q to your trunk on some vlan X, the router then makes a routing decision and sends the same packet back along the dot1q trunk on some new vlan Y now destined for the destination machine. Btw, I'm simply describing the situation of internal traffic to your customers/organization that crosses your different subnets.
Instead, you can configure the 3560 at the, assuming normal conventions, first address of each vlan/subnet. E.g. 192.168.0.81 and enable ip routing. The next step is you create a new subnet specifically for between the router and switch. For convenience, i'd use something completely different, for example, 192.0.2.0/24 is reserved for documentation examples. Configure the router at 192.0.2.1 and the switch at 192.0.2.2. Have the switch use 192.0.2.1 as the default route. Configure the router to reach 192.168.0.0/16 via the switch at 192.0.2.2. If your network is small enough, static routes should be sufficient. No need for OSPF or anything.
Of course, this would be a rather dramatic change; but it has potential for being a large improvement. It all depends on the nature of your traffic.
For reference, cisco lists the Cisco Catalyst 3560G-48TS and Catalyst 3560G-48PS having a 38.7 Mpps forwarding rate and the Cisco 3825 as having 0.35Mpps forwarding rate. Mpps, just in case you don't know, is millions of packets per second.
It's not bandwidth, but it's how many 64 byte packet routing decisions the device can make a second. The length of the packet doesn't affect how long it takes to making a routing decision. So the peak performance in bits/bytes will be somewhere in a range. In terms of bandwidth, it means that 350kpps is 180Mbps w/ 64byte packets and 4.2Gbps w/ 1500 byte packets. Mind you, that's in bits per second, so think of it as 18 Megabytes or 420 Megabytes per second in regular file-size terms.
In theory, this means that your 3560G can route somewhere between 19.8Gbps and 464Gbps or rougly 2GBps and 45GBps.
Actually, looking at those numbers, you most definitely should consider the plan I described above. Dedicate your 3825 to handling, presumably, NAT'd external traffic and let your 3560 handle the rest.
I'm sorry this is so long; I'm bored at work waiting for tapes to finish.
Cheers.


text:
Q: R subset rows for all occurrences of first variable in column I would like to create a subset of a large data frame based on two columns, ColA and ColB (below). For each variable in ColA (e.g. A, B, C...), I would like to extract the rows corresponding to each occurrence of the first variable in ColB. Therefore DF1:
ColA  ColB  ColC
A     Red     7thing
A     Red     OneBot
A     Blue    BotOne
B     Green   Thing7
B     Green   Twosies
B     Green   Square
B     Yellow  Circle
B     Yellow  Polygon
B     Purple  Triangle
B     White   Octagon
C     Orange  Cube
C     Black   Line

Would become DF2:
ColA  ColB  ColC
A     Red     7thing
A     Red     OneBot
B     Green   Thing7
B     Green   Twosies
B     Green   Square
C     Orange  Cube

I am not concerned about duplicates in ColC, and there is no pattern to the number of occurrences of a variable in ColB. The related subsetting strategies I have found focus on extracting unique cases, but I have neither come across nor been able to devise an approach to permit selecting all occurrences of the first variable type and would be grateful for some assistance.
I have tried
DF2 <- DF1[match(unique(DF1$ColB), DF1$ColB),]

...and subsetting that targets the variable when the variable content is known (e.g. Subset first n occurrences of certain value in dataframe in R), these are not appropriate seemingly.

A: The power of ave in base R, to compare all ColB cases to the first ColB in each group:
dat[with(dat, ColB == ave(ColB, ColA, FUN=function(x) head(x,1) )),]

#   ColA   ColB    ColC
#1     A    Red  7thing
#2     A    Red  OneBot
#4     B  Green  Thing7
#5     B  Green Twosies
#6     B  Green  Square
#11    C Orange    Cube

Using your original logic, you could also merge back on the non-duplicated records of ColA/ColB only:
merge(dat, dat[c("ColA","ColB")][!duplicated(dat$ColA),])

A: Another approach with aggregate
df[df$ColB %in% unlist(aggregate(ColB~ColA, df, function(x) head(x, 1))[2]), ]

#    ColA   ColB    ColC
#1     A    Red  7thing
#2     A    Red  OneBot
#4     B  Green  Thing7
#5     B  Green Twosies
#6     B  Green  Square
#11    C Orange    Cube

A: As it is a big dataset, approaches using data.table are
library(data.table)
setDT(df1)[df1[, .I[ColB==ColB[1L]], ColA]$V1]
#   ColA   ColB    ColC
#1:    A    Red  7thing
#2:    A    Red  OneBot
#3:    B  Green  Thing7
#4:    B  Green Twosies
#5:    B  Green  Square
#6:    C Orange    Cube

Or with .SD
setDT(df1)[, .SD[ColB==ColB[1L]], ColA]

A: You can use dplyr to accomplish what you want:
library(dplyr)
df2 <- df1 %>% group_by(ColA) %>% filter(ColB == first(ColB))

First group_by ColA, then filter to keep only rows where ColB equals the first value in ColB. The results using your data is:
print(df2)
##Source: local data frame [6 x 3]
##Groups: ColA [3]
##
##    ColA   ColB    ColC
##  <fctr> <fctr>  <fctr>
##1      A    Red  7thing
##2      A    Red  OneBot
##3      B  Green  Thing7
##4      B  Green Twosies
##5      B  Green  Square
##6      C Orange    Cube


text:
Q: Tailwindcss with SCSS I would like to implement SCSS plugin with Tailwindcss. Everything is compiled except my custom classes.
npm script:
"tw:scss": "tailwindcss --postcss -i ./src/style/index.scss -o ./src/dist/style.css"
main scss file (I also tried basic @tailwind base, @tailwind components, @tailwind utilities imports):
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";

@import "./_general.scss";
@import "./card.scss";

card.scss:
@layer components {
    .card {
    @apply bg-very-dark-blue-second rounded-lg w-11/12 p-4;
  }
}

_general.scss:
@import url("https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600&display=swap");`
body {
  font-family: "Outfit", sans-serif;
}

postcss.config.js:
module.exports = {
  plugins: [
    require("postcss-import"),
    require("tailwindcss"),
    require("autoprefixer"),
  ],
};

When I start npm run tw:scss, only _general.scss is transpiled.
Question is, is it even possible to use scss in this way? If yes, how to fix this issue.


text:
Q: Bootstrap 4 : Icon in a card header I'm trying to place an icon on the right of a card header but i'm struggling to do it.
Here's my code :

.btn {
  display: inline-block;
}

.fa-pen {
  float: right;
  display: inline-block;
  font-size: 0.75rem;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" integrity="sha384-oS3vJWv+0UjzBfQzYUhtDYW+Pj2yciDJxpsK1OYPAYjqT085Qq/1cq5FLXAZQ7Ay" crossorigin="anonymous">

        <button class="btn btn-link text-left" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
          Collapsible Group Item #1
        </button>

        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

Do you know why my icon is going on the top right corner of my
 instead of staying on the same line as my button ?

A: Flex can also do this:
h2.mb-0 {
 display: flex;
 justify-content: space-between;
 align-items: center;
}

Have you seen: https://codepen.io/iamponsiva/pen/mYpWVB

A: for 2 inline elements , you may use text-align-last and drop float:
.card-header#headingOne h2.mb-0 {
  text-align-last:justify
}

https://developer.mozilla.org/en-US/docs/Web/CSS/text-align-last
The text-align-last CSS property sets how the last line of a block or a line, right before a forced line break, is aligned.

Since you have a single line, it is also the last one .
demo below, run the snippet

.card-header#headingOne h2.mb-0 {
  text-align-last: justify
}

.fa-pen {
  font-size: 0.75rem;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" integrity="sha384-oS3vJWv+0UjzBfQzYUhtDYW+Pj2yciDJxpsK1OYPAYjqT085Qq/1cq5FLXAZQ7Ay" crossorigin="anonymous">

        <button class="btn btn-link text-left" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
          Collapsible Group Item #1
        </button>

        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
        on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
        raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

flex can also do the job :
.card-header#headingOne h2.mb-0 {
  display:flex;
  justify-content:space-between;
}

demo below, run the snippet

.card-header#headingOne h2.mb-0 {
  display:flex;
  justify-content:space-between;
}

.fa-pen {
  font-size: 0.75rem;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" integrity="sha384-oS3vJWv+0UjzBfQzYUhtDYW+Pj2yciDJxpsK1OYPAYjqT085Qq/1cq5FLXAZQ7Ay" crossorigin="anonymous">

        <button class="btn btn-link text-left" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
          Collapsible Group Item #1
        </button>

        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird
        on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
        raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

A:

.btn {
  display: inline-block;
}
h2{
  display:flex;
  align-items:center;

}
.fa-pen {
  float: right;
  display: inline-block;
  font-size: 0.75rem;
}
a{
  overflow:hidden;
  margin-left: auto;

}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" integrity="sha384-oS3vJWv+0UjzBfQzYUhtDYW+Pj2yciDJxpsK1OYPAYjqT085Qq/1cq5FLXAZQ7Ay" crossorigin="anonymous">

        <button class="btn btn-link text-left" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
          Collapsible Group Item #1
        </button>

        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.

A: Try adding this CSS
.modificationUtilisateur{
  float: right;
  margin-top:15px
 }