text:
Q: Bracket Balancing can someone help me with this code it is not working with this test case{(([])[])[]]}.
package myProject;
import java.util.*;

public class bracketBalancing {

    public static void main (String[] args) {
    Scanner sc=new Scanner(System.in);

        System.out.println("Enter String");
    String s=sc.next();
    Stack<Character> stack=new Stack<Character>();
    if(s.length()==0)
    System.out.println("string is empty");
    else {
      for(int i=0;i<s.length();i++){
      char ch=s.charAt(i);

      if(ch=='('||ch=='{'||ch=='['){
         stack.push(ch);
      }
      else if(ch==')'&& stack.peek()=='('){
          stack.pop();
      }
      else if(ch=='}'&& stack.peek()=='{'){
          stack.pop();
      }
      else if(ch==']'&& stack.peek()=='['){
          stack.pop();
      }

      }
    }
      if(stack.empty()){
          System.out.println("YES");
      }
      else{
      System.out.println("No");
      }
      sc.close();
    }
}

A: You should add the else condition to print No if you are neither able to push not pop. Because in that condition it means you have some additional closing brackets which will lead to unbalanced.
Code:
if (s.length() == 0) {
      System.out.println("string is empty");
    } else {
      for (int i = 0; i < s.length(); i++) {
        char ch = s.charAt(i);

        if (ch == '(' || ch == '{' || ch == '[') {
          stack.push(ch);
        } else if (ch == ')' && stack.peek() == '(') {
          stack.pop();
        } else if (ch == '}' && stack.peek() == '{') {
          stack.pop();
        } else if (ch == ']' && stack.peek() == '[') {
          stack.pop();
        } else {
          System.out.println("No");
          stack = null;
          break;
        }

      }
    }
    if(stack != null) {
      if (stack.empty()) {
        System.out.println("YES");
      } else {
        System.out.println("No");
      }
    }


text:
Q: Selenium - Проблема с поиском элемента на странице Добрый день,
Пишу бота для инстаграма (масслайкинг, можете загуглить). Использую Selenium в первый раз.  Столкнулся с такой проблемой:
После перехода на пост, боту необходимо нажать на кнопку  "ещё "(см. прикрепленный файл). Я не могу найти button. У кнопки нет четких атрибутов, например постоянного класса. XPath - пытался:
driver.find_element_by_xpath('//*/div[3]/div[2]/div/article/div[2]/section[2]/div/div[2]/button')

Не находит. Подскажите, как можно найти элемент.
Заранее спасибо!

A: Используйте конструкцию вида:
driver.find_elements_by_xpath("//button[contains(text(), 'ещё')]")

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error when assign value for matrix in iml procedure I simply want to assign a row of matrix by a vector in iml procedure, but it returns error. The code is as follow, how can I fixed it?
 proc iml;
 za=repeat(0,4,3);
 a=123;
 b=321;
 c=222;
 za[1,]={a,b,c};
 run;
 print(za);
 proc print;run;

A: There are a few problems with your code. {x, y, z} is a column vector. {x y z} is a row vector. Which means you attempt to insert a column in a row. Also, the syntax is a bit off.
Using your own code, you can do this.
proc iml;
 za=repeat(0,4,3);
 a=123;
 b=321;
 c=222;
 za[1,] = a || b || c;
 print(za);
quit;

A simpler way would be
proc iml;
   za = j(4, 3, 0);
   v = {123 321 222};
   za[1, ] = v;
   print za;
quit;


text:
Q: Вопрос по туле Jmeter, подскажите пожалуйста, что означает "Runs in 10 threads once." Что имеется в ввиду, запуск 10ти потоков за один раз? я не совсем понимаю этот момент.

A: А почему вы спрашиваете об этом здесь, а не автора этого документа? Английский там очень кривой, но по контексту я могу предположить что в первой Thread Group речь идет о 10 пользователях и 1 итерации:

а во второй - об одном пользователе и неограниченном количестве итераций

к пункту 2 тоже есть некоторые вопросы т.к. HTTP Request Defaults не выполняет никаких запросов, это просто конфигурационный элемент где можно указать значения "по умолчанию" для разных полюшек HTTP Request сэмплера, так что у автора этого документа беда не только с английским, он еще и не совсем профпригоден.


text:
Q: Android - Forecast.io icon label to custom font: weather-icons I'm currently building a weather app using the forecast.io api.
They provide custom font for Forecast.io, as well as for other apis such as Yahoo. I'm not sure about how to proceed to use their API mapping.
For instance, I receive "partly-cloudy-night" and this should render the icon.
I would welcome advices or clues on how to proceed.
Thanks a lot,

A: You have to use the ttf file il your android project, and convert the css to xml string ressource.
I did it for Web Hosting hub glyph (a bit like font awesome but many more icons).
See https://github.com/neoteknic/whhg-to-android
I can reuse my convertion script an make a repo with these icons.
Edit :
This is for you :
https://github.com/neoteknic/weather-icons-to-android
To use it (I prefer load only once the typeface and make it available globally) :
public class YourAppName extends Application {
    public static Typeface weatherIcons;

    @Override
    public void onCreate(){
YourAppName.weatherIcons= Typeface.createFromAsset(getApplicationContext().getResources().getAssets(), "fonts/weathericons-regular-webfont.ttf");
        super.onCreate();
    }
}

Then when you wanna use it :
TextView myicon=(TextView) findViewById(R.id.myicon);
myicon.setTypeface(YourAppName.weatherIcons);
myicon.setText(R.string.wi_day_snow_wind);


text:
Q: Write and stream a templated Xml as efficiently as possible I am trying to find the best solution to prevent us to allocate too much memory when building an Xml document. I have to construct a fairly large Xml with the less resource possible (the web service must be able to handle hundreds of calls per seconds). The structure of the Xml itself doesn't change much, however the data consistently change.
My current solution is XDocument and XElement (LINQ). Below is a quick sample of what I am doing today:
static Stream GetXml(string d1, string d2, string d3)
{
    XElement x =
        new XElement("myElement",
            new XElement("myOtherElement1", d1),
            new XElement("myOtherElement2", d2),
            new XElement("myOtherElement3", d3));
    // ... more XElement
    // ... return Stream
}

When the Xml document becomes too large, instantiating an XDocument and many hundreds of XElement becomes very expensive and the number of calls per second drops.
I am currently thinking of creating some sort of template engine that would simply stream the strings (XElement) without instantiating any objects. How would you do that? Is that the right thing to do?
static Stream GetXml(string d1, string d2, string d3)
{
    const string xml = @"
<myElement>
  <myOtherElement1>{0}</myOtherElement1>
  <myOtherElement2>{1}</myOtherElement2>
  <myOtherElement3>{2}</myOtherElement3>
</myElement>";

    // What's the best way to {0}, {1}, {2} without allocating
    // objects and using as little RAM as possible. I cannot
    // use string.Format since it allocates strings.

    StreamWriter sw = new StreamWriter(stream);
    sw.Write(xml);
}

A: Consider using the XStreamingElement implementation discussed at http://msdn.microsoft.com/en-us/library/system.xml.linq.xstreamingelement.aspx if you want to avoid loading your memory with the XML that you are parsing/generating.

A: The only reason I can think of for dismissing string.Format is that you don't want to keep the whole XML-document in memory at once. I wrote this Stream class that should only keep a small portion of the document in memory at the time.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace StreamTest
{
    public class EnumeratorStream : Stream
    {
        private readonly IEnumerator<string> source;
        private readonly Encoding encoding;

        public Encoding Encoding { get { return encoding; } }

        private byte[] current = new byte[0];
        private int currentPos = 0;

        public EnumeratorStream(IEnumerable<string> source, Encoding encoding)
        {
            if (source == null) throw new ArgumentNullException("source");
            if (encoding == null) encoding = Encoding.Default;

            this.source = source.GetEnumerator();
            this.encoding = encoding;
        }

        private bool MoveNext()
        {
            while (source.MoveNext())
            {
                if (source.Current.Length > 0)
                {
                    current = encoding.GetBytes(source.Current);
                    currentPos = 0;
                    return true;
                }
            }
            current = new byte[0];
            currentPos = 0;
            return false;
        }

        #region Overrides of Stream

        public override bool CanRead { get { return true; } }
        public override bool CanSeek { get { return false; } }
        public override bool CanWrite { get { return false; } }

        public override int Read(byte[] buffer, int offset, int count)
        {
            if (buffer == null) throw new ArgumentNullException("buffer");
            if (offset < 0) throw new ArgumentOutOfRangeException("offset");
            if (offset + count > buffer.Length) throw new ArgumentException("Not enough buffer space");

            int totalWritten = 0;
            while (count > 0)
            {
                int remaining = current.Length - currentPos;
                if (remaining == 0 && !MoveNext()) break;
                remaining = current.Length - currentPos;
                if (remaining <= 0) break;
                if (remaining > count)
                {
                    remaining = count;
                }
                Array.Copy(current, currentPos, buffer, offset, remaining);
                offset += remaining;
                count -= remaining;
                totalWritten += remaining;
                currentPos += remaining;
            }
            return totalWritten;
        }

        public override void Flush() { }
        public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); }
        public override void SetLength(long value) { throw new NotSupportedException(); }
        public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); }
        public override long Length { get { throw new NotSupportedException(); } }
        public override long Position
        {
            get { throw new NotSupportedException(); }
            set { throw new NotSupportedException(); }
        }

        #endregion
    }
}

Example:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace StreamTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var stream = new EnumeratorStream(Generate("x","y","z"), null);
            var buffer = new byte[256];
            int read;
            while ((read = stream.Read(buffer,0,256)) > 0)
            {
                string s = stream.Encoding.GetString(buffer, 0, read);
                Console.Write(s);
            }
            Console.ReadLine();
        }

        public static IEnumerable<string> Generate(string d1, string d2, string d3)
        {
            yield return "<myElement>";
            yield return "<myOtherElement1>";
            yield return d1;
            yield return "</myOtherElement1>";
            yield return "<myOtherElement2>";
            yield return d2;
            yield return "</myOtherElement2>";
            yield return "<myOtherElement3>";
            yield return d3;
            yield return "</myOtherElement3>";
            yield return "</myElement>";
        }
    }
}

A: You can pass a StringBuilder around. Any duplicate strings (like opening and closing tags) would reference the same data in memory, so you'd get some savings there.
static Stream GetXml(string d1, string d2, string d3)
{
    StringBuilder xml = new StringBuilder();
    xml.Append("<myElement>");
    AppendElement(xml, d1);
    AppendElement(xml, d2);
    AppendElement(xml, d3);
    xml.Append("</myElement>");

    // Create/return stream
}
static void AppendElement(StringBuilder xml, string value)
{
    xml.Append("<myOtherElement>");
    xml.Append(value);
    xml.Append("</myOtherElement>");
}

To save even more, you can piece together the opening and closing elements like this:
static Stream GetXml(string d1, string d2, string d3)
{
    StringBuilder xml = new StringBuilder();
    OpenElement(xml, "myElement");
    AppendElement(xml, d1);
    AppendElement(xml, d2);
    AppendElement(xml, d3);
    CloseElement(xml, "myElement");

    // Create/return stream
}
static void AppendElement(StringBuilder xml, string value)
{
    OpenElement(xml, "myOtherElement");
    xml.Append(value);
    CloseElement(xml, "myOtherElement");
}

static void OpenElement(StringBuilder xml, string elementName)
{
    xml.Append("<");
    xml.Append(elementName);
    xml.Append(">");
}
static void CloseElement(StringBuilder xml, string elementName)
{
    xml.Append("</");
    xml.Append(elementName);
    xml.Append(">");
}


text:
Q: Large Variations in Identical Python Process Run Times I just bought a new, machine to run python scripts for large scale modeling. It has two CPUs with 4 cores each (Xeon, 2.8GhZ). Each core has hyper-threading enabled for 4 logical cpu cores.
Now for the problem: When I run identical python processes in 8 separate terminals, top command shows that each process is taking 100% of the cpu. However, the process in terminal 1 is running about 4 times slower than the process in terminal 8. This seems odd to me...
I wonder if it has something to do with how the processes are scheduled on the various (logical?) cores? Does anyone have an idea of how I could all of the to run in about the same speed?
EDIT (in response to larsmans): Good point. The script is a ginat loop that runs about 10,000 times. Each loop reads in a text file (500 lines) and runs some basic calculations on the quantities read in. While the loop runs, it uses about 0.2% of Memory. There is no writing to disk during the loop. I could understand that the read access could be a limiting factor but I am perplexed about the fact that it would be the first process that would be the slowest if that was the case. I would have expected that it would get slower as I start more processes...
I timed the processes a couple of times using the time command in the terminal.
EDIT2: I just found out that sometimes a single core is designated to handle all reading and writing - so multiple processes (even if they run on separate cores) will use one single core for all the I/O... This would however only affect one of the cores, not cause all to have various processing speeds...

A: One reason for this might be the use of hyper-threading. HT logical CPUs appear to the operating system as separate CPUs, but really are not. So if two threads run on the same core in separate logical (HT) CPUs, performance would be smaller than if they ran on separate cores.
The easiest solution might be to disable hyper-threading. If that is not an option, use processor affinity to pin each Python process to its separate CPU.


text:
Q: How to write customised show function in Haskell I am defining a Octave type:
data Octave = 1 | 2 | 3
  deriving (Show, Read, Ord, Enum)

Since '1' is not valid for data constructor identifiers, I have to do it like so:
data Octave = O1 | O2 | O3
  deriving (Show, Eq, Read, Ord, Enum)

Now, if I show Octave O1 it shows "O1" which is not exactly what I want. I want the result to be "1". I know we can customise our Show behaviour like this:
instance Show Blabla where
  show (Blabla ints chars list num) =
    "integers = " ++ show ints ++ "\n"

But the problem is that I am using enumeration type which means it doesn't have a value except its identifier name 'O1'. How can I access that in Haskell?
Another question: How can I read it back?
read "O1" :: Octave works, but I want read "1" :: Octave
instance Read Octave where
  read "1" = O1
  read "2" = O2
  read "3" = O3

This doesn't work: "read is not a (visible) method of class Read".

A: Taking advantage of Octave's Enum instance and using the Show and Read instances for Int we can implement showing and reading like this:
data Octave = O1 | O2 | O3 deriving (Eq, Ord, Enum)

instance Show Octave where
    show o = show (fromEnum o + 1)

instance Read Octave where
    readsPrec prec = map (\(n,s) -> (toEnum (n - 1), s)) . readsPrec prec

I.e. fromEnum and toEnum convert between octaves and ints so that O1 <-> 0 and O2 <-> 1, so we have to adjust by one in both reading and writing.

A: Seems like all you need is this, right?
instance Show Octave where
  show O1 = "1"
  show O2 = "2"
  show O3 = "3"

Define show with three clauses, and let the pattern matcher figure it out.

A: Here's a different approach:
data Octave_ = O1 | O2 | O3 deriving (Show, Eq, Read, Ord, Enum)
newtype Octave = O { unO :: Octave_ }  deriving (Eq, Ord, Enum)

instance Show Octave where
    show = tail . show . unO

Depending on what you are doing this could be good or bad.

A: You can always use existing instances for Int, like so:
data Octave = O1 | O2 | O3 deriving (Enum,Bounded)

instance Show Octave where
   show = show . (+1) . fromEnum

instance Read Octave where
   readsPrec pr = map (\ (int,str) -> ((toEnum (int-1)),str) . readsPrec pr

This correctly renders O1..O3 as 1..3 and reads them back. The only pitfall is when trying to read a different integer, like 4:
*** Exception: toEnum{Octave}: tag (3) is outside of enumerations'range (0,2)

This could be fixed by writing more code and checking for valid values in readsPred.

A: It looks like you want to access the identifier name. you could use something like template haskell to do it but this is a terrible idea.
Actually, the fist bad idea is probably to rely on show. Show class is traditionally use to "serialize" data, while Read class will de-serialize them. If you want to pretty print the output, you'd better write your own Octave -> String function. To do so, you could rely on the result of show (and truncate the result). However, the most efficient solution might be to encode it directly, as proposed by amalloy.


text:
Q: variable problems, a = b is messing up value of b if i update a; javaScript if i set variable A equal to variable B then sometimes when i update value of a then b is also updated.
var b = 0;
var a = b;
b++;

now both a and b returns 1; why?
I know what you all mean, even the part about the objects, i use firefox to run my code on codepen. Usually the code runs fine but every once in a while this sort of problem comes up.
I found a solution:-
when the happens it must be happening because some how the compiler is reading the variables as objects.
so ii tried the following solution and it worked.
var b = 0;
var a = JSON.stringify(b);
a = JSON.parse(a);
a++;
// now a returns 1 and b returns 0 thanks for helping

A: Primitive values are passed by value but objects are always passed by reference.. this can only happen when you're talking about objects.

var a = 0,
    b = a;

a = 3;
console.log(a, b); // will be different

a = {a: 0};
b = a;

a.a = 3;
console.log(a, b); // will be the same


text:
Q: Vectorizing complex georeferenced map I have question about QGIS. I have georeferenced a fairly complex geological map (raster file) and would like to vectorize the different geological units. However, the georeferenced map contains text, contour lines, rivers, etc. in addition to the geological units that I would like to convert to shapefiles. I have tried to polygonize the map in bulk, but the resultant Shapefile is too bogged down by the extraneous data that I have no interest in to make any sense of.
Do you have any suggestions of how I can more easily do this without manually tracing all of the boundaries?
I have attached an image of the geological map below to give you all a sense of what I'm dealing with.


text:
Q: How to make WindowManager button clickable? I use WindowManager to create a button to show in the incoming call screen, I would like to make this button clickable to trigger an intent. However, I can make it swipe to anywhere by Button.OnTouchListener() but I don't know how to make it clickable. How to set the WindowManager parameters to make it?? thanks
 int LAYOUT_FLAG;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_PHONE;
        }
        wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
        params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                LAYOUT_FLAG,
                0,
                PixelFormat.TRANSPARENT);
        params.flags =
                 WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
        params.gravity = Gravity.LEFT | Gravity.TOP;

        params.x = 500;
        params.y = 500;

        addBtn=new Button(ctx);
        addBtn.setText("button");
        wm.addView(addBtn, params);
        addBtn.setOnTouchListener(addBtnTouchListener);
        addBtn.setOnClickListener(addBtnClickListener);

in the addBtnTouchListener:
 private Button.OnTouchListener addBtnTouchListener = new Button.OnTouchListener() {
    int lastX, lastY;
    int paramX, paramY;

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastX = (int) event.getRawX();
                lastY = (int) event.getRawY();
                paramX = params.x;
                paramY = params.y;
                break;
            case MotionEvent.ACTION_MOVE:
                int dx = (int) event.getRawX() - lastX;
                int dy = (int) event.getRawY() - lastY;
                params.x = paramX + dx;
                params.y = paramY + dy;

                wm.updateViewLayout(addBtn, params);
                break;
        }

        return true;
    }
};

A: I found that I make the Button.OnTouchListener return false , then the OnClickListener can be work.


text:
Q: Test whether random slopes are significantly different from 0 for individual subjects I am working (in R 3.2.3 using lme4 for doing mixed effect modeling) with vowel data from many different subjects. The question I'm interested is whether certain vowels undergo change over time (as in the English word 'I') as a function of the following consonant type, and in particular whether this is the case for all subjects, or only for some. Suppose, for simplicity, that I am only measuring a single vowel in many different words, and that there are no relevant differences between these words. My model would then looks as follows:
measure ~ (1|subject) + timepoint + (timepoint|subject) +
          following_segment + (following_segment|subject) +
          timepoint:following_segment + (timepoint:following_segment|subject)

where timepoint is a continuous variable referring to the timepoint in milliseconds of each measurement, and following_segment is a binary variable referring to either a neutral context or a context where I am expecting a change over time.
If I run ranef on this model and look in the final column, corresponding to the (timepoint:following_segment|subject) term, I indeed get either very large numbers (e.g. 500 Hz) or very small numbers (e.g. 100 Hz, just to name two random examples; there is a large amount of variability, because these estimates are correlated with the subject's physiological properties such as jaw size).
I now want to know whether these differences in random slope estimates between subjects are significant, for individual subjects (i.e. 'is this subject sensitive to the following_segment manipulation or not?'). Since I know that t = B/SE, all I believe I would need is the standard error for the individual participant within this specific term of the model, and then I can use pnorm to get a p value (please correct me if this is too simple). Regarding obtaining the estimated SE, this question gave me a starting point in suggesting summary(model)@REmat, which unfortunately returns only NULL. Another question suggests using ranef(model,condVar=TRUE), which unfortunately gives an error that conditional variances not currently available via ranef when there are multiple terms per factor. Is there another way to test whether the individual random slope estimates are significantly different from 0?
Here is a histogram of the random slopes:

The peak around 800 Hz looks interesting; any way I can test for each participant's slope estimates whether they are located around that 800-Hz peak, versus around the big peak near the 0 point?

A: The ranef(model,condVar=TRUE) method is not working because you have the random effects written in separate parenthesis blocks. In this specification, no covariances are estimated among the random slopes (because covariances are only included for terms that share a parenthesis block), but covariances are estimated between the the random intercept and each random slope (because each parenthesis block implicitly also includes the intercept). That's fine, but another totally reasonable specification (although with more parameters) is to allow all the random effects to have nonzero covariance. In other words, you can rewrite the model syntax as
measure ~ timepoint*following_segment + (timepoint*following_segment|subject)

For this rewritten model, the ranef(model,condVar=TRUE) method should work.
If you don't want to rewrite the model in this way and include the extra covariance parameters, then another way to implement the tests you want is via bootstrapping. In each iteration, sample with replacement from each subject's data (do not mix observations between subjects), fit your mixed model, and save the array of random effects. After some large number of iterations (1000? 10000?), you will have distributions for each subject's random effects, which you can compare to 0. Note that this could take a while for your complex model!


text:
Q: Install OS X 10.7 to 10-10 on MacBook Air MD232 I have MacBook Air MD232. As we need to test our software on all OS X from 10.7 to 10.10, we need to install them all. Is it possible to install them on my MBA? When I buy, this MBA has been installed with Yosemite. I tried to install any other OSs by using "restore" feature from Disk Utility. However, restoring process were successful and pressing alt/option during restart, I get only gray screen with a stop sign and nothing happen afterwards. Would you please tell me how?

A: Hardware Requirements
Every Mac has a minimum supported operating system. Older versions of OS X will not run on a Mac with a higher minimum.
For example, the MacBook Air (Early 2014) requires OS X 10.9.2 or later.
EveryMac has a comprehensive list of Mac models and their minimum supported OS X.
Virtual Machines
To work around this, consider using a virtual machine for your testing; VMware Fusion, Parallels, and VirtualBox are all reasonable choices.

A: I understood correctly your question, you want to test your software on several versions of OS X. I think what you should do is partion your ssd into 4 parts for each OS X version. You can install any version of OS X using a usb key. How to create a bootable usb key with a OS X you can watch THIS
So what I want to suggest you to do is make sure that the current files and documents from MBA are backed up
Restart the machine and hold ALT key, you will see a gray screen with two options, choose Disk Utility and from there you will have to erase the hard drive and patron it into 4 parts. You can watch THIS to see how do so. Even so in the video it is performed inside the OS X and on external drive the moves are the same.
After you partioned your drive you can start installing different versions of OS X with a usb stick, how to do it you can watch THIS
Hope this helps


text:
Q: Proof that the harmonic series diverges (without improper integrals)
Show that $$\sum\limits_{k=1}^n \frac{1}{k} \geq \log(n)$$ Use this to deduce that the series $$\sum\limits_{k=1}^\infty \frac{1}{k}$$ diverges.
  Hint: Use the estimate $$\frac{1}{k} \geq \int_k^{k+1} \frac{1}{x}\,\mathrm{d}x$$

Note that all instances of "$\log$" mean the natural logarithm, the inverse of the exponential. After doing the integration, I've concluded that $\frac{1}{k} \geq \log(1+\frac{1}{k})>-\log(k)$
I suspect I'm supposed to use the hint to arrive at the first inequality, and then since $\log(n)$ can become arbitrarily large as $n$ increases, so must the harmonic series (essentially the comparison test).
I'm having trouble making this jump. Hints are appreciated, but please no solutions.

A: $$\frac1k\ge\int_k^{k+1}\frac{dx}x=\log\frac{k+1}k\implies\sum_{k=1}^n\frac1k\ge\log\left(\prod_{k=1}^n\frac{k+1}k\right)\ge\log n$$

A: we can use the fact that $$\dfrac{1}{k-1} + \dfrac{1}{k}+\dfrac{1}{k+1} =  \dfrac{1}{k}+\dfrac{2k}{k^2 - 1} >  \dfrac{1}{k}+\dfrac{2}{k} = \dfrac{3}{k}\text{ for } k \ge 2$$ to show that $s=1 + \frac12 + \frac13 + \cdots$ cannot be finite, therefore the harmonic series must diverge.
$\begin{align}
s &= \dfrac{1}{1} + \dfrac{1}{2} + \dfrac{1}{3}  +\dfrac{1}{4} + \dfrac{1}{5}+ \cdots \\
&=1+\left(\dfrac{1}{2} + \dfrac{1}{3}+\dfrac{1}{4} \right)+
 \left(\dfrac{1}{5} + \dfrac{1}{6}+\dfrac{1}{7} \right) +
 \left(\dfrac{1}{8} + \dfrac{1}{9}+\dfrac{1}{10} \right) +
 \left(\dfrac{1}{11} + \dfrac{1}{12}+\dfrac{1}{13} \right) + \cdots \\
 &> 1+3\left(\frac13 + \frac16+\frac19+\frac1{12} \cdots\right) =
1+1 +\frac12 + \frac13+\frac14 + \cdots\\
&=1 + s
\end{align}$
we have $ > s+1$, therefore $s$ cannot be a finite number.

A: An other way:
Let $S_n=\sum_{k=1}^n\frac{1}{k}$.
$$|S_{2n}-S_n|=\sum_{k=n+1}^{2n}\frac{1}{k}=\underbrace{\frac{1}{n+1}}_{\geq \frac{1}{2n}}+\underbrace{\frac{1}{n+2}}_{\geq \frac{1}{2n}}+...+\underbrace{\frac{1}{2n}}_{\geq \frac{1}{2n}}\geq \frac{n}{2n}=\frac{1}{2}$$
and thus, $(S_n)$ is not a Cauchy sequence, therefore it doesn't converge.

A: HINT:$$\frac{1}{2}+(\frac{1}{3}+\frac{1}{4})+(\frac{1}{5}+\frac{1}{6}+\frac{1}{7}+\frac{1}{8})...\gt\frac{1}{2}+(\frac{1}{4}+\frac{1}{4})+(\frac{1}{8}+\frac{1}{8}+\frac{1}{8}+\frac{1}{8})\cdots$$


text:
Q: Empty files in /var/spool/postfix/maildrop/ I've got Postfix 2.5.5 running on a Debian 5.0 server. Very small volume, no incoming mail, only sending out occasional notification emails sent from a web app and internal (system) emails like cron notifications. Web application sends mails using SMTP to localhost.
A few days ago, during a spike of web traffic, monitoring graphs for queue levels went up, and maildrop queue stays at 40 since then. Monitoring graphs number of files in /var/spool/postfix/*. After looking in, I see about 40 empty files in /var/spool/postfix/maildrop/.
When I use 'sendmail' after shutting down Postfix, a file appears in maildrop but it contains binary data; after starting Postfix, it disappears and mail is delivered. I can't find any information on empty files in the queue directory - is it expected? Harmful in any way? Or is making graphs look ugly its only function? Can I safely delete these files?

A: If they are empty, it probably won't hurt to delete them. Not sure why there are empty files in your queue, could be any number of reasons. When you delete them, make sure you use postsuper -d <queue_id>.

A: Maybe this will help figure this out:
http://markmail.org/message/kf2z5nkpsl457qkg
or
http://blog.gmane.org/gmane.mail.maildrop/month=20030501
Seems like quota related problem (?)


text:
Q: SQL select does not return any entries I am using a Sql query to load a subset of data
SELECT [sfb_id]
      ,[prs_id_201304]
      ,[prs_id_201204]
      ,[vorname]
      ,[sex]
  FROM [IAB\KruegerJ049].[test]
  WHERE sex='Weiblich'

the column sex contains the characters Männlich or Weiblich (male or female). I only want to read out rows which contain sex='Weiblich'. But this code does not return any entries!
Thanks in advance

A: It may be your collation is not right. change the collation and repeat the query . there is not error on your query.

A: Try WHERE sex LIKE '%Weiblich%' in case there are some spaces before or after.

A: Try to debug it with babysteps. First check should be if
SELECT *  FROM [IAB\KruegerJ049].[test]

returns entrys, then try
SELECT *  FROM [IAB\KruegerJ049].[test] WHERE sex='Weiblich'

i think you misstyped something :) you can also try
WHERE sex LIKE '*Weiblich*'

A: Try this:
WHERE LTRIM(RTRIM(LOWER(sex))) = 'weiblich'


text:
Q: 403 Forbidden error while accessing Azure web api using certificate authentication I am getting 403 Forbidden exception while accessing simple azure webapi with certificate authentication, only while accessing from asp.net web application. I am using WebClient inherited object to overide GetWebRequest to add client certificate.
    public class CertificateWebClient : WebClient
    {
        private readonly X509Certificate2 certificate;

        public CertificateWebClient(X509Certificate2 cert)
        {
            certificate = cert;
        }

        protected override WebRequest GetWebRequest(Uri address)
        {
            HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
            request.ClientCertificates.Add(certificate);
            return request;
        }
    }

And I am using the object CertificateWebClient DownloadString function to access the web api.
X509Certificate2 newCertificate = new X509Certificate2("bytearray");

CertificateWebClient webClient = new CertificateWebClient(newCertificate)
{
    Proxy = new WebProxy("proxy address")
};

var result = webClient.DownloadString("https://webapiaddress/api/Values");

I am accessing the web api in the similar manner in windows forms and it works absolutely fine.

A: I could resolve this issue by storing and retrieving the certificate from Azure key vault in Base 64 string format. Using Convert.ToBase64String("raw certificate data") and Convert.FromBase64String("base64 cert string"), so I had to modify the above code as
X509Certificate2 newCertificate = new X509Certificate2(Convert.FromBase64String("base64 cert string"));

Only base 64 format keeps the certificate raw data intact while Adding/Retrieving certificate data to azure key vault.
The Certificate should have been ideally added to Azure key vault certificate store but the project requirement was to store it as key.


text:
Q: What does it mean for an orbit to "accumulate"? For example, from Beardon's "A Primer On Riemann Surfaces",

...Show that g is a homeomorphism of D onto itself, and that no orbit accumulates in D.

I'm simply looking for a definition of the word accumulates; I haven't encountered it yet and he presents no formal meaning previously.

A: Very roughly, it is saying something like that the orbit should not have a subsequence with a Limit Point.  That wiki page contains various definitions related to  accumulation points in a topological space.  The specific one given is:
"A point x ∈ X is a cluster point or accumulation point of a sequence
(xn)n ∈ N if, for every neighbourhood V of x, there are infinitely many
natural numbers n such that xn ∈ V."


text:
Q: Expose limited method from specific API : WSO2 API Manager Version 2.6.0 free I want to expose limited methods from my micoservice to outside.
I have 2 applications, each of one have its own access token (App1 and App2). Able to subscribe API with all methods to App1.
Want to subscribe same api with limited method's(not all methods) to App2.
Example : App1 ---subscribe ---X microservice (X having 2 post method's)
App2 ---subscribe ---X microservice should expose only one method from out of 2

A: You can achieve this using scopes.
Let's say you have an API with the following resources and respective scopes.

*

*/check-status

*/upload-photo

*/upload-file

Then you can create 2 scopes as read and write. The read scope is attached to read role and write scope is attached to write role.
Apply the scopes to resources as follows.

*

*/check-status  : read

*/upload-photo. : write

*/upload-file.  : write

In the devportal, when a user1(with read role) logs in, he can create an app and subscribe to the API. When generating an access token he will get only the read scope. He will see both the scopes. But the request is protected with the scope. So users with that scope only can access that particular resource.
Refer - https://wso2.com/library/articles/2017/01/article-an-overview-of-scope-management-with-wso2-api-manager/


text:
Q: 2022: Keyboard Shortcut for Lock Screen just stopped working This is a related, older question that isn't what this post is about: Keyboard shortcut for "Lock screen" not working
My question is different. For the past year or more, I've had no problem locking my screen with Super+L. You can see in my settings that the shortcut is still enabled:

However, I recently installed some Ubuntu-recommended update and the Super+L shortcut now no longer works. I don't know what exactly was updated. Does anyone know how to either (a) get my lock keyboard shortcut working again, or (b) hunt down the update that broke it?
I'm specifically using:
Distributor ID: Ubuntu
Description:    Ubuntu 18.04.6 LTS
Release:    18.04
Codename:   bionic

Thanks in advance!
Edit: Now my machine no longer locks when I shut the lid. What is happening?


text:
Q: php file path of server I am trying to get this script to work. it opens up a directry and lists the files in the directory.
I have copied this code from somewhere else and the problem is that this php file is hosted on an apache server not my localhost. what is the correct $dir_name = "c:/"; to use?
The file is in this directory /domains/domainxxxx.com.au/public_html/lsitfiles.php so would I use domainxxxx.com.au/public_html/lsitfiles.php ?
<?php

$dir_name = "c:/";

$dir = opendir($dir_name);

$file_list = "
";

while ($file_name = readdir($dir)) {
    if(($file_name != ".") && (file_name != "..")) {
    $file_list .= "
$file_name";
                               }
}

$file_list.= "
";

closedir($dir);

?>

Files in: <? echo "$dir_name"; ?>

<? echo "$file_list"; ?>

A: Depends which folder you want to scan.
Obviously, you cannot scan any folder on client's computer. I guess you know that.
If you want to scan folder where the script resides it's best to use:
$dir_name = dirname(__FILE__);

A: $dir_name is the folder you want to scan. Where you upload your script, you can specify the folders there from using absolute or relative paths upward and backward eg ../foldername or myfolder/myfolder2.

A: Depends on OS. In Linux it would be '/'.
P.S. If server is configured properly, you should not be able to read '/' (or 'c:/').


text:
Q: TypeError : tan^-1 (tan inverse) of the ratio of two dataframe column I have two dataframe columns "vibration_X" and "vibration_Y".Also I have few zero values in some columns. I want to create new column "theta" which would be the ratio of tan inverse of vibration_Y and vibration_X.
Below is my sample data:
     vibration_Y  vibration_X
0           10            7
1           10            8
2            9            8
3           10           11
4           13            5
5            3            0
6           12            8
7           12            9
8           11           10
9           10           11

Below is my code that I have tried and for which I am getting error:
df['theta'] = math.atan(df['vibration_Y']/df['vibration_X'].astype(float))

TypeError: cannot convert the series to class 'float'

A: I believe you need numpy.arctan:
df['theta'] = np.arctan(df['vibration_Y']/df['vibration_X'])
print (df)
   vibration_Y  vibration_X     theta
0           10            7  0.960070
1           10            8  0.896055
2            9            8  0.844154
3           10           11  0.737815
4           13            5  1.203622
5            3            0  1.570796
6           12            8  0.982794
7           12            9  0.927295
8           11           10  0.832981
9           10           11  0.737815


text:
Q: How did the original and final "City on the Edge of Forever" scripts differ? I remember reading in, I believe, The Making of Star Trek, how Harlan Ellison was quite upset with Gene Roddenberry over the rewriting Roddenberry did on Ellison's script The City on the Edge of Forever.  He was so upset that, while waiting in the outer office, he supposedly picked up some cord or twine that was nearby, fashioned a hangman's noose, threw it over a pipe running through the room just under the ceiling and, when Roddenberry walked out of his office, Ellison pointed at the noose and said, "Tell me it's not true someone re-wrote my words."
I remember reading comments by Roddenberry that included him saying, "He had Scotty selling drugs," and that the original script had Kirk and Spock arrive in the middle of worker riots and that many other parts made the script too expensive.
I also remember an interview (I think it was in the photo-novel) where Ellison made some comment like, "If they loved the version that aired, they would have been crazy over the original."
How did Ellison's original script differ from the final version that we saw on screen?

A: As summarized in the Wikipedia entry, the script went through many rewrites; apart from the info already available in Memory Alpha, here is Harlan Ellison on the subject, as quoted in the oral histories included in the 2016 book by Mark A. Altman & Edward Gross, The Fifty-Year Mission: The Complete, Uncensored, Unauthorized Oral History of Star Trek - The First 25 Years:

The idea of "City" came from the image of the City on the Edge of Forever, and it was an image of two cities, which is what it says in the script. The City on the Edge of Forever is the city on this planet. It was not a big donut in my script; it was a city. That was a city that was on the edge of time, and it was where all of the winds of time met. That was my original idea. All the winds of time coalesce, and when you go through to the other side, here is this other city which is also on the edge of forever, which is New York during the Depression. They're the mirror image of each other. In that time, all I was concerned about was telling a love story. I made the point that there are some loves that are so great that you  would sacrifice your ship, your crew, your friends, your mother, all of time, and everything in defense of this great love.
That's what the story was all about. All of the additional stuff that Gene Roddenberry kept trying to get me to put in, kept taking away from that. The script does not end the way the episode does. Kirk goes for her to save her. At the final moment, by his actions, he says, "Fuck it. I don't care what happens to the ship, the future, and everything else. I can't let her die. I love her," and he starts for her. Spock, who is cold and logical, grabs him and holds him back and she's hit by the truck.
The TV ending, where he closes his eyes and lets her get hit by the truck, is absolutely bullshit. It destroyed the core of what I tried to do. It destroyed the art; it destroyed the drama; it destroyed the extra human tragedy of it.

A: I don't have my copy of David Gerrold's book about making The Trouble With Tribbles, but I think it's covered in there, as well.
Wikipedia has a good explanation that matches what I recall reading about Ellison's version.
One thing I recall from Gerrold's book that makes sense to me is that the differences in characterization and in the overall "feel" of the Federation and Starfleet were too extreme.  It wouldn't have fit with the rest of the series.

A: In Ellison's original script it wasn't McCoy who went back and changed history; it was a crew member who was a murderer and drug dealer. After history was changed, there was a scene in which they beamed back up to the ship and found themselves in an alternate timeline(I've heard that this was Roddenbery's idea). In Ellison's version the captain froze at the crucial moment and it was Spock who prevented Keeler from being saved. It was the villain of the episode who tried to save her, which seemed out of character for him. There was a maimed World War I veteran who died saving Kirk's life and there was a reference to American racism and nativism.


text:
Q: How to get the link of "Edit site" button of ecwid I am using ecwid store. I want to put a button in my portal (my website) to do the same action as the "Edit site" button:

My question is, is there any api to get the URL of the action of this button?
Thank you

A: This is Lance, Ecwid Apps&API Support team. Thanks for your question!
Basically, we don't have a direct API for getting the URL of the action of the "Edit Site" button.
This button just redirects you to the editor's page via such a link: https://my.ecwid.com/edit-starter-site?ownerid={StoreID}&lang={Language}
Where:

*

*{StoreID} is replaced with your store ID,

*{Language} is replaced with the two-signs value (for example, en for English) of the needed language of the website editor.

Just in case, we also have many opportunities to customize the design and layout. You can find out more about them here: https://api-docs.ecwid.com/reference/customize-appearance.
Also, feel free to reach out to us via our email ec.apps@lightspeedhq.com if you have any questions, we'll be happy to help!


text:
Q: insert record in one table by copying single row of a single column from another table I have a table SEND with one column Aname:
Aname
------
GREAME
PETER

Another table RECEIVE with 2 columns:
Aname                              Permission
-----------------------------------------------
GREAME (copied from table SEND)    'my own value will be inserted here,
                                    specified in insert query'

PETER  (copied from table  SEND)    'my own value will be inserted here,
                                    specified in insert query'

Now as shown above, I want to insert into a new table RECEIVE only the Aname column  from table SEND and in the second column I would insert a new value.
Also, I want that no duplicate values could be inserted in RECEIVE table:
I want this:
Aname   Permission
---------------------
GREAME  PLAYER
GREAME  PLAYER --- COULD NOT BE INSERTED
GREAME  SALESMAN   --- COULD BE INSERTED

I am using this query :
insert into receive(Aname, Permission)
  select Aname , 'Select'
  from SEND
  where not exists
     (select * from RECEIVE where Aname = 'GREAME' and Permission = 'select')

This query takes both the names GREAME & PETER from the SEND table and  inserts them into the RECEIVE table, but I want that only GREAME is picked up, not PETER.
How do I do it?
IT TAKES ALL THE ROWS FROM TABLE SEND, and inserts them in table RECEIVE, but I want that only one row gets inserted. So I want the query to be like this but it gives syntax error:
insert into RECEIVE(Aname , Permission)
  select Aname , 'select'
  from SEND
  WHERE Aname = 'GREAME'  -------------this line gives error
  where not exists
    (select *  from RECEIVE where aname = 'GREAME' and Permission = 'select')

A: You can't have two WHERE clauses in one statement:
insert into RECEIVE(Aname , Permission)
  select Aname , 'select'
  from SEND
  WHERE Aname = 'GREAME'   <=== WHERE #1
  where not exists         <=== WHERE #2
    (select *  from RECEIVE where aname = 'GREAME' and Permission = 'select')

You need to change the second part to an AND:
insert into RECEIVE(Aname , Permission)
  select Aname , 'select'
  from SEND
  WHERE Aname = 'GREAME'
  AND not exists
    (select *  from RECEIVE where aname = 'GREAME' and Permission = 'select')


text:
Q: Logarithmic accuracy Does anyone know how the method of logarithmic accuracy works and what do I have to know about it (as far as applied Mathematics is concerned)? Any references, examples or guidelines would be appreciated.
Thank you

A: A quantity is said to be calculated "to logarithmic accuracy" when in an expansion like
$$
F(\varepsilon) = c \sum_{n=2}^{\infty} A^n \sum_{m=2}^{n} a_{n,m} \ln^{n-m}(\varepsilon/E) ~,
$$
only the coefficients $a_{n,m}$ associated with the most divergent terms are calculated exactly while the coefficients for $m>2$ are determined by an approximation procedure.
ref: Duke, C. B., and S. D. Silverstein,
"Does Logarithmic Accuracy Uniquely Define the Low‐Temperature Properties of Dilute Magnetic Alloy Systems?", J. Appl. Phys. 39 (1968) 708, http://dx.doi.org/10.1063/1.2163592 .
As a side remark, infra-red divergence, i.e., divergence of calculated physical quantities at low energy/momentum/temperature scales, is a widely known (and perhaps, ubiquitous) issue in current-day condensed matter physics, and has many important consequences.

In models of condensed matter physics, ultraviolet divergences present
  not a problem but a nuisance. Their presence indicates that the
  continuum description is incomplete, i.e. the behaviour of
  long-wavelength excitations depends on shorter length scales. ... .
  Infrared divergences are more interesting. Their appearance is always
  an indication of an incorrectly chosen reference ground state. For
  example, if electrons in a metal attract, it is wrong to approximate
  them as free particles; the real ground state is a superconducting
  condensate of electron pairs. This ground state is orthogonal to the
  ground state of the non-interacting electron gas and therefore is
  unreachable by a perturbation expansion. There is no universal recipe
  for how to choose a correct ground state. Sometimes it is relatively
  easy (as for ordinary superconductors), sometimes it is not easy at
  all.

[Tsvelik, A. M. Quantum field theory in condensed matter physics. Cambridge University Press (2006), p. 48]


text:
Q: mod_deflate: 'Vary' header not set but unsettable for .css and .js files I'm setting a website hosted on Apache/2.2.17. I don't have access to apache's installation directory nor httpd.conf file (just www folder with eventually some .htaccess files).
I've got gzip compression enabled but .css and .js (the others files than images and .php files I've tested so far) response doesn't have got the Vary: Accept-Encoding header as expected even if they have the Content-Encoding: gzip header.
I can't force it via .htaccess file with Header set Vary Accept-Encoding nor Header append Vary Accept-Encoding with or without semi-colon after Vary (I can't even append User-Agent to it).
Thanks.
UPDATE:
Here's my .htaccess file
ErrorDocument 404 404.php

# Permissions
Order Allow,Deny
Allow from all
RedirectMatch 403 /(data|private)/

# Index
DirectoryIndex index.php
Options -All

# Set/Add Headers
AddDefaultCharset utf-8
Header set Cache-Control no-store
Header set Connection keep-alive

Header set Vary Accept-Encoding
SetEnvIfNoCase Request_URI "\.php" mvary
Header append Vary User-Agent env=mvary

# Remove Headers
ExpiresActive Off
FileETag None
Header unset ETag
Header unset Expires
Header unset Last-Modified
Header unset Pragma
Header unset X-Powered-By

Here are loaded modules:

core mod_authn_file mod_authn_default mod_authz_host
  mod_authz_groupfile mod_authz_user mod_authz_default mod_auth_basic
  mod_dbd mod_include mod_filter mod_log_config mod_env mod_expires
  mod_headers mod_setenvif mod_version prefork http_core mod_mime
  mod_status mod_autoindex mod_asis mod_info mod_negotiation mod_dir
  mod_actions mod_alias mod_rewrite mod_so mod_php5 mod_ruid2
  mod_deflate mod_remoteip mod_binary mod_tonyscanner

A: mod_deflate won't compress non-html file that are too "light", but CloudFlare will (without always? adding the Vary: Accept-Encoding header).


text:
Q: Is there an equivalent (or close) to numpy.loadtxt for julia? I'm trying to convert some of my python programs over to julia and one requires that I take in a values in the shape of a matrix from a txt file, then proceed to use the matrix for multiplication and such.
So is there any better way to input from a file and load a matrix in julia besides iterating over lines or character by character?
For example, a text file would look like
5 9
10 3

so my matrix would then be
[[5,9],
 [10,3]]

which I'd then use to multiply other matrices, etc.
I just got started with julia this week so I'm still doing my best to comb through the library and MIT sources. So far my best idea (assuming there is no equivalent to numpy.loadtxt) would be to load line by line into an array then just reshape it afterwards, but I want to make this as efficient as possible and that seems like a slow and not clean way of importing it.

A: Try Readdlm(). Check this article for more details
julia> file="23 12 13 22
       15 61 17 10
       1 0 11 12"

You can read and transform it to an array readdlm(IOBuffer(file)), u can also force the array's items to be integers this way readdlm(IOBuffer(file),int)
julia> readdlm(IOBuffer(file))
3x4 Array{Float64,2}:
 23.0  12.0  13.0  22.0
 15.0  61.0  17.0  10.0
 1.0   0.0   11.0  12.0

A: The CSV.read() function can also be used to read delimited files. The advantage of CSV.read() over readdlm() is that the CSV.read() is much faster for large files. To read, for example, the following,
julia> file =
       """
       23 12 13 22
       15 61 17 10
       1 0 11 12
       """

The code would be,
julia> CSV.read(IOBuffer(file),delim=" ",ignorerepeated=true,header=false)
3×4 DataFrames.DataFrame
│ Row │ Column1 │ Column2 │ Column3 │ Column4 │
│     │ Int64   │ Int64   │ Int64   │ Int64   │
├─────┼─────────┼─────────┼─────────┼─────────┤
│ 1   │ 23      │ 12      │ 13      │ 22      │
│ 2   │ 15      │ 61      │ 17      │ 10      │
│ 3   │ 1       │ 0       │ 11      │ 12      │

For small files, readdlm() is faster.
julia> using BenchmarkTools

julia> @btime CSV.read(IOBuffer(file),delim=" ",ignorerepeated=true,header=false);
  68.197 μs (185 allocations: 14.80 KiB)

julia> @btime readdlm(IOBuffer(file));
  2.465 μs (20 allocations: 40.70 KiB)

But for larger files, CSV.read() is much faster and efficient.
julia> @btime CSV.read(IOBuffer(file^100000),delim=" ",ignorerepeated=true,header=false);
  32.027 ms (230 allocations: 3.26 MiB)

julia> @btime readdlm(IOBuffer(file^100000));
  142.187 ms (3600025 allocations: 116.44 MiB)

It can be converted to an array as,
julia> dffile = CSV.read(IOBuffer(file),delim=" ",ignorerepeated=true,header=false);

julia> convert(Matrix, dffile)
3×4 Array{Int64,2}:
 23  12  13  22
 15  61  17  10
  1   0  11  12

Many other customizations can be done for reading different types of files and are detailed in the documentation.


text:
Q: How do I redirect a url with parameters How do I redirect a url with parameters
I will like to write this url:
http://mydomain.com/dk/silkeborg?latitude=56.1631229&longitude=9.536976500000037&zoom=14

and redirect it to
http://mydomain.com/index.php?country=dk&city=silkeborg&latitude=56.1631229&longitude=9.536976500000037&zoom=14

To day I use the below rule, that don't take any parameters
RewriteRule (dk|de)/(.*)  index.php?country=$1&city=$2 [NC]

Please help me

A: You do need to use [QSA] because you're rewriting the query (it's enabled by default unless you rewrite the query). Here we're capturing the country code and passing it as a var. Then QSA is catching the rest of the variables and adding them to the query string.
RewriteCond %{REQUEST_URI} ^/(dk|de)/ [NC]
RewriteRule .* index.php?country=%1 [QSA,L]

To use your existing rule, you would append [QSA]
RewriteRule (dk|de)/(.*)  index.php?country=$1&city=$2 [QSA,NC,L]

When the page loads you can access the country via $_GET['country'] and city via $_GET['city'].


text:
Q: Firebase Realtime Database - Wait for multiple queries to finish I am working with the Firebase Realtime Database and would like to collect all the "notes" I have access to - ie. where I am listed as "author" or invited "member".
My database structure illustrated below.

I am currently using the below code to fetch all "notes" I have access to.
return new Promise( (resolve, reject) => {
  try{
    let notes = []

    //Get notes where I am author : uid = my user uid
    database.ref('notes')
    .orderByChild("access/author")
    .equalTo(`${uid}`)
    .on('value', (snapshot) => {
      snapshot.forEach( (childSnapshot) => {
        const note = {
          id: childSnapshot.key,
          ...childSnapshot.val()
        }
        notes.push(note)
        })
      })

    //Get notes where I am member
    database.ref('notes')
    .orderByChild(`access/members/${uid}`)
    .equalTo(true)
    .on('value', (snapshot) => {
      snapshot.forEach( (data) => {
        const note2 = {
          id: data.key,
          ...data.val()
        }
        notes.push(note2)
      })
    })
    //Return all notes
    resolve(notes)
  } catch(e) {}
})

The code does not work. The resulting array does not include notes where I am listed as "member". I suspect the reason being that the database calls are synchronous - they do not wait to be completed before returning the array of all notes.
How can I make sure all notes are fetched before resolving the array?
Kind regards /K

A: You are actually dealing with two promises here, which is one reason that your code won't work. Promises are just context wrappers around asynchronous actions. You have two unrelated synchronous actions (your two database calls), so you'll want those to be wrapped separately.
Start by splitting your code into separate promises, and move your resolve statement into the "on" method of your db call, so that it doesn't get processed before the database call is finished:
const promise1 = new Promise( (resolve, reject) => {
    let notes = []

    //Get notes where I am author : uid = my user uid
    database.ref('notes')
    .orderByChild("access/author")
    .equalTo(`${uid}`)
    .on('value', (snapshot) => {
      snapshot.forEach( (childSnapshot) => {
        const note = {
          id: childSnapshot.key,
          ...childSnapshot.val()
        }
        notes.push(note)
        })
      })
      resolve(notes);
});

const promise2 = new Promise( (resolve, reject) => {
  try{
    let notes = [];

    //Get notes where I am member
    database.ref('notes')
    .orderByChild(`access/members/${uid}`)
    .equalTo(true)
    .on('value', (snapshot) => {
      snapshot.forEach( (data) => {
        const note2 = {
          id: data.key,
          ...data.val()
        }
        notes.push(note2)
      })
      resolve(notes);
    });
})

Then, what you really want here is to resolve the value you get back from the call. Meaning that when this promise is resolve, it collects that value.
Now put your promises in an array, and use Promise.all to wait for both of those to happen.
Promise.all([
  promise1,
  promise2,
]).then(twoNotesArrays => { //[ [notesFromPromise1], [notesFromPromise2] ]
  console.log(notes[0].concat(notes[1])); //[all notes]
});


text:
Q: Proving bijection between homotopy classes of clutching functions and vector bundles I am reading Hatcher's book on Vector Bundles and K-Theory(freely available online). I am reading about clutching functions in the first chapter and there is a step in the proof of Proposition 1.11 (p.23) that I don't understand. In order to be concrete I introduce a capture:

I summarize the steps of the proof (as I understand them):

*

*In order to show there is a bijection we will construct and inverse $\psi$ to $\phi$. Remember that $p\colon E\to \mathbb{S}^k$ is our vector bundle.

*Given two trivializations (given by the two hemispheres) $h_+\colon E_+ \to D^k_+\times \mathbb{C}^n$ and $h_-\colon E_- \to D^k_-\times \mathbb{C}^n$, we define
$$\psi(E)\in [\mathbb{S}^{k-1},GL_n(\mathbb{C})]$$
to be the homotopy class of the map $\mathbb{S}^{k-1}\to GL_n(\mathbb{C})$ defined by $${h_+}\circ {h_-}_{|\partial D^k_- \times \mathbb{C}}={h_+}\circ {h_-}_{|\mathbb{S}^{k-1} \times \mathbb{C}}$$

*We have to prove that the map $\psi$ is well-defined and that $\psi$ and $\phi$ are inverses to each other.

My problems arise when trying to prove that $\psi$ is well-defined. So let's begin and I will point out the step I don't understand:

*

*Given other trivializations over the hemispheres $h'_+\colon E_+ \to D^k_+\times \mathbb{C}^n$ and $h'_-\colon E_- \to D^k_-\times \mathbb{C}^n$, we define $$\psi(E)\in [\mathbb{S}^{k-1},GL_n(\mathbb{C})]$$ to be the homotopy class of the map
$$\mathbb{S}^{k-1}\to GL_n(\mathbb{C})$$
defined by
$${h'_+}\circ {h'_-}_{|\mathbb{S}^{k-1} \times \mathbb{C}}$$
We have to check that the two maps:
$${h_+}\circ {h_-}_{|\mathbb{S}^{k-1} \times \mathbb{C}}$$
$${h'_+}\circ {h'_-}_{|\mathbb{S}^{k-1} \times \mathbb{C}}$$

are homotopic. And here is where I lost Hatcher's argument. I see that both $h_+\colon E_+ \to D^k_+\times \mathbb{C}^n$ and $h_-\colon E_- \to D^k_-\times \mathbb{C}^n$ are unique up to homotopy. But in order to prove that
$${h_+}\circ {h_-}_{|\mathbb{S}^{k-1} \times \mathbb{C}}$$ is unique up to homotopy I think I need to show that the restrictions of the trivializations:
$${h_+}_{|\partial D^k_+ \times \mathbb{C}}$$
$${h_-}_{|\partial D^k_- \times \mathbb{C}}$$
are unique up to homotopy and here the argument provided does not work since the domains of the restriction are not contractible.
I am sure that there is something here I don't understand properly. So any clarification, explanation or help would be appreciated. Thanks!

A: It is explained here. The key step is to use the notion of equivalent cocycles.


text:
Q: input text type alter height if exceed width size Im not sure if this is a javascript fix or CSS Im happy with either, no jquery please.
The problem is that some of my input text value is larger than the width set to it. how can i auto size the height so that it continue to display the text in the next line?
<input type="text" value="Hi ssfgsdg dgd gdf bdf bdf bdfb fb fb fb fb fb" readonly class="lbl-txt">

output: Hi ssfgsdg dgd gdf bdf
.lbl-txt{
width: 250px;
height: auto;
white-space: normal;
overflow: hidden;
color: ghostwhite;
font-size: 20px;
background-color: rgba(0,0,0,0);
border: none;
margin-left: 5px;
}

I need it to be Input Type text.

A:
how can i auto size the height so that it continue to display the text in the next line?

You can't with an <input>.
Use a textarea insead, that is meant for multiline input: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea
<textarea name="...">default value</textarea>


text:
Q: HTML/CSS Markers using Google Maps Javascript API v3 Our company just moved from Leaflet.js to the Google Maps API; I've search high and low trying to find a simple way of integrating HTML/CSS Markers/Boxes as overlays into the Google Maps Javascript API v3.
So far, i've found this tutorial: https://developers.google.com/maps/documentation/javascript/overlays#CustomOverlays
Nevertheless, I find it extremely clunky and I haven't been able to inject HTML/CSS code successfully into the map.
Does anybody know of an easier way of adding HTML/CSS Markers/Boxes unto Google Map?
I could go ahead and hack the map by assigning top/left coordinates to divisions and then attach them to the map with jQuery to markers on google map, but this is a workaround/hack and there must be a simple way of integrating these.
Thanks in advance!

A: To save readers' time, I provide demo-purpose website here
For this question. Basically, to add HTML/CSS customized markers, I suggest implementing one subclass of OverlayView with the help of some external library.

*

*First I need to clarify why you should inherit OverlayView class.

*Second I need to demonstrate why an external library might help.

Okay. First, The google.maps.Marker class extends MVCObject. The OverlayView class also extends MVCObject. To make your HTML/CSS implemented customized marker behave normally and resemble one google.maps.Markerat behavioral and event-communication level (but not visual level), extending OverlayView class is one safe way, since constructing one instance of OverlayView will somehow "register" the instance itself to the internal map events management. I will explain how this "registration" happened below.
In order to extend OverlayView, you need to override three methods, onRemove() onAdd(), draw().  The purpose of overriding draw() is that, this method is intrinsically bound to several google map events, such as zoom_changed. The purpose of draw() is to redraw the dom element, make it appear at right position of map canvas, and have it correctly sized on map canvas. For example, one google.maps.Marker redraws itself every time when user zoom in or zoom out the map.  Additionally, there are many different situations that will trigger draw()
Similarly, onAdd() is invoked when tiles of map are ready, onRemove() is invoked when setMap() is invoked. There is a series of events being listened by these three methods.  This is how "registration" happens in my point. This also explains why extending class OverlayView is one safe way to implement your HTML/CSS customized marker. Because you do not need to deal with map events listening yourself when you extending OverlayView. Otherwise, you have to.
Specifically to this question, "to implement one custom maker", you need to do things described above also.
On the "custom OverlayView example" given in your question. I can tell you what you need to change to make it behave like one marker.
In that example. the css left and top, and width is determined by pre-defined google.maps.Bounds, you should change this. You need code like following:
    CustomMarker.prototype.draw = function(){
      var overlayProjection = this.getProjection();
      // console.log("draw" + this.latLng);
      var anchor = overlayProjection.fromLatLngToDivPixel(this.latLng);

      if (this.dom_) {
        this.dom_.style.top = (Math.round(anchor.y- this.height_)).toString()+'px';
        this.dom_.style.left = Math.round( anchor.x - this.width_ / 2).toString() + 'px';
        $(this.dom_).outerWidth(this.width_); // I need to have this jQuery method
      }

      // generally, the dom node left-top corner should not be generated at clicking poistion, but with offsets of both left and top
    };

Also you need to handle so called "dom events" by addDomListener() method provided by google maps API. Why they are "so-called" events?
Because, to make the HTML nodes attached to marker instances of the extended "OverlayView" class be able to respond to user behaviors (I am not calling browser events here) like "clicking" "double clicking", developer should append the nodes to pane `overlayMouseTarget".
The reason is that, actually above overlayMousetarget pane, there are several other  non-zero width none-zero height map HTML nodes, which "shadowed" our custom marker node added to the DOM tree. So our marker CANNOT directly receive browser events like onclick, even if you have implemented the DOM event handler functions for it. They are "deaf".
So the purpose of appending our customized Marker to overlayMouseTarget pane(node) is that, Google Maps has its own mechanism for how to process received outmost browser events. Google map process them, and then notify those nodes appended to google map mangaged panes(those five nodes: floatPane mapPane markerLayer overlayLayer overlayMouseTarget)
Now you can understand why I am calling the "so-called" events when you invoking "addDomListener()". Because the original "click" browser event never reached our poor markers, instead, it responds to "click" action by listening to one internal google map event which is trigger by outmost original "click" browser event.
Now, lets focus one the second point:
"I need to demonstrate why an external library might help"
You have to handle different google map dom listeners to complete tasks originally you can do with several lines of CSS code.
For example, to realize pseudo class hover, you need to implement handler of mouseover mouseout and so on, do some CSS classes adding and removal.
With external library such mapcover.js, you can just set("mouseover": function cb() {  /*your implementations here*/}).
Have written so much, I will just show one demo here:
http://easysublease.org/mapcoverjs/
The detailed implementations how you can create your HTML markers can be found here

A: You might want to check google.maps.InfoWindow (https://developers.google.com/maps/documentation/javascript/overlays#InfoWindows) and the google.maps.Marker (https://developers.google.com/maps/documentation/javascript/reference#Marker) of google maps. Any CSS you apply on the page will be applied to the InfoWindow as well.


text:
Q: RequireJS Optimizer from mainConfigFile not working I am using grunt-requirejs and my app structure looks like this:
site/
  dev/
    index.html
    config.coffee
    app.coffee
    etc.
  srv_dev/
    index.html
    config.js
    app.js
    etc.
  dist/
  node_modules/
  Gruntfile.coffee

When I run grunt dev files get compiled to js from coffee among other tasks and copied from dev/ to srv_dev/ and then are served from there.
My grunt dist task does what dev does and then runs a requirejs task, which, I hope, should compile / combine all the main dependancies of my app, but still allow for require(somevar) and define calls to run later on. Basically I have some parts of my single-page app which dont load until the user clicks on the link to it, which fires off a requrire() and define() call.
My current problem seems quite basic... I have set up my requirejs grunt task as follows:
requirejs:
  options:
    baseUrl: './'
    mainConfigFile: 'srv_dev/config.js'
  dist:
    options:
      out: 'dist/script.js'

This throws Error: Error: Missing either a "name", "include" or "modules" option
I have read most of the optimizer docs as well as the example build file and don't understand what is going on with this error. tkellen in this project uses the name option for almond.js -- but I don't think I want to do that, because I need those lazy - loader require() calls. The example build file states: "Just specifying a module name means that module will be converted into a built file that contains all of its dependencies." So that was my next attempt:
requirejs:
  options:
    baseUrl: './'
    name: 'srv_dev/config.js'
  dist:
    options:
      out: 'dist/script.js'

With this I get Error: ENOENT, no such file or directory >> '/Users/user/Desktop/project/site/app.js'
So it finds config.js, but then can't find the paths listed in the config, because it using the baseUrl of the require.js config.
And if I specify the baseUrl of './srv_dev' in the requirejs task config then it cant find my config.js file. I have tried a variety of paths to get this to work with no luck. I think the gruntfile needs to be in the same dir as the config.js file, but thats not how my project is set up.
Thanks Folks !!!
Here is the full text of my config.coffee file
config =

  baseUrl: './'

  paths:
    # require plugins
    text             : '/components/requirejs-plugins/lib/text'
    json             : '/components/requirejs-plugins/src/json'

    # lib
    jquery           : '/components/jquery/jquery'
    bootstrap        : '/components/bootstrap/dist/js/bootstrap'
    lodash           : '/components/lodash/dist/lodash'
    backbone         : '/components/backbone/backbone'
    marionette       : '/components/marionette/lib/backbone.marionette.min'
    handlebars       : '/components/handlebars/handlebars'
    prism            : '/components/customPrism/prism'
    coffeescript     : '/components/coffee-script/extras/coffee-script'

    # app
    app              : '/app/app'
    appSettings      : '/app/appSettings'
    AppController    : '/app/AppController'
    AppRouter        : '/app/AppRouter'

    postMasterRecord : '/posts/postMasterRecord'

    util             : '/scripts/util'
    templates        : '/templates'
    handlebarsHelpers: '/scripts/handlebarsHelpers'

  shim:
    # lib
    bootstrap:
      deps: ['jquery']
    backbone:
      deps: ['lodash', 'jquery']
      exports: 'Backbone'
    marionette:
      deps: ['backbone', 'lodash', 'jquery']
      exports : 'Marionette'
    handlebars:
      exports: 'Handlebars'
    templates:
      deps: ['handlebars']

    # app
    app:
      deps: [
        'marionette'
        'bootstrap'
        'handlebars'
        'templates'
      ]

  # deps: ['app']

require.config(config)

require(['app'])

A: It is perfectly acceptable to specify the same file as your mainConfigFile and for name so:
requirejs:
  options:
    mainConfigFile: 'srv_dev/config.js'
    baseUrl: './srv_dev'
    name: 'config'
    findNestedDependencies: true
  dist:
    options:
      out: 'dist/script.js'

mainConfigFile tells r.js "here is where you can find my runtime configuration", whereas name says "here is my main module". One does not imply the other.
Without mainConfigFile r.js cannot find your runtime configuration. Without name (or include or modules), it cannot know what the entry point of your application is.
findNestedDependencies: true is required for r.js to follow the require([app]) in your config.js file.


text:
Q: a simple program to sort random numbers i just made a simple program that sorts random numbers in order:
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;

void swap(int &a,int &b){
    int temp=a;
    a=b;b=temp;
}

int main(int argc, char* argv[]){
    static int option;
    if(argv[1])option=atol(argv[1]);
    else option=0;
    srand((unsigned)time(0));
    const int size=option;
    int array[size];
    for(int i=0;i<size;i++){
        array[i]=rand()%size;
    }

    //algorithm
    for(int i=0;i<size;i++){
        for(int j=i+1;j<size;j++){
            if(array[i]>array[j])swap(array[i],array[j]);
        }
    }
    //print
    for(int i=0;i<size;i++){
        cout<<array[i]<<' ';
    }
    return 0;
}

you run it like this:
time ./a.exe (how much random number to generate)

it works fine upto 100000, but more than that gives me a seg fault error.
what am i doing wrong? is it because of insufficient memory??? or is the OS secretly doing something im not acknowledged of??

A:
"is it because of insufficient memory??"

Yes, your stack size is probably too small to hold this. Use
std::vector<int> array(size);

instead of
int array[size];

A: Yes, your stack size is too small, you can allocate the array in the heap like: int *array = (int*)malloc(size*sizeof(int)). Of course, you can use vector, but the vector has more complex encapsulation so the performance will be not very good.


text:
Q: How to POST backbone model data to DB through Slim php and Paris I'm trying to get an understanding of how Backbone.js, Slim PHP and Paris/Idiorm might work together and I'm having trouble completing the flow, starting with model attribute data, all the way to the database. PROBLEM: What exactly gets sent to my server when I do model.save() ?
Client-side: Backbone.js
var Donut = Backbone.Model.extend({
    defaults: {
        name: null,
        sparkles: false,
        creamFilled: false
    },
    url: function() {
        return '/donut';
    }
});

var bostonCream = new Donut({
    name: 'Bawston Cream',
    sparkles: true,
    creamFilled: true
});

bostonCreme.save();  // <-- Problem: Not sure what & format this is sending

I think the above is my main problem. My understanding is that backbone will by default, know to send POST data since it's new. It sends it to /donut which is routed, but the question I have is WHAT does it send? And in what format? The outcome I want is to save those donut attributes to my DB. I can pass this server-side code a json like this using jQuery $.post()...
var myDonut = {"name":"Jelly Filled", "sparkles":false, "creamFilled":true};
$.post('http://localhost/donut', myDonut);

...and it happily takes it, saves it to my database. But with the current setup trying to send my backbone donut data, I get POST 500 Internal Server Error. Below I have some server-side code.
Server-side: Slim PHP w/ Paris
class Donut extends Model {}

$app->post('/donut', function() use ($app) {  // Slim framework routes my POST...

    $donuts = Model::factory('Donut')->create();  // Paris stuff...

    $donuts->name = $app->request()->post('name');  // Slim request parameters...
    $donuts->sparkles = $app->request()->post('sparkles');
    $donuts->creamFilled = $app->request()->post('creamFilled');

    $donuts->save();   // Paris... Save name, sparkles, and creamFilled to my DB
});

I have a feeling the answer is out there, but every example I've looked at seems to be missing one piece of the puzzle or another and I can't get that "A-hA!" moment. I thank you in advance and apologize if this is a really ignorant question. :-P
FOLLOWUP/EDIT: 1

Can you paste the error messages?

I get a POST http://localhost:8888/donut 500 (Internal Server Error) in the current state. I can get more information with the following code.
bostonCream.save({}, {  // REPLACE bostonCream.save();
    success: function(model, response) {
        console.log('SUCCESS:');
        console.log(response);
    },
    error: function(model, response) {
        console.log('FAIL:');
        console.log(response);
    }
});

Now when I run backbone's save(), I still get the 500 Error but also XMLHttpRequest as my FAIL response. The only remarkable clue from the XMLHttpRequest is responseText = SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'name' cannot be null.
So my guess is that either 1) I'm messing something up with the save() in that it isn't capturing my attributes correctly, 2) It is currently sending my attributes in a format that my server isn't recognizing with the standard $app->request()->post() Slim methods (Doesn't seem to do much when I try accessing directly with $_POST either), 3) My server isn't setup correctly to take the kind of data that is being sent.
Another thing I noticed although I don't know what to make of it is that when I add
echo $_POST;

It returns to me an empty array. Still gives me the FAIL. If I do THIS however...
echo json_encode($_POST);

It gives me a SUCCESS and the response is a [ ]. Nothing in there. Clearly my POST data is still wonky.

A: I came up with a solution to completing the problem: how to get data from client to server using the default backbone save() and .sync - passed over to the Slim php framework and going through Paris/Idiorm to my DB.
I am including my working updated code below:
Client-side: Backbone.js
var Donut = Backbone.Model.extend({
    defaults: {
        name: null,
        sparkles: false,
        creamFilled: false
    },
    url: function() {
        return '/donut';
    }
});

var bostonCream = new Donut({
    name: 'Bawston Cream',
    sparkles: true,
    creamFilled: true
});

bostonCream.save();

/***** If you want to check out the response to save() ? ***
bostonCream.save({}, {
    success: function(model, response) {
        console.log('SUCCESS:');
        console.log(response);
    },
    error: function(model, response) {
        console.log('FAIL:');
        console.log(response);
    }
});
************************************************************/

Sever-side: Slim PHP w/ Paris/Idorm
class Donut extends Model {}

$app->post('/donut', function() use ($app) {

    $donuts = Model::factory('Donut')->create();

    /* EDIT: Works... but not the Slim way
    $parameters = json_decode(file_get_contents('php://input'), true);
    $donuts->name = $parameters['name'];
    $donuts->sparkles = $parameters['sparkles'];
    $donuts->creamFilled = $parameters['creamFilled']; */

    /* SLIM: Using Slim Request Object */
    $requestBody = $app->request()->getBody();  // <- getBody() of http request
    $json_a = json_decode($requestBody, true);
    $donuts->name = $json_a['name'];
    $donuts->sparkles = $json_a['sparkles'];
    $donuts->creamFilled = $json_a['creamFilled'];

    $donuts->save();

    // echo json_encode($parameters); // Prove you've captured POST data, send it back
}

Now my code is happily using the default settings of Backbone.js (no changes to sync) and sending proper model attribute information to my server which seems to be successfully accepting the data and saving it to my DB.
The key here seems to be this line...
/* $parameters = json_decode(file_get_contents('php://input'), true); */
// EDITED: getBody() method not documented in Develop Doc, only Stable @ time of post

$requestBody = $app->request()->getBody();

A: If you want to know "what exactly is sent to the server", you should have a look at the Backbone.sync function in Backbone's code. It is very well documented, step-by-step. Then, the cleanest way to achieve what you need is to write you own sync function, inspired by Backbone's sync.
Also, a quick way to see what is sent to the server is to use your browser debug console (Network tab). You can compare here what is sent by Backbone vs. what is sent when you use $.post directly. Please post this information if you need more help !

A: backbone sends json data to your php backend server, which you should expose your RESTful api to respond to http verb like get, post, put, delete and etc.
your backend api is responsible for communicating with database.
I am not sure about SLIM PHP. it seems to handle the request. Can you paste the error messages?


text:
Q: Framerate in command line usage of Compressor I use Apple compressor from the command line to generate video clips from sequences of images. Here
https://support.apple.com/en-gb/guide/compressor/cpsr9be73312/mac
it looks like the command line command allows for control of the framerate of the output movie, but I can't get things to work. Does anyone know how to do this?

A: So
Compressor -jobpath file:///path_to_png_directory?frameRate=60

does the trick.


text:
Q: How does using char(17) as primary key to store VIN numbers in a table with SQL Server affect performance? I am designing a database with a table to store vehicles and since the vehicle identification number is a 17 digit alphanumeric serial number my idea is to use it as the primary key, with a datatype of char(17).
Numerous other tables will then have the VIN as a foreign key.
A number of queries/searches will run with the VIN number as parameter since it's how we would like to track the vehicles as well as other data related to it.
The VIN number will never change, but I'm unsure if it would cause any serious performance degradation (or other complications I'm not aware of) since some queries will use joins and others not :/
By using the VIN as primary key I do not have to create a unique constraint / additional index - BUT it has to be char(17) a data type other than int for which primary keys are supposedly optimized...
What I'm also not 200% sure of is that every VIN number out there is the same length (very unlikely) but in that case how would using a varchar(17) affect the whole situation... if at all.
Thanks!

A: In my opinion, regarding performance, it indeed is not a good idea. It very much depends how many cars you will store in the database though. On the other hand, if your applications and queries use the VIN as parameter then it is the best option as the column is indexed and must be unique.
hope this helps
ps: akward seeing other people's suggestions on this topic!

A: Just a personal opinion..
I always use int as a primary key. Primary key is in most cases always a clustered index. It's 4 bytes vs. 17 bytes and you can always put a non-clustered index on your VIN column. Keep things simple and clear. It's just my opinion though.


text:
Q: How to obtain wi-fi noise? Is there any way to obtain the noise level (dBm) from wi-fi signals? I've looked up everywhere and came across this answer however my output doesn't include the noise.
Thank you in advance.


text:
Q: Django form action attribute I want to connect my form to views.login in my views.py file. I know similar questions have been asked I tried them but didn't work for me or could not understand the answers as I am weak in English. Here is my form
<form actoin="/login/" method="POST">
  {% csrf_token %}
  <input name="nm" value ="nm" type="text" style="height:40px; width:255px;" required placeholder="phone number,username or email">

  <input name="ps" value="ps" type="password" style="height:40px; width:255px;" required placeholder="password" min="6">

  <input type="submit" style="height:35px; width:255px;         background-color:rgb(0,180,214);
  border:solid 1px white; color:white; border-radius:5px;" value="login">

</form>

Here is my views.py
from .models import store, Item

def login(response):
    ls = store.objects.get(name="username")
    ls1 = store.objects.get(name="password")
    if response.method == "POST":
        txt = response.POST.get("nm")
        if len(txt) > 3:
            ls.item_set.create(text=txt, complete=False)
        psw = response.POST.get("ps")
        if len(psw) > 3:
            ls1.item_set.create(text=psw, complete=False)
        print("done")

def frm(response):
    return render(response, "main/instagram.html", {})

and this my urls.py
urlpatterns = [
    path("", views.frm, name="frm"),
    path("login/", views.login, name="login"),
]


text:
Q: Measuring string width in Python I have some font (Times New Roman, 14) and I need to measure string width. I found matplotlib and example from API:
from matplotlib import rcParams
import os.path
afm_filename = os.path.join(rcParams['datapath'], 'fonts', 'afm',
               'ptmr8a.afm')
from matplotlib.afm import AFM
afm = AFM(open(afm_filename))
afm.string_width_height('What the heck?')

But I can't understand what I should paste instead of "datapaths", "fonts", "afm".
Is it the way to get sting width in Python? Maybe another way?

A: import tkinter as Tkinter
from tkinter import font as tkFont

Tkinter.Frame().destroy()
txt = tkFont.Font(family="Times New Roman", size=14)
width = txt.measure("What the heck?")
print(width)


text:
Q: Measuring inductance and ESR of a motor using LCR meter I am building a circuit, where a MCU will drive an unipolar stepper motor through MOSFETs and constant current source (not included in the schematic).

simulate this circuit – Schematic created using CircuitLab
The MOSFETs will switch at a frequency of somewhere in 10's or 100's kHz square wave. To design a constant current source, I need to measure the inductances of the coils and also their ESR. I have a LCR meter and multimeter at hand, but am unsure of how exactly to measure it.
If I measure the resistance of the coils (L1, L2, L3 or L4) with a multimeter I get around 5.5Ohms, if I do the same with the LCR meter set at 10kHz or 100kHz, I get like 500Ohm and 450uH.
How should I measure inductance and ESR of the coils?

A: Your RLC meter assumes that the parameter you select is the only significant attribute of the item being measured, so when you tell it to measure R it assumes that the stepper motor coil is a pure resistor with no inductance or capacitance. In reality the coil has significant inductance which will increase the reading. At 10kHz the coil's impedance is mostly inductive, so the L reading should be fairly accurate but the R reading won't be.
For PWM current control the inductance value isn't critical - it just has to be high enough to keep current ripple down to an acceptable amount. However the resistance value is critical, as it determines the average current through the coil. At high frequencies the resistance will increase due to skin effect, but in the frequency range you intend to use and with the small diameter of the coil wire, its AC resistance should not be much higher than your DC measurement.
Ignore the RLC meter's AC resistance measurement. The DC value should be close enough. Use the lowest available PWM frequency that still maintains continuous current flow in the coil at the lowest PWM ratio you intend to use.


text:
Q: ffmpeg Unrecognized option...Error splitting the argument list: Option not found This is probably a pretty simple question for those of you who use ffmpeg, but I'm very new at it, and I'm using it on Windows, which apparently isn't the norm.
From cmd, with my environment variable set at my ffmpeg install directory, I'm running
ffmpeg -i C:\Users\Me\Videos\InputVideo.wmv
-vcodec libx264 -acodec aacenc C:\Users\Me\Desktop\OutputVideo.mp4

(My actual script doesn't have a line break, I just put that there to make reading easier)
and ffmpeg is throwing
Unrecognized option 'i C:\Users\Me\Videos\InputVideo.wmv
-vcodec libx264 -acodec aacenc C:\Users\Me\Desktop\OutputVideo.mp4'.
Error splitting the argument list: Option not found.

Is something wrong with my script?  Am I calling an encoder that isn't currently on my machine?  Is it something to do with the file paths?
Thanks for the help, everyone.


text:
Q: How to convert OGG_OPUS input audio stream into a bytestream format acceptable for Google Speech-to-Text API? Context: I have a URL for a recorded audio stream which is originally in OGG_OPUS format.
I am converting it the audio from URL into a byte stream (as required by Google API - https://cloud.google.com/speech-to-text/docs/reference/rest/v1p1beta1/RecognitionAudio).
When I provide this byte-stream into Google Speech-to-text API, I am receiving a null response !!
Question:

*

*Why is Google API returing a Null response here?

*Does Google API really support OGG_OPUS format for audio input?

Code Block
import time
from urllib.request import urlopen
from io import BytesIO
import requests
import base64

# Imports the Google Cloud client library
from google.cloud import speech

# Instantiates a client
client = speech.SpeechClient()
url = "https://drive.google.com/file/d/1zlJaptJYJe0ge_SkpB52N6uRTsEKUGG4/view?usp=sharing"

response  = requests.get(url,stream=True)
output = base64.b64encode(BytesIO(response.content).read())

audio = speech.RecognitionAudio(content=output)

config = speech.RecognitionConfig(
   encoding=speech.RecognitionConfig.AudioEncoding.OGG_OPUS,
   sample_rate_hertz=16000,
   language_code="en-US",
)

# Detects speech in the audio file
response = client.recognize(config=config, audio=audio)
print("response: ", response)
'''


text:
Q: \input in figure environment not centering I'm making a presentation with beamer, and I've drawn some figures in TikZ that I'm inserting into the presentation using \input{footikz.tex}
For some reason the tikz picture is appearing off to the right of where they should be.  Below is some of my code, I was wondering if anyone could spot a silly mistake I'm making?
\begin{frame}
\frametitle{\insertsubsection}
\begin{alertblock}{\insertsubsubsection}

\begin{figure}
\centering
\begin{subfigure}[c]{0.2\textwidth}
{\scalebox{0.4}{\input{Figures/Tikz/Arrows0.tex}}}
\end{subfigure}
~
\begin{subfigure}[c]{0.2\textwidth}
{\scalebox{0.4}{\input{Figures/Tikz/Arrows180.tex}}}
\end{subfigure}
~
\begin{subfigure}[c]{0.2\textwidth}
{\scalebox{0.4}{\input{Figures/Tikz/Arrows360.tex}}}
\end{subfigure}
\caption{caption}
\end{figure}

\end{alertblock}
\end{frame}

In this instance, the first subfigure appears in the center of the page and the next two are placed to the right of it.  I'd like them to be left, center, right.
Later in the presentation I have an extremely similar layout and it works fine.
Thanks.

A: Please always post complete code in future.
This is an alternative. Since you are not using separate captions (which are not needed for a presentation IMO), you need not use subcaption package. Simple minipage will do. Further, if you can save your pictures as .tikz files (I hope you use tikz for those pictures, if not I will discard this answer), you can use tikzscale package and then the tikz files can be included using the regular \includegraphics command with all the keys like width, height etc available.
A sample code:
\documentclass{beamer}
\usepackage{tikz}
\usepackage{tikzscale}
\usepackage{filecontents}
\begin{filecontents*}{test1.tikz}
  \begin{tikzpicture}
    \node {Here};
    \draw (0,0) circle (2cm);
  \end{tikzpicture}
\end{filecontents*}
\begin{filecontents*}{test2.tikz}
  \begin{tikzpicture}
    \node {Here};
    \draw (0,0) circle (3cm);
  \end{tikzpicture}
\end{filecontents*}
\begin{filecontents*}{test3.tikz}
  \begin{tikzpicture}
    \node {Here};
    \draw (0,0) circle (4cm);
  \end{tikzpicture}
\end{filecontents*}
\begin{document}
  \begin{frame}
\frametitle{\insertsubsection}
\begin{alertblock}{\insertsubsubsection}
\begin{figure}
\centering
\begin{minipage}{0.2\textwidth}
\includegraphics[width=\linewidth]{test1.tikz}
\end{minipage}
\hfill
\begin{minipage}{0.2\textwidth}
\includegraphics[width=\linewidth]{test2.tikz}
\end{minipage}
\hfill
\begin{minipage}{0.2\textwidth}
\includegraphics[width=\linewidth]{test3.tikz}
\end{minipage}
\caption{caption}
\end{figure}
\end{alertblock}
\end{frame}
\end{document}


text:
Q: Automatically assign unique random ids for instances of a struct Completely new rustacean. Suppose I have this piece of code:
use random_string;

struct IDManager {
    length: usize,
    charset: String,
    registered_ids: Vec<String>,
}

impl IDManager {
    fn generate(&mut self) -> &String {
        loop {
            let id = random_string::generate(
                self.length,
                &self.charset
            );
            if !self.registered_ids.contains(&id) {
                self.registered_ids.push(id);
                return self.registered_ids.last().unwrap();
            }
        }
    }
}

impl Default for IDManager{
    fn default() -> Self {
        IDManager {
            length: 32,
            registered_ids: vec![],
            charset: [
                "abcdefghijklmnopqrstuvwxyz",
                "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
                "0123456789",
            ].concat(),
        }
    }
}

#[derive(Debug)]
struct Person<'a> {
    id: &'a String,
    name: String,
    age: u32,
}

fn main() {
    let mut person_id_manager: IDManager = Default::default();
    let person = Person {
        id: person_id_manager.generate(),
        name: "Bob".to_string(),
        age: 32,
    };
    println! ("{:?}", person)
}

The problem with this code is that the person_id_manager is not really tied to the struct Person. Users are still free to give whatever id they want to the Person which is not what we want. Instead, ideally, we want to yield no control to the users how the id of a Person is generated, better if it is completely invisible.
I thought of adding a IDManager "static attribute" to the "class" of Person, which Person is obviously not because it is a struct. What is the idiomatic way to do this in Rust?

A: Usually in Rust, you limit access to fields by not making them public. In your example, the user of Person is only able to access the private fields because you've put everything in one module.
It's hard to say exactly what is idiomatic here, because it looks like a slightly unusual requirement and the "best" approach will depend on what you really are trying to achieve. However, it is idiomatic in Rust to use new method to control how objects are constructed.
Since the fields are all private, if you provide a public new method, this will be the only way that Person can be constructed outside of the module, so you can control exactly how this is done.
At this point you could make use of a shared static instance of IdManager, but since you asked about an idiomatic approach and global variables are not typically recommended in any language, let's do something different:
impl<'a> Person<'a> {
    pub fn new(id_manager: &'a mut IdManager, name: String, age: u32) -> Self {
        Person {
            name,
            age,
            id: id_manager.generate()
        }
    }
}

This requires users of the Person struct to have access to an IdManager in order to create one.


text:
Q: Limit of polynomial functions Problem: Given a sequence $(f_n)_{n\in\mathbb{N}}$ of polynomial functions such that $f_n(x)=\sum_{j=0}^{n}\dfrac{j^3}{4^{j+2}}x^j$, find the largest real number $r$, such that $(f_n)_{n\in\mathbb{N}}$ converges to a function $f:(0,r)\to\mathbb{R}$ pointwise on $(0,r)$. Also show that $f$ is continuous on $(0,r)$.
Question: I was able to show pointwise convergence on the maximal interval $(0,4)$ by treating $(f_n(x))_{n\in\mathbb{N}}$ as a power series and calculating its radius of convergence. However, I haven't been able to prove that $f$ is continuous on $(0,4)$, as the only thing that came to my mind was to use that polynomial functions are continuous.

A: Let $x\in (0,4)$. Choose $\alpha>0$ with $x+\alpha<4$. Then, for any $y\in (0,4)$ and $m>n$,
\begin{align}
|f_m(y)-f_n(y)|
&\leq \sum_{k=n+1}^m \frac{k^3}{4^{k+2}}\,|y|^k\\ \ \\
&\leq \sum_{k=n+1}^m \frac{k^3}{4^{k+2}}\,(x+\alpha)^k\\ \ \\
&=\frac1{16} \sum_{k=n+1}^m  {k^3}\,\left(\frac{x+\alpha}4\right)^k\\ \ \\
&=\frac1{16} \sum_{k=n+1}^m  {k^3}\,q^k\\ \ \\
\end{align}
where $q=\tfrac{x+\alpha}4\in(0,1)$. As this last sum is the tail of a convergent series, we get that $\{f_n\}$ is uniformly Cauchy, so its limit is a continuous function on $(0,4)$.


text:
Q: why does the JS toFixed(2) function works insanely?
How could it get a round 0.17 instead of 0.18 from 0.175?

A: It doesn't work insanely. You tell the function to keep two decimal digits and that's what it does. If you want to round your number, you can try multiplying your number with 10^x, using Math.round and then dividing by the same number:

const roundToDecimals = function (number, decimals) {
  const num = Math.pow(10, decimals);
  return Math.round(number * num) / num;
}

console.log(roundToDecimals(0.175, 2));

A: You have told to round it till 2 points .so the answer will be 0.17 because the third number is less than or equal to 5.


text:
Q: Performance assessment based on conditional probability with a reference model Say I have a reference binary classifier model with its' confusion matrix. Then I construct another model and I can assess the probability they agree (relative confusion matrix). Is there any way to put a lower bound on the new classifier performance? I am looking for something that is based on Bayes' theorem etc...
Initial try
Say I want to estimate the
$$P(\hat{a}|a)=P(\hat{a}|a\cap\hat{a}_{ref})P(\hat{a}_{ref}|a)+P(\hat{a}|a\cap\hat{\bar{a}}_{ref})P(\hat{\bar{a}}_{ref}|a)$$
where $P(\hat{\bar{a}}_{ref}|a)$ and $P(\hat{a}_{ref}|a)$ are known from the confusion matrix.
I also know $P(\hat{a}|\hat{a}_{ref}), (\hat{\bar{a}}|\hat{a}_{ref}), (\hat{a}|\hat{\bar{a}}_{ref}), (\hat{\bar{a}}|\hat{\bar{a}}_{ref})$. I try to threshold $P(\hat{a}|a\cap\hat{a}_{ref})$ based on my knowledge:
$$P(\hat{a}|a\cap\hat{a}_{ref})=\frac{P(a\cap\hat{a}_{ref}|\hat{a})P(\hat{a})}{P(a\cap\hat{a}_{ref})}$$
where all the elements beside $P(a\cap\hat{a}_{ref}|\hat{a})$ are known from the confusion matrix. Here, I could use $$P(a\cap\hat{a}_{ref}|\hat{a})\leq P(a|\hat{a})$$ or
$$P(a\cap\hat{a}_{ref}|\hat{a})\leq P(\hat{a}_{ref}|\hat{a})$$ and solve the whole problem but the inequality is not in the right direction which does not allow my to provide a lower bound performance!