text:
Q: Updating varchar column over linked server with parameterized query causes remote scan and cursorfetch I'm issuing a fairly simple update of a single varchar column against a remote linked server - like this:
UPDATE Hydrogen.CRM.dbo.Customers
SET EyeColor = 'Blue'
WHERE CustomerID = 619

And that works fine when is written as an ad-hoc query:

Parameterized queries bad
When we do what we're supposed to do, and have our SqlCommand issue it as a parameterized query, the SQL ends up being: (not strictly true, but close enough)
EXEC sp_executesql N'UPDATE [Hydrogen].[CRM].[dbo].[Customers]
SET [EyeColor] = @P1
WHERE [CustomerID] = @P5',
N'@P1 varchar(4),@P5 bigint',
'Blue',619

This parameterized form of the query ends up performing a remote scan against the linked server:

It creates a cursor on the linked server, and takes about 35 seconds to pull back 1.2M rows to the local server through a series of hundreds of sp_cursorfetch - each pulling down a few thousand rows.
Why, in the world, would the local SQL Server optimizer ever decide to pull back all 1.2M rows to the local server in order to update anything? And even if it was going to decide to pull back rows to the local server, why in the world would it do it using a cursor?
It only fails on varchar columns. If I try updating an INT column, it works fine. But this column is varchar - and it fails.
I tried other parametrizing the column as nvarchar, and it's still bad.
Every answer I've seen actually are questions:

*

*"is the collation the same?"

*"What if you change the column type?"

*"Have you tried OPENQUERY?"

*"Does the login have sysadmin role on the linked server?"

I already have my workaround: parameterized queries bad - use ad-hoc queries.
I was hoping for an explanation of the thing that makes no sense. And hopefully if we have an explanation we can fix it - rather than workaround it.
Of course I can't reproduce it anywhere except the customer's live environment. So it is going to require knowledge of SQL Server to come up with an explanation of what's happening.
Bonus Reading

*

*Stackoverflow: Remote Query is slow when using variables vs literal

*Stackoverflow: Slow query when connecting to linked server

*https://dba.stackexchange.com/q/36893/2758

*Stackoverflow: Parameter in linked-server query is converted from varchar to nvarchar, causing index scan and bad performance

*Performance Issues when Updating Data with a SQL Server Linked Server

*Update statements causing lots of calls to sp_cursorfetch?

*Remote Scan on Linked Server - Fast SELECT/Slow UPDATE


text:
Q: Weird behaviour with retainCount When I am logging retain count with NSArray and NSString objects, I am having uneven behavior.
See the code below,
NSArray *aryTemp = [NSArray arrayWithObjects:@"One",nil];
NSLog(@"Retain Count :%d",[aryTemp retainCount]);

NSArray *aryTemp2 = [[NSArray alloc] initWithObjects:@"One",nil];
NSLog(@"Retain Count :%d",[aryTemp2 retainCount]);

NSString *strTemp = @"One";
NSLog(@"Retain Count :%d",[strTemp retainCount]);

NSString *strTemp2 = [[NSString alloc] initWithString:@"One"];
NSLog(@"Retain Count :%d",[strTemp2 retainCount]);

And this is the output I am getting
2011-03-01 19:19:32.410 Test[14607:207] Retain Count :37
2011-03-01 19:19:32.412 Test[14607:207] Retain Count :1
2011-03-01 19:19:32.413 Test[14607:207] Retain Count :2147483647
2011-03-01 19:19:32.413 Test[14607:207] Retain Count :2147483647

What is the wrong with the code??
Thanks
Pratik Goswami

A: nothing wrong with 2147483647
2147483647 is INT_MAX. And INT_MAX is the retaincount for string literals (ie @"foo" strings defined in your code). This means they will never be released.
btw, don't use retainCount.

A: You should never use -retainCount, because it never tells you anything useful.  The implementation of the Foundation and AppKit/UIKit frameworks is opaque; you don't know what's being retained, why it's being retained, who's retaining it, when it was retained, and so on.
Also see: StackOverflow | when to use retainCount for an excellent recount of why you don't use retainCount.
And to echo Dave DeLong:
Please everyone go to http://bugreport.apple.com and request that -retainCount be deprecated.  The more people that ask for it, the better.

A: retainCount returns NSUInteger and you should print it in this way ...
NSLog( @"%lu", (unsigned long)[blabla retainCount] );

%d is used for signed 32-bit integer (int). NSUInteger is on 32-bit platform defined as unsigned int and on 64-bit platform as unsigned long. Upper example is safe for both 32/64-bit platforms.

A:
What is the wrong with the code??

You are calling retainCount.
retainCount is next to useless for debugging and should never, ever, be used in production code.   The retain count of an object is an internal implementation detail that will often be of a value that is unfathomable.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Starting Developing for Blackberry Playbook I am a novice to blackberry development. I have quite a hands on experience in blackberry smartphones. After I heard a lot about blackberry playbook, now i want to enhance my skills towards it.
Please help me out how and where to start with ?
The tools or env setup ?

A: More useful resources to anybody looking in a similar scenario:
You may want to start here
Playbook development is Adobe AIR based
also, if your a C++ or Java developer. They are coming out with a blackberry player for the tablet with an SDK. BlackBerry Tablet OS NDK It should be hitting limited Beta soon.

A: Please find the below link
http://supportforums.blackberry.com/t5/Tablet-OS-SDK-for-Adobe-AIR/Flex-for-the-BlackBerry-PlayBook-in-90-Minutes/ta-p/720803


text:
Q: overloading operator .  Ok, I know that operator. is not overloadable but I need something like that.
I have a class MyClass that indirectly embeds (has a) a std::string and need to behave exactly like a std::string but unfortunately cannot extend std::string.
Any idea how to achieve that ?
Edit: I want that the lines below to compile fine

MyClass strHello1("Hello word");
std::string strValue = strHello1;
  const char* charValue = strHello1.c_str();

A: You can overload the conversion operator to implicitly convert it to a std::string:
class MyClass
{
    std::string m_string;
public:
    operator std::string& ()
    {
        return m_string;
    }
};

A: If you're not interested in polymorphic deletion of a string*, you can derived from std::string, just getting the behavior of your class behaving "as-a" std::string. No more, no less.
The "you cannot derived from classes that don't have a virtual destructor" litany (if that's the reason you say you cannot extend it) it like the "dont use goto", "dont'use do-while" "don't multiple return" "don't use this or that feature".
All good recommendation from and for people that don't know what they are doing.
std::string doesn't have a virtual destructor so don't assign new yourcalss to a std::string*. That's it.
Just make your class not having a virtual destructor itself and leave in peace.
Embedding a string and rewriting all its interface just to avoid inheritance is simply stupid.
Like it is stupid writing dozens of nested if to avoid a multiple return, just as its stupid introduce dozens of state flags to avoid a goto or a break.
There are cases where the commonly considered weird things must be used. That's why those things exist.

A: As per your later edit, that:
MyClass strHello1("Hello word");

std::string strValue = strHello1;
const charValue = strHello1.c_str();

should compile fine, the only solution is to write a wrapper over std::string:
class MyClass
{
private:
   std::string _str;
public:
   MyClass(const char*);
   //... all other constructors of string

   operator std::string& ();
   //... all other operators of string

   const char* c_str();
   //... all other methods of string

   friend std::string& operator + ( std::string str, Foo f);
};

//+ operator, you can add 2 strings
std::string& operator + ( std::string str, Foo f);

This however is tedious work and must be tested thoroughly. Best of luck!

A: You can extend an interface without publically deriving from it.  This prevents the case of problematic polymorphic destruction (aka no virtual destructor):
#include <iostream>
#include <string>
using namespace std;

class MyClass
   : private std::string
{
public:
   MyClass(const char* in)
      : std::string(in)
   {}

   // expose any parts of the interface you need
   // as publically accessible
   using std::string::c_str;
   using std::string::operator+=;
};

int main()
{
   MyClass c("Hello World");

   cout << c.c_str() << "\n";

   c += "!";

   cout << c.c_str() << "\n";

   // Using private inheritance prevents casting, so
   // it's not possible (easily, that is) to get a
   // base class pointer

   //  MyClass* c2 = new MyClass("Doesn't work");
   // this next line will give a compile error
   //  std::string* pstr = static_cast<MyClass*>(c2);
   // delete c2;
}

A: Trying to sum-up all the discussions, it looks like you will never find a suitable dolution because ... your requirements are in cotraddiction.

*

*You want you class to behave as ats::string

*std::string behave as a value but

*a value does not "change" when accessed but (think to c = a+b: do you expect a and b to change their value ??) ...

*when accessing your "value" you want to change it.

If what I summed up collecting all the peaces (suggestion: edit your question otherwise all the answerer will risk to be lost) is correct you are in trouble with 3 & 4 (note the 3. derives from the concept of "assignment", and you can do noting to change it, while 4. comes from you directly)
Now, I can try to reverse-engineer your psychology (because you didn't provide good information about what your class represent and why you cannot "extend" a string) I can find
two possibility neither of which will fit all the above requirements.

*

*Store a string into your class and make your class to behave as a std::string.  There are threee ways to come to this point:
a. embed a string and make your class to decay to it:
essentially your class must contain
.
operator std::string&() { return my_string; } //will allow l-value assignments
operator const std::string&() const { return my_string; } //will allow r-value usage
const char* c_str() const { return my_string.c_str(); }

b. derive from std::string. In fact that's like having an anonymous my_string in it, which "decay" operations implicit. Not that different as above.
c. embed or privately derive, and rewrite the std::string interface delegating the std::string functions. It's just a long typing to get exactly the b. result. so what the f..k? (this last question is dedicated to all the ones that believe a. or b. will break encapsulation. c. will break it as well, it will only take longer!)

*

*Don't store a string, but just get it as a result from a calculation (the "lookup" you talk about, not clarifying what it is).

In this last case, what you need is a class that decay automatically into std::string as a value.
So you need, in your class
operator std::string() const { return your_lookup_here; }

note that const is necessary, but there is no need to modify your class inner state, since the resulting string is not stored.
But this last solution has a problem with const char*: since the string is temporary, until you don't assign it, its buffer is temporary as well (will be destroyed) so decaying into const char* to assign the pointer is clueless (the pointer will point to a dead buffer).
You can have a
const char* c_str() const { return std::string(*this).c_str(); } //will call the previous one

but you can use this only into expressions or a pass-through parameter in function calls (since the temporary will exist until the evaluating expression is fully evaluated), not in an assignment towards an l-value (like const char* p; p = myclassinstace.c_str(); )
In all of the above cases (all 1.) you also need:
 myclass() {}
 myclass(const std::string& s) :my_string(s) { ... }
 myclass(const char* s) :my_string(s) { ... }

or - in C++11, just
template<class ...Args>
myclass(Args&&... args) :my_string(std::forward<Args...>(args...)) {}

In case 2., instead of initialize the not existent my_sting, you should use the arguments to set what you will look up (we don't know what it is, since you did not tell us)
Hope in all these option you can find something useful.

A: You can add an operator const reference to string, as follows:
class C
{
public:
  // Implicit conversion to const reference to string (not advised)
  operator const std::string &() const
  {
    return s_;
  }

  // Explicit conversion to a const reference to string (much better)
  const std::string &AsString() const
  {
    return s_;
  }

private:
  std::string s_;
};

As you can see from the comments, it would be much better to add an explicit conversion function if you really need this behavior. You can read about why this is bad in the Programming in C++ Rules and Recommendations article.


text:
Q: Apple CarPlay entitlements missing I need your help. Apple has been accepted my request for Apple CarPlay development.
1. I inserted line com.apple.developer.playable-content into my file.entitlements:

*To my provision profile i added entitlement Apple CarPlay

*But when i tried to make archive from my project i have error:

What i am doing wrong? I use and Swift language and Objective-c

A: I found solution. You should disable automatically signing, and choose Provision profile with CarPlay entitlements. I suppose this answer can help for anyone.


text:
Q: Macro to copy variable number of rows with fixed columns I have searched high and low on the internet to find an answer to my macro problem-I don't think what I am trying to so is that difficult, but maybe it is!
In my dataset column K contains my data markers. What I want to do is find "22" in column K and find "23" is column K and copy all the rows of data in columns C to J that fall between the row numbers indicated by the markers contained in column K. The number of rows between markers 22 and 23 is different for each spreadsheet, which is where I am running into problems. I've tried to set the range for these variables but I am basically a macro novice and am not having much luck. Any help greatly appreciated.

A: Probably the easiest way would just find 22 & 23 and establish where the rows are located
Then you can create the range to copy with those known rows and columns.
Name a sheet "Copy to Sheet" for this example.
Sub Button1_Click()
    Dim Rws As Long, Rng As Range
    Dim c1 As String, c2 As String
    Dim FndC1 As Range, FndC2 As Range
    Dim c1C As Integer, c2C As Integer
    Dim ws As Worksheet
    Set ws = Sheets("Copy to Sheet")
    c1 = 22
    c2 = 23
    Rws = Cells(Rows.Count, "K").End(xlUp).Row
    Set Rng = Range(Cells(1, "K"), Cells(Rws, "K"))

    Set FndC1 = Rng.Find(what:=c1, lookat:=xlWhole)
    Set FndC2 = Rng.Find(what:=c2, lookat:=xlWhole)

    If Not FndC1 Is Nothing Then
        c1C = FndC1.Row
    Else: MsgBox c1 & " Not Found"
        Exit Sub
    End If
    If Not FndC2 Is Nothing Then
        c2C = FndC2.Row
    Else: MsgBox c2 & " Not Found"
        Exit Sub
    End If
    Range(Cells(c1C + 1, "C"), Cells(c2C - 1, "J")).Copy _
            ws.Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)

End Sub


text:
Q: Discord Bot w/ Discord.py skipping lines I tried today to make a python discord.py based bot for a bit of fun, and following some random tutorials and copying code it worked great, and I added a few new commands once I'd gotten the hang of it, but apparently randomly most of the commands stopped working, and for some reason now only the bottom most command actually functions in discord, any ideas why this could be?
Code:
import discord
from discord.ext import commands

description = 'Tutorial Bot'
bot_prefix = '!'

client = commands.Bot(description=description, command_prefix=bot_prefix)

list_of_strings = ['hello', 'hi']

@client.event
async def on_ready():
    print('Connected')

@client.event
async def on_message(message):
    if message.content.startswith('!what'):
        await client.send_message(message.channel, 'Huh?')

@client.event
async def on_message(message):
    if message.content in list_of_strings:
        await client.send_message(message.channel, 'Hey there')

client.run('*set to code before attempting*')

I had set the client.run to the newest code, but whenever I use the bottom list of strings command it works fine, but the !what section doesn't work. I tried reversing them and the same problem persisted, with only the bottom most one working regardless of which order they're in. Is there something obvious I'm probably missing here?

A: I'm no expert at Python but part of your issue might be the two function declarations being fully defined the same way.  I would imagine the second function is redefining the first.
@client.event
async def on_message(message):
    //Function 1 code
@client.event
async def on_message(message):
    //Function 2 code

Instead of using two move the conditional of the second into the first like so:
@client.event
async def on_message(message):
    if message.content.startswith('!what'):
        await client.send_message(message.channel, 'Huh?')

    elif message.content in list_of_strings:
        await client.send_message(message.channel, 'Hey there')

A: When you use the Client.event decorator, that's actually assigning the client.on_message attribute to be the coroutine you wrote.  client.on_message can't be two things at the same time, so the older one is discarded.
You have the right idea though: you should be splitting your commands into discrete units instead of keeping them in a single monolithic coroutine.  For this, you actually use the Bot.command() decorator.
import discord
from discord.ext import commands

description = 'Tutorial Bot'
bot_prefix = '!'

client = commands.Bot(description=description, command_prefix=bot_prefix)

list_of_strings = ['hello', 'hi']

@client.event
async def on_ready():
    print('Connected')

@client.command(pass_context=True)
async def what(ctx):
    await client.say('Huh?')

@client.event
async def on_message(message):
    if message.author == client.user:
        return  # We don't want our bot to respond to itself
    if message.content in list_of_strings:
        await client.send_message(message.channel, 'Hey there')
    await client.process_commands(message)  # Hand off to the command logic

client.run('*set to code before attempting*')


text:
Q: Is it possible to open tabs in existing window? Let's say there is a page behind a login system that I would like to run puppeteer for web automation and for simplicity, I don't want to launch a new browser and enter the login system with puppeteer. Instead, I want puppeteer to activate the tab where I've manually logged in to the system.
I found something like page.bringToFront() but it works for pages, not windows/browser.
This leads me to the question: Is it possible to open tabs in existing window with puppeteer?


text:
Q: How to throw a checked exception from a java thread? Hey, I'm writing a network application, in which I read packets of some custom binary format. And I'm starting a background thread to wait for incoming data. The problem is, that the compiler doesn't let me to put any code throwing (checked) exceptions into run(). It says:
run() in (...).Listener cannot implement run() in java.lang.Runnable; overridden method does not throw java.io.IOException
I want the exception to kill the thread, and let it be caught somewhere in the parent thread. Is this possible to achieve or do I have to handle every exception inside the thread?

A: What I do is to catch the exception in the thread and store it as a member variable of the Runnable.  This exception is then exposed via a getter on the Runnable.  I then scan all the threads from the parent to see if any had exceptions, and take the appropriate action.

A: If you really cannot do anything useful when the exception is raised you can wrap the checked exception in a RuntimeException.
try {
    // stuff
} catch (CheckedException yourCheckedException) {
    throw new RuntimeException("Something to explain what is happening", yourCheckedException);
}

A: To be able to send the exception to the parent thread, you can put your background thread in a Callable (it allows throwing also checked exceptions) which you then pass to the submit method of some Executor. The submit method will return a Future which you can then use to get the exception (its get method will throw an ExecutionException which contains the original exception).

A: Caveat: this may not meet your needs if you have to use the exception mechanism.
If I understand you correctly, you don't actually need the exception to be checked (you've accepted the answer suggesting an unchecked exception) so would a simple listener pattern be more appropriate?
The listener could live in the parent thread, and when you've caught the checked exception in the child thread, you could simply notify the listener.
This means that you have a way of exposing that this will happen (through public methods), and will be able to pass more information than an exception will allow. But it does mean there will be a coupling (albeit a loose one) between the parent and the child thread. It would depend in your specific situation whether this would have a benefit over wrapping the checked exception with an unchecked one.
Here's a simple example (some code borrowed from another answer):
public class ThingRunnable implements Runnable {
    private SomeListenerType listener;
    // assign listener somewhere

    public void run() {
        try {
            while(iHaveMorePackets()) {
                doStuffWithPacket();
            }
        } catch(Exception e) {
            listener.notifyThatDarnedExceptionHappened(...);
        }
    }
 }

The coupling comes from an object in the parent thread having to be of type SomeListenerType.

A: This answer is based on Esko Luontola one but it provides a working example.
Unlike the run() method of the Runnable interface the call() method of Callable allows to throw some exceptions. Here is an implementation example :
public class MyTask implements Callable<Integer> {

    private int numerator;
    private int denominator;

    public MyTask(int n, int d) {
        this.numerator = n;
        this.denominator = d;
    }

    @Override
    // The call method may throw an exception
    public Integer call() throws Exception {
        Thread.sleep(1000);
        if (denominator == 0) {
            throw new Exception("cannot devide by zero");
        } else {
            return numerator / denominator;
        }
    }

}

Executor provides a mechanism to run a Callable inside a thread and to handle any kind of exceptions :
public class Main {

    public static void main(String[] args) {

        // Build a task and an executor
        MyTask task = new MyTask(2, 0);
        ExecutorService threadExecutor = Executors.newSingleThreadExecutor();

        try {
            // Start task on another thread
            Future<Integer> futureResult = threadExecutor.submit(task);

            // While task is running you can do asynchronous operations
            System.out.println("Something that doesn't need the tasks result");

            // Now wait until the result is available
            int result = futureResult.get();
            System.out.println("The result is " + result);
        } catch (ExecutionException e) {
            // Handle the exception thrown by the child thread
            if (e.getMessage().contains("cannot devide by zero"))
                System.out.println("error in child thread caused by zero division");
        } catch (InterruptedException e) {
            // This exception is thrown if the child thread is interrupted.
            e.printStackTrace();
        }
    }
}

A: the thread can't throw the exception to any other thread (nor to the main thread). and you cannot make the inherited run() method throw any checked exceptions since you can only throw less than the inherited code, not more.

A: If your thread's code throw a RuntimeExpection, you doesn't need to add  run() throw Exception.
But use this solution only when appropriate because this can be a bad pratice:
http://java.sun.com/docs/books/tutorial/essential/exceptions/runtime.html
Any RuntimeException or unchecked Exception can help you.  Maybe you'll need to create your own RuntimeException

A: On the assumption that your code is in some kind of loop, you'd write:
public class ThingRunnable implements Runnable {
  public void run() {
    try {
      while(iHaveMorePackets()) {
        doStuffWithPacket()
      }
    } catch(Exception e) {
      System.out.println("Runnable terminating with exception" + e );
    }
  }
}

The exception will automatically break you out of your loop, and at the end of the run() method, the thread will stop.

A: Use this Runnable to create your Thread:
public abstract class TryRunner implements Runnable{
    protected abstract void tryToRun();
    protected void onException(Exception e){}

    @Override
    final public void run() {
        try{ tryToRun(); }catch(Exception e){ e.printStackTrace(); onException(e); }
    }
}

A: Wrapping your exception inside a RuntimeException seems to do the trick.
someMethod() throws IOException
{
    try
    {
        new Thread(() ->
        {
            try
            {
                throw new IOException("a checked exception thrown from within a running thread");
            }
            catch(IOException ex)
            {
                throw new RuntimeException("a wrapper exception", ex); // wrap the checked exception inside an unchecked exception and throw it
            }
        }).start();
    }
    catch(RuntimeException ex) // catch the wrapped exception sent from within the thread
    {
        if(ex.getCause() instanceof IOException)
            throw ex.getCause; // unwrap the checked exception using getCause method and use it however you need
        else
            throw ex;
    }
}


text:
Q: finding an explanation from munkres about quotient topology I am trying to learn quotient topology from the book of Munkres where he writes that
Let X be the closed Unit ball $\{x\times y : x^2+y^2 \le 1\}$ in $\mathbb{R}^2$, and let $X^*$ be the partition of $X$ consisting of all the one-point sets $\{x\times y\}$ for
which $x^2 + y^2 < 1$, along with the set $S^1 = \{x\times y : x^2 + y^2 = 1\}$.One can show that $X^*$ is
homeomorphic with the subspace of $\mathbb{R}^3$ called the unit 2-sphere, defined by
$S^2= \{(x,y,z) : x^2+y^2+z^2=1\}$
But I can not find the required function from $X^*$ to $S^2$ which is a homemorphism.Can someone help me please.Thanks for your help.

A: HINT: Call the point $\langle 0,0,-1\rangle$ the south pole of $S^2$, the point $\langle 0,0,1\rangle$ the north pole, and the circle $\{\langle x,y,0\rangle:x^2+y^2=1\}$ in the $xy$-plane the equator of $S^2$. The lines of latitude on $S^2$ are the intersections of $S^2$ with planes $z=k$ for $-1<k<1$.
Your map from $X^*$ to $S^2$ should take $\{\langle 0,0\rangle\}$ to the south pole. For $0<r<1$ it should take the points of $X^*$ corresponding to the circle $x^2+y^2=r^2$ to the line of latitude corresponding to the plane $z=2r-1$. And it should take the point $S^1$ to the north pole of $S^2$.
Added: This is quite easy to arrange if you work in polar coordinates in $X$ and cylindrical coordinates in $S^2$. I've really already told you what the map is: send the point of $X^*$ corresponding to $\langle r,\theta\rangle$ to the point of $S^2$ whose cylindrical coordinates are $\langle\rho,\theta,2r-1\rangle$, where $\rho$ is whatever is required in order for the point to be in $S^2$; since $\rho^2+z^2=1$ for any point $\langle\rho,\theta,z\rangle\in S^2$, this is easy to determine.


text:
Q: Aligning text side by side in different divs I'm new to web design and I'm making a website as a project for my friend. I've got two divs with different content in each div, one for the main content and one for news and other things which I want at the side.
I've sorted the content div out and thats fine its where I want it. But when I go to float the news div right it goes from under the content div (Inside the wrapper div still) to out side the wrapper div but to where I want it. (I know this because for now I've got a blue border round so I can make sure everything is inside where I want it to be.)
Heres my code and css:
<!DOCTYPE html>

<link rel="stylesheet" href="style/style.css" type="text/css">
<title>Bake Away</title>

Home

About

Responsibility

Working With Us

News

Contact Us

Welcome to the Bake Away Bakery, here you can find out about
all the wonderful things we bake. How you can place orders, who we
bake for, where we're based, apply for jobs and contact head office.

Latest news:

We've just started our new line of cakes that should
hit the shelves by Monday.
Read More

body{
margin:0;
padding:0;
width:100%;
background-color:#E6E6E6;
font-family:consolas;
font-size:16px;
font-weight:normal;
text-align:center;
}
img{
margin-top:5px;
margin-right:15px;
}
#wrapper{
width:1000px;
border:1px solid blue;
margin:3px;
margin-left:13px;
text-align:left;
}
#navBar{
color:white;
margin:2px;
margin-right:43px;
height:50px;
font-size:25px;
font-weight:bold;
float:center;
text-align:center;
}
#navBar ul{
list-style-type:none;
}
#navBar li{
display:inline;
}
#navBar a{
text-decoration:none;
background-color:#BDBDBD;
color:black;
padding:2px;
}
#navBar a:hover{
text-decoration:underline;
background-color:#FE2E2E;
color:white;
}
#images img{
margin-left:50px;
}
#content{
width:450px;
margin-left:7px;
margin-bottom:3px;
font-size:16px;
}
#news{
width:300px;
}

A: Well, you can add display: inline-block;, Simple as hell ;)

A: Add display: inline-block to the following css:
#navBar {
    color:white;
    margin:2px;
    margin-right:43px;
    height:50px;
    font-size:25px;
    font-weight:bold;
    float:center;      // there is nothing like this. Wrong text-align:center;
    display: inline-block;
}
#images img {
    margin-left:50px;
    display: inline-block;
}
#content {
    width:450px;
    margin-left:7px;
    margin-bottom:3px;
    font-size:16px;
    display: inline-block;
}
#news {
    width:300px;
    display: inline-block;
}

Check this JSFiddle

A: display:flex is how you do it.


text:
Q: Staggered infinite CSS animation I was wondering if it was possible to have a looped animation that staggers each time the animation completes one full loop?
.hex{
    animation: fio $animation-speed ease-in-out infinite;
    transform: scale(.9);
    opacity: 0;
    &.one{

    }

    &.two{
      animation-delay: $animation-speed * 1;
    }

    &.three{
      animation-delay: $animation-speed * 2;
    }
}

@keyframes fio{
  0% {
    opacity:0;
    transform:  scale(0.90);
  }
  50% {
    opacity:1;
    transform:  scale(1.00);
  }
  100% {
    opacity:0;
    transform:  scale(0.90);
  }
}

As you can see from the code, it is currently staggering the first time it goes through the animation, however after that it just fades all 3 elements in and out at the same time. Is it possible to get it to stagger after every loop?
If you need any more information please let me know.
Thanks!

A: You just need to calculate the whole animation duration with all the delays and set them accordingly like this:
.hex {
    animation: fio 1800ms ease-in-out infinite; /* This devided to three is the amount you want for the delay below */
    animation-delay: 3600ms; /* All animation delays in one + two + three and add animation duration above to this */
    transform: scale(.9);
    opacity: 0;
  &.one {
    animation-delay: 0ms;
    width: 50px;
    height: 50px;
    background-color: red;
  }

  &.two {
    animation-delay: 600ms;
    width: 50px;
    height: 50px;
    background-color: blue;
  }

  &.three {
    animation-delay: 1200ms;
    width: 50px;
    height: 50px;
    background-color: green;
  }
}

Fiddle: https://jsfiddle.net/2u43tc8z/2/


text:
Q: Mysql Import Error with Python 2.7 I have met a problem on mysqlclient 1.3.10 after installing libssl1.1
import MySQLdb
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/MySQLdb/__init__.py", line 19, in <module>
    import _mysql
ImportError: /usr/local/lib/python2.7/dist-packages/_mysql.so: undefined symbol: OPENSSL_add_all_algorithms_noconf

Reproduce steps:

*

*On a ubuntu 14.04 machine

*Python 2.7.6

*

*echo 'deb http://archive.mariadb.org/mariadb-10.0.29/repo/ubuntu/
  trusty main' > /etc/apt/sources.list.d/mariadb.list

*apt-get -f install --yes --allow-unauthenticated mariadb-server

*Login as root and show default databases successfully

*add-apt-repository ppa:ondrej/php

*apt-get update

*apt-get install
  libssl-dev(version:1.1.0f-2~ubuntu14.04.1+deb.sury.org+1)

*pip install mysqlclient

*python -c "import MySQLdb"

A: I found a workaround to skip this import error.

*

*apt-get install python-mysqldb. It will create a _mysql.so at
/usr/lib/python2.7/dist-packages/

*Pip install MySQL-python=1.2.3

*mv /usr/local/lib/python2.7/dist-packages/_mysql.so /home/

*cp /usr/lib/python2.7/dist-packages/_mysql.so
/usr/local/lib/python2.7/dist-packages/

*chmod a+x /usr/local/lib/python2.7/dist-packages/_mysql.so


text:
Q: Python find broken symlinks caused by Git I'm currently working on a script that is supposed to go through a cloned Git repo and remove any existing symlinks (broken or not) before recreating them for the user to ease with project initialization.
The solved problems:

*

*Finding symbolic links (broken or unbroken) in Python is very well documented.

*GitHub/GitLab breaking symlinks upon downloading/cloning/updating repositories is also very well documented as is how to fix this problem. Tl;dr: Git will download symlinks within the repo as plain text files (with no extension) containing only the symlink path if certain config flags are not set properly.

The unsolved problem:
My problem is that developers may download this repo without realizing the issues with Git, and end up with the symbolic links "checked out as small plain files that contain the link text" which is completely undetectable (as far as I can tell) when parsing the cloned files/directories (via existing base libraries). Running os.stat() on one of these broken symlink files returns information as though it were a normal text file:
os.stat_result(st_mode=33206, st_ino=14073748835637675, st_dev=2149440935, st_nlink=1, st_uid=0, st_gid=0, st_size=42, st_atime=1671662717, st_mtime=1671662699, st_ctime=1671662699)

The st_mode information only indicates that it is a normal text file- 100666 (the first 3 digits are the file type and the last 3 are the UNIX-style permissions). It should show up as 120000.
The os.path.islink() function only ever returns False.
THE CONFUSING PART is that when I run git ls-files -s ./microservices/service/symlink_file it gives 1200000 as the mode bits which, according to the documentation, indicates that  this file is a symlink. However I cannot figure out how to see this information from within Python.
I've tried a bunch of things to try and find and delete existing symlinks. Here's the base method that just finds symlink directories and then deletes them:
def clearsymlinks(cwd: str = ""):
    """
    Crawls starting from root directory and deletes all symlinks
    within the directory tree.
    """
    if not cwd:
        cwd = os.getcwd()

    print(f"Clearing symlinks - starting from {cwd}")
    # Create a queue
    cwd_dirs: list[str] = [cwd]
    while len(cwd_dirs) > 0:
        processing_dir: str = cwd_dirs.pop()
        # print(f"Processing {processing_dir}")  # Only when debugging - else it's too much output spam
        for child_dir in os.listdir(processing_dir):
            child_dir_path = os.path.join(processing_dir, child_dir)

            # check if current item is a directory
            if not os.path.isdir(child_dir_path):
                if os.path.islink(child_dir_path):
                    print(f"-- Found symbolic link file {child_dir_path} - removing.\n")
                    os.remove(child_dir_path)

                # skip the dir checking
                continue

            # Check if the child dir is a symlink
            if os.path.islink(child_dir_path):
                print(f"-- Found symlink directory {child_dir_path} - removing.")
                os.remove(child_dir_path)
            else:
                # Add the child dir to the queue
                cwd_dirs.append(child_dir_path)

After deleting symlinks I run os.symlink(symlink_src, symlink_dst) and generally run into the following error:
Traceback (most recent call last):
  File "C:\Users\me\my_repo\remakesymlinks.py", line 123, in main
    os.symlink(symlink_src, symlink_dst)
FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'C:\\Users\\me\\my_repo\\SharedPy' -> 'C:\\Users\\me\\my_repo\\microservices\\service\\symlink_file'

A workaround to specifically this error (inside the create symlink method) is:
try:
    os.symlink(symlink_src, symlink_dst)
except FileExistsError:
    os.remove(symlink_dst)
    os.symlink(symlink_src, symlink_dst)

But this is not ideal because it doesn't prevent a huge list of defunct/broken symlinks from piling up in the directory. I should be able to find any symlinks (working, broken, non-existent, etc.) and then delete them.
I have a list of the symlinks that should be created by my script, but extracting the list of targets from this list is also a workaround that also causes a 'symlink-leak'. Below is how I'm currently finding the broken symlink purely for testing purposes.
if not os.path.isdir(child_dir_path):
    if os.path.basename(child_dir_path) in [s.symlink_install_to for s in dirs_to_process]:
        print(f"-- Found symlink file {child_dir_path} - removing.")
        os.remove(child_dir_path)

    # skip the dir checking
    continue

A rudimentary solution where I filter for only 'text/plain' files with exactly 1 line (since checking anything else is pointless) and trying to determine whether that single line is just a file path (this seems excessive though):
# Check if Git downloaded the symlink as a plain text file (undetectable broken symlink)
if not os.path.isdir(child_dir_path):
    try:
        if magic.Magic(mime = True, uncompress = True).from_file(child_dir_path) == 'text/plain':
            with open(child_dir_path, 'r') as file:
                for i, line in enumerate(file):
                    if i >= 1:
                        raise StopIteration
                else:
                    # this function is directly copied from https://stackoverflow.com/a/34102855/8705841
                    if is_path_exists_or_creatable(line):
                        print(f"-- Found broken Git link file '{child_dir_path}' - removing.")
                        print(f"\tContents: \"{line}\"")
                        # os.remove(child_dir_path)
                        raise StopIteration
    except (StopIteration, UnicodeDecodeError, magic.MagicException):
        file.close()
        continue

Clearly this solution would require a lot of refactoring (9 indents is pretty ridiculous) if it's the only viable option. Problem with this solution (currently) is that it also tries to delete any single-line files with a string that does not break pathname requirements- i.e. import _virtualenv, some random test string, project-name. Filtering out those files with spaces, or files without slashes, could potentially work but this still feels like chasing edge cases instead of solving the actual problem.
I could potentially rewrite this script in Bash wherein I could, in addition to existing symlink search/destroy code, parse the results from git ls-files -s ... and then delete any files with the 120000 tag. But is this method feasible and/or reliable? There should be a way to do this from within Python since Bash isn't going to run on every OS.

Note: file names have been redacted/changed after copy-paste for privacy, they shouldn't matter anyways since they are generated dynamically by the path searching functions


text:
Q: how to add custom scroll bar for textbox and listbox in c# winforms Can some explain thoroughly or share your source code on how to change textbox / listbox scroll bar to custom scroll bar on c# winforms.
Cause textbox and listbox doesnt have a scroll attribute like on panel. Thanks! Cant find a source code here to study, all i get is locating the scroll position using the GetScrollInfo API. I want to learn how set values or adapt my scroll bar to the default listbox and textbox. Thanks!


text:
Q: Can't Open ASP.Net Beta 4 Solution after Upgrading to ASP.Net RC1 I have a solution that was built using ASP.Net Beta 4.  After upgrading to ASP.Net RC1, I am unable to open the solution in Visual Studio 2015 Update 1.
In the Solution Explorer, it says

< ProjectName > (Incompatible)

When I expand it, it says

This project is incompatible with the current edition of Visual Studio

When I opened the project, it created a "Migration Report" and the migration report says

src\< ProjectName >\< ProjectName >.xproj: The application which this project type is based on was not found. Please try this link for further information: http://go.microsoft.com/fwlink/?LinkId=628321&projecttype=8BB2217D-0F2D-49D1-97BC-3654ED321F3B

The link provided talks about using Visual Studio 2013 to open projects that were created in Visual Studio 2010 or 2012, which is completely not helpful.
Any ideas? What do I need to do in order to open this Solution?
Thanks!

A: I used Visual Studio Code to follow Shawn Wildermuth's posts on upgrading from one version to another.
http://wildermuth.com/2015/7/22/Upgrading_ASP_NET_5_Beta4_to_Beta5
http://wildermuth.com/2015/10/20/Upgrading_from_ASP_NET_5_Beta_7_to_Beta_8
http://wildermuth.com/2015/11/18/Upgrading_ASP_NET_5_Beta_8_to_RC1
After that it build build use command line tools but I still couldn't open it in Visual Studio 2015.
When I initially installed ASP.Net RC1 I used the instructions to install it via command line.
https://docs.asp.net/en/latest/getting-started/installing-on-windows.html
I reinstalled it but this time I used the "Install ASP.NET 5 with Visual Studio" instructions.
After doing that everything worked correctly. Hopefully this will help someone else.
Thanks!


text:
Q: Integrate two types of Gregorian and solar (shamsi,jalali) calendar with each other in calendar view i just wondering if we can integrate two types of calendar in android(like solar and Gregorian) with each other and show them in one calendar view
is it possible even?
its a example of what i am saying:

A: for anyone who has this problem i solved it by making a custom calendar view with Grid Layout and create two calendar class by help of icu4j library(on for Gregorian Calendar and one for Persian Calendar and set them on my view)
lib: http://site.icu-project.org/download/59


text:
Q: Unexpected token error when running gulp on react application I have this React application:
var React = require('react');
var ReactDOM = require('react-dom');
var Application = require('./components/Application.react');

ReactDOM.render(<Application />, document.getElementById('react-application'));

and when I run sudo gulp, I get this error:
events.js:141
      throw er; // Unhandled 'error' event
      ^

SyntaxError: /home/react/snapterest/source/app.js: Unexpected token (5:16)
  3 | var Application = require('./components/Application.react');
  4 |
> 5 | ReactDOM.render(<Application />, document.getElementById('react-application'));
    |                 ^
    at Parser.pp.raise (/home/react/snapterest/node_modules/babylon/lib/parser/location.js:24:13)
    at Parser.pp.unexpected (/home/react/snapterest/node_modules/babylon/lib/parser/util.js:91:8)
    at Parser.pp.parseExprAtom (/home/react/snapterest/node_modules/babylon/lib/parser/expression.js:507:12)
    at Parser.pp.parseExprSubscripts (/home/react/snapterest/node_modules/babylon/lib/parser/expression.js:260:19)
    at Parser.pp.parseMaybeUnary (/home/react/snapterest/node_modules/babylon/lib/parser/expression.js:240:19)
    at Parser.pp.parseExprOps (/home/react/snapterest/node_modules/babylon/lib/parser/expression.js:171:19)
    at Parser.pp.parseMaybeConditional (/home/react/snapterest/node_modules/babylon/lib/parser/expression.js:153:19)
    at Parser.pp.parseMaybeAssign (/home/react/snapterest/node_modules/babylon/lib/parser/expression.js:120:19)
    at Parser.pp.parseExprListItem (/home/react/snapterest/node_modules/babylon/lib/parser/expression.js:966:16)
    at Parser.pp.parseCallExpressionArguments (/home/react/snapterest/node_modules/babylon/lib/parser/expression.js:336:20)

Can anyone help decypher what this error is trying to tell me?
Edit: The contents of my gulp.js file are:
var gulp = require('gulp');
var browserify = require('browserify');
var babelify = require('babelify');
var source = require('vinyl-source-stream');

gulp.task('default', function() {
    return  browserify('./source/app.js')
        .transform(babelify)
        .bundle()
        .pipe(source('snapterest.js'))
        .pipe(gulp.dest('./build'));

});

A: You need some transform for jsx. I don't know the command line way but here is something.
package.json

{
  "name": "ReactPatterns.14-BasicStarter",
  "version": "1.0.0",
  "description": "A collection of simple react projects providing reusable components, startup and test examples.",
  "license": "MIT",
  "author": {
    "name": "Janaka Stevens",
    "email": "jmstevens@calitek.com"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/calitek/ReactPatterns.git"
  },
  "scripts": { "start": "node js/server.js" },
  "dependencies": {
    "express": "latest",
    "react": "^0.14",
    "react-dom": "^0.14",
    "serve-favicon": "latest"
  },
  "devDependencies": {
    "babelify": "latest",
    "babel-preset-es2015": "latest",
    "babel-preset-react": "latest",
    "babel-preset-stage-0": "latest",
    "browserify": "latest",
    "gulp": "latest",
    "gulp-concat": "latest",
    "gulp-minify-css": "latest",
    "vinyl-source-stream": "latest"
  }
}

gulpfile.js

'use strict';

let gulp = require('gulp');
let concat = require('gulp-concat');
let minifyCSS = require('gulp-minify-css');
let browserify = require('browserify');
let vsource = require("vinyl-source-stream");
let babel = require('babelify');

let source = {
  appjs: './ui-src/app.js',
  js: ['./ui-src/**/*.js'],
  appcss: ['./ui-src/css/*.css'],
  apphtml: ['./ui-src/**/*.html'],
  appimg: ['./ui-src/img/*']
};

gulp.task('appjs', function(){
  browserify({ debug: true })
    .transform(babel, {presets:["es2015", "react", "stage-0"]})
    .require(source.appjs, { entry: true })
    .bundle()
    .pipe(vsource('app.min.js'))
    .pipe(gulp.dest('./ui-dist'));
});

gulp.task('appcss', function () {
  gulp.src(source.appcss)
    .pipe(concat('app.min.css'))
    .pipe(minifyCSS())
    .pipe(gulp.dest('./ui-dist'))
});

gulp.task('apphtml', function() {
  gulp.src(source.apphtml)
    .pipe(gulp.dest('./ui-dist'));
  gulp.src(source.appimg, {base: 'ui-src'})
    .pipe(gulp.dest('./ui-dist'));
});

gulp.task('watch', function() {
  gulp.watch(source.appcss, ['appcss']);
  gulp.watch(source.apphtml, ['apphtml']);
  gulp.watch(source.js, ['appjs']);
});

gulp.task('default', ['appjs', 'appcss', 'apphtml', 'watch']);

gulp.task('nw', ['appjs', 'appcss', 'apphtml']);


text:
Q: How to set the default UITableViewCell height? I am using variable heights for my UITableViewCells. This works fine normally however
I am finding that whatever the very last cell's height is, that becomes the height for all of the blank cells below it.
Is there a way to set a default height for the blank cells that appear below the last cell?
Thanks.

A: if you are using switch statement then set the default height for empty cells in default case of switch. Like so
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    int rowHeight = 40;
    switch (indexPath.row) {
        case 0:
            rowHeight = 80;
            break;
        case 1:
            rowHeight = 300;
            break;
        default:
            rowHeight = <your default value>;
            break;
    }

    return rowHeight;
}


text:
Q: Implement zoom with camera2 api Hello I am new to android. I am working on app which uses camera2 api and I am trying to implement Zoom. I figured out a method but there is no affect on the zoom while testing the camera app on my android phone (means, there is no zoom when I pinch to zoom). Please tell me what am I missing or anything that I am not doing correctly. thank you.
I am implementing the following 2 functions to implement the camera zoom.
public boolean onTouchEvent(MotionEvent event) {
        try {
            CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
            CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
            float maxZoom = (characteristics.get(CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM))*10;

            Rect m = characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE);
            int action = event.getAction();
            float current_finger_spacing;

            if (event.getPointerCount() > 1) {
                // Multi touch logic
                current_finger_spacing = getFingerSpacing(event);

                if(finger_spacing != 0){
                    if(current_finger_spacing > finger_spacing && maxZoom > zoom_level){
                        zoom_level++;

                    }
                    else if (current_finger_spacing < finger_spacing && zoom_level > 1){
                        zoom_level--;

                    }
                    int minW = (int) (m.width() / maxZoom);
                    int minH = (int) (m.height() / maxZoom);
                    int difW = m.width() - minW;
                    int difH = m.height() - minH;
                    int cropW = difW /100 *(int)zoom_level;
                    int cropH = difH /100 *(int)zoom_level;
                    cropW -= cropW & 3;
                    cropH -= cropH & 3;
                    Rect zoom = new Rect(cropW, cropH, m.width() - cropW, m.height() - cropH);
                    captureRequestBuilder.set(CaptureRequest.SCALER_CROP_REGION, zoom);
                }
                finger_spacing = current_finger_spacing;
            }
            else{
                if (action == MotionEvent.ACTION_UP) {
                    //single touch logic
                }
            }

            try {
                mCameraCaptureSession.setRepeatingRequest(captureRequestBuilder.build(), captureCallbackListener,
                        null);
            }
            catch (CameraAccessException e) {
                e.printStackTrace();
            }
            catch (NullPointerException ex)
            {
                ex.printStackTrace();
            }
        }
        catch (CameraAccessException e)
        {
            throw new RuntimeException("can not access camera.", e);
        }

        return true;
    }

    private float getFingerSpacing(MotionEvent event) {
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);
        return (float)Math.sqrt(x * x + y * y);
    }


text:
Q: What is the best way to access Cucumber's instance variables form nested classes inside steps? It's a simple question. I have Cucumber steps, for example:
Given /We have the test environment/ do
  @user = # Create User model instance
  @post = # Create Post model instance
  # etc...
end

In the Then step I'm using my own classes, they simplify the process of testing:
Then /all should be fine/ do
  # MyValidatorClass has been defined somwhere in features/support dir
  validator = MyValidatorClass.new
  validator.valid?.should be_true
end

Inside the MyValidatorClass instance, I deal with the above instance variables @user, @post, etc.
What is the best and simpliest way to access Cucumber variables from MyValidatorClass class instance?
class MyValidatorClass
  def valid?
    @post
    @user
  end
end

Now I have manually passed all arguments to MyValidatorClass instance:
validator = MyValidatorClass.new @user, @post

But I think this purpose is bad. I need something more transparent, because we are using Ruby, that why!
What is the best way to do this?

A: Instance variables that are defined in World scope are available only inside World. Step definitions belong to World. You should put MyValdatorClass inside World by World{MyValdatorClass.new}. After that instance variables defined previously in this scenario's stepdefs will become available in this class and other step definitions in the same scenario.
Some other thoughts that refer to your question:

If you have a step Given we have the test environment, then:

*

*you will duplicate it in all feaures

*your features are becoming longer and less pleasant to read because of those unnecessary for current feature's reading details

*setting up not needed environment details will take some time

Easier way to create instances is to add helper method that will create them for you:
module InstanceCreator
  def user
    @user ||= # Create user instance in World
  end
  #etc
end
World(InstanceCreator)

Then you just use this user when you need it (without any @ or @@).
If you need something else besides creating instances, use hooks
Your scenarios should be natural reading. You shouldn't spoil them with steps that you need just to get your automation layer work.

It's better to have regex starting from ^ and ending with $. Without it step definition becomes too flexible. Your first step definition will match also Given We have the test environment with some specifics.

A: I have found the posible soultion. You just should migrate from instance variables to class variables:
Given /We have the test environment/ do
  @@user = # Create User model instance
  @@post = # Create Post model instance
  # etc...
end

Then /all should be fine/ do
  # MyValidatorClass has been defined somwhere in features/support dir
  validator = MyValidatorClass.new
  validator.valid?.should be_true
end

...

class MyValidatorClass
  def valid?
    @@post
    @@user
  end
end


text:
Q: Problem with implementing \ifcsname ... \endcsname into a custom macro I apologise in advance if this is a bad question but I have been trying to read up macros in Latex with the TeX-book but I just cannot work out why this doesn't work.
So I have a 'working' macro (pasted below) which lets you wrap \ans{<answer>} around answers in a tutorial sheet to save the answer to an 'array' of sorts; the answers in the array are then used to create an answer sheet with the command \s.
'Working' macro code:
        \titleformat{\section}{\titlerule\vspace{1mm}\normalfont\secfnt\bfseries}{\thesection}{2em}{}
        \renewcommand{\thesection}{{\noindent\hrulefill}\\ Problem \arabic{section}.}
    %%%%%%%Each problem label generated with \section{}

    \newcounter{Questionpart}[section]
    \newcommand{\Qpart}{(\stepcounter{Questionpart}\alph{Questionpart})
        \global\expandafter\def\csname Prob\the\value{section}\endcsname{\the\value{Questionpart}}
        }
    %%%An attempt to count the parts in each problem but \csname Prob<number> \endcsname doesnt work with \foreach \y in {1,...,\csname Prob<number> \endcsname}
    %%%%%Parts a),b).....e), generated by \Qpart.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%Command of interest%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    \long\def\ans#1{
            \expandafter\global\expandafter\def\csname ans\the\value{section}\the\value{Questionpart} \endcsname{\item\quad#1}
            #1
            }%An 'array' structure which names each element as ans<problem_number><problem_part_in_numbers>

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    \newcommand{\p}[1]{
            \csname ans#1 \endcsname
    }%lets \s call the elements in the 'array'

    \newcommand{\s}{\newpage
            \begin{center}
                \Large\textbf{Solutions}
            \end{center}
            \foreach \x in {1,...,\value{section}}
            {
               \textbf{Problem \x}\par
               \begin{enumerate}[label=(\alph*)]
               \foreach \y in {1,...,10}
    %couln't count the parts in a problem so set to 10 as a general size.
               {\p{\x\y}\par
               }
               \end{enumerate}
         }
    }

ISSUE:
I would like to implement a concatenate feature to the \ans{} command so that each \ans{} in the same Problem part will add together to create a full answer.
(sometimes it may be a 'prove that' question and the key points are spread out)
I tried something like this (which didn't work):
\makeatletter
    \long\def\ans#1{% if \DP@#1 is defined append to it otherwise create it
      \if\csname ans\the\value{section}\endcsname
        \edef\DP@tmp{\csname ans\the\value{section}\endcsname,#1}%
      \else
        \edef\DP@tmp{#1}%
      \fi
      \global\expandafter\let\csname ans\the\value{section}\endcsname\DP@tmp
    #1
    }
    \makeatother

I will greatly appreciate help or any pointers.


text:
Q: Python ZeroDivisionError in Open Uniform B-Spline Curve So I was working with implementing B-spline curves in python (and I am aware there are existing libraries, but I wanted to do it myself) and it worked well for non-open uniform B-spline curves as shown here:

The graph on the right showing the Basis Function (Cox de Boor's recursion formula) calculations correspond really well with what is shown in this video with the only difference being the number of control points. (https://www.youtube.com/watch?v=qhQrRCJ-mVg&t=2136):

As soon as I try to make this an open uniform B-Spline curve. I expect a graph like this (https://www.youtube.com/watch?v=qhQrRCJ-mVg&t=2501):

But instead, I get a ZeroDivisionError:
a = ((t - knotVector[i]) / (knotVector[i + j] - knotVector[i]) * CoxDeBoorRecursion(i, j - 1, t, knotVector))
ZeroDivisionError: float division by zero

where the knot vector is defined as [0, 0, 0, 1, 2, 3, 3, 3] like shown in the video at https://www.youtube.com/watch?v=qhQrRCJ-mVg&t=2460.
Here is my code:
def UniformBSpline(t, controlPoints, open=False):
    sumX, sumY = 0, 0
    degree = 2
    knotVector = [x for x in range(len(controlPoints) + 2 + degree)]

    if open:
        knotVector = knotVector[0:len(controlPoints)]
        for _ in range(degree):
            knotVector.insert(0, knotVector[0])
            knotVector.insert(-1, knotVector[-1])

    for i in range(len(controlPoints)):
        sumX += CoxDeBoorRecursion(i, degree, t, knotVector) * controlPoints[i].x
        sumY += CoxDeBoorRecursion(i, degree, t, knotVector) * controlPoints[i].y

    return sumX, sumY

def CoxDeBoorRecursion(i, j, t, knotVector):
    if j == 0:
        return 1 if knotVector[i] <= t < knotVector[i+1] else 0

    a = ((t - knotVector[i]) / (knotVector[i + j] - knotVector[i]) * CoxDeBoorRecursion(i, j - 1, t, knotVector))
    b = (((knotVector[i + j + 1] - t)/(knotVector[i + j + 1] - knotVector[i + 1])) * CoxDeBoorRecursion(i + 1, j - 1, t, knotVector))
    return a + b

This seems to be an issue in the function I am using which is defined as:

How can I fix this? and is this perhaps a better question for the Math StackExchange?

A: There are two errors in your code:
The knot vector for uniform closed B-Splines is supposed to count up to the number of segments, not the number of control points. The number of segments is the number of control points minus the degree. I.e., if you have three points for a degree-2 spline (i.e., a simple Bezier curve), you get a single segment. For each additional point, you get one more segment. Hence, the knot vector has to be:
if open:
    knotVector = [x for x in range(len(controlPoints) - degree + 1)]
    for _ in range(degree):
        knotVector.insert(0, knotVector[0])
        knotVector.insert(-1, knotVector[-1])

For four control points, this will give you
[0, 0, 0, 1, 2, 2, 2]

You have a similar problem for the closed case. That's why your spline has that corner at (0, 0). Haven't checked exactly, though.
The second problem: The weights can have a divisor of zero if knots repeat. If this is the case, just ignore that part of the weight:
d1 = (knotVector[i + j] - knotVector[i])
a = ((t - knotVector[i]) / d1 * CoxDeBoorRecursion(i, j - 1, t, knotVector)) if d1 > 0 else 0

d2 = (knotVector[i + j + 1] - knotVector[i + 1])
b = (((knotVector[i + j + 1] - t)/d2) * CoxDeBoorRecursion(i + 1, j - 1, t, knotVector)) if d2 > 0 else 0

You can also extract that part into a separate function like the Wikipedia article does (function ω).


text:
Q: How to check some elements of a matrix and generate a set of matrices accordingly? I'm trying to check elements of a 2D array (matrix) and generate a number of matrices (of equal size) depending on some conditions as below:
Consider my matrix:
x = [[1, 0, 2],[7, 0, 7],[1, 1, 1]]

I need to check for the (2) and generate two matrices where the position of (2) will be replaced by 0 and 1 respectively. I also need to check for the 7's and generate 3 combinations of the matrix with values of 7 being (0,1),(1,0),(1,1) respectively. This mean the total number of matrices generated are 6 as follows:
[[1, 0, 0],[0, 0, 1],[1, 1, 1]]
[[1, 0, 0],[1, 0, 0],[1, 1, 1]]
[[1, 0, 0],[1, 0, 1],[1, 1, 1]]
[[1, 0, 1],[0, 0, 1],[1, 1, 1]]
[[1, 0, 1],[1, 0, 0],[1, 1, 1]]
[[1, 0, 1],[1, 0, 1],[1, 1, 1]]

There can be more than 1 (2), and the position of 7's can be vertical or hirizental.
I've tried a naiive way just looping through x looking for 2's and appending:
for i in range(len(x)):
  for j in range(len(x[0])):
    if x[i][j] == 2:
      inter[i][j] = 0
      test.append(inter)
      inter2[i][j] = 1
      test.append(inter2)

But that only works if I have the value of 2 only. I've also tried converting to numpy array and using where() to find the indexes of 2's and 7's, but then don't know how that can be used to generate the required outcome. Any thoughts?

A: The conditions described are very vague. If I understand correctly, you want this:
sevens = [[0,1],[1,0],[1,1]]
twos = [0,1]

for i in twos:
    for j in sevens:
        m = x.copy()
        m[m==2] = i
        m[m==7] = j
        print(m)

output:
[[1 0 0]
 [0 0 1]
 [1 1 1]]
[[1 0 0]
 [1 0 0]
 [1 1 1]]
[[1 0 0]
 [1 0 1]
 [1 1 1]]
[[1 0 1]
 [0 0 1]
 [1 1 1]]
[[1 0 1]
 [1 0 0]
 [1 1 1]]
[[1 0 1]
 [1 0 1]
 [1 1 1]]

UPDATE: per OP's comment for (2)s multiplicities:
x = np.array([[2, 0, 2],[7, 0, 7],[1, 1, 1]])
sevens = [[0,1],[1,0],[1,1]]
v = (x==2).sum()*([0,1],)
twos = np.array(np.meshgrid(*v)).T.reshape(-1,2)

for i in twos:
    for j in sevens:
        m = x.copy()
        m[m==2] = i
        m[m==7] = j
        print(m)

output:
[[0 0 0]
 [0 0 1]
 [1 1 1]]
[[0 0 0]
 [1 0 0]
 [1 1 1]]
[[0 0 0]
 [1 0 1]
 [1 1 1]]
[[0 0 1]
 [0 0 1]
 [1 1 1]]
[[0 0 1]
 [1 0 0]
 [1 1 1]]
[[0 0 1]
 [1 0 1]
 [1 1 1]]
[[1 0 0]
 [0 0 1]
 [1 1 1]]
[[1 0 0]
 [1 0 0]
 [1 1 1]]
[[1 0 0]
 [1 0 1]
 [1 1 1]]
[[1 0 1]
 [0 0 1]
 [1 1 1]]
[[1 0 1]
 [1 0 0]
 [1 1 1]]
[[1 0 1]
 [1 0 1]
 [1 1 1]]


text:
Q: Auto line break in cell every X characters I have a huge cell containing text which is without line breaks. Once I need to copy&paste it I use online auto line breaker tool which makes new break lines every X characters.
I'm looking for solution how to make this work in Excel.

A: This may not be practical, depending upon how often required and how many cells are to be split by line at a time, but most things possible with VBA are also possible without, even if impractical.
Assuming your text is in B1 and the requisite character limit in A1. In C1:
=MID($B1,1+$A1*(COLUMN()-3),$A1)

copied across to D1. In C2 =C1, in D2:
=C2&CHAR(10)&D1

then copy D1:D2 across until first blank shows up in Row1 (assumes you won't have a multitude of consecutive space 'characters').
The result should be below the last non-blank cell in Row1.


text:
Q: Select rows from dataframe by checking the value of other column I have a dataframe like below:
+--------+----------------+----+----------+
|role_num|   email_address|role|counters  |
+--------+----------------+----+----------+
|     110| EMAIL2@TEST.COM|null|         2|
|     110| EMAIL2@TEST.COM| P  |         2|
|     114|EMAIL10@TEST.COM| A  |         2|
|     114|EMAIL10@TEST.COM|null|         2|
+--------+----------------+----+----------+

From this dataframe, my output should be like below:
+--------+----------------+----+----------+
|role_num|   email_address|role|counters  |
+--------+----------------+----+----------+
|     110| EMAIL2@TEST.COM| P  |         2|
|     114|EMAIL10@TEST.COM| A  |         2|
+--------+----------------+----+----------+

The condition is whenever the duplicates count is 2 then I should select the role "P" but if that role is not there then I need to select "A".
I have tried like below. But this doesn't seem working.
import sc.implicits._

val targetDF = Seq(
      ("110", "EMAIL2@TEST.COM", "", "2"),
      ("110", "EMAIL2@TEST.COM", "PAH", "2"),
      ("114", "EMAIL10@TEST.COM", "AAH", "2"),
      ("114", "EMAIL10@TEST.COM", "", "2")
      )
      .toDF(
        "role_num",
        "email_address",
        "role",
        "counters")

targetDF.where(
        (col("counters") > 1 )
           || ?)

Can you help ?

A: This solution will work with your current roles:
targetDF
      .withColumn("priority", rank().over(Window.partitionBy("acct_num").orderBy(desc_nulls_last("role"))))
      .where(col("priority") === 1)
      .drop("priority")


text:
Q: Fullcalendar Year View in Angular 8 How to get a view of all month in a single page in Fullcalendar.
I have installed the fullcalendar through npm and using the dayGridPlugin to get the output.
It's rendering a calendar in monthly view, however no where I found how to get the yearly view


text:
Q: Poor performance with a large topn value for most_similar_approx I have an API that returns most_similar_approx from a magnitude model  . The model is built from native Word2Vec format with 50 dimensions and 50 trees. The magnitude model is close to 350MB, with approximately 350000 tokens.
Load testing this API I observed that the performance deteriorates as I increase the topn value for most_similar_approx, I need a high number of similar tokens for downstream activities,
with topn=150 I get a throughput of 500 transactions per second on the API,
while gradually reducing it I get 800 transactions with topn=50 and and ~1300 with topn=10.
The server instance is not under any memory/cpu load, am using a c5.xlarge AWS EC2 instance.
Is there anyway I can tune the model to improve the performance for a high topn value?
My aim is to obtain most_similar tokens from word embeddings, and pymagnitude was the most recommended option I found, are there any similar high performing alternatives.


text:
Q: When you change the value in the dialog box, the value in the main table changes Project on Angularjs.
There is a table with data
<mat-card>
  <mat-card-content class="employee-table__content">

      <ng-container matColumnDef="name" >
         Name
         {{element.name}}
      </ng-container>

  </mat-card-content>
</mat-card>

from which I call the data editing dialog box
openEditDialog(quizDto: QuizDto) {
  const dialogRef = this.dialog.open(QuizEditDialogComponent, {
    data: [quizDto,
      'edit'
    ],
    width: '400px'
  });
}

template
<mat-dialog-content>

{{dialogTitle}}

  <mat-form-field appearance="standard">
    <mat-label>Name</mat-label>
    <input
      matInput maxlength="100"
      [(ngModel)]="quizDto.name"
      (keydown.enter)="confirm()"
    />
  </mat-form-field>
</mat-dialog-content>

The problem is as follows. In the dialog box, I change the value of the "name" field. At the same time, the same field changes in the main table. It seems like everything is logical, a reference to one object, the connection is bidirectional. But this is wrong. How do I break this connection?
I can't think of anything smarter than adding another variable
openEditDialog(quizDto: QuizDto) {
  const curQuiz = new QuizDto(quizDto.id, quizDto.name);
  const dialogRef = this.dialog.open(QuizEditDialogComponent, {
    data: [curQuiz ,
      'edit'
    ],
    width: '400px'
  });
}

But this code doesn't look very good. Maybe there is a more beautiful solution?

A: As you note, if you are using two way binding with a shared object, any change to that object (by anyone) will immediately be reflected in the UI. You'll need to have a copy of the original object one way or another to allow the dialog to edit it without having changes reflected immediately in the UI.
Your proposed solution won't do you any good, because even though curQuiz and quizDto are different variables, they are references to the same object:
openEditDialog(quizDto: QuizDto) {
  const curQuiz = quizDto; // oops! these still refer to same object
  const dialogRef = this.dialog.open(QuizEditDialogComponent, {
    data: [curQuiz ,
      'edit'
    ],
    width: '400px'
  });
}

I would suggest providing the dialog with a copy of the object data it needs to do its job, and then having it return the updated data to you when it is closed. You can then update the original object, and therefore the UI.
openEditDialog(quizDto: QuizDto) {
  const props = {...quizDto}; // copy props (adjust as necessary)
  const dialogRef = this.dialog.open(QuizEditDialogComponent, {
    data: [props,'edit']
  });
  dialogRef.afterClosed().subscribe(result => {
    if (result) {
      quizDto.name = result.name;
      // ...
    }
}

Your dialog would then look something like:
export class QuizEditDialogComponent {
  // ...
  close() {
    this.dialogRef.close({ name: 'updated name here' );
  }

A: you can use one way binding.
[ngModel]=quizDto.name


text:
Q: kernel programming - Makefile error i am not getting output for this code. What changes have to make in my Makefile??
code:
#define MODULE
#define LINUX
#define __KERNEL__

#include<linux/module.h>
#include<linux/kernel.h>
#include<linux/init.h>``
MODULE_LISENCE("GPL");
MODULE_AUTHOR("Peter Jay Salzman");

static u8 (mybyte='A');
static int (myint='i');

MODULE_PARM(mybyte, "b");
MODULE_PARM(myint, "i");

MODULE_PARM_DESC(mybyte, "this cannot do anything\n");

static int  __init hello5_init(void)

{
    printk("my byte %i\n",mybyte);
printk("my integer %i \n",myint);
 }
static void __exit hello5_exit()
{
printk("bye world\n");
}
module_init(hell05_init);
module_exit(helo5_exit);

Makefile:
    obj-m += hello5.o
all:
        make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

exit:
        make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

.PHONY: all, exit

Error:
 /home/kumarmagi/Desktop/amit/hello5/hello5.c:23:24: error: 'mybyte' undeclared     (first       use in this function)
    /home/kumarmagi/Desktop/amit/hello5/hello5.c:23:24: note: each undeclared identifier is reported only once for each function it appears in
    /home/kumarmagi/Desktop/amit/hello5/hello5.c:24:28: error: 'myint' undeclared (first use in this function)
    /home/kumarmagi/Desktop/amit/hello5/hello5.c:25:1: warning: no return statement in function returning non-void [-Wreturn-type]

A: Try to change:
MODULE_PARM(mybyte, "b");
MODULE_PARM(myint, "i");
static int (myint='i');
static u8 (mybyte='A');

to:
module_param(mybyte, short, 0660);
module_param(myint, int, 0660);
static short mybyte='A';
static int myint='i';


text:
Q: How to apply template to the scrollbar of a listbox I have a very simple question. I know this is possible but since I am new to XAML so may be I cant express it properly and thus google doesnt help me.
In simple words:
I want to apply a template to the Scrollbar in the ListBox ?
How ? any example would be great.

A: You have to dig in a bit into the template, what you need to change is the ScrollBar inside the ScrollViewer template.
It's a bit complex, but there are good tutorials walking through each bit, like this: http://mark-dot-net.blogspot.com/2008/04/styling-listbox-in-silverlight-part-2.html


text:
Q: Font issues while using doctype XHTML 1.0 I have a web application for my project and I am planning to upgrade it by using jquery in various areas.
I am using chosen.jquery.cs script for dropdown lists. However, I faced an issue wherein the contents of the page are getting mixed with the contents of dropdown upon expanding it. This issue got resolved when I changed the doctype from <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > to <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">. Unfortunately, this new doctype is not also perfect. With this doctype, fonts are not visible properly. Also, width of some textboxes has increased abruptly.
Being a new user on this forum I am unable to post the screenshots :(
Can anyone please provide a solution/alternative for this problem. Any help will be appreciated.
Thanks in advance.
Regards,
Arpit

A: By using the XHTML doctype instead of HTML 4 Transitional, you are forcing the browsers into "strict mode" instead of "quirks mode", and that's a good thing.
However, it seems that your CSS was coded for quirks mode, so you are probably using the "border-box" box model. You will have to rework your CSS code.


text:
Q: How to export a table with input fields using JavaScript? The table is like this:

   1
   <input type="text" size="5" id="in2" name="txt2" value="0"/>
   <input type="text" size="5" id="in3" name="txt3" value="0"/>
   <input type="text" size="5" id="in4" name="txt4" value="0"/>

the js code is like this:
function export(filename) {
    var csv = [];
    var rows = document.getElementById('tbl_posts').querySelectorAll("table tr");

    for (var i = 0; i < rows.length; i++) {

        var row = [], cols = rows[i].querySelectorAll("td, th");

        for (var j = 0; j < cols.length; j++){
            row.push(cols[j].innerText);
        }

        csv.push(row.join(","));

}

// Download CSV file not posted here
downloadCSV(csv.join("\n"), filename);
}

and the export button:
<button type="button" onclick="export('myFile')">Export</button>

since it reads td not input fields it adds empty '' strings into csv list. How can I access inputs and push them into row list?

A: If you can ensure only inputs occur as child nodes inside a td you could use the following approach. When iterating over a td check if there are any child nodes (only happens in your example if an input is inside a td).
If there's a child (input) use .value on the child to get the value. Otherwise use .innerText. If there is something unclear, feel free to comment :)

function fetchData(filename) {
  var csv = [];
  var rows = document.getElementById('sample_table').querySelectorAll("table tr");

  for (var i = 0; i < rows.length; i++) {

    var row = [],
      cols = rows[i].querySelectorAll("td, th");

    for (var j = 0; j < cols.length; j++) {
      if (cols[j].children.length > 0) { //assuming your structure is always the same and the table only contains inputs as child elements inside a td
        row.push(cols[j].firstChild.value);
      } else {
        row.push(cols[j].innerText);
      }
    }

    csv.push(row.join(","));

  }
  console.log(csv);
}

    1
    <input type="text" size="5" id="in2" name="txt2" value="0" />
    <input type="text" size="5" id="in3" name="txt3" value="0" />
    <input type="text" size="5" id="in4" name="txt4" value="0" />

<button type="button" onclick="fetchData('myFile')">Export</button>

A: What I think is you want to push each row's input value into a CSB file. Then you have to change you cols code like this
cols = document.querySelectorAll("td input, the input");
for (var j = 0; j < cols.length; j++){
    row.push(cols[j].value);
}

I think this would work

A: I saw your comments. If we seek a solution by minimum editing to your code and also I don't know the rest of the document structure, then this will work for multiple rows.
The basic idea is when you already have a table row, then all you need is inputs inside them. So we seek inputs and then go on them one by one.
function exportF(filename) {
var csv = [];
var rows = document.getElementById('sample_table').querySelectorAll("table tr");

for (var i = 0; i < rows.length; i++) {

    var row = [], cols = rows[i].querySelectorAll("input");

    for (var j = 0; j < cols.length; j++){
                    //console.log(cols[j])
        row.push(cols[j].value);
    }

    csv.push(row.join(","));

 }
  // Download CSV file not posted here
  console.log(csv.join("\n"));
}

Link to fiddle: https://jsfiddle.net/tewo2drn/1/

A: You could also go with Array.from and map it

function fetchData() {
   let data = Array.from(document.querySelectorAll("#sample_table td"))
      .map(el => el.firstChild.value || el.innerText)
      .join(",");

   console.log(data);
}

   1
   <input type="text" size="5" id="in2" name="txt2" value="0"/>
   <input type="text" size="5" id="in3" name="txt3" value="0"/>
   <input type="text" size="5" id="in4" name="txt4" value="0"/>
   <button onclick="fetchData()">Fetch</button>

A: Just a variation on @Aaron's answer, giulp's way :)
...  using .map is definitely the way I'd choose, more concise, less error prone, see @Ifaruki's answer for yet another path in this direction

function fetchData(filename) {
  let cells = document.querySelectorAll("table#sample_table tr td");
  // using map over a NodeList -> see below
  var csv = Array.prototype.map.call(cells, function(cell){
       // if the first is undefined (falsey in js)
       // then return the second, a widely used pattern
       return cell.firstChild.value || cell.innerText;
  }).join(",");
  console.log(csv);
}

    1
    <input type="text" size="5" id="in2" name="txt2" value="0" />
    <input type="text" size="5" id="in3" name="txt3" value="0" />
    <input type="text" size="5" id="in4" name="txt4" value="0" />

<button type="button" onclick="fetchData('myFile')">Export</button>

MDN Array.prototype.map


text:
Q: this getting converted into object in jQuery Im trying to write a small function which gets a div element from the html, hides it, assigns a value and a variable name and then parse it into the function to check if the month assigned (the value) is equal equal to the current month. The reason I think its not working is that the 'this' is being converted into an object Object and its not storing the value of the variable that im parsing into it.
var currentMonth = (new Date).getMonth() + 1;
var valentinesdiv = $('#valentinesmenu');
$(valentinesdiv).hide();
valentinesdiv = 5;
$.fn.datechecker1 = function () {
    if ($(this) == currentMonth) {
        this.show();
    } else {
        alert(this);
    }
};
$(valentinesdiv).datechecker1();

It just goes straight to the alert box and outputs object Object so its not holding the value of the variable as I parse it in.

A: A couple issues I see are that you're trying to use the jQuery show() on a pure JS this object, and you're seeing Object object in your alert box because alert(this) is literally passing in the object rather than a certain value inside the object.
What you most likely want is here:
var element = $(this), value = element.val();
if(value == currentMonth){
  element.show();
} else {
  alert(value);
}

A: js below assumes that implementation is to set a variable x: 5 at a specific element: #valentinesmenu ; then check if the variable is equal to variable currentMonth .
x: 5 is set as text of #valentinesmenu ; $.fn.datechecker1 checks if the element is is called on has text equal to currentMonth ;
if true , call .show() on this element , if not true , log this.text(), currentMonth, x to console
Not sure if this is the expected result , or requirement; below js is based on assumptions above

Try utilizing .text()

var currentMonth = (new Date).getMonth() + 1;
var x = 5; // ?

var valentinesdiv = $("#valentinesmenu");
// set text of `valentinesdiv` to `currentMonth`
valentinesdiv.text(x).hide();

$.fn.datechecker1 = function() {
  // if `this.text() == currentMonth` do stuff
  if (this.text() == currentMonth) {
    this.show();
  } else {
    // else, do other stuff
    console.log(this.text(), currentMonth, x);
  }
};

valentinesdiv.datechecker1();

A: The problem is you are giving the variable valentinesdiv a new value.  When you do that it forgets the reference to the $("valentinesmenu"), and when you use it later, you are actually doing this:

$(5).datechecker1();

Here is a way you can do what you want (JSFiddle):

var currentMonth = (new Date).getMonth() + 1;

var valentinesdiv = $('#valentinesmenu');
$(valentinesdiv).hide();

$.fn.datechecker1 = function(compare) {
    if(compare == currentMonth){
        $(this).show();
    } else {
        alert(this);
    }
};

valentinesdiv.datechecker1(5);


text:
Q: Find out which website page are connected to SQL databases or instances Is there a way to find out which parts of my different websites are connected to which SQL databases and/or tables? (database and websites were not built by me)
I want to know that page "whatever.aspx" is connected to the SQL instance "dbo.Whatever". Is there a way to do that?

A: I think that it's going to depend a lot on how the pages were coded. Is there a middle tier?
You can use SQL Profiler to capture connections to the database, but whether or not there will be any information there to allow you to distinguish pages will depend on how they were coded.
Likewise, assuming that you have a code base of the various web sites you should be able to do a search through those, but again it depends on how they were coded.

A: There are two ways I can think of doing this:

*

*If you have a list of tables names from your database you can search your .aspx or corresponding .aspx.cs code for references them. This will tell you which database a web page is using.

*You can also search for connection strings in your web.config file and then find references to those connection string in your .aspx or corresponding .aspx.cs pages.

Note: Every page in your .aspx or corresponding .aspx.cs code that connects to a database must use a connection string (or a reference to a connection string in the web.config). It might be time consuming but you can build a map of which pages connect to which databases by looking for references to tables or connection strings.


text:
Q: upload image from html form and display it in your website? i have this form
<form action="up.php" method="post" enctype="multipart/form-data">

Title	<input type="text" name="title" />

Price	<input type="text" name="price" />

Kilometers	<input type="text" name="km" />

CC	<input type="text" name="cc" />

HP	<input type="text" name="hp" />

Color	<input type="text" name="color" />

Fuel	<input type="text" name="fuel" />

Doors	<input type="text" name="doors" />

Phone	<input type="text" name="tel" />

<input type="hidden" name="max_size" value="1000000" />

Image 1	<input name="img1" type="file" />

<input type="submit" name="go" value="Submit" />
</form>

and when i click submit i want to display all the data above to the up.php file which contain this code so far

<?php

$ttitle=$_POST['title'];
$pric=$_POST['price'];
$klm=$_POST['km'];
$ccc=$_POST['cc'];
$hpp=$_POST['hp'];
$colorr=$_POST['color'];
$fuell=$_POST['fuel'];
$dors=$_POST['doors'];
$thl=$_POST['tel'];
?>

<?php
echo '

' . $ttitle . '

';
echo '
Τιμή:	' . $pric . '
';
echo '
Χιλιόμετρα:	' . $klm . '
';
echo '
Κυβικά:	' . $ccc . '
';
echo '
Ιπποδύναμη:	' . $hpp . '
';
echo '
Χρώμα:	' . $colorr . '
';
echo '
Καύσιμο:	' . $fuell . '
';
echo '
Πόρτες:	' . $dors . '
';
echo '
Τηλέφωνο:	' . $thl . '
';
?>

<?php

echo "";

?>

i've searched for many tutorials but i cannot make it work, so i really need your help to make this work..
when i click the submit button, i get this.

can you please help me? thank you in advance.

A: This is incorrect:
echo "";
                    ^^^^^

You have not defined $img1 anywhere, hence your error. This is also NOT how file uploads are performed in PHP. Given

Image 1	<input name="img1" type="file" />

you will get file upload metadata in $_FILES['img1']. There will be no $_POST['img1'], period. How to handle file uploads in PHP is documented here: http://www.php.net/manual/en/features.file-upload.post-method.php

A: <?php if (isset($_POST['submit'])) {
                        $image_name = $_FILES['image']['name'];
                        $image_type = $_FILES['image']['type'];
                        $image_size = $_FILES['image']['size'];
                        $image_tmp_name = $_FILES['image']['tmp_name'];

                        move_uploaded_file($image_tmp_name, "uploads/$image_name");
                        echo "";
                } ?>

Hey Brother! Just Try This code and everything works fine...


text:
Q: How to convert the current date to digit format? I am getting the new date like this:
getCalender: function () {

            var monthNames = [
                "January", "February", "March",
                "April", "May", "June", "July",
                "August", "September", "October",
                "November", "December"
            ];

            var date = new Date();
            var day = date.getDate();
            var monthIndex = date.getMonth();
            var year = date.getFullYear();

            return (day + '-' + monthNames[monthIndex] + '-' + year);

        },

my above method returns the date format like "day" month name from array and the year.
But the back-end people requires the date format like this:
"IssueDate": "/Date(1407445200000+0300)/",

how to convert the date format to match this?
Any one help me?

A: I tried this, it works fine for me:
var date1 = new Date();
var n = date1.getTimezoneOffset();

console.log( '/Date(' + (+date1) + n +')/' );

Thanks everyone!

A: Try using getTime() in jquery as below -
var date = new Date();

var time = date.getTime(); //1447995963967

A: You can try like this:
var dt = new Date(myDate);
var newDate = new Date(Date.UTC(dt.getFullYear(), dt.getMonth(), dt.getDate(), dt.getHours(), dt.getMinutes(), dt.getSeconds(), dt.getMilliseconds()));
return '/Date(' + newDate.getTime() + ')/';

DEMO
If you want to add the offset time then simply do
var dt = new Date();
var newDate = new Date(Date.UTC(dt.getFullYear(), dt.getMonth(), dt.getDate(), dt.getHours(), dt.getMinutes(), dt.getSeconds(), dt.getMilliseconds()));
return '/Date(' + newDate.getTime()  +  newDate.getTimezoneOffset() +')/' ;

DEMO


text:
Q: Crawl a web page and call javascript functions in Python I need to crawl a website, however, its content is dynamic. Are there any packages in Python that could call js functions? For example, suppose I have a link and JS functions 1, 2, and 3 in JS that I should call on that webpage, and I need the final webpage after all JS function calls.

A: Executing client-side javascript can get very complicated, so the most reliable way to run all javascript on a page just like a user would would be to use a real browser in headless mode.
Specifically for Python, there is a Python+Selenium combo for working with headless Chrome.
If you are willing to trade Python for Nodejs, a more powerful toolset is Puppeteer+headless Chrome (it lets you do a lot more than Selenium). There is also an early unofficial port of Puppeteer to Python but I haven't tried it and can't comment on how stable it is https://pypi.org/project/pyppeteer/


text:
Q: Model, view and projection matrix do not want to work well for opengl glsl I am trying to make my first cube using open gl. Unfortunately I stucked in easy rotation. This is how it should look:

Instead I am getting those weird, do not even know how to called it : https://youtu.be/0A5Hi-8bygE
Vertex shader
#version 330 core

layout (location = 0) in vec2 a_position;
layout (location = 1) in vec2 a_uv;
layout (location = 2) in vec4 a_color;

out vec2 v_fragmentPosition;
out vec2 v_fragmentUV;
out vec4 v_fragmentColor;

uniform mat4 u_model;
uniform mat4 u_view;
uniform mat4 u_projection;

void main()
{
    gl_Position = u_projection * u_view * u_model * vec4(a_position, 0.0, 1.0);

    v_fragmentPosition = a_position;
    v_fragmentUV = vec2(a_uv.x, 1 - a_uv.y);
    v_fragmentColor = a_color;
}

Fragment
#version 330 core

out vec4 outColor;

in vec2 v_fragmentPosition;
in vec2 v_fragmentUV;
in vec4 v_fragmentColor;

void main()
{
    outColor = v_fragmentColor;
}

Main
#include <glad.h>

#include <glm.hpp>
#include <gtc/matrix_transform.hpp>
#include <gtc/type_ptr.hpp>
#include <iostream>

#include "Mesh.h"
#include "Shader.h"

int main(int argc,char*args[])
{
    SDL_Init(SDL_INIT_EVERYTHING);

    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 4);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

    SDL_Window* window = SDL_CreateWindow("fdas", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, SDL_WINDOW_OPENGL);
    SDL_GLContext context = SDL_GL_CreateContext(window);

    gladLoadGLLoader(SDL_GL_GetProcAddress);

    glEnable(GL_DEPTH_TEST);

    Shader shader;

    std::string vertex = shader.LoadFromFile("vertex.shader");
    std::string fragment = shader.LoadFromFile("fragment.shader");
    shader.CreateShaderProgram(vertex.c_str(), fragment.c_str());
    shader.useProgram();

    Mesh mesh;
    mesh.CreateVertexArray();

    bool quit = false;
    SDL_Event event;
    while (!quit)
    {
        while (SDL_PollEvent(&event))
        {
            if (event.type == SDL_QUIT)
            {
            exit(0);
                }
        }
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glm::mat4 model;
        model = glm::rotate(model, glm::radians(-55.0f), glm::vec3(1.0f, 0.0f, 0.0f));

        glm::mat4 view;
        view = glm::translate(view, glm::vec3(0.0f, 0.0f, -3.0f));

        glm::mat4 projection;
        projection = glm::perspective(glm::radians(45.0f), 1280 / 720.0f, 0.1f, 100.0f);

        GLint u_model = shader.GetUniformLocation("u_model");
        GLint u_view = shader.GetUniformLocation("u_view");
        GLint u_projection = shader.GetUniformLocation("u_projection");

        glUniformMatrix4fv(u_model, 1, GL_FALSE, glm::value_ptr(model));
        glUniformMatrix4fv(u_view, 1, GL_FALSE, glm::value_ptr(view));
        glUniformMatrix4fv(u_projection, 1, GL_FALSE, glm::value_ptr(projection));

        Rect destRect = { -0.5f, -0.5f, 1.0f, 1.0f };
        Rect uvRect = { 0.0f, 0.0f, 1.0f, 1.0f };
        ColorRGBA color = { 255, 255, 128, 255 };

        mesh.CreateQuad(destRect, uvRect, color);
        mesh.Draw(0);

        SDL_GL_SwapWindow(window);
    }
    return 0;
}

Mesh
void Mesh::CreateVertexArray()
{
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);

    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);

    glGenBuffers(1, &ebo);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);

    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);
    glEnableVertexAttribArray(2);

    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, position));
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, uv));
    glVertexAttribPointer(2, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(Vertex), (void*)offsetof(Vertex, color));

    glBindVertexArray(0);
}

void Mesh::CreateQuad(Rect destRect, Rect uvRect, ColorRGBA color)
{
    vertex[0].color = color; // topleft
    vertex[0].setPosition(destRect.x, destRect.y + destRect.h);
    vertex[0].setUV(uvRect.x, uvRect.y + uvRect.h);

    vertex[1].color = color;
    vertex[1].setPosition(destRect.x, destRect.y); // bottom left
    vertex[1].setUV(uvRect.x, uvRect.y);

    vertex[2].color = color;
    vertex[2].setPosition(destRect.x + destRect.w, destRect.y); // bottom right
    vertex[2].setUV(uvRect.x + uvRect.w, uvRect.y);

    vertex[3].color = color;
    vertex[3].setPosition(destRect.x + destRect.w, destRect.y + destRect.h); // top right
    vertex[3].setUV(uvRect.x + uvRect.w, uvRect.y + uvRect.h);

    GLuint indices[6] = {
        0, 1, 2,
        2, 3, 0
    };

    glBindVertexArray(vao);

    glBufferData(GL_ARRAY_BUFFER, 6 * sizeof(vertex), NULL, GL_STATIC_DRAW); // orphan the buffer
    glBufferSubData(GL_ARRAY_BUFFER, 0, 6 * sizeof(vertex), vertex);

    glBufferData(GL_ELEMENT_ARRAY_BUFFER, 6 * sizeof(GLuint), NULL, GL_STATIC_DRAW); // orphan the buffer
    glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, 6 * sizeof(GLuint), indices);

    glBindVertexArray(0);

}

void Mesh::Draw(GLuint texture)
{
    glBindVertexArray(vao);

  //  glEnable(GL_CULL_FACE);
   // glCullFace(GL_FRONT);
    //glFrontFace(GL_CW);

    glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, NULL);

    glBindVertexArray(0);
}

Vertex
struct Rect {
    float x, y;
    float w, h;
};
struct Position {
    float x, y;
};

struct UV {
    float u, v;
};

struct ColorRGBA {
    GLubyte r, g, b, a;
};
class Vertex
{
public:
    Vertex();
    ~Vertex();

    void setPosition(float x, float y);
    void setcolor(ColorRGBA color);
    void setUV(float u, float v);

    UV uv;
    ColorRGBA color;
    Position position;
};

I will not show shader class, because there is all good with it.
I know it, because I did an experiment.
I created a new uniform in fragment class called u_expColor and set outColor = u_expColor and a quad's color changed.
Also I created uniform vec4 u_expPos in vertex shader and said gl_Position = e_expPos and it created quad with no problems.
Only if I want to create/multiply position by mvp in vertex shader there is a problem like on the you tube video.
How to fix it?

A: I have fixed it thanks http://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices/#putting-it-all-together. I saw he had
glm::mat4 model = glm::mat4(1.0f)

and it was all I had to do.


text:
Q: Docs for Bootstrap adding data-bs-overflow to body? I'm using Bootstrap 5 and trying to find anywhere in the documentation where it mentions how things like modals or offcanvases will add attribute data-bs-overflow to the body element, and not finding info.
Anyone know how this attribute is added and behaves? It's causing a weird, irreproducible situation in my code. I think it's just interacting with something else that's managing body: overflow but without knowing how Bootstrap's native behavior works I can't be sure


text:
Q: Boolean column in pandas with a windowed function that checking a complex score condition I have a frame that looks like this:
x        y         score
Cat      Dog       0.1
Dog      Monkey    0.5
Fish     Cat       0.2
Cat      Fish      0.2
Monkey   Dog       0.4
Dog      Cat       0.7

Basically I want a new boolean column that looks at all pairs and their reverse, for example (Cat, Dog) and (Dog,Cat) and assign a True for when the score of a pair is greater than the score of the reversed pair, otherwise False. If there is equality, both pairs are assigned True. That is:
x        y         score    bool
Cat      Dog       0.1      False   # False because Dog,Cat > Cat,Dog
Dog      Monkey    0.5      True    # True because Dog,Monkey > Monkey, Dog
Fish     Cat       0.2      True    # True because both have the same score
Cat      Fish      0.2      True    # ...
Monkey   Dog       0.4      False
Dog      Cat       0.7      True

I am certain I can get a function done by applying on the rows a filter for the reverse and then return a checks on the score; however, the list can be quite long (n>100k) and time is a factor. It turns out this is trickier than I thought. I was wondering if this can be done in a more pythonic way with a magic Pandas function that haven't encoutered yet or a rolling window.
Note:

*

*Every pair (x,y) is unique.

*For every pair (x,y) there is exactly
one reverse (y,x).

*There can be multiple occurences of the same category
within the same column, e.g. Cat appears twice in this frame for x.

*Scores range from 0-1.

Frame:
df = pd.DataFrame.from_records(zip(["Cat","Dog","Fish","Cat","Monkey","Dog"], ["Dog","Monkey","Cat","Fish","Dog","Cat"], [0.1,0.5,0.2,0.2,0.4,0.7]),columns=["x","y","score"])

A: You can swap columns x & y, merge on x/y pair, and compare score vs reversed score:
(df.merge(
     df.assign(x = df.y, y = df.x)
       .rename(columns={'score': 'rev_score'})
 ).assign(bool = lambda x: x.score >= x.rev_score)
 .drop('rev_score', axis=1))

        x       y  score   bool
0     Cat     Dog    0.1  False
1     Dog  Monkey    0.5   True
2    Fish     Cat    0.2   True
3     Cat    Fish    0.2   True
4  Monkey     Dog    0.4  False
5     Dog     Cat    0.7   True


text:
Q: How to find Roku IP + Port on network using SSDP search in VB.NET I am trying to find my Roku TV on my network and apparently it needs some SSDP discovery based on Roku API help, however, I am unable to search for my device with any of the Nuget libraries.
I came across ssdpradar and was able to install the Nuget package for Visual Studio (VB.NET) through Visual Studio 2017 community release. However, I am not able to find any documentation on how to use it.
Any advice would be helpful.
Solution:
I found a solution but not with ssdpradar and rather RSSDP. After you add the nugget in your project you can use the following line of code to get all devices and then find the Roku location (ip+port) from that list.
Imports Rssdp

For Each founddevice As DiscoveredSsdpDevice In founddevices.Result
    If founddevice.Usn.Contains("roku:ecp") Then
        Rokulocation = founddevice.DescriptionLocation.ToString()
        Exit For
    End If
Next

A: I was able to successfully use a library called RokuDotNet recently. It's written in C# but you could load it as a project in your solution and reference it from VB.NET.
This is roughly the way I used it:
Imports RokuDotNet.Client

Public Class Form1
    Private _discoveryClient As RokuDeviceDiscoveryClient

    Public Sub New()
        _discoveryClient = New RokuDeviceDiscoveryClient
        AddHandler _discoveryClient.DeviceDiscovered, AddressOf DiscoveryHandler
    End Sub

    Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
        _discoveryClient.DiscoverDevicesAsync()
    End Sub

    Private Async Sub DiscoveryHandler(sender As Object, e As DeviceDiscoveredEventArgs)
        If InvokeRequired Then
            BeginInvoke(New Action(Sub() DiscoveryHandler(sender, e)))
            Return
        End If

        ' Get the display name for the device (if the user entered one when setting it up)
        Dim deviceInfo = Await e.Device.Query.GetDeviceInfoAsync
        Dim name = deviceInfo.UserDeviceName
        If String.IsNullOrEmpty(name) Then
            name = deviceInfo.ModelName
        End If
        AddDevice(e.Device, name)
    End Sub

    Private Sub AddDevice(device As RokuDevice, name As String)
        ' Your code here
    End Sub
End Class

You might want to add a try/catch around the await in that async function so it can show an error if there's a network problem.