text:
Q: Setting data source and delegate crashes the app for UITableView New here so bear with me... I have a simple View Controller which contains a UITableView.  I am not sure whether I should connect the data source and the data controller to the View Controller. Doing so crashes the app, but if I don't do it, I don't see any output in the table view when I run the app. How should this work?
class ViewController: UIViewController {
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        }
        else {
            return 2
        }
    }

    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if section == 0 {
            return "One"
        } else {
            return "Two"
        }
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! UITableViewCell

        let cellImage: UIImage = UIImage (named: "generic.png")!

        print("cell")

        if indexPath.section == 0 {
            cell.textLabel!.text = "Section 0, Row 0"
            cell.detailTextLabel!.text = "Detail goes here."
            cell.imageView!.image = cellImage
            print("inside cell1")
        }
        else{
            if indexPath.row == 0 {
                cell.textLabel!.text = "Section 1, Row 0"
                cell.detailTextLabel!.text = "Detail goes here."
                cell.imageView!.image = cellImage
                print("inside cell2")
            }
            else {
                cell.textLabel!.text = "Section 1, Row 1"
                cell.detailTextLabel!.text = "Detail goes here."
                cell.imageView!.image = cellImage
                print ("inside cell3")
            }
        }
        return cell
        }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

}

A: Your view controller needs to conform to UITableViewDataSource and UITableViewDelegate in order to use those methods. Change your class declaration to this:
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate


text:
Q: linux - how to start listening to stdin and redirecting the lines? I've written a simple script that runs through a given list of hosts and executed a given command on these hosts.
the script basiclly looks like:
while read host; do
    ssh -f $user@$host $@
echo < servers

I want to be able to run the script so that it will start "listening" to lines from stdin and running them in the loop instead of $@.
The script will stop working by a normal termination - ctrl +c..
Any idea?

A: If I'm reading the question properly, you want to send a set of commands to a bunch of servers, all of which are passed along singularly.
For this, you should wrap the inner loop in an outer read loop; something akin to:
while read command; do
    while read host; do
        ssh -f $user@$host "$command"
        echo
    done < servers
done

When run, you can type a command and it is executed across all the servers. Resolving issues with shell escape characters being sent to the remote system is an exercise for the developer.

A: Your script is already doing that! Just understand how it works - just save it into some.bash file:
user="myuser"
while read host; do
    ssh -f $user@$host $@
done

$@ means add remaining parameters from command line, if you use none, it will add none
read host will read the line - not just word.
So basically, when you run it:
www.somehost.com
--> ssh -f myuser@www.somehost.com
www.somehost.com other parameters
--> ssh -f myuser@www.somehost.com other parameters

redpajama_set_name: RedPajamaStackExchange


text:
Q: In hiding price plugin add to cart not working I have an extension of mage me which helps to hide the price for not logged in customers and shows for logged in customers.
But add to cart button is not showing in PDP page it is showing in listing page and other places but not in PDP page.
The extension I am using is https://mageme.com/magento-2-hide-price-extension-free.html (it is a free extension anyone can use).
The code required to block the price and add to cart is default.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <referenceBlock name="product.info.form.options">
        <action method="unsetChild" ifconfig="hideprice/general/enable">
            <argument name="alias" xsi:type="string">product_options_wrapper_bottom</argument>
        </action>
    </referenceBlock>
    <referenceBlock name="product.info">
        <action method="unsetChild" ifconfig="hideprice/general/enable">
            <argument name="alias" xsi:type="string">product_info_form_content</argument>
        </action>
    </referenceBlock>
    <referenceBlock name="product.info.addtocart">
        <action method="setTemplate" ifconfig="hideprice/general/enable">
            <argument name="template" xsi:type="string" />
        </action>
    </referenceBlock>
</page>

Any idea why add to cart is not coming only there.

A: "To make layout changes available on every page, modify the default.xml file"
https://devdocs.magento.com/guides/v2.4/frontend-dev-guide/layouts/xml-instructions.html
According to magento directives, applying a change to the default.xml all pages are modified according to what is written in them. If you need different behavior for a specific page you have to change the inherent layout.
I may not have learned the question unfounded, if so please be more specific.
###Edit from here###
go in default.xml and delete this lines
<referenceBlock name="product.info">
    <action method="unsetChild" ifconfig="hideprice/general/enable">
        <argument name="alias" xsi:type="string">product_info_form_content</argument>
    </action>
</referenceBlock>
<referenceBlock name="product.info.addtocart">
    <action method="setTemplate" ifconfig="hideprice/general/enable">
        <argument name="template" xsi:type="string" />
    </action>
</referenceBlock>

The code of this module has been wrongly written, removing these lines you can see the button inside the product sheet.
You should patch via ece-tool or composer by adjusting these lines instead of removing them.
I have removed the lines to perform a quick test, now it is up to you to find the best solution for your need
Cheers


text:
Q: Django query set filter reverse startswith on charfield Image some kind of product-rule which has 2 conditions:

*

*name are equal

*sku's have partial match, starts with.

The rule model looks like this:
class CreateAndAssignRule(models.Model):
    name_equals = models.CharField(max_length=100)
    sku_starts_with = models.CharField(max_length=100

Now I want to fetch all of the rules with name Product 1 and match sku sku-b-292
class CreateAndAssignRuleQuerySet(QuerySet):
    def filter_by_name_and_sku(self, name, sku):
        # We're looking which of the rules have a matching name, and where the rule have a string which is the string of the sku provided.
        rules = self.filter(name_equals=name)

        approved_ids = []
        for rule in rules:
            # We're looping through the rules to find out which of them has the beginnings of the sku.
            # a sku_starts_with field would contains value eg: 'sku-a' where as the search string would be the full sku 'sku-a-111'.  We want to match 'sku-a-111' but not 'sku-b-222'.
            if sku.startswith(rule.sku_starts_with):
                approved.append(rule.id)

        return self.filter(id__in=approved_ids)

although the above works, it's hardly efficient especially as the number of rule is starting to grow a lot.
How can I resolve this with a queryset?  Filtering on __startswith doesn't do the trick as it the reverse.

A: Filter with:
from django.db.models import F, Value

class CreateAndAssignRuleQuerySet(QuerySet):
    def filter_by_name_and_sku(self, name, sku):
        return self.alias(
            sku=Value(sku)
        ).filter(
            name_equals=name,
            sku__startswith=F('sku_starts_with')
        )
We thus here inject the sku in the queryset, and then use this to work with a __startswith lookup [Django-doc].


text:
Q: Can someone explain my 3 MAC addresses on my router modem I have an odd issue. On my netgear router/modem admin page I have 2 MAC addresses with last letter difference one is an A the other a B.  But on my bridge router connected to the netgear one I am seeing a 3rd MAC address with a 9 at the end and the IP address points to 192.168.0.254.  I know netgear has a default login at that address, but my login page is always 192.168.0.1 and the 254 one never works.
Is this normal and not some phantom device use a fake MAC connected to network

A: This is common to see three MAC addresses on a router.  One is for the internet side connection, also called WAN for wide area network.  One is for the Ethernet LAN, local area network.  One is for the WiFi wireless LAN, or WLAN.  These numbers are normally sequential and in hexadecimal, base-16, numbering.  There's no single digit for ten so we use letters of the alphabet, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.  Seeing them differ by one digit, 9, A, then B, is normal.

A: More than likely the 3 MAC's are for the 3 different interfaces of your router.  One is for the WAN which is your public facing interface on the internet.  One is for the wired LAN, all the devices connected via ethernet.  The last one is for the wireless LAN, all the devices on WiFi.


text:
Q: How to correctly align structs in C using posix_memalign? I know that there have been many questions about this topic, but I still find myself confused.
I have written this simple program to help me visualize memory alignment in C:
#include <stdio.h>
#include <stdlib.h>
struct S{
  int a;
  short b;
  char c;
};
int main()
{
    struct S *s;
    posix_memalign((void**)&s, 8, 12) == 0 ? printf("allocation successful"):printf("allocation failed");
    printf("\nlocation of struct:\t%p\n", s);
    printf("\nlocation of int:\t%p\nlocation of short:\t%p\nlocation of char:\t%p\n", &(s->a), &(s->b), &(s->c));
    printf("\nsizeof struct: %lu\n", sizeof(s));
    free(s);
    return 0;
}

This is working well, but I am getting confused with the alignments.
Using these arguments (alignment=8 bytes, size=12):
allocation successful
location of struct: 0x205e010

location of int:    0x205e010
location of short:  0x205e014
location of char:   0x205e016

sizeof struct: 8

The int is the largest element of the struct, at 4 bytes. I can see here that the short begins 4 bytes later, and the char 2 bytes after that. Why isn't there another 2 bytes of padding between the short and char?
Also, why does the allocation fail if I use an alignment of 4 bytes? Since that is the size of the largest element in the struct, shouldn't it work?
allocation failed
location of struct: (nil)

location of int:    (nil)
location of short:  0x4
location of char:   0x6

sizeof struct: 8

A: The char member can be aligned on any byte boundary; there is never a need to insert padding before a char member, even though a compiler could if it wanted to.  The way it is laid out, there is just a single padding byte in the structure.  If there was a gap after the short member, the structure would have five bytes of padding, which is wasteful.
The chances are that the minimum alignment that posix_memalign() supports is 8 on your machine.  POSIX says it can fail:

[EINVAL]
      The value of the alignment parameter is not a power of two multiple of sizeof(void *).

Having said that, it looks like sizeof(void *) is probably 4 (the addresses you print fit in a 32-bit address space).  Maybe you should print errno (and/or strerror(errno)) to see what the cause of failure is.


text:
Q: Functional API Keras alternate solution for predict_classes() Please refer here for my previous question for background information. As per answer suggested by Nassim Ben. I trained model of two-path architecture using functional API. Now  I feel stuck as I need to predict the class of each pixel. here is the code for the same:
    imgs = io.imread(test_img).astype('float').reshape(5,240,240)
    plist = []

 # create patches from an entire slice
            for img in imgs[:-1]:
                if np.max(img) != 0:
                    img /= np.max(img)
                p = extract_patches_2d(img, (33,33))
                plist.append(p)
            patches = np.array(zip(np.array(plist[0]), np.array(plist[1]), np.array(plist[2]), np.array(plist[3])))

    # predict classes of each pixel based on model
            full_pred = self.model_comp.predict_classes(patches)
            fp1 = full_pred.reshape(208,208)

But according to the github-link predict_classes() is unavailable. So my question is there any other alternative that I can try?

A: Nassim answer is great but I want to share with you the experience I have with similiar tasks:

*

*Never use predict_proba Keras for version. Here you could find why.

*Most of methods used for turning predictions into classes doesn't take into account your data statistics. In case of image segmentation - very often detecting an object is more important then detecting a background. For this reason I advise you to use a threshold obtained from a precision-recall curve for each class. In this case - you need to set a threshold value for which precision == recall (or it's as close as possible). After you obtain the thresholds - you need to write your custom function for a class prediction.

A: Indeed, predict_classes is not available for functionnal models as it might not make sense to use it in some cases.
However, a "one liner" solution exists to this :
y_classes = keras.utils.np_utils.probas_to_classes(self.model_comp.predict(patches))

This works in keras 1.2.2, not sure about keras 2.0, I couldn't find the function in the source code. But there is really nothing shady about this, your model outputs a vector of probabilities to belonging to each class. What the function does is just take the argmax and outputs the class coresponding to the highest probability.
I hope this helps.


text:
Q: How to "fuzzy" fingerprint an array For my current project I need to find a way to "fuzzy" - fingerprint a javascript array client-side.
The problem is that the elements inside the array can change over time. By change I mean the order is stable but some elements may be removed and others my be included. Now I need to find a way that produces exactly the same fingerprint (within a given threshold).
I'm currently thinking about a kind of a partial match implementation but I'm curious how others would do it.

A: You could wrap your array into an object and add a modification counter to that object. On each array modification you must increment the modification counter.
by defining a treshold for array modifications, you can make decisions.
var fuzzyArray = {
                   data : [],
                   modCount : 0,
                   changeElement : function (elementId, newData){
                                      data[elementid] = newData;
                                      modCount++;
                                   }
               };

 //adding some elements...

 fuzzyArray.changeElement(1,"foo");
 if (fuzzyArray.modCount > treshold){
     // do something
 }

A: It depends on what your definition of "fuzzy" is.
Filype's suggestion will give you a highly specific fingerprint. Nothing fuzzy about that.
One solution would be looking at the levenstein difference between the JSON representations of the test case and the reference data set (divide the score by the length of the reference set to get a proportion). A quick google found this implementation.
Alternatively you might simply do a count of the elements which are different


text:
Q: Tem como criar regra no MYSQL para dividir o valor de uma coluna por outra? Quero saber a média dos valores (valorm2) em uma tabela usando o AVG() (ou outra forma).
Tenho uma tabela no MYSQL com as colunas id, valortotal (Valor total), valorm2 (Valor por m²) e area.
Em algumas linhas o valorm2 está vazio e em outras o valortotal está vazio.
Tem alguma forma de fazer um select para se o campo estiver vazio, ele faça uma conta? Tipo o abaixo:
tabela_terrenos
id|valortotal|valorm2|area
1 |100000    | 1000  |100
2 |150000    |       |100
3 |          | 1500  |200

aí precisaria antes de trazer a média, algo do tipo:
SE valorm2 = vazio, então valorm2 = valortotal / area
SENÃO valorm2 = valorm2

SELECT AVG(valorm2)
FROM tabela_terrenos

A: Tente isso:
SELECT IFNULL(AVG(valorm2), valortotal/area) valorm2
FROM tabela_terrenos


text:
Q: "An unhandled exception occurred while processing the request" with ABP asp.net core 3.1 I have just set up the ABP code in the machine and when I run the web project, I am getting this issue.
An unhandled exception occurred while processing the request.
SocketException: No connection could be made because the target machine actively refused it.
System.Net.Http.ConnectHelper.ConnectAsync(string host, int port, CancellationToken cancellationToken)

HttpRequestException: No connection could be made because the target machine actively refused it.
System.Net.Http.ConnectHelper.ConnectAsync(string host, int port, CancellationToken cancellationToken)

Stack Query Cookies Headers Routing
SocketException: No connection could be made because the target machine actively refused it.
System.Net.Http.ConnectHelper.ConnectAsync(string host, int port, CancellationToken cancellationToken)

Show raw exception details
HttpRequestException: No connection could be made because the target machine actively refused it.
System.Net.Http.ConnectHelper.ConnectAsync(string host, int port, CancellationToken cancellationToken)
System.Threading.Tasks.ValueTask<TResult>.get_Result()
System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable<TResult>+ConfiguredValueTaskAwaiter.GetResult()
System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, bool allowHttp2, CancellationToken cancellationToken)
System.Threading.Tasks.ValueTask<TResult>.get_Result()
System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable<TResult>+ConfiguredValueTaskAwaiter.GetResult()
System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
System.Threading.Tasks.ValueTask<TResult>.get_Result()
System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable<TResult>+ConfiguredValueTaskAwaiter.GetResult()
System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
System.Threading.Tasks.ValueTask<TResult>.get_Result()
System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable<TResult>+ConfiguredValueTaskAwaiter.GetResult()
System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, bool doRequestAuth, CancellationToken cancellationToken)
System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
System.Net.Http.DiagnosticsHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
Polly.Retry.AsyncRetryEngine.ImplementationAsync<TResult>(Func<Context, CancellationToken, Task<TResult>> action, Context context, CancellationToken cancellationToken, ExceptionPredicates shouldRetryExceptionPredicates, ResultPredicates<TResult> shouldRetryResultPredicates, Func<DelegateResult<TResult>, TimeSpan, int, Context, Task> onRetryAsync, int permittedRetryCount, IEnumerable<TimeSpan> sleepDurationsEnumerable, Func<int, DelegateResult<TResult>, Context, TimeSpan> sleepDurationProvider, bool continueOnCapturedContext)
Polly.AsyncPolicy<TResult>.ExecuteAsync(Func<Context, CancellationToken, Task<TResult>> action, Context context, CancellationToken cancellationToken, bool continueOnCapturedContext)
Microsoft.Extensions.Http.PolicyHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task<HttpResponseMessage> sendTask, HttpRequestMessage request, CancellationTokenSource cts, bool disposeCts)
Volo.Abp.Http.Client.DynamicProxying.ApiDescriptionFinder.GetApiDescriptionFromServerAsync(HttpClient client, string baseUrl)
Volo.Abp.Http.Client.DynamicProxying.ApiDescriptionCache.GetAsync(string baseUrl, Func<Task<ApplicationApiDescriptionModel>> factory)
Volo.Abp.Http.Client.DynamicProxying.ApiDescriptionFinder.GetApiDescriptionAsync(HttpClient client, string baseUrl)
Volo.Abp.Http.Client.DynamicProxying.ApiDescriptionFinder.FindActionAsync(HttpClient client, string baseUrl, Type serviceType, MethodInfo method)
Volo.Abp.Http.Client.DynamicProxying.DynamicHttpProxyInterceptor<TService>.MakeRequestAsync(IAbpMethodInvocation invocation)
Volo.Abp.Http.Client.DynamicProxying.DynamicHttpProxyInterceptor<TService>.MakeRequestAndGetResultAsync<T>(IAbpMethodInvocation invocation)
Volo.Abp.Http.Client.DynamicProxying.DynamicHttpProxyInterceptor<TService>.GetResultAsync(Task task, Type resultType)
Volo.Abp.Http.Client.DynamicProxying.DynamicHttpProxyInterceptor<TService>.InterceptAsync(IAbpMethodInvocation invocation)
Volo.Abp.Castle.DynamicProxy.CastleAsyncAbpInterceptorAdapter<TInterceptor>.InterceptAsync<TResult>(IInvocation invocation, IInvocationProceedInfo proceedInfo, Func<IInvocation, IInvocationProceedInfo, Task<TResult>> proceed)
Castle.DynamicProxy.AsyncInterceptorBase.ProceedAsynchronous<TResult>(IInvocation invocation, IInvocationProceedInfo proceedInfo)
Volo.Abp.Castle.DynamicProxy.CastleAbpMethodInvocationAdapterWithReturnValue<TResult>.ProceedAsync()
Volo.Abp.Validation.ValidationInterceptor.InterceptAsync(IAbpMethodInvocation invocation)
Volo.Abp.Castle.DynamicProxy.CastleAsyncAbpInterceptorAdapter<TInterceptor>.InterceptAsync<TResult>(IInvocation invocation, IInvocationProceedInfo proceedInfo, Func<IInvocation, IInvocationProceedInfo, Task<TResult>> proceed)
Volo.Abp.AspNetCore.Mvc.Client.CachedApplicationConfigurationClient.<GetAsync>b__13_0()
Volo.Abp.Caching.DistributedCache<TCacheItem, TCacheKey>.GetOrAddAsync(TCacheKey key, Func<Task<TCacheItem>> factory, Func<DistributedCacheEntryOptions> optionsFactory, Nullable<bool> hideErrors, CancellationToken token)
Volo.Abp.AspNetCore.Mvc.Client.CachedApplicationConfigurationClient.GetAsync()
Volo.Abp.AspNetCore.Mvc.Client.RemoteLanguageProvider.GetLanguagesAsync()
Microsoft.AspNetCore.RequestLocalization.DefaultAbpRequestLocalizationOptionsProvider.GetLocalizationOptionsAsync()
Microsoft.AspNetCore.RequestLocalization.AbpRequestLocalizationMiddleware.InvokeAsync(HttpContext context, RequestDelegate next)
Microsoft.AspNetCore.Builder.UseMiddlewareExtensions+<>c__DisplayClass5_1+<<UseMiddlewareInterface>b__1>d.MoveNext()
Volo.Abp.AspNetCore.MultiTenancy.MultiTenancyMiddleware.InvokeAsync(HttpContext context, RequestDelegate next)
Microsoft.AspNetCore.Builder.UseMiddlewareExtensions+<>c__DisplayClass5_1+<<UseMiddlewareInterface>b__1>d.MoveNext()
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Volo.Abp.AspNetCore.Tracing.AbpCorrelationIdMiddleware.InvokeAsync(HttpContext context, RequestDelegate next)
Microsoft.AspNetCore.Builder.UseMiddlewareExtensions+<>c__DisplayClass5_1+<<UseMiddlewareInterface>b__1>d.MoveNext()
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

A: Run projects in this order: *.IdentiyServer project, *.HttpApi.Host project and then *.Web project.


text:
Q: Update command updating wrong values I am using C#, MS Access as database.I create class with properties of same as Table in database and trying to update database by this class properties using Reflection and class key value use in where condition for updatation purpose. Following is method which handle this:
    public void UpdateDBByObject(object objClass, string key, object keyValue, string tableName = null)
    {
        string _updateQuery = string.Empty;

        Type objType = objClass.GetType();
        List<PropertyInfo> propertyList = new List<PropertyInfo>(objType.GetProperties());

        Dictionary<string, object> _props = new Dictionary<string, object>();

        _updateQuery += "update " + (string.IsNullOrEmpty(tableName) ? objType.ToString().Split('.').LastOrDefault().TrimEnd('s') : tableName) + " set";

        foreach (var prop in propertyList)
        {
            string _name = prop.Name;
            if (_name == key) continue;

            _updateQuery += " [" + _name + "] = ?,";

            _props.Add(_name, prop.GetValue(objClass, null));
        }
        _updateQuery = _updateQuery.TrimEnd(',');
        _updateQuery += " where " + key + " = ?";

        OleDbCommand cmd = new OleDbCommand();
        OleDbConnection conn;
        cmd.CommandType = CommandType.Text;

        cmd.CommandText = _updateQuery;

        foreach (string value in _props.Keys)
        {
            object _addValue;
            cmd.Parameters.AddWithValue("@" + value, _props.TryGetValue(value, out _addValue));
        }

        cmd.Parameters.AddWithValue("@" + key, keyValue);

        conn = GetOpenConnection();
        cmd.Connection = conn;
        cmd.ExecuteNonQuery();
        CloseConnection(conn);
    }

this method working but updating wrong values in database, i.e. for string value it update "-1" value, for DateTime it update min DateTime value. Please find out error and let me know.

A: TryGetValue(value,out object) will out bool value hence for every time it will bool value.
 object outValue;
 cmd.Parameters.AddWithValue("@" + value, _props.TryGetValue(value, out outValue));

A: I was adding bool value as paramenter in following line of code:
cmd.Parameters.AddWithValue("@" + value, _props.TryGetValue(value, out _addValue));

After changing this code works fine.


text:
Q: How to use two findElement in the same line? I have these code lines in my project. It supposed to click an element but when I run this code, my browser gets shut down. I don't know what causes that. Is it about the variables inside findElement?
List <WebElement> listItems=driver.findElement(RESULTCONT).findElements(MEDİA);
((JavascriptExecutor) driver).executeScript("arguments[0].click();", listItems);

A: arguments[0] should be webElement and not List

A: Here is the quick fix. From the list, get the first webelement and use the the same while passing the argument.
List <WebElement> listItems=driver.findElement(RESULTCONT).findElements(MEDİA);

// Getting the first webelement in the list and storing it
WebElement first = listItems.get(0);
((JavascriptExecutor) driver).executeScript("arguments[0].click();", first);


text:
Q: AWS CDK assign Elastic IP to Elastic Beanstalk Single Instance I am trying to assign an existing Elastic IP to an EC2 instance in a SingleInstance Elastic Beanstalk environment created with CDK.
However, I could not find out:

*

*How to get the reference to an existing Elastic IP with CDK

*How to get the reference to the EC2 instance created by the Elastic Beanstalk Environment

*How to allocate the Elastic IP to that Instance

Environment Source
  const environment = new elasticbeanstalk.CfnEnvironment(this, `somename`, {
        applicationName: 'someappname',
        environmentName: 'someenvname',
        platformArn:
            'arn:aws:elasticbeanstalk:eu-central-1::platform/Node.js 16 running on 64bit Amazon Linux 2/5.5.0',
        optionSettings: [
            {
                namespace: 'aws:elasticbeanstalk:environment',
                optionName: 'EnvironmentType',
                value: 'SingleInstance',
            },
            {
                namespace: 'aws:autoscaling:launchconfiguration',
                optionName: 'InstanceType',
                value: 't3.small',
            },
            {
                namespace: 'aws:autoscaling:launchconfiguration',
                optionName: 'IamInstanceProfile',
                value: 'aws-elasticbeanstalk-ec2-role',
            },
        ],
        versionLabel: applicationVersion.ref,
    });


text:
Q: Сложная выборка данных из БД SQL Server У меня есть большая база данных. Она локальная поэтому я не могу скрины принести. Итак
В базе есть
таблица Users
Поля id, name
Таблица Clients
Поля id, user_id, name
Таблица Sessions
Поля id, client_id, description
Таблица SessionMeta
поля id, user_id, session_id, status
Все таблицы связаны соответствующими ключами
Короче мне нужно посчитать сколько у каждого Пользователя по каждому из его Клиентов всего Сессий и Сессий со статусом = 2 из SessionMeta таблицы.
Это не лень, я просто реально запутался и у меня взрывается голова. Я пытался делать через Inner JOIN но с SQL не на проф уровне работаю.
Подскажите пожалуйста как сформировать такой сложный запрос. Какие команды использовать и в каком порядке. Большое спасибо.

A: Первый вопрос так решается:
SELECT
    u.id,
    u.name,
    c.id,
    c.name,
    COUNT(s.id) AS SessionCount
FROM Users u
    INNER JOIN Clients c ON c.user_id = u.id
    INNER JOIN Sessions s ON s.client_id = c.id
GROUP BY u.id, u.name, c.id, c.name

Второй так:
SELECT
    u.id,
    u.name,
    c.id,
    c.name,
    COUNT(s.id) AS SessionCount
FROM Users u
    INNER JOIN Clients c ON c.user_id = u.id
    INNER JOIN Sessions s ON s.client_id = c.id
    INNER JOIN SessionMeta sm ON sm.session_id = s.id AND sm.status = 2
GROUP BY u.id, u.name, c.id, c.name


text:
Q: Magento Unable to send mail I have a custom module that sends email on localhost but now when I uploaded it to a live server, it generates an exception saying that "Unable to send mail."
Note: emails are enabled on the server and it sends registration or other emails.
I think it is not a duplicate question as in this: Magento e-mail sending does not work question email never got delivered. where as in my case registration/order emails are successfully delivering.

A: Are you using the Email sending classes?
If not, try doing it this way, as this will give you the flexibility of outputting an error message when the message is sent. Using both Mage::log and Session based error output will allow you to see what's going on even if you don't witness the event.
$mail = Mage::getModel('core/email')
        ->setToName($senderName)
        ->setToEmail($customerEmail)
        ->setBody($body)
        ->setSubject('Subject :')
        ->setFromEmail($senderEmail)
        ->setFromName($senderName)
        ->setType('html');

try{
    $mail->send();
} catch(Exception $error) {
    Mage::log($error->getMessage());
    Mage::getSingleton('core/session')->addError($error->getMessage());
    return false;
}

Failing this, it's probably something you'll need to speak to your hosting company about, as they sometimes block certain mail methods.


text:
Q: How to display standardized y-scores in interaction plot I am trying to plot a two-way interaction of standardized data in R using the package "interplot". However, the displayed y-scores are not standardized anymore. Why is that and how can I fix that?
I have tried to change the y-limits and to use the "scale_y_continuous()" function.
# generate data
x <- rnorm(100, 0, 1)
y <- x + rnorm(100, 0, 1)
z <- y + rnorm(100, 0, 1)
df <- as.data.frame(cbind(x,y,z))

# build model with interaction term
model1 <- glm(y ~ x*z, data=df)

# plot interaction
require(interplot)
interplot(model1, var1 = "x",var2 = "z", ci = 0.95, predPro = TRUE,
    var2_vals = c(-1, 1), hist=F) + xlim(-3, 3) +
    theme_classic()

I expect the y-scale to display values between -3 and +3, since the scores are standardized. However, the displayed y-values are between 20 and 80.

A: With the help of ?interplot example :
set.seed(123)
# generate data
x <- rnorm(100, 0, 1)
y <- x + rnorm(100, 0, 1)
z <- y + rnorm(100, 0, 1)
df <- as.data.frame(cbind(x,y,z))

# build model with interaction term
model1 <- glm(y ~ x*z, data=df)
# lm(y ~ x*z, data=df) # glm => is a linear model

# plot interaction
require(interplot, quietly = TRUE, warn.conflicts = FALSE)
interplot(model1, var1 = "x",var2 = "z", ci = 0.95,
          predPro = TRUE, var2_vals = c(-1,1)) +
        xlim(-3, 3) +
        xlab("x values") +
        ylab("Estimated Coefficient for z") +
        ggtitle('Estimated Coefficient of z by x conditionally to y in c(-1,1)') +
        theme_classic()

interplot(model1, var1 = "x",var2 = "z", ci = 0.95) +
        xlim(-3, 3) +
        xlab("x values") +
        ylab("Estimated Coefficient for z") +
        ggtitle('Estimated Coefficient of z by x') +
        theme_classic()
#> Warning: Removed 28 rows containing missing values (geom_path).


text:
Q: What is the difference between Theme.AppCompat and Theme.Material in Android? In My case, what is difference in here:
<style name="AppTheme" parent="android:Theme.Material.Light.DarkActionBar">

and
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

A: This is the raw material design theme, which is used by Android 5 and upNot sure how this works wrt. new Android libraries for app design:
<style name="AppTheme" parent="android:Theme.*">

This is a way to use material design on pre-lollipop devices, which maintains compatibility.
<style name="AppTheme" parent="Theme.AppCompat.*">

You can design for newer APIs using AppCompat and still have it work on earlier API levels than what the base level for material design is.
In this case, it essentially means that you can run material design on platforms that predate material design. This isn't as important anymore now that versions that early make up at most ~2.5% of the market share at the time of writing.
Note, however, that using AppCompat does give you additional compatibility helpers beyond just being able to use the material theme on older devices. Also note that AppCompat has since been deprecated in favor of whatever system is currently mainstream and that Google hasn't axed yet (Jetpack?), which may or may not work differently.

A: <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<style name="AppTheme" parent="android:Theme.Material.Light.DarkActionBar">

Theme.AppCompat is for above API 7+
Theme.Material is for above API 21+


text:
Q: How to populate many config files with same value(s) I have many programs and all of them have some identical values in their config files (most, if not all, of which are in /etc).
Let's say it is hostname, which is stored in the config files of Apache, Postfix, SQL, clamAV, whatever...
Sometimes I need to change those values. What I do now is to edit all those files and find&replace the previous value with the new one.
I would like to change it in one place, and set all those files properly.
I thought about bash's export variable, source command or something similar; however, since the config files are not executable, I don't think it will work.
What would be the recommended method?

A: Obviously, you must identify all the parameters that you want to manage,
and all locations where they appear.
(Duh.)
You knew that already.
Here's an approach that might get you started on the right track:

*

*Choose a character string that will never, ever,
appear in one of the configuration files.
(That makes it sound like you must get it right on the first try.
That's not really true; if you choose a string (for example, @@)
and you later need to use that string in one of the files, you can fix it.
You'll just have to redo a lot of this setup.)
For example, a long time ago, Unix had a version control system
called the Source Code Control System (SCCS);
it used the string @(#) as a string
that would never appear naturally in a file.
As far as I know, SCCS isn't in use any more (at least, not much),
so it should be safe to use @(#).
Or you could use something like !user2461440?,
or whatever your real name is.
You could include control character(s);
e.g., Ctrl+A or Ctrl+G.

*Choose a naming convention for parameter placeholders.
This could be something simple and straightforward
like @(#){HOSTNAME}, @(#){IP}, @(#){GATEWAY}, etc.

*Create template versions of all your configuration files,
like apache.template, etc.
Edit those templates to replace all occurrences
of the parameters you want to manipulate
with their corresponding parameter placeholders
(from the previous paragraph).
You should put these (and the following) in a safe, out-of-the-way place,
like a subdirectory of /root.

*Write a script like this:
HOST=Zanzibar
IP=10.11.12.42
    ︙
LOG=/var/log/lumber
    ︙

fullpath[apache]=/etc/apache.conf
fullpath[postfix]=/etc/postfix/configuration
    ︙

for file in apache postfix …
do
    path=${fullpath[$file]}
    sed -e "s/@(#){HOSTNAME}/$HOST/g" \
        -e "s/@(#){IP}/$IP/g" \
                   ︙
        -e "s|@(#){LOG}|$LOG|g" \
                   ︙
        "$file.template" > "$path.new"  &&
        mv "$path" "$path.bak"          &&
        mv "$path.new" "$path"
done

Observe that the subcommand that replaces @(#){LOG} with $LOG
uses a different delimiter (|), because the $LOG value contains /s.
Note that, therefore,
the @(#) string must not contain this delimiter (|).
(And, of course, it must not contain the standard (/) delimiter.)

*Arrays (e.g., fullpath[apache]) don't work in all shells.
If you don't have bash or another shell that supports arrays,
the script will need to be adapted to simulate or work around them.

*You might need to add chown and chmod commands to the script
to set the system attributes of the files correctly.
Or, if you're really really sure
that you've gotten the script working correctly,
you can modify it to overwrite the files in place, as in
    sed  …      > "$path"

thus retaining the inode and its attributes,
and not use the mv command or the .new and .bak files.

*When you want to change one of the parameters
that you've chosen to automate, edit the corresponding assignment statement
(e.g., HOST=Wonderland) at the beginning of the script.
If you don't want to have to edit the script,
break the script into two files:
one that contains the parameter values (HOST=…, IP=…, etc…)
and one that does all the handling of the configuration files.
The second script would source the first one to get the parameter values.
That way, when a parameter value changes,
you need to edit only the (script) file that contains the values,
and not the main script.

*Be sure not to manually edit the files in place,
as those changes will be overwritten the next time
you run the parameterization script.
Instead, edit the corresponding template file and re-run the script.
You might want to put comments in the files to remind you of this.
(If you don't like the idea
of regenerating all of the configuration files
for a change that affects only one of them,
you can modify the script
so it has the capability to regenerate only selected file(s).)


text:
Q: Speed up mouse wheel in jScrollPane (jQuery) I have a div with a fixed height and in it a ul-list and many li-items. I apply to the div a jScrollPane for which I want to customize the appearance of the scrollbar. My code is like:
$(function() {
    $('.myDiv').jScrollPane( { showArrows: true, arrowScrollOnHover: true, wheelSpeed: 120 });
});

As jScrollPane I use the scripts of http://jscrollpane.kelvinluck.com and it is kind of working. But the speed of the mouse wheel (velocity of scrolling) is much too slow although I tried to set the speed up as you can see in my example above.
Does anybody has had the same effect and can give me a hint how I can speed it up?

A: You have to define the wheel speed when you initialize the plugin like this:
$('.scroll-pane').jScrollPane({
    mouseWheelSpeed: 50
});

A: In the jquery.jscrollpane.js (or even .min.js file), find "mouseWheelSpeed" in the "defaults". This was 3 for me originally, I bumped it up to 30. Perhaps it is 3 or 30 pixles/click.
Edit
Sargin Sargin's answer is probably better for most cases. Given his solution, editing the plugin file would only make sense if you wanted to set a new default for reuse around a site. You'd also need to make note of changes made so that you don't lose your customisation when you update the file.


text:
Q: How to calculate sectional curvature? I'm some new here, sorry if my question is not correct. I need to calculate the sectional curvature of a Riemannian manifold. I found this formula in several books.
$$K(\sigma,p)=\frac{R(X,Y,Y,X)}{g(X,X)g(Y,Y)-g(X,Y)}$$
My problem is that none of them do the detailed accounts, and it frustrates me because most that I have been able to read have a different notation. I am quite confused, I would like to know if anyone knows any book where I can find some text that makes a summary of the formulas (from defining the metric, Christoffel symbols, Riemannian tensor, etc.) and applies them in an example to understand. And if someone would be so kind to do it here, I would be very grateful, it does not matter if it is a simple example such as the sphere or hyperbolic space or a surface of revolution I don't know... I just want to see the technique to be able to understand and apply it.


text:
Q: Compile error; user defined type not defined I'm now to Excel VBA and recently got this error when trying to run a Macro (Compile error; user defined type not defined).  The highlighted error (in bold) is as follow:
Dim xmlToImport AS MSXML.2.DOMDocument
Set xmlToImport = New MSXML2.DOMDocument

Not sure why I've been getting this recently, but any assistance would be helpful.  I'm also very new to VBA so bear with me. :)  Thanks!!


text:
Q: Ajax toolkit 2013 version errors I download the package whit ajax 4.5 version, I added the DDL to toolbox, reference to same DDL as a added items to toolbox, using this on aspx
<ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></ajaxToolkit:ToolkitScriptManager>

<ajaxToolkit:CalendarExtender ID="TextBox1_CalendarExtender" runat="server" Enabled="True" TargetControlID="TextBox1">
    </ajaxToolkit:CalendarExtender>

But this error occur, what did I do wrong?
Unhandled exception at line 3, column 412 in http://localhost:6944/View/Chart/Chart.aspx?_TSM_HiddenField_=ToolkitScriptManager1_HiddenField&_TSM_CombinedScripts_=;;AjaxControlToolkit,+Version=4.5.7.123,+Culture=neutral,+PublicKeyToken=28f01b0e84b6d53e:en-US:e669ce41-1aa1-4541-aae9-fa5dc37e70db:de1feab2:fcf0e993:f2c8e708:720a52bf:f9cec9bc:589eaa30:698129cf:fb9b4c57:ccb96cf9

0x800a139e - JavaScript runtime error: AjaxControlToolkit requires ASP.NET Ajax 4.0 scripts. Ensure the correct version of the scripts are referenced. If you are using an ASP.NET ScriptManager, switch to the ToolkitScriptManager in AjaxControlToolkit.dll.
All was added from toolbox.

A: When you create one WEB API, the project already has one AJAX version and give a lot of problems, I solve it creating one empty WebForms. Add ajaxtoolkit to tollbox and the correct DLL will be added automatically if any version was add, And be happy.


text:
Q: IN my case Button1.setEnable(True); is not working in my case when i try to set the button enable using BUTTON1.setEnable(false);
so the emulator does not start the apk...
i want to create a game level menu with some buttons Enable and rest of the buttons Disable .as each button is a game level .. so if my integer flag has value 5 so first five levels buttons should be active and rest of the buttons be disable.... but i could not even set a single button disable ... please help am i missing some concept with buttons ... where to change their state in OnResume() or in OnCreate();
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button b1=(Button)findViewById(R.id.button);

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

}
}

A: I don't have an android development environment at hand right now, but I could imagine, that it has somethin to do, with the view (and therefore the button) not beining available at the time of the initiation of the attribute b1. Could you try the following:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

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

        getButton1().setEnabled(false);

    }

    private Button getButton1() {
        return (Button)findViewById(R.id.button);
    }
}

A: You should add b1 = (Button) findViewById(R.id.button) into your onCreate() method.
Try this:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    Button b1;

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

        b1 = (Button) findViewById(R.id.button);
        b1.setEnabled(false);
    }
}

A: so in order to set buttons Enable/Disable one have to declare the buttons into OnCreate ...otherwise it wont find the view of the button and show errors ...
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

Button b1;

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

    b1 = (Button) findViewById(R.id.button);
    b1.setEnabled(false);
}

}
is the right way .............thanks everone


text:
Q: Powershell - Return Azure Blob Size by first split string value So I am trying to list the contents on an Azure blog container size, I can get how much storage is being used as a whole. What I trying to do is break it down, by the first position of the filename.
And this is my sad attempt. Could someone point me in the right direction please?
$ResourceGroup = "RG"
$StorageAccountName = "SAN"
$ContainerName = "CN"

$storageAccount = Get-AzStorageAccount `
  -ResourceGroupName $ResourceGroup `
  -Name $StorageAccountName
$Context = $storageAccount.Context

$Blobs = Get-AzStorageBlob -Container $ContainerName -Context $Context
$length = 0
$Blobs | ForEach-Object {$length = $length + $_.Length }

#$Blobs.Name.Split("_",2)[0]

$Blobs | Select-Object Name, Length

$TotalSize = [math]::Round(($length / 1024 / 1024 / 1024 / 1024),2)
Write-Host "Total Size: $TotalSize Terabytes"

Current Output.
ABCD_History_20221127_110045            9306112
ABCD_History_20221204_110052            11010048
ABCD_History_20221211_110045            10616832
EFGH_20220327_110201                    48562176
EFGH_20220403_110159                    46596096
Total Size: 29.63 Terabytes
Desired Output
ABCD                                    30932992
EFGH                                    95158272
Total Size: 29.63 Terabytes

A: I have reproduced in my environment and got expected results as below and I followed Microsoft-Document:
$ResourceGroup = "XX"
$StorageAccountName = "rith"
$ContainerName = "rithwik"

$storageAccount = Get-AzStorageAccount `
  -ResourceGroupName $ResourceGroup `
  -Name $StorageAccountName
$Context = $storageAccount.Context

$Blobs = Get-AzStorageBlob -Container $ContainerName -Context $Context
$length = 0
$Blobs | ForEach-Object {$length = $length + $_.Length }
$Blobs | Select-Object Name, Length

After that used below code to get required Output:
foreach($emo in $blobs)
 {
 $BlobName=$Blobs.Name.Substring(0,3)
 }
$Target = @()
foreach($emo in $BlobName)
 {
 $bn=$emo
 $x=0
foreach($b in $blobs)
 {
 if ($b.Name -match $Bn)
 {
 $x=$x+$b.Length
 }
 }
 $out = $bn + $x
 $Target += $out
 }
$Target | select -uniq

If you want 4 letters in output give 4 in substring command instead of 3.
If you space between name and length you use like below in place of  $out = $bn + $x in for loop:
$out = $bn +" "+ $x


text:
Q: Using VBA script to highlight cells based on a formula from the active cell Let's start with my spreadsheet & code so far (cleaned up to remove irrelevant and personal information):

A
B
C
D

22
Who
How Much
What Day
Notes

23
HE WHO MUST NOT BE NAMED
10
1

24
HE WHO MUST NOT BE NAMED
25
1

25
HE WHO MUST NOT BE NAMED
35
2

26
HE WHO MUST NOT BE NAMED
32
5

27
HE WHO MUST NOT BE NAMED
21
8

28
HE WHO MUST NOT BE NAMED
32
8

29
HE WHO MUST NOT BE NAMED
1
9

30
HE WHO MUST NOT BE NAMED
29
9

31
HE WHO MUST NOT BE NAMED
3
10

32
HE WHO MUST NOT BE NAMED
13
12

33
HE WHO MUST NOT BE NAMED
5
15

34
HE WHO MUST NOT BE NAMED
6
15

35
HE WHO MUST NOT BE NAMED
32
17

36
HE WHO MUST NOT BE NAMED
20
20

37
HE WHO MUST NOT BE NAMED
30
21

38
HE WHO MUST NOT BE NAMED
2
26

39
HE WHO MUST NOT BE NAMED
15
26

40

41
Pay date
Bill Total
Additional
Carrying Balance

42
22-Oct
119

43
5-Nov
174

44
19-Nov
137

45
3-Dec
142

46
17-Dec
99

47
31-Dec
201

48
14-Jan
110

49
28-Jan
188

50
11-Feb
106

51
25-Feb
205

52
11-Mar
106

53
25-Mar
172

54
8-Apr
192

55
22-Apr
119

56
6-May
142

57
20-May
137

58
3-Jun
142

59
17-Jun
134

60
1-Jul
201

61
15-Jul
110

62
29-Jul
201

63
12-Aug
106

64
26-Aug
202

65
9-Sep
139

66
23-Sep
119

67
7-Oct
162

68
21-Oct
117

69
4-Nov
174

70
18-Nov
137

71
2-Dec
177

72
16-Dec
99

73
30-Dec
212

74
16-Jan
0

This function:
Sub HighLightCells()
ActiveSheet.UsedRange.Cells.FormatConditions.Delete
Dim day As Range
For Each day In Range("Table1[What Day]")
    ActiveSheet.UsedRange.Cells.FormatConditions.Add Type:=xlExpression, _
        Formula1:="=IF(MONTH(Cells(ActiveCell.Row,1))=MONTH(Cells(ActiveCell.Row+1,1)),AND(day>=DAY(Cells(ActiveCell.Row,1)),day<DAY(Cells(ActiveCell.Row+1,1))),OR(day>=DAY(Cells(ActiveCell.Row,1)),day<=DAY(Cells(ActiveCell.Row+1,1))))"
    ActiveSheet.UsedRange.Cells.FormatConditions(1).Interior.ColorIndex = 4
Next day
End Sub

This is in the sheet's code:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
 Call HighLightCells
End Sub

What am I trying to accomplish? Yesterday I had some assistance creating a script to add up all of my bills according to what day they fell in my pay checks. The formula I am using for that (the entire Bill Total column):
=IF(MONTH(A42)=MONTH(A43),SUMIFS(Table1[How Much],Table1[What Day],">="&DAY(A42),Table1[What Day],"<"&DAY(A43)),SUMIF(Table1[What Day],">="&DAY(A42),Table1[How Much])+SUMIF(Table1[What Day],"<="&DAY(A43),Table1[How Much]))

Now, I am trying to use VBA to highlight the bills that are due within a specific pay period when I click on the row in the table that correlates with that pay period. Right now I have the macro set to the entire sheet, but it would be nice if I could get it to only work on the range of the table (which is named "Table3")
So basically, if I clicked on row 44 which has a pay date of Nov 19, I would like for it to highlight all of the bills due between Nov 19 and Dec 3 (the formula to sum it is above, which is what I am basing this highlight off as well).
Where am I right now with my code: The Formula1 I am using works if I replace the variable "day" and replace the information contained within DAY() to an actual cell. When I do this in the actual VBA script, it takes around 30 seconds (as if it is cycling through almost an infinite loop) and then stops and nothing is highlighted. I am not sure what I am doing wrong.
Version: O365 on Windows


text:
Q: Monotouch 4.9 Alpha with MonoDevelop 2.8 Alpha: socket error starting simulator I'm doing some testing with MonoDevelop 2.8 Alpha and MonoTouch 4.9 alpha to check out some of the new UI controllers Apple offers with iOS 5.
When trying to launch my app, all I get in MonoDevelop is:
Socket error while connecting to 127.0.0.1 on port 10001: Connection refused


text:
Q: Streaming between two NSURLConnections, blocking NSInputStream read blocks all connections? I'm trying to stream data between two iOS NSURLConenctions (one downloading, the other uploading), but can't seem to make it work.

*

*I have two NSURLConnections running simultaneously.

*One is downloading content from a url using a GET request.

*The other is uploading the same content just received, to another url, in the request body of a PUT request.

*In the upload connection I'm using setHTTPBodyStream to specify a custom NSInputStream whose read method returns data previously received from the other connection.

*Both NSURLConnections are scheduled in the run loops of separate background threads, so that any (possibly blocking) delegate callbacks don't mess with each other (and neither with the main thread).

So I thought it would work like this:

*

*The upload connection calls [read:maxLength] (which I have overridden) on the input stream.

*Since there's no data available yet, the read call blocks.

*On another thread, [connection:didReceiveData:] is called on the delegate of the download connection.

*It puts the received data in a shared buffer, thus making it available for the input stream of the upload connection.

*The upload stream's read call now isn't blocked anymore, it can return a chunk of data.

Unfortunately in practice, this does not work. After the upload stream's read method blocks, the download connection's delegate methods (eg. didReceiveData) don't get called anymore. (Note that if I disable the blocking on the upload side, then didReceiveData on the download side does get called all right.)
I suspect that this has to do something with the fact that the upload input stream's read method is called not on the thread where the connection and the stream objects were created, but on some other thread (apparently created by Cocoa). As if this was some shared thread used by both NSURLConnections, so once it's blocked, all other connections stop working as well. Or something like that.
Does anyone have an idea about what's really happening?
Also, is there a way to control on which thread the request body input stream's read method gets called?


text:
Q: Want to write a loop to find reflectance values for each column So I have this code in R that I'm using on a dataframe df that comes in the format where each row is a wavelength (823 rows/wavelengths) and each column is a pixel (written as V1-V2554).

I have the code to normalise each reflectance value as such per each spectrum/pixel:
# Define function to find vector length
veclen=function(vec) {
    sqrt(sum(vec^2))
}
# Find vector length for spectrum of each pixel
df_vecV6 <- df %>%
              group_by(Wavelength) %>%
              summarise(veclengthV6 =  veclen(V6))

# Join new variable "veclength"
df <- df %>%
      left_join(df_vecV6, by = "Wavelength")

# Define function that return normalized vector
vecnorm=function(vector) {
          vector/veclen(vector)
}
# Normalize by dividing each reflectance value by the vector's length
df$refl_normV6 <- vecnorm(df$V6)

but I want to create a loop to do this for all 2553 columns. I started writing it but seem to come up with problems. In this case df is finaldatat and I wanted to create a list svec to store vector lengths before the next steps:
for(i in (1:ncol(finaldatat))){
  svec[[i]]<- finaldatat %>%
    #group_by(Wavelength) %>%
    summarise (x = veclen(finaldatat[,i]))
}

That first step runs, but the vector lengths that are meant to be below zero are way above so I already know there's a problem. Any help is appreciated!
Ideally in the final dataframe I would only have the normalised results in the same 2554x824 format.

A: You can use dplyr's across function to apply vecnorm to all columns from V1 to V2554.
result <- df %>%
            group_by(Wavelength) %>%
            summarise(across(V1:V2554, vecnorm))
            #In older version of dplyr use summarise_at :
            summarise_at(vars(V1:V2554), vecnorm)


text:
Q: Symfony2 Saving selected date from form to the database as DateTime In my form a user selects when he would like to get the the purchase simply like this:
        ->add('start_date', 'date', array(
            'input'  => 'datetime',
            'widget' => 'choice',
        ))

Now I would like to save this date to the database in this field:
/**
 * @var \DateTime
 *
 * @ORM\Column(name="campaign_list_end_date", type="date", nullable=true)
 */
private $endDate;

So when the form is submited I get the date. But its an array of strings:
$data = $request->request->get('courier');
echo var_dump($data['start_date']); die;

array (size=3)
  'month' => string '2' (length=1)
  'day' => string '1' (length=1)
  'year' => string '2012' (length=4)

How can I convert this value to a DateTime object?
I tried something like this, it didnt work:
$date = new DateTime('now');
$start_date = $date->setTimestamp($data['start_date']);

Any ideas?

A: When using symfony forms, you should retrieve the posted data from the form itself. The form will transform the data to the correct type for you:
$date = $form->get('start_date')->getData();

in addition, if your form is bound to an entity, you can also get the bound entity with the posted values extracted into it:
$entity = $form->getData();


text:
Q: Bash command with pipe('|') alway return exit code of 0, even in error case Code
a.py
import sys
import errno

def main():
    try:
        raise Exception("asdf")
        sys.stdout.write('{"v1": "kk"}')
        sys.stdout.flush()
    except IOError as e:
        # This catching exception is for preventing 'Broken Pipe' error
        # ref: https://www.geeksforgeeks.org/broken-pipe-error-in-python/
        if e.errno == errno.EPIPE:
          pass

if __name__ == "__main__":
    main()

b.py
import io
import sys

def main():
    # Getting input from the previous process's std output
    input_messages = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8')
    for message in input_messages:
        print(message)

if __name__ == '__main__':
    main()

1. Experiment 1
1.1 a.sh
echo $?   # print 'exit code'
python a.py
echo $?

1.2 Execution result
$ sh a.sh
>>
0
Traceback (most recent call last):
  File "/Users/chois/Dropbox/Programming/Workspace/chois_workflow/data_ingestor/a.py", line 67, in <module>
    main()
  File "/Users/chois/Dropbox/Programming/Workspace/chois_workflow/data_ingestor/a.py", line 57, in main
    raise Exception("asdf")
Exception: asdf
1

--> Exit code is 1 due to the exception
2. Experiment 2
2.1 a.sh
echo $?   # print 'exit code'
python a.py | python b.py
echo $?

2.2 Execution result
$ sh a.sh
>>
0
Traceback (most recent call last):
  File "a.py", line 67, in <module>
    main()
  File "a.py", line 57, in main
    raise Exception("asdf")
Exception: asdf
0

--> Exit code is still 0, even process has an error.
How can I make the command with pipe have exit code of 1?


text:
Q: Cannot add Microsoft.AspNet.Mvc.Core to classic library I'm having a classic library that is based on .Net4.6 and I would like to add the nuget-package of the new mvc6. I try doing this using the Package Manager Console. The error is the follwing:
Install-Package : Failed to add reference to 'System.Runtime'. Please make sure that it is in the Global Assembly Cache.
At line:1 char:1
+ Install-Package Microsoft.AspNet.Mvc.Core -Pre
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Install-Package], Exception
    + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand

Installing the requested System.Runtime is no problem - it works fine:
Install-Package System.Runtime -Pre

And this is the total result:
PM> Install-Package Microsoft.AspNet.Mvc.Core -Pre
Attempting to gather dependencies information for package 'Microsoft.AspNet.Mvc.Core.6.0.0-rc1-final' with respect to project 'LibTest', targeting '.NETFramework,Version=v4.6'
Attempting to resolve dependencies for package 'Microsoft.AspNet.Mvc.Core.6.0.0-rc1-final' with DependencyBehavior 'Lowest'
Resolving actions to install package 'Microsoft.AspNet.Mvc.Core.6.0.0-rc1-final'
Resolved actions to install package 'Microsoft.AspNet.Mvc.Core.6.0.0-rc1-final'
Adding package 'System.Diagnostics.DiagnosticSource.4.0.0-beta-23516' to folder 'C:\Data\MyProject\SourceCode\packages'
Added package 'System.Diagnostics.DiagnosticSource.4.0.0-beta-23516' to folder 'C:\Data\MyProject\SourceCode\packages'
Added package 'System.Diagnostics.DiagnosticSource.4.0.0-beta-23516' to 'packages.config'
Successfully installed 'System.Diagnostics.DiagnosticSource 4.0.0-beta-23516' to LibTest
Adding package 'Microsoft.AspNet.Mvc.Core.6.0.0-rc1-final' to folder 'C:\Data\MyProject\SourceCode\packages'
Added package 'Microsoft.AspNet.Mvc.Core.6.0.0-rc1-final' to folder 'C:\Data\MyProject\SourceCode\packages'
Install failed. Rolling back...
Package 'Microsoft.AspNet.Mvc.Core.6.0.0-rc1-final : Microsoft.AspNet.Authorization [1.0.0-rc1-final, ), Microsoft.AspNet.FileProviders.Abstractions [1.0.0-rc1-final, ), Microsoft.AspNet.Hosting.Abstractions [1.0.0-rc1-final, ), Microsoft.AspNet.Mvc.Abstractions [6.0.0-rc1-final, ), Microsoft.Extensions.Logging.Abstractions [1.0.0-rc1-final, ), Microsoft.Extensions.MemoryPool [1.0.0-rc1-final, ), Microsoft.Extensions.PlatformAbstractions [1.0.0-rc1-final, ), System.Diagnostics.DiagnosticSource [4.0.0-beta-23516, )' does not exist in project 'LibTest'
Removed package 'System.Diagnostics.DiagnosticSource.4.0.0-beta-23516 : System.Diagnostics.Tracing [4.0.0, ), System.Runtime [4.0.0, ), System.Threading [4.0.0, )' from 'packages.config'
Removing package 'Microsoft.AspNet.Mvc.Core.6.0.0-rc1-final : Microsoft.AspNet.Authorization [1.0.0-rc1-final, ), Microsoft.AspNet.FileProviders.Abstractions [1.0.0-rc1-final, ), Microsoft.AspNet.Hosting.Abstractions [1.0.0-rc1-final, ), Microsoft.AspNet.Mvc.Abstractions [6.0.0-rc1-final, ), Microsoft.Extensions.Logging.Abstractions [1.0.0-rc1-final, ), Microsoft.Extensions.MemoryPool [1.0.0-rc1-final, ), Microsoft.Extensions.PlatformAbstractions [1.0.0-rc1-final, ), System.Diagnostics.DiagnosticSource [4.0.0-beta-23516, )' from folder 'C:\Data\MyProject\SourceCode\packages'
Removed package 'Microsoft.AspNet.Mvc.Core.6.0.0-rc1-final : Microsoft.AspNet.Authorization [1.0.0-rc1-final, ), Microsoft.AspNet.FileProviders.Abstractions [1.0.0-rc1-final, ), Microsoft.AspNet.Hosting.Abstractions [1.0.0-rc1-final, ), Microsoft.AspNet.Mvc.Abstractions [6.0.0-rc1-final, ), Microsoft.Extensions.Logging.Abstractions [1.0.0-rc1-final, ), Microsoft.Extensions.MemoryPool [1.0.0-rc1-final, ), Microsoft.Extensions.PlatformAbstractions [1.0.0-rc1-final, ), System.Diagnostics.DiagnosticSource [4.0.0-beta-23516, )' from folder 'C:\Data\MyProject\SourceCode\packages'
Removing package 'System.Diagnostics.DiagnosticSource.4.0.0-beta-23516 : System.Diagnostics.Tracing [4.0.0, ), System.Runtime [4.0.0, ), System.Threading [4.0.0, )' from folder 'C:\Data\MyProject\SourceCode\packages'
Removed package 'System.Diagnostics.DiagnosticSource.4.0.0-beta-23516 : System.Diagnostics.Tracing [4.0.0, ), System.Runtime [4.0.0, ), System.Threading [4.0.0, )' from folder 'C:\Data\MyProject\SourceCode\packages'
Install-Package : Failed to add reference to 'System.Runtime'. Please make sure that it is in the Global Assembly Cache.
At line:1 char:1
+ Install-Package Microsoft.AspNet.Mvc.Core -Pre
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Install-Package], Exception
    + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand

PM>

Any idea what could be the problem here?

A: I'm not sure what it really was... but I changed some points:

*

*I had my projects on net461. I changed them back to net451. This removed some warnings in the dependency-graph of the references in the aspnet5-application.

*After I tried to add Microsoft.AspNet.Mvc.Core and it failed I changed the packages.config manually: I added this line:

<package id="Microsoft.AspNet.Mvc.Core" version="6.0.0-rc1-final" targetFramework="net451" />
And after recompiling it seems to work.


text:
Q: CSS centralising elements So I'm learning about css graphics and I'm trying to create this image in css:

I have started with flexbox to try and lay out my items but have since learnt I can't centre my circle in the centre. It's also not yet responsive. I haven't tried to centre the logo yet either. All elements need to keep their aspect ratio.
Can someone tell me where i'm going wrong please?
Once I've got the image centred too, I want to make the orange and blue boxes into buttons. I'd appreciate how to overlay a transparent button too if possible.
I have put my code on codepen and in a snippet below.

*{
 color: #535252;
 font-family: --var(BB_font);
}

body {
 font-size: 15px;
 background-color: #c3c5c8;
}

.title{
 font-size: 5em
}

.image {
 background-repeat: no-repeat;
 background-position: center;
}

.orangeRectangle {
 width: 100%;
 height: auto;

 border-top-right-radius: 150px;
 border-bottom-right-radius: 150px;
 z-index: 0;

 background: #ec673e;
}

.blueRectangle {
 width: 100%;
 height: auto;

 border-top-left-radius: 150px;
 border-bottom-left-radius: 150px;
 z-index: 0;

 background: #67b9ce;
}

.rectangleTitle {
 text-align: center;
 font-size: 3em
}

.greyCircle {
 width: 40%;
 height: 40%;
 position: absolute;
 left: 30%;
 top: 25%;
 align-self: center;
 z-index: 5;
 background-color: #535252;
 border-radius: 50%;
}
<!DOCTYPE html>

 <title>Landing Page</title>

 <link href="https://fonts.googleapis.com/css?family=Lato:400,700" rel="stylesheet">

 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">

 <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">

 <link rel="stylesheet" type="text/css" href="BB1.css">

Header

Heading 1

Heading 2

Lorem ipsum dolor sit amet consectetur adipisicing elit. Laboriosam cum iste voluptatibus reprehenderit in dolor veritatis non eveniet at. Suscipit molestiae maxime laboriosam! Ipsa praesentium consectetur ratione quo distinctio iure nulla explicabo quas consequatur, id deserunt ducimus labore error vitae omnis animi facilis harum debitis. Facere architecto impedit eaque excepturi dolorum optio nemo ab! Iusto, vel non veritatis dolorem debitis voluptatum provident omnis commodi perspiciatis velit distinctio! Deleniti, nam aliquid quidem repudiandae voluptates, excepturi aperiam nesciunt quo ad officia impedit. Ipsa eveniet culpa ullam odio amet ea cupiditate consectetur et? Illo, accusamus tempore. Dolor voluptas voluptatum asperiores esse illo eaque.

Thanks

A: Centering in Flexbox
With flexbox, the simplest trick for centering anything is to set the containing element to display: flex; or display: inline-flex; and then add align-items: center; (this will vertically center all content) and justify-content: center (this is for horizontal centering).
Like this:

* {
  margin: 0;
  padding: 0;
}

.flex-container {
  border: 5px solid red;
  display: flex;
  height: calc(100vh - 10px);
  width: calc(100vw - 10px);
}

.center-everything {
  align-items: center;
  justify-content: center;
}

  center me!

Maintaining Aspect Ratio
Regarding maintaining aspect ratio, you will want to define height and width for each element. If you need this layout to be responsive (aka, maintain all aspect ratios when sized up or down), you can use relative units to ensure that your proportions are fixed.
Making Elements Into Anchors or Buttons Via Wrapping
Making an element into a button is as easy as wrapping it in  or <button></button> tags, which are inline tags that should maintain your layout when used as wrappers. You can then customize the actions these links/buttons execute using href, onclick, or JavaScript event listeners (see my demo below). There's a plethora of resources online if you search for any of that.
Overlaying and position: absolute
Regarding overlaying, you can easily create an overlay element by nesting it inside a container and then laying the nested element over that container using position: absolute (this breaks the element out of the z-plane and positions it relative to a container with position: relative). You can set the height and width to 100% since this nested element is now relative to its position: relative container, so these settings will ensure the element overlays the entire containing element. You can then position the element using top: 0 and left: 0, which will ensure the element is flush with two sides of its container.
A good article on this: https://teamtreehouse.com/community/how-css-position-absolute-brings-the-overlay-element-to-the-front
See this demo with multiple overlays of semi-transparent colors, using position: absolute inside of a position: relative container (with some fun toggling action for kicks):

const overlayYellow = document.querySelector(".overlay.yellow");
const overlayBlue = document.querySelector(".overlay.blue");
const buttonYellow = document.querySelector(".btn.yellow");
const buttonBlue = document.querySelector(".btn.blue");

buttonYellow.addEventListener('click', () => {
  toggleOverlay('yellow');
});

buttonBlue.addEventListener('click', () => {
  toggleOverlay('blue');
});

function toggleOverlay(color) {
  const overlay = (color === 'yellow') ? overlayYellow : overlayBlue;

  if (overlay.classList.contains('hidden')) {
    overlay.classList.remove('hidden');
  } else {
    overlay.classList.add('hidden');
  }
}
* {
  margin: 0;
  padding: 0;
}

.container {
  background: red;
  height: 100vh;
  width: 100vw;
}

.overlay {
  display: block;
  height: calc(100% - 10px);
  left: 5px;
  opacity: 0.5;
  position: absolute;
  top: 5px;
  width: calc(100% - 10px);
  z-index: 1;
}

.overlay.yellow {
  background: yellow;
}

.overlay.blue {
  background: blue;
}

.overlay.hidden {
  display: none;
}

.btn {
  cursor: pointer;
  height: 36px;
  position: absolute;
  right: 12px;
  width: 180px;
  z-index: 2;
}

.btn.yellow {
  top: 12px;
}

.btn.blue {
  top: 60px;
}

  <button class="btn yellow">Toggle yellow overlay!</button>
  <button class="btn blue">Toggle blue overlay!</button>

A: The best way to approach this is to make an additional div container. Inside this container, you have your background and the logo with the grey background as a kind of an overlay. I updated your codepen accordingly.
.greyCircle {
    width: 40vh;
    height: 40vh;
    z-index: 5;
    background-color: #535252;
    border-radius: 50%;
}
.circle-container-overlay {
  position: absolute;
  width: 100%;
  height: 100%;
  align-items: center;
  justify-content: center;
  display: flex;
  top: 0;
}

.additional-outer-container {
  position: relative;
  height: 950px
}

I recommend you having a look on How to Center in CSS and A Complete Guide to flexbox. These two sites are awesome resources, when it comes to creating layouts in css.


text:
Q: Java tiled based rendering, possible to move the already painted? So if I don't clear my painting area it will just paint over there I paint and leave the other parts there I haven't painted as the old was. So can I take what's already is painted and move it to the left for example. So I can fit an new set of tiles on the right without needing to repaint all of it?
Or am I getting at this at the wrong angle?

A: You can do what you're describing but there's no point to it that I can think of. Rendering part of the screen after some offset will yield no real improvement.
I'll assume you're trying to do this for faster rendering.
Most games do 2 things for faster tiled rendering.

*

*Clipping. Don't render what's offscreen. Don't render what's underneath other opaque tiles if you're rendering 2.5D.

*Rendering sections of your map to bigger images, then render these bigger images instead of each tile image individually.

The second is more difficult, and has limitations. For example, you'd need to rerender the larger images if your tile content changes. This would probably get you the most improvement.


text:
Q: How to change between python, pascal, and javascript language easily in Visual Studio Code? I just learned programming, and I just installed vscode. Can I change between programming languages easily? And how to run Pascal programming in it?

A: You can just write your files, and vscode will handle everything for you, as it has a very good understanding of file associations.
The only things that might be confusing are when using f5 for example to run your code.
You can set what happens when pressing f5 (Debug) and control shift b (build)by altering the tasks defined in tasks.json.
To find this file, go to your command pallet (f1 or control shift p), and search for Tasks: Open User Tasks.
There's a link in that file to the schema docs.
I think the file is saved in the .vscode folder at the root of your project's directory.


text:
Q: Spring @Scheduled annotation method runs more than once in a given time Spring scheduled cron job is running twice in a scheduled time.
Using spring 4.2.5 version.
REST API -> Jersey + Spring Integration.
web.xml as below.
 <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
    <servlet-name>REST-Service-Servlet</servlet-name>
    <servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
    <init-param>
        <param-name>com.sun.jersey.config.provider.packages</param-name>
        <param-value>RESTController</param-value>
    </init-param>
    <init-param>
        <param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
        <param-value>com.om.ResponseCorsFilter</param-value>
    </init-param>
     <init-param>
        <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
        <param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
        <param-value>com.sun.jersey.api.container.filter.LoggingFilter</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>REST-Service-Servlet</servlet-name>
 <url-pattern>/api/*</url-pattern>

spring application context xml file for the task entry.
<task:annotation-driven/>

Spring bean as follows.
@Component("springBean")
public class SpringBean {

@Scheduled(cron = "0 35 23 * * ?")
public void job() {....}

A: Thanks for your help. Problem resolved.
Solution: I was loading the same bean twice, so removed the duplicate bean.


text:
Q: Is it possible to uninstall Bash on Ubuntu on Windows, since the latest updates provide a different Ubuntu and SUSE app? If it is, how do I safely remove the Bash on Ubuntu on Windows application while leaving a working Ubuntu and OpenSUSE?

A: Running lxrun /uninstall /full in (e.g.) Windows Powershell with administrative privileges will remove Bash on Ubuntu while leaving your new app-based Ubuntu installation untouched.

A: TLDR
wsl --unregister Legacy

Explanation
I believe Christan Davén's answer just removes the shortcut from the start menu, but does not actually remove the WSL (you will still be able to run the WSL by executing C:\Windows\System32\bash.exe and find all of your files and installed apps as you left them).
Silviu's answer is correct. However, if you've upgraded to the Windows 10 Fall Creators Update the lxrun /uninstall /full command will not be available anymore and you should instead run wsl --unregister Legacy.
A third option is to run wslconfig /u Legacy (try this if you are not using Windows Version 1903 or higher).
Source
https://docs.microsoft.com/en-us/windows/wsl/install-legacy#uninstallingremoving-the-legacy-distro

A: Since lxrun was deprecated and removed in the Windows 10 April 2018 Update (see Command Reference for Windows Subsystem for Linux), the only way for me to get rid of "Bash on Ubuntu on Windows" was:

*

*Remove Windows Subsystem for Linux (WSL) via the Control Panel

*Restart the computer

*Try to start "Bash on Ubuntu on Windows"

*Agree to remove the shortcut

*Re-install WSL

*Restart the computer

Hat tip to How-To Geek:

If you'd like to remove the bash.exe tool and the Windows Subsystem for Linux from your computer completely, you'll need to revisit the "Turn Windows Features On or Off" dialog in the Control Panel.
To find it, open the Control Panel and head to Programs > Turn Windows Features On or Off.
Uncheck the "Windows Subsystem for Linux" option here and click OK. Windows will uninstall the Windows Subsystem for Linux, bash.exe, and lxrun.exe commands. You can always revisit the Windows Features dialog to reinstall them in the future.


text:
Q: Converting from Sql to Linq I have, what I thought was a pretty straight-forward query.
In normal Sql this would read:
SELECT    [column names]
FROM      agentscheduledetail
WHERE     (date = '2012-07-04') AND
           (
            exception = 'Break (No Sign Off)' OR
            exception = 'Break' OR
            exception = 'Break (Signed Out)'
           )

This returns approx 900 records.
However, when I try to enter this into my controller, I end up with around 300,000 records - so I think my AND and ORs are not working.  I've tried Linqer, but can't get it to work (I'm aware this may not be actual LINQ but the equivalent query in VS - if there is a linq version... I'd be grateful for that too if possible).
My controller query is:
        var dte = DateTime.Today;

        return View(db.agentscheduledetails.Where
           (
            d => d.date == dte && d.agentName.StartsWith("ta") &&
             (
              d.exception == "Break (No Sign Off)" ||
              d.exception == "Break" ||
              d.exception == "Break (Signed Out)"
             )
            ).ToList()
           );

Can anyone either a) let me know where I'm going wrong with my && || (and/or), or b) is there a way of stepping through the code in VS, to see what the above query translates to in normal SQL so I can try to figure out where I'm going wrong?
Thanks for any help,
Mark

A: The following is perhaps a simplified version of what you are trying to do, also your LINQ contains an additional statement compared to the SQL where it is comparing the agent name?
var currentDate = DateTime.Today;
var exceptionTypes = new List<string>() { "Break (No Sign Off)",
                                          "Break", "Break (Signed Out)" };

db.agentscheduledetails.Where(d => d.date == currentDate &&
                                           exceptionTypes.Contains(d.exception));

One thing that you could try is getting hold of a copy of LinqPad, this will let you run your LINQ statement against a database and will show you what the generated SQL statement is.

A: Aside from anything else,
    d.agentName.StartsWith("ta")

does not appear in your original sql...?


text:
Q: Function as response value in JS I found the following example in a course and I don't understand it.
This code takes two arguments, in this case two years, and returns true if 1912 is within those two years, otherwise the result is false. Example:
function yearToCheck(year) {
  return function(x, y) {
    return year >= x && year <= y;
  }
}

const checkYears = yearToCheck(1912);

checkYears(1900, 1913) // true
checkYears(1900, 1911) // false

The code works. I just want ot undestand why does the anonymous function "function (x, y)" take the values 1900 and 1913/1911 from the variable checkYears?


text:
Q: How to use LIKE SQL query in JS RESTFUL api? Trying to make a search query for mySQL with JS.
Working code:
    searchRestaurants(request, respond){
        var term = request.params.id
        var sql = "SELECT restaurant FROM restaurant_details WHERE restaurant LIKE '%' ? '%'";
        db.query(sql, term, function(error, result){
            if(error){
                throw error;
            }
            else{
                respond.json(result);
            }
        });
    }

Here's my code: (old)
"use strict"

var db = require("../db-connection");

class RestaurantDB{
    searchRestaurants(request, respond){
        var key = request.params.id
        var sql = "SELECT restaurant FROM restaurant_details WHERE restaurant LIKE '% ? %'";
        var values = [key];
        db.query(sql, function(error, result){
            if(error){
                throw error;
            }
            else{
                respond.json(result);
            }
        });
    }
}

module.exports = RestaurantDB;

Id is received through user input through url.
"use strict"

const restaurantdb = require("../models/RestaurantDB");

var restaurantDBObject = new restaurantdb();

function routeRestaurants(app){
    app.route("/restaurant")
        .get(restaurantDBObject.getAllRestaurants);
    app.route("/restaurant/:id")
        .get(restaurantDBObject.searchRestaurants)
}

module.exports = {routeRestaurants};

So when I try going to "localhost:8080/restaurant/way" to try and search for Subway, it returns nothing. Just a "[]".
What is the correct way to go about doing this? Thanks in advance
Here's a working example
    addReview(request, respond) {
        var now = new Date();
        var reviewObject = new Review(null, request.body.restaurant, request.body.rating, request.body.comment,
            request.body.username, now.toString());
        var sql = "INSERT INTO reviews (restaurant, rating, comment, username, timestamp) VALUES(?,?,?,?,?)";

        var values = [reviewObject.getRestaurant(), reviewObject.getRating(),
        reviewObject.getComment(), reviewObject.getUsername(), reviewObject.getTimestamp()];

        db.query(sql, values, function (error, result) {
            if (error) {
                throw error;
            }
            else {
                respond.json(result);
            }
        });
    }

db-connection
var mysql = require("mysql");
var connection = mysql.createPool({
    host:"localhost",
    port:"3306",
    user:"root",
    password:"",
    database:"project"
});
module.exports = connection;


text:
Q: Symfony 2 - Setting a Flash Message outside of Controller I have a logout Listener where I'd like to set a flash message showing a logout confirmation message.
namespace Acme\MyBundle\Security\Listeners;

use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;

class LogoutListener implements LogoutSuccessHandlerInterface
{
  private $security;

  public function __construct(SecurityContext $security)
  {
    $this->security = $security;
  }

  public function onLogoutSuccess(Request $request)
  {
    $request->get('session')->getFlashBag()->add('notice', 'You have been successfully been logged out.');

    $response = new RedirectResponse('login');
    return $response;
  }
}

Here is my services.yml (as it pertains to this):
logout_listener:
   class:  ACME\MyBundle\Security\Listeners\LogoutListener
   arguments: [@security.context]

This is generating an error:
Fatal error: Call to a member function getFlashBag() on a non-object

How do I set a flashBag message in this context?
Also, how do get access to the router so I can generate the url (via $this->router->generate('login')) instead of passing in a hard-coded url?
Resolution Note
To get the flash to work, you must tell your security.yml config not invalidate the session on logout; otherwise, the session will be destroyed and your flash will never appear.
logout:
    path: /logout
        success_handler: logout_listener
        invalidate_session: false

A: The answers are very old on this post. 10 years later (2022), Symfony allows to deal with flashes very easily outside of a controller using the FlashBagInterface:
<?php

namespace App\Service;

use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;

class MyService
{
    private $flash;

    public function __construct(FlashBagInterface $flash)
    {
        $this->flash = $flash;
    }

    public function myRandomMethod(): string
    {
        // ...
        $this->flash->add('success', 'This is a success!');
    }
}

A: You should inject the services for session and router into the LogoutListener and use them to perform these tasks. This is the way to do it in yml:
logout_listener:
class: ACME\MyBundle\Security\Listeners\LogoutListener
arguments: [@security.context, @router, @session]

Then in your class you write:
class LogoutListener implements LogoutSuccessHandlerInterface
{
    private $security;
    private $router;
    private $session;

    public function __construct(SecurityContext $security, Router $router, Session $session)
    {
        $this->security = $security;
        $this->router = $router;
        $this->session = $session;
    }
    [...]

When you want to use the session now you can just say:
$this->session->getFlashBag()->add('notice', 'You have been successfully been logged out.');

And in the same way you can use the router service to generate routes.

A: You can get the Session object (as well as any other service) trough the service container:
$session = $ServiceContainer->get('session');
$session->setFlash('notice', 'Message');

The way you can access to the service container in different ways:

*

*From a controller or any container aware class: just use $this->get('session');

*From a service:  you have to inject the service container object as Aldo Said


text:
Q: How to kill a script running in terminal, without closing terminal (Ctrl + C doesn't work)? I have written a bash script that calls several other programs and executes a bunch of commands. I run this script from the terminal. Now I want to kill the script.
Pressing Ctrl + C sometimes doesn't cut it, I think because sometimes the script is executing another program, and for some reason the kill signal doesn't work.
However, if I close the terminal window, it kills the script.
Is there something I can do (a keyboard combination), that is analogous to closing the terminal window, without actually closing the terminal window (I don't want to lose command history, current directory, output history, etc.)?

A: If you know the processes that are associated with the script you can find their PID using
 ps -A

and then use the PID number to kill the corresponding processes using
 kill -9 PID_Number

A: You have few options. One is to stop the script (CtrlZ), get the PID of the script and send SIGKILL to the process group.
When a command is executed in a shell, the process it starts and all its children are part of the same process group (in this case, the foreground process group). To send a signal to all processes in this group, you send it to the process leader. For the kill command, process leader is denoted thus:
kill -PID

Where PID is the process ID of the script.
Example:
Consider a script test.sh which launches some processes. Say you ran it in a shell:
$ ./test.sh

In another terminal,
$ pgrep test.sh
17802
$ pstree -ps `!!`
pstree -ps `pgrep test.sh`
init(1)───sshd(1211)───sshd(17312)───sshd(17372)───zsh(17788)───test.sh(17802)─┬─dd(17804)
                                                                               ├─sleep(17805)
                                                                               └─yes(17803)

In this case, to send a signal to process group created by test.sh, you'd do:
kill -INT -17802

-INT is used to send SIGINT, and so this command is the equivalent of pressing CtrlC on the terminal. To send SIGKILL:
kill -KILL -17802

You only need to stop the script if you can't open another terminal. If you can, use pgrep to find the PID.
One of the commands that the script launches may be trapping SIGINT, which is probably why CtrlC is ineffective. However, SIGKILL can't be trapped, and it is usually a last-resort option. You might want to try SIGTERM (-TERM) before going for the kill. Neither SIGKILL or SIGTERM can be set up as a keyboard shortcut the way SIGINT is.
All this is moot if your script doesn't contain a shebang line. From this SO answer:

Usually the parent shell guesses that the script is written for the the same shell (minimal Bourne-like shells run the script with /bin/sh, bash runs it as a bash subprocess) ...

Because of this, when the script is executed, you won't find a process named after script (or a process with the script's name in the command line) and pgrep will fail.
Always use a shebang line.

A: As Harris said you could run Kill -9 PID_Number but you could also install the package known as htop to have an interactive process browser that makes finding specific processes a lot easier. htop also supports killing processes.


text:
Q: Singleton constructor question I created a Singleton class in c#, with a public property that I want to initialize when the Singleton is first called.
This is the code I wrote :
public class BL
{
    private ISessionFactory _sessionFactory;
    public ISessionFactory SessionFactory
    {
        get { return _sessionFactory; }
        set { _sessionFactory = value; }
    }

    private BL()
    {
        SessionFactory = Dal.SessionFactory.CreateSessionFactory();
    }

    private object thisLock = new object();

    private BL _instance = null;
    public BL Instance
    {
        get
        {
            lock (thisLock)
            {
                if (_instance == null)
                {
                    _instance = new BL();
                }
                return _instance;
            }
        }
    }
}

As far as I know, when I address the Instance BL object in the BL class for the first time, it should load the constructor and that should initialize the SessionFactory object.
But when I try :
BL.Instance.SessionFactory.OpenSession();
I get a Null Reference Exception, and I see that SessionFactory is null...
why?

A: This is not a singleton. You should refer to Jon Skeet's excellent guide on singletons in C#. For example, use this pattern:
public sealed class Singleton
{
    static readonly Singleton instance=new Singleton();

    // Explicit static constructor to tell C# compiler
    // not to mark type as beforefieldinit
    static Singleton()
    {
    }

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            return instance;
        }
    }
}

Notice in particular that instance is static.


text:
Q: tmLanguage: how to match custom patterns in match I'm developing a VS Code extension for a small language that I made.
In my lang.tmLanguage.json,
let's say that in the repository I have defined patterns #A and #B.
I want to create the following pattern
{
  "X": {
    "match": "start <#A> <#B>"
  }
}

Good examples of what I'm trying to do would be
if <#if-condition> <#statement>
or class [\w\d_]+ <#inheritance>? <class-body>
How to embed patterns from the repository in other patterns?


text:
Q: A potentially dangerous Request.Form - EpiServer When quick-editing a page on episerver - it's detecting a potentially dangerous request from one of the textboxes. Now the content to this text box IS potentially dangerous, but I don't want to validate each request. I've followed the obvious instructions of adding validateRequest="false" to the pages node in web.config and have even added ValidateRequest="false" on the page that I'm running (default.aspx) but the browser still appears to be validating.
Can anyone advise? By the way - I've mentioned that it's episerver CMS because the edit page of default.aspx differs (visually) from the typical default.aspx (although the same file name is listed in the address box).

A: Problem solved:
http://world.episerver.com/Articles/Items/EPiServer-CMS-60-now-supporting-ASPNET-40/
A problem with EpiServer CMS 6.0's compatibility with ASP .net 4.


text:
Q: C++: How to enforce derived class to set base member variables? I have a base class with a member variable (preferably private) and I need to enforce derived classes to initialize it with a value based on their implementation; much like a pure virtual function.
To clarify, I want to declare a member in Base, have derived classes initialize it, and if they don't they get a compiler error. In the following code, I declared default constructor of Base to be protected. Then declared default constructor of Derived to be private.
class Base {
private:
    int _size;

protected:
    Base(){}
    /* pure virtual methods */

public:
    Base(int size) : _size(size){} // must enforce derived to call this.
    virtual ~Base(){}

    /* more pure virtual methods */
};

class Derived : public Base {
private:
    Derived() {}
public:
    Derived(int size) : Base(size) {
        //Base::Base(size);
    }
};

int main()
{
    Derived* d1 = new Derived();    // throws an error as needed:
                                    // "Cannot access private member declared in class 'Derived'"

    Derived* d2 = new Derived;      // throws an error as needed:
                                    // "Cannot access private member declared in class 'Derived'"

    Derived* d3 = new Derived(5);   // works as needed

    return 0;
}

The problem with the above code is that if another definition of Derived doesn't hide the default constructor. I'm still stuck with an uninitialized Base::_size.
I don't know if there is another way to go about this other than inheritance, because I still need derived classes to implement their own behavior for several methods declared in Base.
Any pointers are appreciated.

A: After the confusion about calling a base class ctor and default ctors, maybe the solution is just to not have a default ctor in Base?
class Base {
private:
    int _size;

public:
    // no default ctor
    Base(int size) : _size(size) {} // must enforce derived to call this.
    virtual ~Base(){}

    /* more pure virtual methods */
};

class Derived : public Base {
public:
    // no default ctor
    Derived(int size) : Base(size){
    }
    // examplary default ctor:
    //Derived() : Base(42) {}
};

int main()
{
    Derived d1;                   // error: no default ctor
    Derived* d2 = new Derived;    // same, but why use the free store?

    Derived d3(5);                // works as needed
    Derived* d4 = new Derived(5); // same, but why use the free store?

    return 0;
}

To be explicit about not having a default ctor, one could use
class Base {
    /* ... */
    Base() = delete;
    /* ... */
};

A: Use a constructor
class Base1 {
    protected:
        Base1(int forward) {
            thingYouWantToHide = forward;
        }
    private:
        int thingYouWantToHide;
    };
class Derived1: public Base1 {
public:
    Derived1(): Base1(5) {}
};

class Base2 {
private:
    int value;
protected:
    Base2() {
        value = calledToGet();
    }
    virtual int calledToGet() = 0;

    virtual ~Base2() {} //shut compiler warnings up
};

class Derived2: public Base2 {
    virtual int calledToGet() {
        return 5;
    }
};

int main(int,char**) {
    Derived1 a;
    Derived2 b;
    return 0;
}

You may think Derived2 will work, but remember Derived2 is not constructed until Base2 is, so that virtual is an undefined reference when Base2 is being constructed.
You should use the first case, type-traits if it is a constant (static const) or fundamental to the type.


text:
Q: array data not being sent to API controller c# I am working on angularJS application where I am making post call to send data to API controller everything is being sent to controller apart from array of data.
Here is code to make controller call
this.UpdateJobWithDeadlines = function (JobData) {
    var request = $http({
        method: "POST",
        url: "/api/JobAPI/UpdateJobWithDeadlines",
        data: JSON.stringify(JobData)
    });
    return request;
}

I have checked the JobData object, it's value (indented for easier reading) is:
{
    "jobNum":null,
    "jobName":"fgfg",
    /* snip */
    "StatusDatas":[
        {
            "scId":0,
            "JobNum":9746.030148450296,
            "StatusComment":"03-03-2017 : 1",
            "scTimeStamp":"2017-03-03T15:47:48.174Z",
            "IsNew":0
        },
        {
            "scId":0,
            "JobNum":8527.946898255957,
            "StatusComment":"03-03-2017 : 3",
            "scTimeStamp":"2017-03-03T15:47:49.459Z",
            "IsNew":0
        }
    ],
    /* SNIP */
    "telephone":"9"
}

The controller method signature is as below:
public int UpdateJobWithDeadlines(JobDataWithDeadlines JobData)

And the JobDataWithDeadlines class is as below:
public class JobDataWithDeadlines
{
    public int? jobNum;
    public string jobName;
    /* snip */
    public List<StatusData> StatusDatas;
}

public class StatusData
{
    public int scId;
    public int JobNum;

    public string StatusComment;

    public string scTimeStamp;

    public bool IsNew;
}

But I am getting an empty list for the StatusDatas property of the controller method parameter.

A: You have to add the following properties to the object you pass to the $http method:
this.UpdateJobWithDeadlines = function (JobData) {
    var request = $http({
        method: "POST",
        contentType: "application/json",
        dataType: "json",
        url: "/api/JobAPI/UpdateJobWithDeadlines",
        data: JSON.stringify(JobData)
    });
    return request;
}

You can optionally specify a charset to the content type, i.e.:
contentType: 'application/json; charset=utf-8'

Some people also suggest adding traditional: true to it, but in my experience that is not always what causes this problem.

A: The problem is your fields, they all need to be properties instead. The deserialization and serialization for json.net will not bind to fields (out of the box anyways, it is possible with additional configuration / custom mapping code).
public class JobDataWithDeadlines
{
    public int? jobNum {get;set;}
    public string jobName {get;set;}
    /* snip */
    public List<StatusData> StatusDatas {get;set;}
}

public class StatusData
{
    public int scId {get;set;}
    public double JobNum {get;set;}
    public string StatusComment {get;set;}
    public string scTimeStamp {get;set;}
    public bool IsNew {get;set;}
}

Also you should specify the content-type in the http header of the request. In this case set it to application/json


text:
Q: Real Time Collaboration free Java IDE I am looking for real-time collaborative Java IDE, which is light and fast. Me and my friend are working on same project, so any suggestions.? It should be easy to operate.

A: There's a plugin for Eclipse called Saros that supports collaborative editing.

A: got it...compilr it is.