text:
Q: Building async with setTimeout like a promise with setTimeout doesn't work On https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function they say that writing
async function foo() {
   return 1
}

is the same as writing
function foo() {
   return Promise.resolve(1)
}

So that means that if we want to 'transform' a promise into an async function, we have to replace resolve(promise_result) with return promise_result.
But when I try to use setTimeout with async it doesn't work:
const test1 = async () => {
    setTimeout(
        () => {
            return 5;
        },
        2000,
    )
}
const test2 = () => new Promise(
    (resolve, reject) => {
        setTimeout(
            () => resolve(25),
            1000
        )
    }
)

const execute = async () => {
    const result = await test1();
    console.log(result); // undefined
}

execute();

If I use await on test2 it works but it doesn't work on test1. Why is that ? Is async/await only meant to deal with pending promises without using .then or can I use async with return result instead of using Promise with resolve ?

A: Its undefined because test1 does not return anything back. take a closer look you return it in the anonymous function back
const test1 = async () => { // <--- this function returns nothing back. Nothing means "undefined"
    setTimeout(
        () => {       // <---- you return it here back in your anonymous  function witch makes no sense
            return 5;
        },
        2000,
    )
}

A: That's a fun one.
The problem here is that
const test1 = async () => {
    setTimeout(
        () => {
            return 5;
        },
        2000,
    )
}

test1 is an async function, BUT setTimeout is not.
setTimeout will just schedule whatever you pass it and return its timeoutID immediately.
In such a case, you'd really need to handle the Promise code manually.


text:
Q: Shared with me documents in OneDrive for Business disappear after 24 hours I have SharePoint 2016 onPrem.  Users can share documents in their OneDrive for Business and they appear in the "Shared with me" area, but they disappear after about 24hrs.
What could be causing this?  Can they stick for a longer time?
Bismarck

redpajama_set_name: RedPajamaStackExchange


text:
Q: finding item in text file during 2nd read In the beginning of my program, i opened a file with f = open("foods.txt", "r+"). Later I called this method i created
def findFood(food):
    foodRegex = re.compile(r'(?P<food>\S+)\s+\-.*')
    for line in f.readlines():
        print line
        duplicateFound = re.search(foodRegex, line)
        if duplicateFound.group('food') == food:
            return duplicateFound
        else:
            return False

However I run the method again. But my program doesn't work the way I want it to. Specifically
def build_meal_plan():
    number_of_items = int(raw_input("How many items would you like to add to your meal plan? "))
    count = 0
    while number_of_items > 0:
        print count
        food = raw_input("Enter in food name: ")
        print food
        if findFood(food):
            servings = int(raw_input("Number of servings: "))
        else:
            print "Food not found! Try again? (y/n): ",
            choice = raw_input()
            if choice == 'y' or choice == "yes":
                number_of_items += 1
            else:
                return

However during the 2nd run of my findFood method I cannot locate an item i know exists within the .txt file. I am not sure why I cannot find the same item I found in the text file during the first run. My assumption is that you can only go through a txt file once.

A: Once you call f.readlines(), you are at the end of the file. To return to the start, so you can go through it again, call f.seek(0):
def findFood(food):
    foodRegex = re.compile(r'(?P<food>\S+)\s+\-.*')
    for line in f.readlines():
        ...
    f.seek(0)

Alternatively, you can import the contents of the file to a list:
def import_file(filename):
    with open(filename) as f:
        content = [line.strip() for line in f]
    return content

And use that instead of referring back to the file.
def findFood(food, data):
    foodRegex = re.compile(r'(?P<food>\S+)\s+\-.*')
    for line in data:
        ...

Then you don't need to worry about returning to the start.


text:
Q: Livereload of .html pages - Gulp I have got this code so far, but it does not work.
var gulp = require('gulp'),
  connect = require('gulp-connect');

gulp.task('webserver', function() {
    connect.server({
      livereload: true
    });
});

gulp.task('default', ['webserver']);

A: You should specify file path to watch look this :
var gulp = require('gulp');
var connect = require('gulp-connect');

gulp.task('connect', function() {
  connect.server({
    root: 'app',
    livereload: true
  });
});

gulp.task('html', function () {
  gulp.src('./app/*.html')
    .pipe(connect.reload());
});

gulp.task('watch', function () {
  gulp.watch(['./app/*.html'], ['html']);
});

gulp.task('default', ['connect', 'watch']);


text: Q: Removing gravity component from android accelerometer I am collecting acceleromter data using android's phone TYPE_ACCELEROMETER sensor. My problem is I want to remove the gravity component from these readings so that data makes sense. I have found many solutions for this problem but can't decide which one actually works. Is subtracting gravity value obtained from TYPE_GRAVITY from acceleromter readings does the job?


text:
Q: Perform signed arithmetic on numbers defined as bit ranges of unsigned bytes I have two bytes.  I need to turn them into two integers where the first 12 bits make one int and the last 4 make the other.  I figure i can && the 2nd byte with 0x0f to get the 4 bits, but I'm not sure how to make that into a byte with the correct sign.
update:
just to clarify I have 2 bytes
byte1 = 0xab
byte2 = 0xcd

and I need to do something like this with it
var value = 0xabc * 10 ^ 0xd;

sorry for the confusion.
thanks for all of the help.

A: int a = 10;
int a1 = a&0x000F;
int a2 = a&0xFFF0;

try to use this code

A: For kicks:
public static partial class Levitate
{
    public static Tuple<int, int> UnPack(this int value)
    {
        uint sign = (uint)value & 0x80000000;
        int small = ((int)sign >> 28) | (value & 0x0F);
        int big = value & 0xFFF0;

        return new Tuple<int, int>(small, big);
    }
}

int a = 10;
a.UnPack();

A: Ok, let's try this again knowing what we're shooting for. I tried the following out in VS2008 and it seems to work fine, that is, both outOne and outTwo = -1 at the end. Is that what you're looking for?
byte b1 = 0xff;
byte b2 = 0xff;
ushort total = (ushort)((b1 << 8) + b2);
short outOne = (short)((short)(total & 0xFFF0) >> 4);
sbyte outTwo = (sbyte)((sbyte)((total & 0xF) << 4) >> 4);

A: Assuming you have the following to bytes:
byte a = 0xab;
byte b = 0xcd;

and consider 0xab the first 8 bits and 0xcd the second 8 bits, or 0xabc the first 12 bits and 0xd the last four bits. Then you can get the these bits as follows;
int x = (a << 4) | (b >> 4);   // x == 0x0abc
int y = b & 0x0f;              // y == 0x000d

A: edited to take into account clarification of "signing" rules:
public void unpack( byte[] octets , out int hiNibbles , out int loNibble )
{
  if ( octets        == null ) throw new ArgumentNullException("octets");
  if ( octets.Length != 2    ) throw new ArgumentException("octets") ;

  int value = (int) BitConverter.ToInt16( octets , 0 ) ;

  // since the value is signed, right shifts sign-extend
  hiNibbles =   value >>  4         ;
  loNibble  = ( value << 28 ) >> 28 ;

  return ;
}


text:
Q: Inverse of Gaussian Kernel Matrix Let a gaussian kernel be defined as $K(x_i, x_j) \equiv \exp(-\alpha |x_i-x_j|^2)+\beta \delta_{ij}$, and define the kernel matrix of some set of datapoints $\{x_i\}_{i=1}^n$ as the $n\times n$ matrix $K$ with $K_{ij} = K(x_i, x_j)$.
This is a common construction in various fields, e.g. Gaussian Processes. Is there a fast way of calculating the inverse of the kernel matrix?

Thoughts: if we could break down the matrix $K$ into the form $\beta I + u u^T$ for some column vector $u$, we could use the Sherman–Morrison formula to quickly calculate the inverse, however, we know such a $u$ would be infinite dimensional. Is there another trick one could use?

A: Much works has been done on the scalability of Gaussian Processes. The main idea is to approximate your kernel matrix $K$ with another matrix that admits faster operations.  This allows us to have fast matrix vector multiplications when optimizing hyper-parameters and use iterative algorithms such as Conjugate Gradients or GMRES to invert $K$.
The Structured Kernel Interpolation(SKI) paper gives a method for approximating your data with data on a grid, which allows you to use inducing point methods, toeplitz, kronecker methods to get the fast computations. See https://arxiv.org/abs/1503.01057


text:
Q: C# Modbus frame splitting and storing procedures The Premise
I am continually polling custom modbus frames from an embedded device with my c# wpf application at a low interval. At the moment the bytes in the frame i receive are located at the same position every time(e.g. frame[15]+frame[16] = 0x0532 = errorcode2).
The Questions

*

*Are there smart procedures (other than simply hardcoding the bytestorage) I could use to go from frame receiving to splitting/parsing?

*What data structures would be preferrable to enable frames to be processed dynamically further down the line?

A: Method 1:
You can define an explicitly laid out struct in C# and marshal the data to it like is done in the code below.  However, you will have problems with the data due to endian ordering if you are not running on big endian hardware (Modbus data is sent in big endian).  This also won't handle variable length Modbus packets (i.e. Read Input Registers).  NOTE: It is assumed that the frame has already been CRC checked so there is no need to declare and read it.
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct MyPacket
{
    public Byte Address;        // Byte 0
    public Byte FunctionCode;   // Byte 1
    public Byte ByteField;      // Byte 2
    public UInt32 UInt32Field;  // Bytes 3-6
    public UInt64 UInt64Field;  // Byte 7-14
    public UInt16 ErrorCode;    // Bytes 15-16
}

public static bool TryParse<T>(byte[] array, out T packet) where T : struct
{
    try
    {
        var size = Marshal.SizeOf(typeof(T));
        var p = Marshal.AllocHGlobal(size);
        Marshal.Copy(array, 0, p, size);
        packet = (T)Marshal.PtrToStructure(p, typeof(T));
        Marshal.FreeHGlobal(p);
        return true;
    }
    catch
    {
        packet = default(T);
        return false;
    }
}

static int Main(string[] args)
{
    // Create a sample frame
    byte[] bytes = new byte[] { 0x0, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };

    MyPacket packet;

    if (TryParse<MyPacket>(bytes, out packet))
    {
        // Process packet here...
    }

    return 0;
}

Method 2:
What I think is a better solution is to define a class for each function type that you use and read each field individually as shown in the code below.  NOTE: It is assumed that the frame has already been CRC checked so there is no need to declare and read it.
// VERY SIMPLE BigEndianReader class
public class BigEndianReader
{
    private Stream _stream;

    public BigEndianReader(Stream stream)
    {
        if (stream == null) throw new ArgumentNullException(nameof(stream));
        if (!stream.CanRead) throw new ArgumentException(nameof(stream));
        _stream = stream;
    }
    public byte ReadByte()
    {
        int b = _stream.ReadByte();
        if (b < 0) throw new EndOfStreamException();
        return (byte)b;
    }

    public UInt16 ReadUInt16()
    {
        UInt16 v = 0;
        for (int i = 0; i < sizeof(UInt16); i++){v <<= 8;v |= ReadByte();}
        return v;
    }

    public UInt32 ReadUInt32()
    {
        UInt32 v = 0;
        for (int i = 0; i < sizeof(UInt32); i++){v <<= 8;v |= ReadByte();}
        return v;
    }

    public UInt64 ReadUInt64()
    {
        UInt64 v = 0;
        for (int i = 0; i < sizeof(UInt64); i++) { v <<= 8; v |= ReadByte(); }
        return v;
    }
}

class MyPacket
{
    public Byte Address { get; private set; }
    public Byte FunctionCode { get; private set; }
    public Byte ByteField { get; private set; }
    public UInt32 UInt32Field { get; private set; }
    public UInt64 UInt64Field { get; private set; }
    public UInt16 ErrorCode { get; private set; }

    public static bool TryParse(byte[] bytes, out MyPacket result)
    {
        result = null;

        try
        {
            BigEndianReader r = new BigEndianReader(new MemoryStream(bytes));
            MyPacket p = new MyPacket();
            p.Address = r.ReadByte();
            p.FunctionCode = r.ReadByte();
            p.ByteField = r.ReadByte();
            p.UInt32Field = r.ReadUInt32();
            p.UInt64Field = r.ReadUInt64();
            p.ErrorCode = r.ReadUInt16();
            result = p;
            return true;
        }
        catch
        {
            return false;
        }
    }
}

static int Main(string[] args)
{
    // Create a sample frame
    byte[] bytes = new byte[] { 0x0, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19 };

    MyPacket packet;

    if (MyPacket.TryParse(bytes, out packet))
    {
        // Process packet here...
    }

    //==================================================================
    Console.Write("(press any key to exit)");
    Console.ReadKey(true);
    return 0;
}


text:
Q: Drawing a 3D Sphere I've been searching for an equation using OpenGl and Java to draw a 3d sphere. Kinda like x=blah blah math + y. Although using actual math. So far all I have is this which renders the items in a tower. How would I go about doing this?
GlStateManager.pushMatrix(); {

        GlStateManager.translate(x, y, z);
        GlStateManager.translate(1, -.825, 0.75);
        GlStateManager.rotate(90F, 0, 0, 1);
        GlStateManager.rotate(322.5F, 0, 1, 0);
        GlStateManager.translate(1.35, 0, -1.35);
        for(int i = 1; i < te.thpoothfyness; i++) {

            Minecraft.getMinecraft().getRenderManager().doRenderEntity(ITEM, 0, 0, 0, 0F, 0F, false);
            GlStateManager.translate(0.03125, 0, -0.03125);

        }

    }
    GlStateManager.popMatrix();


text:
Q: Doctrine 2.2 Datetime string conversion in Symfony 3.4 I am troubleshooting a search bar to return rows within a period chosen from 'To' and 'From' datepickers.
I initially got this error :

Error: Method Doctrine\ORM\Query\Expr\Comparison::__toString() must not throw an exception, caught Symfony\Component\Debug\Exception\ContextErrorException: Catchable Fatal Error: Object of class DateTime could not be converted to string

I converted the relevant query to a string using ->format() function:
            if (is_array($value) && isset($value['to'])) {

            $to = \DateTime::createFromFormat('d/m/Y H:i:s', $value['from'] . ' 23:59:59');
            var_dump($value, $to);die;
            if ($to <> false) {
                $query->andWhere(
                        $query->expr()->lte($path, $to->format('Y-m-d H:i:s'))
                );
            }
        }

Now doctrine throws the following error:

[Syntax Error] line 0, col 977: Error: Expected end of string, got '00'

Is there something else I need to do to format the date to make it acceptable to the querybuilder? I've tried using / instead of : but this causes an issue.

A: If I recall correctly, you should either use literal(), or query parameter. And since the lte argument is not constant, using literal() is highly discouraged (due to potential SQL injection).
Anyway, something like this should probably work:
if (is_array($value) && isset($value['to'])) {
if (is_array($value) && isset($value['to'])) {

    $to = \DateTime::createFromFormat('d/m/Y H:i:s', $value['from'] . ' 23:59:59');

    if ($to <> false) {
        $query->andWhere($query->expr()->lte($path, ':to'));
        $query->setParameter('to', $to->format('Y-m-d H:i:s'));
    }
}

Does it work?
Hope it helps...


text:
Q: Need to combine two data frames without removing any duplicate values Here's what i'm trying to do . Just need to add df2 in df1 as shown below in "Result Should be"
  df1
                   A              B
    1            923955       28-01-2016
    2            226129       28-01-2016
    3            889131       28-01-2016
    4            1047783      28-01-2016
    5            824995       28-01-2016
    6            386925       28-01-2016
df2
               A              B
1            104981       2016-01-28
2            50270        2016-01-28
3            708070       2016-01-28
4            205223       2016-01-28

Result Should be :
masterdf
               A            B              C             D
1            923955       28-01-2016     104981       2016-01-28
2            226129       28-01-2016     50270        2016-01-28
3            889131       28-01-2016     708070       2016-01-28
4            1047783      28-01-2016     205223       2016-01-28
5            824995       28-01-2016       NA            NA
6            386925       28-01-2016       NA            NA

A: Seems like you're not really merging but cbinding two dataframes with different number of rows. If that's the case you can:
# get difference in rows between df's
extra.rows <- nrow(df1) - nrow(df2)

# add the difference in rows to df2 and fill them with NA's
df2[nrow(df2) + extra.rows,] <- NA

# cbind them together
cbind(df1,df2)
#        A          B      A          B
#1  923955 28-01-2016 104981 2016-01-28
#2  226129 28-01-2016  50270 2016-01-28
#3  889131 28-01-2016 708070 2016-01-28
#4 1047783 28-01-2016 205223 2016-01-28
#5  824995 28-01-2016     NA       <NA>
#6  386925 28-01-2016     NA       <NA>


text:
Q: MYSQL IN Clause Issue There are a lot of questions posted on stackoverflow that are almost same like my problem but I found no working solution. I have a table message and entries are:
id | Message | Status
1  |  Hello  |  1
2  |  Hiiii  |  0
4  |  Works  |  1

I have another table which gives ids 1,2,3 and I want to find the status of all these entries from message table. What I want is if an id doesn't exist in message table then it should return null for that id if I use IN clause to find all status. I want following result:
id | Status
1  | 1
2  | 0
3  | null

I have been using IN clause but didn't get working output. Then I got a solution on stackoverflow and tried this query
SELECT `id`,`status` FROM ( SELECT 1 AS ID UNION ALL SELECT 2 AS ID UNION ALL SELECT 3) ids LEFT OUTER JOIN message ON ids.ID = message.id

But this query is not giving the expected results. Any help would be much appreciated.

A: I don't see how your query would work.  The column id should be ambiguous in the select (unless your database is case sensitive).  Try this:
SELECT ids.ID, m.status
FROM ( SELECT 1 AS ID UNION ALL SELECT 2 AS ID UNION ALL SELECT 3
     ) ids LEFT OUTER JOIN
     message m
     ON ids.ID = m.id;


text:
Q: How do you show pictures as fast as Facebook? Can any of you help me to be able to show pictures as fast as facebook does!
Facebook is incredible to watch pictures at, because the pictures are kind of preloaded I think.
Often ved you view galleries on other sites, it is a pain in the a**, because it is so slow every time you change picture.
I think you need javascript to do it!?

A: Depending on your implementation, you could do this with some ajax and hidden dom elements.
Suppose you have a gallery with a slideshow.. You could insert a hidden dom element with the picture next picture of the slide show for each load.  This would cause the image to be loaded.  If you then were to use JS to insert that same image tag later, the browser would rely on it's cache rather than fetching it form the server since it already has that photo.
This is kind of a broad question but I think this approach would work.  You would probally be better off not reinventing the wheel and seeing what Image prefetch librarbies based on JQuery or whatever are available to you..

A: Facebook compresses images to extremes. Try it yourself, take an image you are having trouble with and upload it to Facebook. Then check the size of the image, you will know why. Once I did a small test by uploading 17429 bytes image and it compressed it to 18757 bytes, a complete 7% increase from the original size!
At that compressed size, you can implement some sort of prefetch next image for display. Along with, I think, they have extremely good infrastructure.

A: Preloaded would mean loading when the page is loaded, which is what happens with an <img> tag. No, it's simply because the file size is smaller.

A: Facebook uses Bigpipe, there is an open implementation in the works called openpipe
Bigpipe pushes the content to the browser when server stopped processing, so user will notice that it is faster.
It basically loads pagelets, when they are ready for the user, at the browser the implementation is Javascript based, and you must push the info to the client with your preferred server language.

A: First of all, facebook heavilycompresses images. Many other websites don't. Facebook also has a faster network than most other websites.
With the small image size, the client can prefetch the next image.

A: If your wanting images to be viewed quicker on your site first make sure the images are decently compressed and aren't any bigger than they have to be. The amount of times I have seen websites using an extremely large image scaled down to fit in an element 5 times smaller is just ridiculous.
You can check out these sites that has many implementations and links on how to pre-load / pre-fetch images (css, JavaScript, ajax)
http://perishablepress.com/press/2009/12/28/3-ways-preload-images-css-javascript-ajax/
Since your question was tagged with 'jquery' here is one just for that.
http://engineeredweb.com/blog/09/12/preloading-images-jquery-and-javascript


text:
Q: Scrapy: serializing item data which is not item class item Each product is associated with a large number of price pages for which I do not wish to create an individual item. Instead Id like to aggregate the data into a single field, e.g. avgerage-price for each product.
At present, what happens below is the productprice field is overwritten each time. I.e. the productprice field is a list with a single item (last product price scraped)
Id like to keep each price for the product and aggregate this data once the item has returned.
parse_it(self, response):
    ....
    for path in links:
       yield Request(
         path,
         meta={
         'item': item_loader.load_item()
         },
          callback=self.parse_price_page,
          dont_filter=True
            )

parse_price_page(self, response):
    productname = response.meta['item']['productname']
    product_price= response.xpath("//table/tr/td/text()").extract()
    item_loader.add_value("productprice", product_price)
    return item_loader.load_item()

A: First of all, I don't see you creating the ItemLoader in the parse_price_page(), but you are using it.
Second, there is an ItemLoader.get_collected_values() that you could use to read the last collected value, add it to the new one, and store.
This is an untested example from the top of my head, you should play with the approach until you get it right:
def parse_price_page(self, response):
    item_loader = ItemLoader(item=response.meta['item'])
    productname = item_loader.get_collected_values('productname')
    old_price = item_loader.get_collected_values('productprice')
    new_price = response.xpath("//table/tr/td/text()").extract()[0]
    item_loader.add_value("productprice", int(old_price)+int(new_price))
    return item_loader.load_item()


text:
Q: paypal check shipping address instead of billing In our shop we have set specific countries for our Paypal Express, fx we don't allow this billing option for Vietnam.
Now we see some customers making orders by setting an American billing address and shipping to Vietnam.
How do we make the system check the shipping address instead of the billing address?


text:
Q: Spring - is using new a bad practice? Is creating objects by hand, i.e. using new operator instead of registering Spring bean and using dependency injection considered bad practice? I mean, does Spring IoC container have to know about all objects in the application? If so, why?

A: You want Spring to create beans for classes that :

*

*you want/need to inject instance(s) in other beans

*you need to inject beans (or dependencies) in their own instances.

*you want them to benefit from Spring features (instantiation management, transaction management, proxy classes Spring empowered such as Repository/Interceptor and so for...)

Services,  controllers or interceptors are example of them.
For example a controller may need inject a service or an interceptor.
As well as you don't want to handle the instantiation of these classes by implementing yourself the singleton pattern for each one. Which could be error-prone and  require boiler plate code.
So you want all of these classes to be beans managed by Spring.
But you don't want to Spring create beans for classes that :

*

*you don't want/need to inject  instance(s) in other beans

*you don't need to inject beans (or rdependencies) in their own instances

*you don't need them benefit from Spring features

Entity, DTO, Value Object are example of them.
For example an entity never needs to be injected into another entity or in a service as a dependency because entities are not created at the container startup but are generally created inside a method and have a scope limited to the methods lifespan.
As well as you don't need Spring to create instances which the lifespan is a method. The new operator does very well the job.
So defining them as bean instances makes no sense and appears even counter intuitive.

A: Spring implements the Dependency Injection pattern. You should inject in the container of spring the beans that are going to be used in other classes as dependence to be able to work. Usually classes that implement interfaces are injected so that if you change the implementation, the classes that use that interface do not know about the change.
I recommend you read the post about the dependency injection of Martin Fowler.

A: Using new is not bad and you are just giving the IoC container the responsibility of using new under the hood. IoC will know about all the classes that you register with it. When using frameworks, it's even more important to think about the applications architecture, because a framework makes bad design as easy to implement as good design.
If you don't need multiple implementations of a class, then use new.
If you think it's plausible that you may need to switch between implementations, consider your app design and find a suitable injection point so that refactoring won't be such a drain.
If you need multiple implementation of a class, then use a design pattern like a factory or a DI framework.
Not every nook and cranny of an application needs to be highly configurable. That's what leads to over-engineered and hard to maintain code.


text:
Q: command.exe batch file: %XIL_SCRIPT_LOC:~0,-1% ? %~dp0? I'm Trying to revive an old windows 7 tool to work in Windows 11 under powershell...
What would the PowerShell equivalent look like for the following command.exe batch file?
I get a little bit confused by ~dp0 and %XIL_SCRIPT_LOC:~0,-1%
@echo off
REM XIL_SCRIPT_LOC should point to script location
set XIL_SCRIPT_LOC=%~dp0
REM Remove trailing slash
set XIL_SCRIPT_LOC=%XIL_SCRIPT_LOC:~0,-1%
set XILINX=%XIL_SCRIPT_LOC%
set XILINX_DSP=%XILINX%
set PATH=%XILINX%\bin\nt;%XILINX%\lib\nt;%PATH%
REM Unset XIL_SCRIPT_LOC
set XIL_SCRIPT_LOC=

Here's what I have so far:
# XIL_SCRIPT_LOC should point to script location
$env:XIL_SCRIPT_LOC = %~dp0
# Remove trailing slash
$env:XIL_SCRIPT_LOC = $env:XIL_SCRIPT_LOC:~0,-1%
$env:XILINX         = $env:XIL_SCRIPT_LOC
$env:XILINX_DSP     = $env:XILINX
$env:PATH           = "${XILINX}\bin\nt;${XILINX}\lib\nt;$env:PATH"
# Unset XIL_SCRIPT_LOC
$env:XIL_SCRIPT_LOC = $null

A: $env:XILINX         = $PSScriptRoot
$env:XILINX_DSP     = $PSScriptRoot
$env:PATH           = "$PSScriptRoot\bin\nt;$PSScriptRoot\lib\nt;$env:PATH"


text:
Q: Jetty Websockets - Correctly sending async messages when handling unreliable connections I'm using Jetty 9.3.5 and I would like to know what is the proper way to handle unreliable connections when sending websocket messages, specifically: I noticed cases when a websocket connection does not close normally so, even though the client side is down, it takes a lot of time until onClose() is triggered on the server (for ex. a user closes the laptop lid and puts it in standby - it can take 1-2 hours until the close event is received on the server side).
Thus, because the client is still registered, the server keeps sending messages that begin to build up. This becomes an issue when sending a large number of messages.
I've tested sending byte messages with:
Session.getRemote().sendBytes(ByteBuffer, WriteCallback)
Session.getRemote().sendBytesByFuture(ByteBuffer);

To simulate the connection down on one side (ie. user puts laptop in standby), on Linux, I assigned an IP address to eth0 interface, started sending the messages and then brought it down:
ifconfig eth0 192.168.1.1
ifconfig eth0 up
--- start sending messages (simple incremented numbers) and connect using Chrome browser and print them ---
ifconfig eth0 down

This way: the messages were still being sent by Jetty, the Chrome client did not receive them, the onCllose or onError was not triggered on server-side
My questions regarding Jetty are:

*

*Is there a way to clear queued messages that were not delivered?
I've tried, but with no luck:
Session.getRemote().flush();

*Can a max number of queued messages be set?
I've tried:
WebSocketServletFactory.getPolicy().setMaxBinaryMessageBufferSize(1)

*Can I detect if the client does not receive the message? (or if the connection is in abnormal state let's say)
I've tried:
session.getRemote().sendBytes(bb, new WriteCallback() {

                @Override
                public void writeSuccess() {
                    //print success                     }

                @Override
                public void writeFailed(Throwable arg0) {
                    //print fail
                }
            });

But this prints success even though the messages are not received.
I also tried to use, but couldn't find a solution:
factory.getPolicy().setIdleTimeout(...);
factory.getPolicy().setAsyncWriteTimeout(3000);
sendPing()

Thanks in advance!

A: Unfortunately, the WebSocket protocol, being a message passing protocol isn't really designed for this level of nuance between messages.
The first message MUST complete before you can even think of sending the next message.  So if you have a message in process, then there is no way to safely cancel that message.
At best, an API could exist to truncate that message with a CONTINUATION / empty payload / fin=true.
But even then the remote endpoint wouldn't know that you canceled the message, it would just see a partial message.
Detecting connectivity issues is best handled with either OS level events (like Android's Connectivity intents), or via periodic websocket PING (which inserts itself in front of the line for outgoing websocket frames.
However, even with PING, if your outgoing websocket frame is in-progress, even the PING cannot be sent until that websocket frame is done sending.
RemoteEndpoint.flush() will attempt to flush any pending messages (and frames), not clear out pending messages (or frames).
As for detecting if client got the message, you'll need to implement some sort of message ACK into your own layer to verify that, the protocol has no such concept.  (Some libs/apis built on top of websocket have implemented message ACK in that layer.  The cometd message ack extension comes to mind as a real world example)
What sort of situation are you attempting to solve for?
Perhaps using the RemoteEndpoint.sendPartialString(String, boolean) or RemoteEndpoint.sendPartialBytes(ByteBuffer, boolean) to send smaller frames of the whole message could be useful to you.  However, the other side might not have an API that can read those partial frames (eg: Javascript in a browser).


text:
Q: How to cancel bootstrap CSS left? I would like to give to .dropdown-menu class of bootstrap-only right position, but in bootstrap.css it has left:0;, and the dropdown <ul> stretches to full length, because it has right:0; and left:0;.
How can I cancel left:0 or override it without changing the bootstrap.css?

A: Simply override it to its default value in your own custom CSS:
body .dropdown-menu{
    left: auto; //default value
}

You might need to adjust the specificity of the selector so the style gets applied.


text:
Q: Doubly-linked-list. Code works...should it? Much less code than other solution I'm working through the exercises in the 'Pointers' chapter of 'Programming in C' by Kochan.
I have written a program that creates a doubly-linked-list. It first prints the values. It then proceeds to call a function to remove an entry. The values are printed again.
Finally, an additional function is called to ADD an entry, followed by a print again.
Right now, my code works. You can see it here:
#include <stdio.h>

struct entry
    {
        int value;
        struct entry *next;
        struct entry *previous;
    };

void removeEntry(struct entry *start);
void insertEntry(struct entry *addOn, struct entry *element);

int main (void)
{

    //declarations
    struct entry n1, n2, n3, addOn;
    struct entry *list_pointer = &n1;

    //creates list values and links
    n1.value = 100;
    n1.next = &n2;
    n1.previous = list_pointer;

    n2.value = 200;
    n2.next = &n3;
    n2.previous = &n1;

    n3.value = 300;
    n3.next = (struct entry *) 0;
    n3.previous = &n2;

    //prints out all list values
    while(list_pointer != (struct entry *) 0)
    {
        printf("%i\n", list_pointer->value);
        list_pointer = list_pointer->next;
    }

    printf("\n");

    //resets list_pointer back to start
    list_pointer = &n1;

    //calls function and removes n2 from list by directly linking n1 to n3
    removeEntry(&n2);

    //print out amended list
    while(list_pointer != (struct entry *) 0)
    {
        printf("%i\n", list_pointer->value);
        list_pointer = list_pointer->next;
    }

    printf("\n");

    list_pointer = &n1;
    insertEntry(&addOn, &n3);

    //print out amended list
    while(list_pointer != (struct entry *) 0)
    {
        printf("%i\n", list_pointer->value);
        list_pointer = list_pointer->next;
    }

    return 0;
}

void removeEntry(struct entry *start)
{
    start->previous->next = start->next;
}

void insertEntry(struct entry *addOn, struct entry *element)
{
    element->next = addOn;
    addOn->value = 400;
    addOn->next = (struct entry *) 0;
}

HOWEVER, once done, I wanted to check to see if any other solutions had been posted online, just in case I was missing anything.
Well I found a question and answer HERE and there are considerable differences.
Ignoring the difference in the format of how the values are printed, you can see that there is considerably more code written, especially in the functions. This is my remove function again:
void removeEntry(struct entry *start)
{
    start->previous->next = start->next;
}

and this is theirs:
void RemoveEntry(struct Entry *EntryToRemove)
{
    if (EntryToRemove->Previous != NULL)
    {
        EntryToRemove->Previous->Next = EntryToRemove->Next;
    }
    if (EntryToRemove->Next != NULL)
    {
        EntryToRemove->Next->Previous = EntryToRemove->Previous;
    }
    EntryToRemove->Previous = NULL;
    EntryToRemove->Next = NULL;
}

Now I can see that there is a check for NULL, but aside from that, they are working with both Previous and Next values and have an if statement for each.
Similarly, you can see my insert function here:
void insertEntry(struct entry *addOn, struct entry *element)
{

    element->next = addOn;
    addOn->value = 400;
    addOn->next = (struct entry *) 0;
}

and theirs:
void InsertEntry(struct Entry *InsertPosition, struct Entry *EntryToInsert)
{
    EntryToInsert->Previous = InsertPosition->Previous;
    EntryToInsert->Next = InsertPosition;
    if (InsertPosition->Previous != NULL)
    {
        InsertPosition->Previous->Next = EntryToInsert;
    }
    InsertPosition->Previous = EntryToInsert;
}

Please keep in my mind that my code does exactly what I was trying to do, my printed output is:
100
200
300

100
300

100
300
400

Can you please attempt to explain this to me? I feel like an idiot for not being able to get my head around with this.
This is their full code:
#include <stdio.h>vv

struct Entry
{
    int Value;
    struct Entry *Previous;
    struct Entry *Next;
};

void InsertEntry(struct Entry *InsertPosition, struct Entry *EntryToInsert);
void RemoveEntry(struct Entry *EntryToRemove);

int main()
{
    struct Entry N1, N2, N3, N4, N5, Insert, *Start = &N1;

    //set initial values
    N1.Value = 10;
    N2.Value = 20;
    N3.Value = 20;
    N4.Value = 30;
    N5.Value = 40;
    Insert.Value = 35;

    //link the list

    N1.Next = &N2;
    N2.Next = &N3;
    N3.Next = &N4;
    N4.Next = &N5;
    N5.Next = NULL;
    //Link again

    N1.Previous = NULL;
    N2.Previous = &N1;
    N3.Previous = &N2;
    N4.Previous = &N3;
    N5.Previous = &N4;

    InsertEntry(&N4, &Insert);
    RemoveEntry(&N2);

    //Display the Lists
    while (Start != (struct Entry *) 0)
    {
        printf("Previous: ");
        if (Start->Previous != NULL)
        {
            printf("%i", Start->Previous->Value);
        }
        else
        {
            printf("NULL");
        }
        printf(", Current: %i, Next: ", Start->Value);
        if (Start->Next != NULL)
        {
            printf("%i", Start->Next->Value);
        }
        else
        {
            printf("NULL");
        }
        printf("\n");
        Start = Start->Next;
    }

    return 0;
}

void InsertEntry(struct Entry *InsertPosition, struct Entry *EntryToInsert)
{
    EntryToInsert->Previous = InsertPosition->Previous;
    EntryToInsert->Next = InsertPosition;
    if (InsertPosition->Previous != NULL)
    {
        InsertPosition->Previous->Next = EntryToInsert;
    }
    InsertPosition->Previous = EntryToInsert;

}

void RemoveEntry(struct Entry *EntryToRemove)
{
    if (EntryToRemove->Previous != NULL)
    {
        EntryToRemove->Previous->Next = EntryToRemove->Next;
    }
    if (EntryToRemove->Next != NULL)
    {
        EntryToRemove->Next->Previous = EntryToRemove->Previous;
    }
    EntryToRemove->Previous = NULL;
    EntryToRemove->Next = NULL;
}

Thank you for your time.

A: The code is different because your code does not successfully implement a double linked list. For example try inserting an entry into the middle of the list then print it from the end to the start, you will find the linked code works, but yours does not.

A:
Please keep in my mind that my code does exactly what I was trying to do, my printed output is:....

This is the single most dangerous and naive thing new programmers say. It tells us absolutely nothing.  Programming is not a matter of the ends justify the means.  You can push the wrong buttons on a calculator and get the right answer no?
Your test consists of traversing in a single direction through your list.  A singly linked list would have passed that test.
Did you test reverse traversal? That is after all the key difference between a singly linked list and a doubly linked one.
Did you test insertion and removal from the middle and from the front and back?
How about cycles? What happens if you add an element to the list that's already in the list?


text:
Q: FlatList Data not Appears I'm developing a React Native app.
I'm fetching the data from RealmDB and grouping by listId that data.
I want to render below data in FlatList but no data appears.
 const data = {
  "6": [
    {
      "id": 13,
      "listId": 6,
      "piece": 1,
    },
    {
      "id": 12,
      "listId": 6,
      "piece": 1,
    }
  ],
  "7": [
    {
      "id": 15,
      "listId": 7,
      "piece": 1,
    },
    {
      "id": 14,
      "listId": 7,
      "piece": 1,
    }
  ]
}

My attempt was:
<FlatList
 numColumns={2}
 //keyExtractor={(item) => "key" + item.id}
 data={this.state.data}
 renderItem={({ item }) => (
     <View>
         <Text>{item.piece}</Text>
     </View>
 )}
/>

What is the correct way to use above data in FlatList?

A: You can flat your data with that approach:
const flatten = (data) => Object.values(data).flat();
const data = {
    "6": [
      {
        "id": 13,
        "listId": 6,
        "piece": 1,
      },
      {
        "id": 12,
        "listId": 6,
        "piece": 1,
      }
    ],
    "7": [
      {
        "id": 15,
        "listId": 7,
        "piece": 1,
      },
      {
        "id": 14,
        "listId": 7,
        "piece": 1,
      }
    ]
  };

const flatData = flatten(data);

And then you can use it as wanted:
flatData.map(item => item.piece)

A: You can access like this if don't want to change data style.

<FlatList
 numColumns={2}
 data={this.state.data}
 renderItem={({ item }) => (
     <View>
         <Text>{item[0].piece}</Text>
         <Text>{item[1].piece}</Text>
     </View>
 )}
/>


text:
Q: Gradle plugins DSL: Restriction on declaration location I have a few Gradle scripts that get applied via apply from: 'my-build.gradle'. If I use the new plugins DSL as follows in the external build file my-build.gradle, it fails with the following error:
> startup failed:
  Only Project build scripts can contain plugins {} blocks
  See http://gradle.org/docs/2.3/userguide/plugins.html#sec:plugins_block
  for information on the plugins {} block

Looking at the documentation pointed in the error message didn't reveal as to why the restriction is in place. Why is there a restriction on the location of the plugins declaration?
Files for reference below.

*

*my-build.gradle file:
plugins {
    id "net.saliman.cobertura" version "2.2.5"
}

*build.gradle file:
apply from: "my-build.gradle"

// Other stuff

A: This is how you can use plugins in external Gradle files such as your my-build.gradle:
buildscript {
  repositories {
    mavenCentral()
    maven { url "https://plugins.gradle.org/m2/" }
  }
  dependencies {
    classpath "org.sonarqube.gradle:gradle-sonarqube-plugin:1.1"
    classpath "net.saliman:gradle-cobertura-plugin:2.2.8"
  }
}
// Because this is a helper script that's sourced in from a build.gradle, we can't use the ID of external plugins
// We either use the full class name of the plugin without quotes or an init script: http://www.gradle.org/docs/current/userguide/init_scripts.html
apply plugin: org.sonarqube.gradle.SonarQubePlugin
apply plugin: net.saliman.gradle.plugin.cobertura.CoberturaPlugin

// rest of my-build.gradle omitted

Above I've activated the plugins for SonarQube and Cobertura.
Generally, to get the fully qualified class name of your plugin you will have to look inside its .jar file.
As for the technical reasons why you can't use a plugins {} block in an external file, I do not know. It might have to do something with the following:

[...] plugins [need to] be specified in a way that Gradle can easily
and quickly extract [them], before executing the rest of the build
script. It also requires that the definition of plugins to use be
somewhat static.

But rejoice:

Future versions of Gradle will remove this restriction.

A: I also faced similar issue recently and it got solved by changing Gradle settings in Intellij as follows:


text:
Q: How to get (without vba) the last available data on a row in Excel I have a question regarding a simple formula: Gn=Fn-En, but if En is an empty cell, then search on the same row (n), all the n-1 values in order to find the first non empty cell.
Is it possible to make such formula but without having any vba code?
Regards,

A: =LOOKUP(2,1/(B5:E5<>""),B5:E5)

will work for any single-row or single-column range

A: You can get the last non-empty cell value in a row with hlookup.
For row 5, if values are numeric:
=HLOOKUP(10^10,5:5,1,1)
if values are text:
=HLOOKUP(REPT("z",50),5:5,1,1)
HTH


text:
Q: standard libraries in using statements does not have any autocompletion is vs code 1.61.0 When I am trying to use any of the of standard System libs like System.Text there is no auto completion for my csharp code.  If I just try to use a stringbulider it all works but the vs code has no completion and seems to have no idea about the stringbuilder.  I have the omnisharp installed and normal completion for variables, types, etc works.
I am trying to transition from Visual Studio 2019 Enterprise for some projects and am wondering if VS Code just does not try to provide auto completion for csharp?
I also use python and have no problem with completion when using that with anaconda in the same vs code install.
Thanks


text:
Q: Save dual monitor setup on KDE debian 8 I've just updated from Debian 7 to Debian 8 (please don't ask why just now). I'm now trying to save my monitor configuration, so it is the same after a reboot. My monitors are there and if I go into the KDE control panel, I just have to check the checkbox to activate the second monitor and drag it to the correct position. I have to do it every time I restart my system -- why? It worked with Debian 7. What I can I do to make it stay?
I have the following "graphics card": VGA compatible controller: Intel Corporation Xeon E3-1200 v2/3rd Gen Core processor Graphics Controller (rev 09)


text:
Q: Share Link with Picture URI on Facebook in Wp7 I am using the following parameters to Post a Link along with the picture uri to Facebook. But the thumbnail picture gets cropped. How can i solve this?
var parameters = new Dictionary<string, object>();
parameters.Add("link", link);
parameters["picture"] = picUri;
parameters.Add("caption", "");
parameters.Add("message", "haha");
parameters.Add("name", Title);
client.PostAsync("me/feed", parameters);

I have attached the original image and the image shared.

A: Add "action" parameter . The Image will not be cropped. Please refer this link.
        Dictionary<string, string> action1 = new Dictionary<string, string>();
        action1.Add("name", "View on");
        action1.Add("link", link);

        parameters.Add("actions", action1);

A: You should resize the image to make it a perfect square, e.g. 250x250, so Facebook renders it correctly. Otherwise, Facebook will always crop the image.


text:
Q: How do I associate tables through the model and initializer I'm hoping to get a better understanding how to relate models to each other.  I'm also using seed data with entity framework.  However I think it have it set up incorrectly, and I'm not sure where.  When I try to run the index for company, I get a less than helpful error focusing on the CompanysToList.  Am I do something obviously wrong?  I'm lost at the moment
My db design is simple starting from the top and going down- admin, company, campaign, idea.
The following four classes are saved as individual classes in my model folders.
public class Admin
{

    public int AdminID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public virtual ICollection<Company> Companys { get; set; }
    public virtual ICollection<Campaign> Campaigns { get; set; }
    public virtual ICollection<Idea> Ideas { get; set; }
}

public class Company
{

    public int CompanyID { get; set; }
    public int AdminID { get; set; }
    public string CompanyName { get; set; }
    public string Website { get; set; }
    public string Description { get; set; }

    public virtual ICollection<Campaign> Campaigns { get; set; }
    public virtual ICollection<Idea> Ideas { get; set; }
}

public class Campaign
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int CampaignID { get; set; }
    public int CompanyID { get; set; }
    public int AdminID { get; set; }
    public string Description { get; set; }

    public virtual Idea Idea { get; set; }
    public virtual Company Company { get; set; }
}

Rank is within the idea model.
public enum Rank
{
    A, B, C
}

public class Idea
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int IdeaID { get; set; }
    public int CampaignID { get; set; }
    public int CompanyID { get; set; }
    public int AdminID { get; set; }
    public string Description { get; set; }
    public Rank? Rank { get; set;}

}

then my seed data
    protected override void Seed(CeptContext context)
    {

        var admins = new List<Admin>
        {
        new Admin{AdminID=1, FirstName="Bob",LastName="Test"},
        new Admin{AdminID=2, FirstName="Fred",LastName="Tester"},

        };

        admins.ForEach(s => context.Admins.Add(s));
        context.SaveChanges();

        var companys = new List<Company>
        {
        new Company{AdminID=1, CompanyID=101, CompanyName="Test Company",Website="www.testcompany.com",Description="Test Company"},
        new Company{AdminID=1, CompanyID=102, CompanyName="Big Company",Website="www.bigcompany.com",Description="big company"},
        new Company{AdminID=2, CompanyID=103, CompanyName="Big Technologies",Website="www.bigtechnologies.com",Description="Big technologies"},

        };

        companys.ForEach(s => context.Companys.Add(s));
        context.SaveChanges();

        var campaigns = new List<Campaign>
        {
        new Campaign{AdminID=1, CompanyID=101, CampaignID=201, Description="New campaign"},
        new Campaign{AdminID=1, CompanyID=101, CampaignID=202, Description="New campaign2"},
        new Campaign{AdminID=1, CompanyID=102, CampaignID=203, Description="New campaign3"},
        new Campaign{AdminID=2, CompanyID=103, CampaignID=204, Description="New campaign4"},

        };

        campaigns.ForEach(s => context.Campaigns.Add(s));
        context.SaveChanges();

        var ideas = new List<Idea>
        {
        new Idea{AdminID=1,CompanyID=101, CampaignID=201, IdeaID=301, Description="Big Idea", Rank=Rank.A},
        new Idea{AdminID=1,CompanyID=101, CampaignID=202, IdeaID=302, Description="Tiny Idea", Rank=Rank.B},
        new Idea{AdminID=1,CompanyID=102, CampaignID=203, IdeaID=303, Description="Idea to do great things", Rank=Rank.C},
        new Idea{AdminID=1,CompanyID=102, CampaignID=203, IdeaID=304, Description="Even bigger things", Rank=Rank.B},
        new Idea{AdminID=2,CompanyID=103, CampaignID=204, IdeaID=305, Description="Bad idea", Rank=Rank.C},
        new Idea{AdminID=2,CompanyID=103, CampaignID=204, IdeaID=306, Description="Other Idea", Rank=Rank.A},

        };
        ideas.ForEach(s => context.Ideas.Add(s));
        context.SaveChanges();

    }


text:
Q: Why does as.character drop decimal point? I'm interested to know why as.character(5.0) returns 5 but as.character(5.1) returns 5.1 in R. I tried to get an answer by reading the documentation but had no luck.

A:
I'm interested to know why as.character(5.0) returns 5

The key word here is "returns." What do you mean by that? Note that typing this in the console gives you 5:
> 5.0
[1] 5

5 is the same things as 5.0 for the purposes of calculation. So what you probably really care about is how 5 is printed. You thus need to use joran's method or a function like sprintf.

A: For more precise formatting of numbers as characters, you might use format:
> format(5,nsmall = 1)
[1] "5.0"


text:
Q: mysql_fetch_assoc crashing the php code I need to change of not my PHP code and I ran into some problem (please notice that I usually code in Java and haven't develop in PHP for quite few years).
I have the following peace of code:
   $sql = "SELECT id_class FROM  events e join event_to_class ec on e.id = ec.id_event WHERE e.id = ".$r['id']."  and ec.id_evaluator = 8 and (".$stepNumbers.")";
   $mirekClassesForEvent = mysql_query($sql) or trigger_error(mysql_error().$sql);
   if (!$mirekClassesForEvent) {
      echo "Could not successfully run query from DB: " . mysql_error();
      exit;
   }
   $mirekClasses = array();
   if (mysql_num_rows($mirekClassesForEvent) > 0 ) {
      while($row = mysql_fetch_assoc($mirekClassesForEvent) {
           array_push($mirekClasses, $row['id_class'];
      }
   }

the select statement looks like this:
SELECT id_class FROM events e join event_to_class ec on e.id = ec.id_event WHERE e.id = 1 and ec.id_evaluator = 8 and (e.id_step=4 OR e.id_step=5 OR e.id_step=6)

when I run it in the MySQL DB to runs fine and returns one row of data with

id_class=27

.
However when I run the code above my php script crashes (it doesn't even show any error messages - even when I try to use mysql_error() function)
From my debuggin it looks like the problem is in the while statement, but I don't understand what could be the problem.

A: You are missing a ) at the end of the while line, and another on the array_push line. If you are seeing no error, you probably have error reporting off. Using an editor with syntax highlighting would help you find this kind of error, as they usually include highlighting of mismatched parentheses.
Note that you could simplify your query a little by using IN:
... and e.id_step IN (4,5,6)

Or BETWEEN:
... and e.id_step BETWEEN 4 AND 6

A: There's a syntax error in your code:
while($row = mysql_fetch_assoc($mirekClassesForEvent) {
       array_push($mirekClasses, $row['id_class'];
  }

You're missing the a closing bracket on your while loop:
while($row = mysql_fetch_assoc($mirekClassesForEvent)) {

Editted to add:
And also one on the array_push, too - well spotted Kolink


text:
Q: Designing a menu, repeated message I'm working on a console application which is supposed to have a little menu to choose from different options. I came up with two ideas, in one of which I used int to be a choice variable and it gets me into an infinite loop whenever I enter a character other than numeric. Another one though seems clearer to me but I can't understand why I get "Choose an option Not a digitChoose an option" message even if I choose a valid theoretically option Please let me know what's the problem with my code. I enclose the second example I mentioned.
#include <stdio.h>
#include <ctype.h>

void F1()
{
    printf("Function 1\n");
}
void F2()
{
    printf("Function 2\n");
}
void F3()
{
    printf("Function 3\n");
}

int main()
{
    char c;
    printf("MAIN MENU\n"
         "1. Function 1\n"
         "2. Function 2\n"
         "3. Function 3\n"
         "4. Exit\n");
    while(1)
    {
        printf("Choose an option ");
        scanf("%c", &c);
        if(isdigit(c) == 0) printf("Not a digit");
        else
        {
            if(c == '1') F1();
            else if(c == '2') F2();
            else if(c == '3') F3();
            else if(c == '4') break;
            else printf("Wrong option");
        }
    }
    return 0;
}

A: You need to flush your input buffer to clear the \n character leftr behind by previous call of scanf. Place a space before %c in scanf
 scanf(" %c", &c);

or in general you flush input buffer by placing this snippet after each call of scanf:
int c
while((c = getchar()) != '\n' && c != EOF);

A: The first call to scanf() will real your typed character, and the second one will read a newline character.
You need to finish reading the line after your call to scanf():
int c2;
while((c2=getchar()) != '\n' && c2 !=EOF) {}


text:
Q: How to scroll the results shown by google maps search using selenium I want to get all the 20 results given but currently, I am unable to get that. This is my code and I am unable to scroll to the bottom to get all the results. I can only get the first 7 records returned. Please guide what else steps are needed to achieve this result.
driver = webdriver.Chrome(PATH, options=options)
driver.set_page_load_timeout(20)
driver.implicitly_wait(10)
driver.get(base_url)
driver.maximize_window()
web_element = driver.find_element_by_id("searchboxinput")
web_element.send_keys("hospital in delhi " + "\n")
web_element.submit()
time.sleep(10)
outer_grid = WebDriverWait(driver, 10).until(EC.visibility_of_all_elements_located((By.CLASS_NAME, 'mapsConsumerUiCommonScrollable__scrollable-show')))
print("total grid size result is :{}".format(len(outer_grid)))
if len(outer_grid) == 0:
    print("Empty result try again")
    exit(-1)

time.sleep(3)

result_table = outer_grid[0]
driver.execute_script('arguments[0].scrollTo(0, document.body.scrollHeight);', result_table)
h_ele = WebDriverWait(result_table, 10).until(
    EC.visibility_of_all_elements_located((By.CLASS_NAME, "sJKr7qpXOXd__result-container")))
print("Total results from lot : {}".format(len(h_ele)))

for ele in h_ele:
    print("Name : {}".format(ele.text))
    website = ele.find_element_by_tag_name("a")
    http_url = "NA"
    if website.get_attribute("href") is not None:
        http_url = website.get_attribute("href")
        print("website : {}".format(http_url))

driver.quit()

A: Some websites do not trigger the automatic load so easily.
If you need to do this more than once then you'll have to implement a loop.
I have two ways of dealing with this:
"Smooth Scrolling"
total_height = int(driver.execute_script("return document.body.scrollHeight"))
for i in range(1, total_height, 4):
   driver.execute_script("window.scrollTo(0, {});".format(i))

"Pseudo Smooth Scrolling"
h_ele = WebDriverWait(result_table, 10).until(
    EC.visibility_of_all_elements_located((By.CLASS_NAME, "sJKr7qpXOXd__result-container")))
loc = h_ele[-1].location['y']
driver.execute_script(f"window.scrollTo(0, {loc} + 200);")
driver.execute_script(f"window.scrollTo(0, {loc} + 210);")


text:
Q: MLP classifier_for multi class I am newbie on keras,
I try to follow the Keras tutorial for Multilayer Perceptron (MLP) for multi-class softmax classification, using my data set.
My data has 3 classes and only one feature, but I don't understand why the result always show just 0,3 of accuracy and the model predicted all training data as first class. then the confusion matrix is like this.
Confusion matrix
Here the coding:
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.optimizers import SGD
import pandas as pd
import numpy as np

# Importing the dataset
dataset = pd.read_csv('StatusAll.csv')
X = dataset.iloc[:, 1:].values
y = dataset.iloc[:, 0:1].values

# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)

from keras.utils import to_categorical
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)

model = Sequential()

# Dense(64) is a fully-connected layer with 64 hidden units.
# in the first layer, you must specify the expected input data shape:
# here, 20-dimensional vectors.
model.add(Dense(64, activation='tanh', input_dim=1))
model.add(Dropout(0.5))
model.add(Dense(64, activation='tanh'))
model.add(Dropout(0.5))
model.add(Dense(4, activation='softmax'))

sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)

model.compile(loss='categorical_crossentropy',
              optimizer=sgd,
              metrics=['accuracy'])

history = model.fit(x_train, y_train,
          epochs=100,
          batch_size=128)
score = model.evaluate(x_test, y_test, batch_size=128)
print('Test score:', score[0])
print('Test accuracy:', score[1])

from sklearn import metrics

prediction = model.predict(x_test)
prediction = np.around(prediction)

y_test_non_category = [ np.argmax(t) for t in y_test ]
y_predict_non_category = [ np.argmax(t) for t in prediction ]

from sklearn.metrics import confusion_matrix
conf_mat = confusion_matrix(y_test_non_category, y_predict_non_category)

print (conf_mat)

I hope I can get some advice, thanksss.
The x_train example
x_train
y_train before converted to categorical
enter image description here

A: Your final Dense layer has 4 outputs, it seems like you are classifying 4 instead of 3.
model.add(Dense(3, activation='softmax')) # Number of classes 3

It would be helpful to see sample data from x_train and y_train to make sure the pre-processing is correct. Because you have only 1 feature, a MLP might be overkill. A decision tree would be simpler unless you want to experiment with MLPs.


text:
Q: Nonisomorphic number fields with the same Galois group and discriminant It is possible for nonisomorphic fields to have the same discriminant, and even to be arithmetically equivalent, meaning with the same Dedekind zeta function. Previous questions which discussed this are "Number fields with same discriminant and regulator?" and "Are there two non-isomorphic number fields with the same degree, class number and discriminant?". The usual way this comes about involves fields with isomorphic subfields. I would find it useful if the discriminant sufficed to characterize number fields whose splitting field had a simple Galois group, so that there were no subfields. So the question is, can there be two nonisomorphic fields with the same degree, the same discriminant and the same simple Galois group for the splitting field?

A: My answer to one of those previous questions provides an example of two Galois cubic fields of the same discriminant. The cyclic group of order three is simple.
Added: Just to give you an idea, if you look in Cohen's book A course in computational algebraic number theory, Theorem 6.4.6 says that if $e$ is the product of 9 times $t-1$ distinct primes that are congruent to 1 mod 3, then there are exactly $2^{t-1}$ cyclic cubic fields of discriminant $e^2$. There's a similar statement for $9\nmid e$.
And more: So using sage/pari, I just found the following example of two non-isomorphic quintic $A_5$-extensions with the same discriminant. Take $f=x^5 - x^2 - 2x - 3$ and $g=x^5 - x^4 + 5x^3 - 3x^2 + 4x - 3$. The associated fields (and the polynomials themselves) have discriminant 243049 (and 1 real place), which is a square. Hence, the Galois group is $A_5, D_5$, or $C_5$. Their factorization mod 3 are $x(x + 1)(x^3 + 2x^2 + x + 1)$ and $x (x + 2)  (x^3 + 2x + 2)$, respectively. Hence, both of their Galois groups contain a 3-cycle and hence must be $A_5$.
In fact, these both have class number 1. However, 5 is inert in the second field, but splits into primes of degree 1,1, and 3 in the first field. Their regulators are 10.7855048337065 and 7.68746944439494, respectively.

A: I just came upon this (old?) thread.  Here is a handy way to produce lots of non-Abelian, non-isomorphic extensions of Q with the same field discriminant:
Let K3/Q be a non-Abelian (resp Abelian) cubic field.  Let h3 be the size of the elementary 2-class group of K3.  Then Heilbronn (On the 2-classgroup of cubic fields, in: Studies in Pure Math}., 1971) showed that there is a (h3-1)  (resp (h3-1)/3) quadruplets of conjugate quartic fields K4 such that disc(K4)=disc(K3) and that the Galois closure of K4 contains K3.
So if you pick a K3 with large elementary 2-rank, then you will get lots of non-isomorphic K4 with Galois group S4 or A4, depending on whether K3 is non-Abelian or otherwise.
There is also a similar (and old) theorem of Hasse for 3-rank of quadratic fields.


text:
Q: How can unions be used to bypass strict aliasing violations? According to this answer the following code invokes undefined behavior:
uint16_t *buf = malloc(16); // 8*sizeof(uint16_t)
buf[1] = *buf = some_value;
((uint32_t *)buf)[1] = *(uint32_t *)buf;
((uint64_t *)buf)[1] = *(uint64_t *)buf;

We may write any type to malloc() memory but we may not read a previously written value as an incompatible type by casting pointers (with the exeption of char).
Could I use this union:
union Data {
    uint16_t u16[8];
    uint32_t u32[4];
    uint64_t u64[2];
};

As such:
union Data *buf = malloc(16);
buf->u16[1] = buf->u16[0] = some_value;
buf->u32[1] = buf->u32[0];
buf->u64[1] = buf->u64[0];

In order to avoid undefined behavior via strict aliasing violations? Also, could I cast buf to any of uint16_t *, uint32_t *, uint64_t *, and then dereference it without invoking undefined behavior, since these types are all valid members of union Data? (i.e. is the following valid):
uint16_t first16bits = *(uint16_t *)buf;
uint32_t first32bits = *(uint32_t *)buf;
uint64_t first64bits = *(uint64_t *)buf;

If not (i.e. the above code making use of union Data is still invalid), when can and cannot unions be used (in pointer casts or otherwise) to produce valid code that does not violate strict aliasing rules?

A: Yes, it is acceptable to write one union member and read another.  Section 6.5p7 of the C standard states:

An object shall have its stored value accessed only by an lvalue
expression that has one of the following types:

*

*a type compatible with the effective type of the object,

*a qualified version of a type compatible with the effective type of the object,

*a type that is the signed or unsigned type corresponding to the effective type of the object,

*a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,

*an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a
subaggregate or contained union), or

*a character type

It is also safe to convert the address of a union to that of any of its members.  From section 6.7.2.1p16:

The size of a union is sufficient to contain the largest of its
members. The value of at most one of the members can be stored in a
union object at any time. A pointer to a union object, suitably
converted, points to each of its members (or if a member is a bit-
field, then to the unit in which it resides), and vice versa

A: The construct someUnion.someArray[i] is defined as meaning *(someUnion.someArray+i), with the latter being an access to an lvalue of the array element type that has no relation whatsoever to the union type.
C implementations will generally recognize a construct which is written using the array-bracket notation as having an association with the union type, even in cases where they would not do so if the construct were written using explicit pointer arithmetic syntax.  Such special treatment for array-bracket notation, however, is purely up to the discretion of individual implementations.
On the flip side, a pointer to an object may only be converted to a pointer to a union type containing that object if the pointer satisfies the alignment requirements of all members within the union, without regard for whether the members in question are accessed.  On platforms that do not support unaligned access, clang will process a construct like:
union quadbyte {
    unsigned char bb[4];
    unsigned short hh[2];
    unsigned int ww[1];
};
#include <string.h>
unsigned  test(union quadbyte *src)
{
    return src->hh[0] | (src->hh[1] << 16);
}

in a manner that will fail if src isn't properly aligned for type union quadbyte, even if it would be properly aligned for type unsigned short.


text:
Q: How to validate input according to Open FST? There is a hacky way to do it: https://stackoverflow.com/a/54067480/3310334
But is there a more modern solution considering over two years have passed?

import openfst_python as fst

input_sym = fst.SymbolTable()
output_sym = fst.SymbolTable()

input_sym.add_symbol('<eps>')
input_sym.add_symbol('a')
input_sym.add_symbol('b')

output_sym.add_symbol('<eps>')
output_sym.add_symbol('A')
output_sym.add_symbol('B')

f = Fst()
f.set_input_symbols(input_sym)
f.set_output_symbols(output_sym)

s0 = f.add_state()
s1 = f.add_state()
s2 = f.add_state()
s3 = f.add_state()

a = input_sym.find('a')
b = input_sym.find('b')
A = input_sym.find('A')
B = input_sym.find('B')

f.add_arc(s0, fst.Arc(a, A, None, s1))
f.add_arc(s0, fst.Arc(b, B, None, s2))
f.add_arc(s1, fst.Arc(a, A, None, s3))
f.add_arc(s2, fst.Arc(b, B, None, s3))

f.set_start(s0)
f.set_final(s3)

Takes 'ab' or 'ba' and produces 'AB' or 'BA'.
How can I test if certain strings or sequences constitute valid inputs?
How can I run inputs through the transducer?


text:
Q: I want to capture the starting and end point of all the series in my multigraph and show it in a table using MeasureX of StockTools in Highstock I have a MultiGraph i.e a graph with multiple series. What I want to do is use MeasureX(stockTools GUI Button) to highlight a particular area in my graph and then display the starting and end point of all the series in that highlighted area in a separate table inside my widget. How can I achieve that? If anyone can tell me atleast how can I capture the MeasureX event in my code with the required value, I can take it forward from there. My series look something like this.
Series:[{type:line,data:[],name:X},{type:line,data:[],name:Y},{type:line,data:[],name:Z}.....],
P.S: Please let me know if I can help with some other clarifications.

A: Use the end event for the measureX bindings, example:
navigation: {
  bindings: {
    measureX: {
      end: function(e, annotation) {
        var x1 = annotation.startXMin,
          x2 = annotation.startXMax,
          series = annotation.chart.series[0],
          filteredPoints = series.points.filter(
            point => point.x > x1 && point.x < x2
          ),
          firstPoint = filteredPoints[0],
          lastPoint = filteredPoints[filteredPoints.length - 1];

        firstPoint.graphic.attr({
          stroke: 'red'
        });
        lastPoint.graphic.attr({
          stroke: 'red'
        });
      }
    }
  }
}

Live demo: https://jsfiddle.net/BlackLabel/b4u7ehjo/
API Reference: https://api.highcharts.com/highstock/navigation.bindings.measureX


text:
Q: Count Occurrences of words with Case sensitives How can we find the occurrences of words in an array of Strings with Case sensitive
e.g. [AA, Bb, Aa, aa, BB]  ===> {AA=3, Bb=2}
[AAa,aaa,BBB,bbb,BbB,AaA,AAc]  ===> {AAa=3, BBB=3 , AAc=1}

The count should be against the first appearance of the word
ConcurrentHashMap<String,Integer> hm = new ConcurrentHashMap<>();
String[] s1 = {"AA", "Bb", "Aa", "aa", "BB"};
    for (String s:s1) {
        if (hm.size()==0)
            hm.put(s,1);
        else {
            Set<String> keySet = hm.keySet();
            for (String s2 : keySet) {
                if (s2.equalsIgnoreCase(s)) {
                    Integer val = hm.get(s2);
                    hm.put(s2, ++val);
                    break;
                } else {
                    hm.put(s, 1);
                }
            }
        }
    }

    System.out.println(hm);

A: TreeMap allows you to provide a custom key comparator. One such comparator is String.CASE_INSENSITIVE_ORDER.
final TreeMap<String, Integer> treeMap
        = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
final String[] s1 = {"AA", "Bb", "Aa", "aa", "BB"};

for (final String s : s1) {
    treeMap.merge(s, 1, Integer::sum);
}

System.out.println(treeMap);

Output:
{AA=3, Bb=2}

I know, boring. Where's the fun in that? :)


text:
Q: Mysql log confusion I have installed a standard installation of mysql on Debian Wheezy and I am confused as to where the logs are supposed to be logged. In my /var/log/ directory, there are files mysql.log which are empty. All logging goes to daemon.log and syslog. To add to the confusion, show variables like '%log%'; shows other logs still (My datadir is /srv/mysql) :
| general_log                             | OFF                               |
| general_log_file                        | /srv/mysql/mysql-systems.log      |
| slow_query_log                          | OFF                               |
| slow_query_log_file                     | /srv/mysql/mysql-systems-slow.log |

I like to keep my logs clean and organized. What would be the best way to log mysql. Should I change it on the mysql level, or in rsyslog. BTW, is there any standard for logs similar to FHS ?

A: The mysql general_log logs all queries made to the mysql server and by default is disabled.
The slow log will log any queries that have "especially long duration" (defaults to 2 minutes). Again this defaults to being disabled.
The default location for mysqld_safe to log is set by: /etc/mysql/conf.d/mysqld_safe_syslog.cnf, which defaults to syslog. You can either filter the results
out to a separate file with your rsyslog config, or you can edit your /etc/mysql/my.cnf
file, and set a log location for errors with:
 log_error = /var/log/mysql.log


text:
Q: How to check during compilation that GCC has at least C++17 running? How do I check during compilation that GCC (or any other compiler) has at least C++17 running? Can you give a minimal preprocessor snippet that emits an error if the version is below C++17?
I presume this can be built from __cplusplus and the #error directive.

A: #if __cplusplus < 201703L
#error "C++17 or later is required!"
#endif


text:
Q: Having trouble with defining linear transformation on a basis I was studying a problem where there was a linear transformation $T_2 \in \mathcal{L}(V,W)$.We were given that $W$ is finite dimensional. So range$T_2$ is also finite dimensional.So there exists a basis for range$T_2=w_1,...,w_m$ this implies for each $j$, there exists $v_j \in V$ such that $w_j=T_2v_j$.
Because the list of vectors $v_1,...v_m$ is linearly independent in $V$, it can be extended to a basis of $V$.
A  transformation $T_2$can be defined on the whole of $V$
such that $T(a_1v_1+\ldots +a_mv_m)=a_1w_1+\dots +a_mw_m$
Confusion arose for me here because usually we define a transformation on the basis vectors, and $v_1,...,v_m$ is not necessarily a basis for $V$
My question was does this transformation imply all the vectors in the basis but not in the set $\{v_1,...,v_m\}$ are mapped into the zero vector?
Somebody replied not necessarily on the previous question I posted.
This reminds me of the problem in an early section:
Suppose $V$ is finite dimensional.Prove that any linear map on a subspace of $V$ can be extended to a linear map on $V$.In other words show that if $U$ is a subspace of $V$ and $S \in \mathcal{L}(U,W)$ then there exists $T \in \mathcal{L}(V,W)$ such that $Su=Tu$ for all $u \in U$
Proof:Let $u_1,...,u_m$ be a basis for $U$ extend to a basis $u_1,...u_m,v_1,...,v_n$ of $V$.
Define $T \in \mathcal{L}(V,W)$ by $T(u_i)=S(u_i)$ for $i \in \{1,...m\}$ Define $T(v_j)=0$ for $j \in \{1,...,n\}$
Here we are taking all the $v_j's$ equal to zero. And that defines our linear map. Why did this person commenting (about the problem above) state that the other basis vectors of $V$ (not mapped into $w_1,...,w_m$) are not necessarily mapped to the zero vector.This makes me very confused.

A: If we start with a basis $u_1,\dots,u_m$ of $\textsf U$ and if we extend it to a basis $u_1,\dots,u_m,u_{m+1},\dots,u_n$ of the whole space $\textsf V$, by the theorem that you mentionned above, there exists a unique linear tranformation, $\textsf T$, such that
$$\textsf{T}(u_i) = \begin{cases}
\textsf{S}(u_i) &\textrm{if } 1\leq i\leq m \\
0 &\textrm{if } m+1\leq i\leq n
\end{cases}$$
Now, we claim that $\textsf{T}(v) = \textsf{S}(v)$ for every $v\in\textsf U$. Since any $v\in\textsf U$ can be written as
$$v = \sum_{i=1}^m a_iu_i \quad \textrm{ for some scalars } a_1,\dots,a_m$$
because $u_1,\dots,u_m$ is a basis of $\textsf U$, it follows that
$$\begin{align}
\textsf T(v) &= \textsf T\Big( \sum_{i=1}^m a_iu_i \Big) \\
&= \sum_{i=1}^m a_i\textsf{T}(u_i) \\
&= \sum_{i=1}^m a_i\textsf{S}(u_i) \quad \textrm{ since $i$ is between 1 and $m$} \\
&= \textsf S\Big( \sum_{i=1}^m a_iu_i \Big) = \textsf S(v).
\end{align}$$
As you can observe, that $\textsf{T}(u_i)$ is the zero vector for every $i\in\{m+1,\dots,n\}$ doesn't matter, you can define it in any way.


text:
Q: Invalid left-hand side in assignment? I created a custom button that marks a check box from false to true. I get an error saying when I click on it and it doesn't update the check box:

Invalid left-hand side in assignment

I copied and pasted this code from another button that we use that, as far as I know, works and just changed the fields. Can someone help me figure out what is wrong with this code? I would've preferred to have used an action, but the standard object "Product2" doesn't support them apparently.
   {!REQUIRESCRIPT("/soap/ajax/22.0/connection.js")}
    var newRecords = [];
    var c = new sforce.SObject("Product2");
    c.id = "{!Product2.Id}";
    {!Product2.Service_Part__c} = true;
    newRecords.push(c);
    result = sforce.connection.update(newRecords);
    window.location.reload();

A: {!Product2.Service_Part__c} = true;

Should be:
c.Service_Part__c = true;


text:
Q: How do I disable a full-Text Search on a column in sql server? I'm trying to convert a column from ntext to nvarchar(MAX), but it seems there is a Full-Text search enabled on it.
Alter table <table> alter column <column> nvarchar

Then i'm going to force the text into rows
update <table> set <column> = <column> +'' where <column> is not null

Finally I'll need to enable the full text search again.
How do I do this in SQL?

A: DROP FULLTEXT INDEX ON mytable.mycolumn;
go
Alter table ... nvarchar(value);
go
ADD FULLTEXT INDEX ON mytable add (mycolumn)

(http://msdn.microsoft.com/en-us/library/ms188359.aspx)

A: This is to SQL Server 2005.
Syntax to drop Fulltext Index:
ALTER FULLTEXT INDEX ON [TABLENAME] DROP (COLUMNNAME)
-- ALTER COLUMN OR MORE STATEMENT --
Syntax to Readd FullText Index:
ALTER FULLTEXT INDEX ON [TABLENAME] add (COLUMNNAME)

A: ALTER FULLTEXT INDEX ON TableName drop (ColumnName)
ALTER TABLE TableName ALTER COLUMN ColumnName nvarchar(MAX)
ALTER FULLTEXT INDEX ON TableName add (ColumnName)

This will drop the column from the index, then you alter it, and after this, you re-add it to the index.


text:
Q: selecting spring profile maven commands Am having spring profiles configured in my application like DEV, TEST, QA. how can i select those profiles using maven commands.
As of now, am selecting those profiles using.
clean package -P DEV

But also i have other configuration like,
clean pacakage -Dtuf.environment="DEV" -Dapi.environment="DEV" -Dspring.profiles.active="DEV"

So, in these two commands which one is best to select. Also, if i want to pass these profile as run time argument from tomcat vmarguments how can i pass these as arguments.
Am using tomcat 8.5 version

A: You can use -Dspring.profiles.active without declaring it every time by creating a script setenv.sh in the bin folder of tomcat, in which you override the variable JAVA_OPTS


text:
Q: How to use @react-native-community/datetimepicker with textinput field with validation in react native I refer this docs https://www.npmjs.com/package/@react-native-community/datetimepicker
I try to implement this in react native with textinput but I don't know how to achieve this, actually I am new in react native pls any one guide me.
I need to add DOB field in registration using datepicker and also user can type dob in textinput with validation pls help, thanks in advance.


text:
Q: How do I loop over a list of strings in R? I want to create a list that contains vectors that display either a 1 or a 0 depending on whether a certain character is present.
The data has the following form:
list <- list('a', 'b', 'c', 'd', 'e')
col1 <- c('ta', 'ta', 'tb', 'tb', 'tb', 'tc', 'td', 'te')

What I want is a list for all elements of 'list' that contains a vector displaying a 1 when the element of list is present in the element of col1 and a 0 when it is not.
For 'a' this vector will look like (1,1,0,0,0,0,0,0) for example.
My question is why the following loop does not work:
test <- list()
for (i in list){
  test[[i]] <- ifelse(grepl(list[i], col1), 1, 0)
}

This loop returns a list with only zeroes.
However, when I run part of the loop individually it does give the correct result:
ifelse(grepl(list[1], col1), 1, 0)

This does in fact return the vector I want: (1,1,0,0,0,0,0,0).
How do I loop over a list of strings in R correctly?

A: You can do this without using the loop and in one line only. See;
List <- list('a', 'b', 'c', 'd', 'e')
col1 <- c('ta', 'ta', 'tb', 'tb', 'tb', 'tc', 'td', 'te')

lapply(List, FUN = function(x) as.numeric(grepl(x, col1)))

A: List <- list('a', 'b', 'c', 'd', 'e')
col1 <- c('ta', 'ta', 'tb', 'tb', 'tb', 'tc', 'td', 'te')

test <- list()
for (i in 1:length(List)){
  test[[i]] <- ifelse(grepl(List[i], col1), 1, 0)
}


text:
Q: Postgres full-text search: make a tsvector by splitting on whitespace or by providing an array of tokens I have a text search problem where I need to search systematically-generated text, i.e. not human-written natural language text.
The typical ts_tovector('english', 'foo bar baz') is not particularly helpful. In some cases it generates tokens which I know will be lead to false-positive search results.
Instead I'd really just like to either provide the tokens in a string where each token is separated by whitespace, or provide an array of ordered tokens.
For example, something along the lines of to_tsvector(array["foo", "bar", "baz"]) should produce three tokens: foo, bar, and baz. This seems like a pretty basic thing, but so far I haven't found any explicit documentation of this functionality.

A: This is indeed a basic thing, and all you have to do is use the simple text search configuration:
to_tsvector('simple', 'foo bar baz')


text:
Q: Problems starting an NServiceBus I've created a very simple NServiceBus console application to send messages. However I cannot start the bus as it complains with a very vague error about 'Object reference not set to an instance of an object'.
        Configure config = Configure.With();
        config = config.DefaultBuilder();
        config = config.BinarySerializer();
        config = config.UnicastBus();
        IStartableBus startableBus = config.CreateBus();
        IBus Bus2 = startableBus.Start(); // **barf**

It's driving me mad, what am I missing? I thought the DefaultBuilder should be filling in any blanks?

A: Hmm, looks like a reference to ncqrs.NserviceBus is causing it to go wrong even though I'm not actually using it yet

A: Looks like manually adding the Assemblies in the overload to With() did the trick, not sure what's upsetting it but that's for another day


text:
Q: PHP - "if" in "while" problems to alternate html table rows colour $banana=0;
$view = mysql_query('SELECT ......') or die ('Encountered an error.') ;
while($rows3=mysql_fetch_array($view))
{
    $total_price2=$rows3['qty']*$rows3['number'];
    $banana = $banana + 1;

    if ($total_price2!=0)
    {
        if ($banana %2 ==0)
        {
            echo "
";
        }
        else
        {
            echo "
";
        }
        echo "".$rows3['member']."	";
        echo "".$rows3['payment']."	";
        echo "$".number_format($total_price2,2)."	";
    }

    echo "
";
}

Problems:

*

*The "banana" alternates the colour of the table row (class="alt") by using modulus (%) to check if banana is a odd number.

*Not Working, I see the browser is self-closing the opening
 tag.

eg:

person	data	$10.00

 (Repeats in this fashion)
UPDATE
I have discovered that the reiterating banana always returns ODD NUMBERS: 1 , 3, 5, etc

MySQL is not running correctly

SELECT table1.member, table1.paid, table1.payment,table2.qty,table3.number FROM table1,table2,table3 WHERE table1.member = table2.member AND table1.payment="fruit"
It is giving me wrong data like so:

*

*person1 $10.00

*person1 $0.00

*person2 $10.00

*person2 $0.00

etc

A: Try doing this for a debug first:
echo "
 ";
My guess is that you have no data contained in your
 and is being squished to 0 px tall by your browser.
EDIT: I'm not entirely sure giving a class to your
 will filter down into the  based on certain browser DOM parsing. Whenever I do a zebra row, I'll assign the class to the . I'm no designer by any standard, though. :)
Humor me and try this please:
$banana=0;
$view = mysql_query('SELECT ......') or die ('Encountered an error.') ;
while($rows3=mysql_fetch_array($view))
{
    $total_price2=$rows3['qty']*$rows3['number'];
    $banana++;
    if ($banana % 2 == 0) {
        $td_class = "alt";
    } else {
        $td_class = "";
    }
    echo "
";
    if ($total_price2!=0) {
        echo "".$rows3['member']."	";
        echo "".$rows3['payment']."	";
        echo "$".number_format($total_price2,2)."	";
    }
    echo "
";
}

A: If all else fails, you could just use CSS:
tr {background-color: blue;}
tr:nth-of-type(2n) {background-color: red;}

A: That's not going to work.  You're only opening the table row if $total_price2!=0.  It seems you should only output the closing
 tag inside that IF block.
Try this instead:
<?php
$banana=0;
$view = mysql_query('SELECT ......') or die ('Encountered an error.') ;
while($rows3=mysql_fetch_array($view))
{
    $total_price2=$rows3['qty']*$rows3['number'];

    if ( !$total_price2)
        continue;

    $banana = $banana + 1;

    if ($banana %2 ==0)
    {
        echo "
";
    }
    else
    {
        echo "
";
    }

    echo "".$rows3['member']."	";
    echo "".$rows3['payment']."	";
    echo "$".number_format($total_price2,2)."	";

    echo "
";
}


text:
Q: Laptop crashes as soon as I login as administrator This has always been the case every single time I start up my Laptop.
Every single time the computer has finished booting up, and asks for my password to start using my computer, the computer will log on as normal. But after a short time, everything just stops, the screen is viewable but frozen. My cursor will not move and the CTRL+ALT+DEL key combinations will not work at all.
I checked if the computer is even responding by pressing the NUM-LOCK key and the NUM-LOCK light indicator will not even turn off/on.
I have tried un-installing a few hefty programs in safe mode to see if it is a start up issue (which I am suspecting it is) but the problem was not fixed at all.
There will be a few times where my computer will not crash at all but when I click the start menu there are no programs detected at all.
I tried running my web browser but instead a window popped up stating that the program does not exist. I do not know what to do. I would love to have it fixed very soon.
Does anyone have any clues on how to go about troubleshooting and fixing this?

A: some Malware caused that by coping theme selves every where in the disk,
try to:
1-scan your disk for Bad sectors  you can use Hiren's boot  under ->dos programs->Hard-disk ->HDAT
2-scan your hard disk for viruses by Antivirus Rescue live Disk  -generally all anti virus provide it for free- you can uses this
http://www.eset.com/int/support/sysrescue/
that feeling when i can't express -_-


text:
Q: define property in code behind and reference it in ASCX file public List<string> Test1
{
    get
    {
        List<string> list1 = new List<string>()
        {
            "a",
            "minie",
            "lilo"
        };

       return list1;
    }
}

Can anybody advise what's wrong with this piece of code? I have this in the code behind file and in the ascx I am trying to render it like this: <%= Test1[0] %> but it doesn't work (no errors, but the ascx is not rendered where I put it, for editing purposes). I work this in correlation with episerver 6, e.g. the ascx is not rendered in the layout block where it's supposed to. As soon as I drop the <%= Test1[0] %>, the block becomes visible. I need a way to reference the Test1 list (or the first element for starters).

A: You're not really doing anything with your list by just putting it there. Render it:
<% foreach(string s in Test1) { %>

<%:s%>

<% } %>


text:
Q: Rails: How do I make a calculation using form input variables in the create action of a controller before saving it in the db? In my form, the user inputs his/her weight and body fat percentage. In my controller create action, I want to calculate the lean mass of the person and save it to the lean_mass column in my db.
lean_mass = weight * (1 - body_fat)
schema.rb
create_table "stats", force: true do |t|
   t.integer  "user_id"
   t.integer  "weight"
   t.decimal  "body_fat"
   t.integer  "lean_mass"
   t.date     "date"
   t.datetime "created_at"
   t.datetime "updated_at"
 end

stats/new.html.erb
<%= form_for @stat do |f| %>
  <%= f.label :date %>
  <%= f.date_field   :date %>

  <%= f.label :weight %>
  <%= f.number_field :weight %>

  <%= f.label :body_fat %>
  <%= f.number_field :body_fat, step: 0.1 %>

  <%= f.submit %>
<% end %>

stats_controller.rb
class StatsController < ApplicationController
  before_action :authenticate_user! #I'm using devise

def index
 @stats = current_user.stats
end

def new
 @stat = current_user.stats.build
end

def create
  ##
  ###How do I calculate and add lean_mass to stat_params here?###
  ##
  @stat = current_user.stats.build(stat_params)
  if @stat.save
    redirect_to root_url, notice: "Stat was successfully created."
  else
    redirect_to dashboard_url, notice: "Problem creating stat."
  end
end

 private

 def stat_params
   params.require(:stat).permit(:date, :weight, :body_fat)
 end
end

I need help with the create action.

A: Manually calculate & insert the lean mass:
You will have to calculate the lean mass first:
lean_mass = params[:stat][:weight].to_i * (1 - params[:stat][:body_fat].to_i)

And then you can add it to the new @stat object
@stat = current_user.stats.build(stat_params.merge(:lean_mass => lean_mass))

# OR

@stat.lean_mass = lean_mass

Then you can go ahead and save the object.
Automatically handle the lean mass
Assuming you validate the presence of the weight & body_fat columns like so:
stat.rb
validates_presense_of :weight, :body_fat

Since the lean mass is always dependant on the weight & body_fat I'd suggest two things:
1) You can add a method lean_mass in your model that returns the calculated value, so the column would no longer be necessary.
stat.rb
def lean_mass
  self.weight * (1 - self.body_fat)
end

2) Add an after_save callback that calculates & stores the lean_mass value automatically
stat.rb
after_save { self.update(:lean_mass => self.weight * (1 - self.body_fat)) }

One of these solutions is highly suggested since you don't have to worry about the lean mass column in the create or update action.


text:
Q: How to search matching charecter in mysql $result = mysqli_query($conn, "SELECT * FROM ProcessTrackingSystem.ProcessDetails WHERE Sample_name LIKE '$userinput' OR Client_name LIKE '$userinput1%'") or die(mysqli_error($conn));

I am trying to execute above query, but its outputting full details from mysql database.
how to fix this issue?
thanks in advance!!

A: Missing % -
Sample_name LIKE '%$userinput%' OR Client_name LIKE '%$userinput1%'

Check the docs

A: You have to use '%' operator. A Like always expect a %. Try this -
$result = mysqli_query($conn, "SELECT * FROM ProcessTrackingSystem.ProcessDetails WHERE Sample_name LIKE '%$userinput'") or die(mysqli_error($conn));

A: you missed % sign in $userinput
$result = mysqli_query($conn, "SELECT * FROM ProcessTrackingSystem.ProcessDetails WHERE Sample_name LIKE '%$userinput%'") or die(mysqli_error($conn));


text:
Q: pkg_resources.DistributionNotFound: The 'platformdirs<3,>=2' distribution was not found and is required by virtualenv I am trying to create an isolated environment using pip, the instructions from "Hands on Machine Learning With Ski-Kit and Tensor Flow" have me run these lines of code and this is the output I get. I've tried uninstalling pipenv and that creates another error where pipenv command not found.  Not sure how to work around this, can anyone help?  I'm using a Mac with python3.9
Darrens-MacBook-Air:~ odonned4$ cd $ML_PATH
Darrens-MacBook-Air:~ odonned4$ virtualenv env
  File "/usr/local/bin/virtualenv", line 6, in <module>
    from pkg_resources import load_entry_point
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 3241, in <module>
    @_call_aside
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 3225, in _call_aside
    f(*args, **kwargs)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 3254, in _initialize_master_working_set
    working_set = WorkingSet._build_master()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 585, in _build_master
    return cls._build_from_requirements(__requires__)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 598, in _build_from_requirements
    dists = ws.resolve(reqs, Environment())
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 786, in resolve
    raise DistributionNotFound(req, requirers)
pkg_resources.DistributionNotFound: The 'platformdirs<3,>=2' distribution was not found and is required by virtualenv```

A: What is the problem?
You are trying to run Python 3.9, right? Well, according to your error message, it seems like you're invoking Python 2.7:
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/__init__.py", line 3241, in <module>
                                                           ^^^

This confusion happens because macOS added Python 2.7 to the distribution for... compatibility reasons. And, probably, you have virtualenv on that distribution, but you don't have platformdirs, so creating a virtualenv fails.
How to solve the problem?
There are many ways to clarify this confusion. A good way is using python3 -m virtualenv (instead of virtualenv). That should create a virtualenv with Python 3.
Also, you can get sure that the virtualenv package is available in your Python 3.9 installation. To identify that, see if virtualenv appears when typing python3 -m pip list. If not, run python3 -m pip install virtualenv.

A: The real problem here is that Mac is hard wired to use python2. When using virtualenv, you might have run the command:
$ /usr/bin/easy_install virtualenv

which should have added virtualenv to the /usr/bin/ for direct use, but to be used with the default python2 instead of python3.9 which you might have installed on your own.
A simple way around is to use
$ python3 -m virtualenv <env-name>

instead of
$ virtualenv <env-name>

Or in my case, add an alias in .bash_profile:
$ alias virtualenv="python3 -m virtualenv"

which is a duct tape solution but it works as well.

A: Try uninstalling setuptools with
pip uninstall -y setuptools

and reinstalling it with
pip install setuptools

OR
Upgrade setuptools with
pip install --upgrade setuptools

OR
For me i have faced this issue some before in python 3.8.
I fixed it by
sudo apt install --reinstall python3-pkg-resources python3-setuptools

OR
Uninstall virtualenv and setuptools first and find pip cache folder.
pip cache dir

Delete the cache and install virtualenv and setuptools.
I JUST SAID SOME STEPS .. TRY THIS . MAY HELP : )


text:
Q: Why does $.ajaxSetup not work with $.post Why does this code post the sessionID parameter
    $.post("ajax/p_getOnePosition.jsp", {
        positionNo: positionNo,
        sessionID: v_sessionID,
    }, function(response2) {

But not this code
    $.ajaxSetup({
        sessionID: v_sessionID,
    });

    $.post("ajax/p_getOnePosition.jsp", {
        positionNo: positionNo,
    }, function(response2) {

A: Use beforeSend instead as follows.  Code inspired from here
$.ajaxSetup({
     beforeSend: function (jqXHR, settings) {
        settings.data += "&sessionID="+v_sessionID;
  }
});

$.post("ajax/p_getOnePosition.jsp", {
    positionNo: positionNo,
}, function(response2) {


text:
Q: How do I promote a User to an admin user a controller method and passing in the user? I have a users index page:

<% @users.each do |user| %>

<%= user.name %> |  <%= link_to "Promote to Admin", :controller => :users_controller, :action => :promote_to_admin(user) %>

<% end %>

When I click on the "Promote to Admin" link, I want the user to be promoted to admin by calling the promote_to_admin action in usersController. How do I do it ?
Here is my usersController:
class UsersController < ApplicationController

def index
@users = User.all
end

def promote_to_admin
  user = User.find(params[:id])
  user.update_attribute!(:admin, true)

  if user.admin == true
    flash[:success] = "User has been sucessfully promoted to admin"

  else
    flash[:error] = "User could not be promoted to manager"
end
end
end

A: this should be like:

<%= user.name %> |  <%= link_to "Promote to Admin", :controller => :users_controller, :action => :promote_to_admin(:user) %>

Please notice:
:promote_to_admin(:user)


text:
Q: jquery custom keycode trigger not working I want to send keystrokes on the selected element like this:
$(":input").click(function(){
    $(this).trigger("keydown", [{
        preventDefault:function(){},
        keyCode:9,
        shiftKey: true
    }]);
});

//wants to send Shift+Tab keystroke on input click

Demo: http://jsfiddle.net/NYwCT/.

A: You cannot send keystrokes. It currently triggers any functions that are bound, but does not execute the relevant thing at browser level (what about a script sending ALT+F4?).
If you want to focus the input before the clicked one, you can use .prev() (previous sibling): http://jsfiddle.net/NYwCT/1/.
$(":input").click(function(){
    $(this).prev().focus();
});

A: This will not fire the actual event
var press = jQuery.Event("keypress");
press.shiftKey = true;
press.keyCode = 9;
$(this).trigger(press);

you could also try this plug-in: fn.sendkeys or jwerty


text:
Q: Generated ZIP file is corrupt / invalid I'm trying to create a simple ZIP file in Java, but once generated, I can't open it with either Windows Explorer or 7-zip, as they say the file is invalid / unrecognized / corrupted.
However, I'm following all the tutorials I've seen and using a very simple code, so I don't see where I went wrong. Here's the simplest snippet I could think of to reproduce the problem:
FileOutputStream fos = new FileOutputStream("test.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
ZipEntry ze = new ZipEntry("test.txt");
zos.putNextEntry(ze);
byte[] data = "content".getBytes();
fos.write(data, 0, data.length);
zos.closeEntry();
zos.finish();
zos.close();

Did I miss a setting somewhere?
For reference, I've uploaded the test.zip file here.

A: You're writing to the wrong stream.
  // fos.write(data, 0, data.length);
  zos.write(data, 0, data.length);