text:
Q: Crystal Reports Excel formatting issue We have an ERP built on .net2.0, Visual Studio 2008 on C# which runs the crystal reports for Visual Studio 2008(Inbuilt version). Issue with this is the excel export option doesn't work properly(no formatting, cells getting merged etc) and this seems to be a known issue, so the question is will we be able to upgrade the crystal reports to the latest version(even a paid one) that do not have these issues? if so which one would work with VS 2008? whats a possible solution for this if anybody is familiar with such a situation

A: I had a lot of these issues, and was able to correct them all via formatting in Crystal Reports 11.
Extra columns/issues with merging can be solved by making sure your design doesn't have any "gaps" in it.
For example: You have a detail of width 1.5, height .34 and position (0,0). If your next cell in that section starts anywhere other than position (1.5,0), you will have a gap between cells. This gap will result in excel making a blank column or row of that width. Similarly, if your second item has height 1.4 you'll then have a blank row of height .1, where your first item is displayed in a merged cell between two rows, one of height 1.4 merged with a row of height 0.1. This is the only way excel knows to give you two cells of a different size on the same row.
Let me know if this isn't clear enough and I'll try to elaborate a bit more or take some screen shots, but I'm pretty sure this is your issue.

A: When exporting to excel, there are several reasons that can cause formatting issue.  For example, If you go to Export options Using the column width of Header 1 may give you better formatting that the whole page.  The best way to avoid formatting problems when exporting to excel is designing your report around the fact that it will be exported to excel.  That means try to keep the fields in every section aligned. so if you have two .5 in fields in one section.  and you have another field in the section below it.  Make that field .5 or 1 in and align it with the fields above it.  Also make sure all the sections are fitted by right clicking a section and click fit to section.  If your still getting unwanted black rows when exporting,
1.)Right click section
2.)click arrange lines
3.)right click section
4.)click fitSection


text:
Q: Pausing the execution of a binary file using C? I have a binary file that I can execute in C by using the system() command or popen(). when running the binary in the linux filesystem I can use ctrl + z to pause the execution of the program and the fg to resume the execution. Is there any possible way in which I could do this in C?

A: Send a SIGSTOP signal to it. See the signals manpage on how to do it. You can continue the process by sending it a SIGCONT signal. You'll need the process ID for this, so you'll have to use fork+exec instead of plain system.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible if I want to change my docker data-root directory to another server? I installed docker inside of a server or what I usually called as a VM (Virtual Machine, with RHEL environment) and I have been thinking of using a new directory in a remoted Windows network as my new data-root directory (due to space reason).
In my case, the data-root directory from my VM located at /home/docker_new and the path where I want to use as a new data-root directory from the remote Windows network is for example, at
\\xx.xx.x.x\a\b\c.
I did try to make my research and finds that most of the solutions are all focusing on changing the data-root directory within the same VM. Some focusing on how to 'move' the docker to another server. While what I intended to do is just to change the data-root directory to another directory in a remoted windows network .
So, my question is:
1. Is it possible to do so?
2. If its possible, what are the steps that I should follow?


text:
Q: Проблема при подключении к прокси: "HTTP/1.0 407 Proxy Authentication Required" купил proxy для парсинга авито с логином и паролем
        System.setProperty("http.proxyHost", ipProxy);
        System.setProperty("http.proxyPort", portProxy);
        System.setProperty("http.proxyUser", login);
        System.setProperty("http.proxyPassword", password);

при попытке подключиться следующая ошибка, в чем может быть проблема? еще есть порт socks, как его использовать? нужен ли он?
java.io.IOException: Unable to tunnel through proxy. Proxy returns "HTTP/1.0 407 Proxy Authentication Required"
    at java.base/sun.net.www.protocol.http.HttpURLConnection.doTunneling(HttpURLConnection.java:2185)
    at java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:169)
    at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:142)
    at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:732)
    at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:707)
    at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:297)
    at org.jsoup.helper.HttpConnection.get(HttpConnection.java:286)
    at parser.Parser.parse(Parser.java:43)
    at bot.ThreadAvitoParser.run(ThreadAvitoParser.java:23)
    at java.base/java.lang.Thread.run(Thread.java:832)


text:
Q: What happens when a Class conforms to a protocol, which contains mutating function? I was just experimenting with Protocol programming in Swift. During this, I came across the following scenario.
Let's say we have a protocol like,
protocol SomeProtocol {
    .....
    mutating func mutatingFunc()
    .....
}

Now let's say I have a class called MyClass and it conforms to my SomeProtocol like,
struct MyStruct {
    var width = 0, height = 0
}

extension MyStruct: SomeProtocol {

//1. If I remove the mutating keyword from following method definition, compiler will give me error, that's understandable as we are modifying structure members
//2. Also note that, if I remove the mutating keyword while defining protocol & keep mutating keyword in the below method, the compiler will say that structure doesn't conform to protocol

    mutating func mutatingMethod() {
        width += 10
        height += 10
    }

}

class MyClass {
    var width = 10
}

extension MyClass: SomeProtocol {

//1. However while implementing the protocol method in class, I can implement the same protocol method, and the compiler doesn't complaint even if I don't mention mutating keyword.
//2. But compiler will complain that mutating isn't valid on methods in classes or class-bound protocols, if I mention the mutating keyword
    func mutatingMethod() {
        width += 10
        print(width)
    }
}

Let's say I have another structure & another Protocol like,
protocol AnotherProtocol {
    func nonMutatingFunc()
}

struct MyAnotherStruct {
    var width = 0
}
extension MyAnotherStruct: SomeProtocol, AnotherProtocol {
    func mutatingFunc() {
//1. Compiler is happy even without the mutating keyword as we are not modifying structure members, also the structure conforms to SomeProtocol.
        print("Hello World")
    }
    mutating func nonMutatingFunc() {
    //1. Compiler cries that we are not conforming to AnotherProtocol as the function is mutating
        width += 10
    }

}

So now my observations are,

*

*For a class, it doesn't matter if the function is mentioned as mutating in the protocol and we are never allowed to mention methods in class as mutating.

*For a struct, if the implemented method, doesn't modify members we need not mention func as mutating even tough in protocol it is mutating.

*For a struct, if we implement protocol method as mutating func and if we don't specify the method as mutating func in the protocol. Compiler gives error.

Currently I am confused with the way the compiler is behaving with the structures due to the above scenarios. If someone could explain the significance of mutating functions inside a protocol i.e. "when we declare the func inside a protocol as a mutating, should we not make the func mutating when we implement it?" It'd be really great and helpful.
P.S. I know what mutating functions are, I am just confused with the mutating methods defined inside a protocol.
Thanks in advance.

A: I don't see what the "confusion" is. You've elucidated the rules beautifully! A struct may implement a protocol's mutating function as nonmutating, but it may not implement a protocol's nonmutating function as mutating. Once you've said those rules, there's nothing to be "confused" about. The rules are the rules.
Classes don't have mutating functions so your investigations there are sort of irrelevant. If you had declared your protocol as a class protocol, your mutating annotation in the protocol would have been illegal.


text:
Q: Feather JS vs Express JS Recently I have been learning about Feather JS. However I am pretty much confused by the difference between Express and Feather. One of the most important reason people use Feather is because of its capability to provide real time API. Can't Express use real time as well? What are the other differences that set Feather apart from Express?

A: From the docs

Feathers is a tiny, fully compatible wrapper over Express and Socket.io

So it still uses express underneath.
Here am assuming, real time means being able to get data as soon as it's available (this could still be ambigous on how one defines, but yeah rough definition)
So, here real time could just mean pages getting loaded with data in real time (approx) using the underlying socket.io functionality.
So comming back to your question:

Can't Express use real time as well?

You can very well integrate socket.io on your own. Or really any other duplex socket technologies like websocket, or others like long polling, server-sent events etc.

What are the other differences that set Feather apart from Express?

This part is out of scope for SO question. But in simple terms Feather adds more functionality using express underneath.


text:
Q: NGINX conditional Rewrite extensionless URLS I am trying to provide extensionless URLs for a client. The systems URLs will be generated without the extension in the navigation elements and links so I will have links that look like.
www.somesite.com
www.somesite.com/foo
www.somesite.com/foo/bar
www.somesite.com/bar/foo/barfoo

lets pretend for a moment that the calls will be either routed to a proxy that can handle a defined file extension or simply serve the html page if it exists. If the url is correctly rewritten then I would think a location command with a matching regex for the extension should work.
so behind the scenes we have.
www.somesite.com/index.abc
www.somesite.com/foo.def
www.somesite.com/foo/bar.abc
www.somesite.com/bar/foo/barfoo.def
...

with Apache .htaccess I can solve this problem by first testing for the existence of the page with a desired filetype.
RewriteCond %{REQUEST_FILENAME}.abc -f
RewriteRule ^(.*)$ $1.abc [L]

I would also make sure that directory browsing is off and that trailing slashes would be removed
#ensure trailing slash is removed
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^(.*)(?:/)$ $1 [R=301,L]

all well and good for Apache, and for me relatively intuitive, but this is NGINX and quite frankly I have no idea how to solve this use-case.
All the similar use cases I have found deal with html & php (How to remove both .php and .html extensions from url using NGINX?) and simply use try_files until they fall-through to a named location that rewrites the uri with .php extension. This would work if one is only dealing with a single dynamic language and fails miserably if we have two dynamic languages.
So the question is how do I do something similar in NGINX like can be done with the .htaccess condition/rewrite above
any help would be appreciated!
Cheers
Gary
UPDATE:
I have been able to get it "mostly" working by using the standard php approach. The issue is www.somesite.com is being directed to www.somesite.com/.php instead of serving the default document. Trailing slashes are also being removed correctly.
so to recap:
www.somesite.com - not working - www.somesite.com/.php
www.somesite.com/foo - working
www.somesite.com/foo/bar - working
www.somesite.com/bar/foo/barfoo - working

here my config:
location / {
        index  index.php index.html
        autoindex off;

        #remove trailing slash
        rewrite ^/(.*)(?:/)$ /$1 permanent;

        #try html files or route to named location
        try_files $uri $uri.html @php;
    }

 location ~ \.php$ {
        ...
    }

 location @php {
        rewrite ^(.*)$ $1.php last;
    }

in other posts the try_files block looks like this: try_files $uri $uri.html $uri/ @php; the problem is if I add $uri/ it will work for the default document e.g. serve www.somesite.com but all other urls like www.somesite.com/foo/ or www.somesite.com/foo/bar/ , which are also directories and have files of the same name, will be redirected to infinity instead of their respective pages.

A: Assuming that you have three ways to process an extensionless URI, you would need three location blocks. You can use try_files to test for the existence of a file by type, and cascade to the next location block in the chain, if the file is not found. See this document for details.
For example:
root /path/to/document/root;

location / {
    try_files $uri $uri.html $uri/ @php;
}
location @php {
    try_files $uri.php @proxy;
    fastcgi_pass ...;
    ...
}
location @proxy {
    proxy_pass ...;
}

The first block processes normal files within the document root. You probably have a location ~ \.php$ block to process PHP files, and the second block is essentially a replica. The third block sends everything else upstream.


text: Q: Ubuntu 16.04: mouse pointer and display flickering, but theres no unknown display, so what do? I have just installed Ubuntu 16.04 on my laptop Asus K45DR which use AMD HD7460 graphic card. Already tried some suggestion on internet that i should turn off any unknown display on system settings>displays>unknown display but i cant find the unknown display, only the built-in display. So what do?


text:
Q: Separate IP for separate browsers Is it possible to use 2 different IP in 2 browsers? I would like to surf in Chrome with IP address A and in IE with IP address B.
If this is possible: how?

A: You can use proxy setting in one of these browsers. Chrome proxy settings


text:
Q: perl6 Is using junctions in matching possible? Is it possible to use junction to match any of the values in a junction? I want to match any of the values in an array. What is the proper way to do it?
lisprog$ perl6
To exit type 'exit' or '^D'
> my @a=<a b c>
[a b c]
> any(@a)
any(a, b, c)
> my $x=any(@a)
any(a, b, c)
> my $y = "a 1"
a 1
> say $y ~~ m/ $x /
False
> say $y ~~ m/ "$x" /
False
> my $x = any(@a).Str
any("a", "b", "c")
> say $y ~~ m/ $x /
False
> say $y ~~ m/ || $x /
False
> say $y ~~ m/ || @a /
「a」
>

Thanks !!

A: Junctions are not meant to be interpolated into regexes. They're meant to be used in normal Perl 6 expressions, particularly with comparison operators (such as eq):
my @a = <x y z>;
say    "y" eq any(@a);  # any(False, True, False)
say so "y" eq any(@a);  # True

To match any of the values of an array in a regex, simply write the name of the array variable (starting with @) in the regex. By default, this is interpreted as an | alternation ("longest match"), but you can also specify it to be a || alternation ("first match"):
my @a = <foo bar barkeep>;
say "barkeeper" ~~ / @a /;     # 「barkeep」
say "barkeeper" ~~ / || @a /;  # 「bar」


text:
Q: How to determine the x value on the edge of the violinplot for a mean line I am trying to draw a mean line on violin plots, since I was not able to find a way to make sns replace the "median" line that comes from "quartiles", I decided to code so that for each case it draws on top. I am planning on drawing horizontal lines using plt.plot on the mean value (y value) of each of the three graphs I have.
I have the exact y (height) values where I want my horizontal line to be drawn, however, I am having difficulty trying to figure out the bound of each violin graph on that specific y value. I know since it is symmetric the domain is (-x, x), so I need a way to find that "x" value for me to be able to have 3 added horizontal lines which each bounded by the violin graphs that I have.
Here is my code, the x value of the plt.plot is -0.37, which is something I found by trial and error, I want python to find that for me for a given y value.
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

data = [2.57e-05, 4.17e-06, -5.4e-06, -5.05e-06, 1.15e-05, -6.7e-06, 1.01e-05, 5.53e-06, 8.13e-06, 1.27e-05, 1.11e-06, -2.87e-06, -1.38e-06, -1.07e-05, -8.04e-06, 4.77e-06, 3.22e-07, 9.86e-06, 1.38e-05, 1.32e-05, -3.48e-06, -4.69e-06, 8.15e-06, 4.21e-07, 2.71e-06, 7.52e-08, 1.04e-06, -1.92e-06, -4.08e-06, 4.76e-06]

vg = sns.violinplot(data=data, inner="quartile", scale="width")

a = sns.pointplot(data=data, zlinestyles='-', join=False, ci=None, color='red')

for p in vg.lines:
    p.set_linestyle('-')
    p.set_linewidth(0.8)  # Sets the thickness of the quartile lines
    p.set_color('white')  # Sets the color of the quartile lines
    p.set_alpha(0.8)

for p in vg.lines[1::3]:  # these are the median lines; not means
    p.set_linestyle('-')
    p.set_linewidth(0)  # Sets the thickness of the median lines
    p.set_color('black')  # Sets the color of the median lines
    p.set_alpha(0.8)

# add a mean line from the edge of the violin plot
plt.plot([-0.37, 0], [np.mean(data), np.mean(data)], 'k-', lw=1)
plt.show()

Refer to the picture where I removed the median point but left the quartile lines, where I want to draw mean lines across where the blue dots are visible

And here is a picture once I draw that plt.plot with the x value I found via trial and error: For case I only

A: You can draw a line that is too long, and then clip it with the polygon forming the violin.
Note that inner='quartile' shows the 25%, 50% and 75% lines. The 50% line is also known as the median. This is similar to how boxplots are usually drawn. It is rather confusing to show the mean in a too similar style. That's why seaborn (and many other libraries) prefer to show the mean as a point.
Here is some example code (note that the return value of sns.violinplot is an ax, and naming it very different makes it rather hard to find your way into matplotlib and seaborn docs and examples).
import matplotlib.pyplot as plt
from matplotlib.patches import PathPatch
import seaborn as sns
import pandas as pd
import numpy as np

tips = sns.load_dataset('tips')
tips['day'] = pd.Categorical(tips['day'])

ax = sns.violinplot(data=tips, x='day', y='total_bill', hue='day', inner='quartile', scale='width', dodge=False)
sns.pointplot(data=tips, x='day', y='total_bill', join=False, ci=None, color='yellow', ax=ax)
ax.legend_.remove()

for p in ax.lines:
    p.set_linestyle('-')
    p.set_linewidth(0.8)  # Sets the thickness of the quartile lines
    p.set_color('white')  # Sets the color of the quartile lines
    p.set_alpha(0.8)
for x, (day, violin) in enumerate(zip(tips['day'].cat.categories, ax.collections)):
    line = ax.hlines(tips[tips['day'] == day]['total_bill'].mean(), x - 0.5, x + 0.5, color='black', ls=':', lw=2)
    patch = PathPatch(violin.get_paths()[0], transform=ax.transData)
    line.set_clip_path(patch)  # clip the line by the form of the violin
plt.show()

Updated to use a list of lists of data:
data = [np.random.randn(10, 7).cumsum(axis=0).ravel() for _ in range(3)]

ax = sns.violinplot(data=data, inner='quartile', scale='width', palette='Set2')
# sns.pointplot(data=data, join=False, ci=None, color='red', ax=ax) # shows the means
ax.set_xticks(range(len(data)))
ax.set_xticklabels(['I' * (k + 1) for k in range(len(data))])

for p in ax.lines:
    p.set_linestyle('-')
    p.set_linewidth(0.8)  # Sets the thickness of the quartile lines
    p.set_color('white')  # Sets the color of the quartile lines
    p.set_alpha(0.8)
for x, (data_x, violin) in enumerate(zip(data, ax.collections)):
    line = ax.hlines(np.mean(data_x), x - 0.5, x + 0.5, color='black', ls=':', lw=2)
    patch = PathPatch(violin.get_paths()[0], transform=ax.transData)
    line.set_clip_path(patch)
plt.show()

PS: Some further explanation about enumerate(zip(...))

*

*for data_x in data: would loop through the entries of the list data, first assigning data[0] to data_x etc.

*for x, data_x in enumerate(data): would loop through the entries of the list data and at the same time increment a variable x from 0 to 1 and finally to 2.

*for data_x, violin in zip(data, ax.collections): would the data_x loop through the entries of the list data and simultaneously a variable violin through the list stored in ax.collections (this is where matplotlib stores the shapes of the violins)

*for x, (data_x, violin) in enumerate(zip(data, ax.collections)): combines the enumeration with zip`


text:
Q: Specify image dimensions when creating PNGs from a PDF with pdflib Can the dimensions of the PNGs created from this script be set?
e.g. setImageWidth = '200', setImageHeight ='500'
Is this possible with pdflib or should I use GD after initial images are created?
Could not find any answers in SO or Google on this using pdflib.
$pdflib = new ImalH\PDFLib\PDFLib();
$pdflib->setPdfPath($pdf_file_path);
$pdflib->setOutputPath($folder_path_for_images);
$pdfLib->setImageFormat(\ImalH\PDFLib\PDFLib::$IMAGE_FORMAT_PNG);
$pdflib->setDPI(50);
$pdflib->setPageRange(1,$pdflib->getNumberOfPages());
$pdflib->convert();

A: They have a imagecropauto function that looks like the closest thing honestly:
resource imagecropauto ( resource $image [, int $mode = -1 [, float $threshold = .5 [, int $color = -1 ]]] )


text:
Q: How do I scale translate x,y values? I am working on a 2d grid with scale touch functionality. I've managed to set the translate boundaries so that the screen viewport doesn't go beyond the grid boundaries. I'm now struggling with the algorithm for determining the new translate values when scaling on both two finger touch and mouse wheel events.
touchStarted sets the vector angle between the two initial touches. lastTouchAngle is for comparison in touchMoved.
function touchStarted() {
  if(touches.length == 2) {
    let touchA = createVector(touches[0].x, touches[0].y);
    let touchB = createVector(touches[1].x, touches[1].y);
    lastTouchAngle = touchA.angleBetween(touchB);
  }
  return false;
}

touchMoved makes the current touches vectors, compares the angle, and then scales accordingly.
t_MinX and t_MinY set the lowest possible translate value for the constrains, but determining what the new translate value should be is where I'm lost. I know it's going to require the current scale, the center point between the two touches, and the width and height of the Canvas.
function touchMoved() {
  if(touches.length == 1) {
    panTranslate(translateX, translateY, mouseX, mouseY, pmouseX, pmouseY);
  } else if (touches.length == 2) {
    let touchA = createVector(touches[0].x, touches[0].y);
    let touchB = createVector(touches[1].x, touches[1].y);

    scl = (abs(lastTouchAngle) < abs(touchA.angleBetween(touchB)) ? (scl+sclStep < sclMax ? scl+sclStep : sclMax) : (scl-sclStep > sclMin ? scl-sclStep : sclMin));

    let t_MinX = (screenH/sclMin) * (sclMin-scl);
    let t_MinY = (screenW/sclMin) * (sclMin-scl);
    let tX = translateX;
    let tY = translateY;

    if(abs(lastTouchAngle) > abs(touchA.angleBetween(touchB))) {
      console.log("Scale out");
      translateX = constrain(tX+mX, t_MinX, 0);
      translateY = constrain(tY+mY, t_MinY, 0);

    } else {
      console.log("Scale in");
      if(scl != sclMax) {
        translateX = constrain(tX-mX, t_MinX, 0);
        translateY = constrain(tY-mY, t_MinY, 0);
      }
    }
    // Set current touch angle to lastTouchAngle
    lastTouchAngle = touchA.angleBetween(touchB);

  }
  return false;
}

Here is the bit getting me confused:
      translateX = constrain(tX+mX, t_MinX, 0);
      translateY = constrain(tY+mY, t_MinY, 0);

Full code: https://editor.p5js.org/OMTI/sketches/9ux6Rq6n5

A: https://stackoverflow.com/questions/5713174
I found the answer at the above link and was able to get this working from the answer there.


text:
Q: Spring framework scope - Is it a misnomer? I know there is a term Bean scope in Spring framework, and for some reasons it is confusing me, mainly because of the term scope, because we have this terms (scope) in languages, like C, Java applied to a variable scope (that is where a variable is visible).
I know there are five bean scope, and I am not asking explanation on them, I am not clear on what Bean scope means. Can anyone help me understand what does this term mean?

A: In programming languages scope of the variables defines where in the code, the variable can be reached.

*

*Global variables can be accesed from everywhere.

*Function parameters or local variables can be accesed only in the function.

In Spring framework scope of the bean defines when during the application runtime we are dealing with the same object.

*

*Singleton scoped bean is an object that is unique to the whole application. Like global variable in programming languages.

*Session scoped bean is an object that is unique to the session.

*Request scoped bean is an object that is unique to the request. Like function parameters.

*Prototype scoped bean is not unique to anything. Every time you get it, you have a new copy. Hard to compare but it can be a heap allocated variable.

In computer science, the scope term  is overloaded, the same as the term interface. You can have a Go or Java interface as well as PCI or ISA.
Well, the term overload is also overloaded.


text:
Q: Why is the bullet going the wrong way? I'm trying to make a shooter game and the bullets are going the wrong way.
I've tried to mess a little bit with the formulas but I have no clue on how to solve this issue.
setInterval(function(){
    $(".bullet").each(function(i,bullet) {
        var x = parseFloat($(bullet).css("left")) + parseFloat($(bullet).attr("y"));
        var y = parseFloat($(bullet).css("top")) + parseFloat($(bullet).attr("x"));

        $(bullet).css({"top":y+"px","left":x+"px"});
    });
},20);

$(window).click(function(e) {
    var dx = (e.pageX - (x+37.5));
    var dy = (e.pageY - (y+37.5));
    var mag = Math.sqrt(dx * dx + dy * dy);
    var velX = (dx / mag) * 15;
    var velY = (dy / mag) * 15;

    $("#game").append("

");
});

Here's a GIF of what's happening

A: You are adding X to Y and Y to X is one observation:
var x = parseFloat($(bullet).css("left")) + parseFloat($(bullet).attr("x"));
var y = parseFloat($(bullet).css("top")) + parseFloat($(bullet).attr("y"));

instead of
var x = parseFloat($(bullet).css("left")) + parseFloat($(bullet).attr("y"));
var y = parseFloat($(bullet).css("top")) + parseFloat($(bullet).attr("x"));


text:
Q: Unable to hide status bar - Flutter - This expression has a type of 'void' so its value can't be used Seeing the following error on setSystemUIOverlayStyle.
Do I have to add some package to pubspec.yaml?

errors:

A: Try below code I think you write wrong code. for more refer this
void main() {
  SystemChrome.setSystemUIOverlayStyle(
    SystemUiOverlayStyle(
      statusBarColor: Colors.red,//change color on your need
    ),
  );
  runApp(const MyApp());
}

Result screen->

A: You can set the StatusBar transparent by adding this in your main():
SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
        statusBarColor: Colors.transparent));

The problem is that you are putting it inside your runApp().
Your main() should look like this:
void main() {
SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
        statusBarColor: Colors.transparent));
runApp(const MyApp());
}

A: You can add this Into your initState() method. this is hide the bottom navigation as well.It is use for Full Screen design.
@override
void initState() {
super.initState();
 SystemChrome.setEnabledSystemUIMode(
  SystemUiMode.manual,
  overlays: [],
);}


text:
Q: how to set PHP_AUTH_PW in php curl How to set the PHP_AUTH_PW and PHP_AUTH_USER parameters in php curl.
At the server end its checking for:
if(!isset($_SERVER['PHP_AUTH_PW']))
{
print "Authorization error"
}
Any help would be appreciated
Thanks

A: It is called basic-auth, and works with most browsers including curl on command line:
curl --user name:password http://www.example.com

and in PHP you set two options on your curl connection ($curl_conn):
curl_setopt($curl_conn, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl_conn, CURLOPT_USERPWD, 'username:password');


text:
Q: How to get result from multiple tables with `leftJoin` in typeorm? I have three tables:
1. ViewTable:
id   type    created_at    status  action_id
-----------------------------------------
1    page_1  2020-01-01    1       2

2. ItemTable:
id   view_id   image       action_id
-------------------------------------
1    1         thumb.png   1

3. ActionTable:
id    message
------------------------------------
1     this is a test
2     this an action for header view

And the result that I am expecting is:
{
    "status": 1,
    "action": {
         "message": "this an action for header view"
     },
     "items": [
         {
           "id": 1,
           "description": "Comments",
           "image": "comment.png",
           "status": 1,
           "action": {
                 message: "this is test"
              }
          }
      ]
}

Also, I have created all Entities with required relations by one-to-one and one-to-many decorators.
So how can I get the result with this.createQueryBuilder('view') inside my ViewRepository?

A: I can get all required columns now by this way:
@EntityRepository(View)
export class ViewRepository extends Repository<View> {
    async getView() {
        return await this.createQueryBuilder('view')
            .leftJoinAndSelect("view.action", "action")
            .leftJoinAndSelect("view.items", "item")
            .leftJoinAndSelect("item.action", "itemAction")
            .select([
                "view.type",
                "action.message",
                'itemAction.message',
                'item.image',
                'item.id'
            ])
            .getOne()
    }
}

A: this.viewRepository.createQueryBuilder('view')
  .leftJoin('view.items', 'item') // 'view.items' will work if you describe 'items' property in ViewEntity as a relation
  .leftJoin('view.action', 'viewAction')
  .leftJoin('item.action', 'itemAction') // the same as above, but for ItemEntity
  .select(['view.status', 'viewAction.message', 'item.id', 'item.description', 'item.image', 'item.status', 'itemAction.message']) // probably you needed to select ids from rest tables too, for correct joining
  .where(<here is your 'where' condition>)
  .getOne() // or .getMany() if you wanna to get multiple results

upd: not sure that it would work inside repository


text:
Q: pass a paramenter into object and use it for querySelector but return null var ajaxFileUploader = function(formId){
    this.formId = formId;

    console.log(this.formId); //myForm
    return console.log(
        document.querySelector(this.formId)// null
    );
}

var foo = new ajaxFileUploader('#myFrom');

I try to create a object and pass a parameter into it.
it works fine when I console.log this property
but when I try to use querySelector, it return null
anyone know why it return null?

A: enclose the whole code within window.onload=function(){}. you might have placed the script in head but the elements are at body thats why element loads late and script returns null. if you use window.onload=function(){} the script will run after the whole document once loaded

window.onload=function(){
var ajaxFileUploader = function(formId){
    this.formId = formId;

    console.log(this.formId); //myForm
    return console.log(document.querySelector(this.formId));
}

var foo = new ajaxFileUploader('#myFrom');
  }
<form id="myFrom" action="demo_form.asp" method="get">
  First name: <input type="text" name="fname">

  Last name: <input type="text" name="lname">

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

A: There is an issue with respect to context get lost of 'this'
Solution 1:
var ajaxFileUploader = function(formId){
    this.formId = formId;
    console.log(this.formId);
    var logger = console.log.bind(this);
   return logger(
       document.querySelector(this.formId)
   );
}

var foo = new ajaxFileUploader('#myFrom');

Solution 2:
Another solution is you can use "formId" which will get by lexical context of function.


text:
Q: iOS 7 status bar overlapping with admob interstitial ads? I'm using phonegap
I'm trying to ad admob interstitial ads but the status bar is always overlapping
things i'v tried so far :
1) hide the status bar from info.plist, which does not work at all
2) hide the status bar with this line of code
    -(BOOL)prefersStatusBarHidden { return YES; }

it does hide the status bar when the app is running but when the interstitial is displayed the status bar appears again,
how can i completely hide the status bar when interstitial is displayed ?
any help is much appriciated


text:
Q: return from incompatible pointer type? I get the warning Return from incompatible pointer type in line where I return sarray, why though? I have been trying to figure out for a while now.. I also get a warning for incompatible pointer type in line
( *iarray )[CHARACTER_LIMIT] = scanCode();

but I think if I fixed the first part, this would be easier to fix this one.
#include <stdio.h>
#define MAX_WORDS 9054 //Scope variables
#define CHARACTER_LIMIT 6
#define MAX_TRIPLETS 3018

char** scanCode(void)
{
    FILE *in_file;
    int i = 0;
    static char sarray[MAX_WORDS][CHARACTER_LIMIT];
    in_file = fopen("message.txt", "r");
    for(i=0; i<WORD_COUNT_MAX; i++)    {
        fscanf(in_file,"%s", sarray[i]);
    }

    return sarray;
    fclose(in_file);
}

int main(void)
{

    char ( *iarray )[CHARACTER_LIMIT] = scanCode();

    while(1);
    return 0;
}

A: sarray is an array or arrays, which can decay to pointer to array, but not pointer to pointer. Converting sarray to char** should be an error.
Besides that, scanCode() returns a pointer to pointer to char. iarray is a pointer to array of char with length CHARACTER_LIMIT. These are not the same type, and the compiler is warning you about this.
You need to change either the return type of the function:
char (*scanCode(void))[CHARACTER_LIMIT] {
  ....
  return sarray;
}

Here, sarray decays to a pointer to array of length CHARACTER_LIMIT.


text:
Q: Wrong parameters for Exception([string $exception [, long $code ]]) Have been staring to this exception for while and have no clue whats going wrong.

Fatal Error: Wrong parameters for Exception([string $exception [, long $code ]])

It seems pretty straight forward, the Exception expects a message and a optional code, though for some reason the code won't agree with me. Even when I drop the last parameter $e (for keeping the stacktrace), this same error pops up.
try {
    // ...
} catch (Exception $e) {
    throw new Exception('Client cannot be created', 0, $e);
}

Only when i omit both the code (0) and the previous exception ($e), the error is thrown correctly.
try {
    // ...
} catch (Exception $e) {
    throw new Exception('Client cannot be created');
}

A: Although i never worked with SOAP technology, so just taken from   SoapClient manual

The exceptions option is a boolean value defining whether soap errors
  throw exceptions of type SoapFault

and soapFault syntax is
SoapFault::SoapFault ( string $faultcode ,
                       string $faultstring [,
                       string $faultactor [,
                       string $detail [,
                       string $faultname [,
                       string $headerfault ]]]] );

so I will suggest you to check all the examples on manual. here i got one exmaple
To get custom Soap Error Codes use in the catch $e->faultcode instead of $e->getCode.
<?php
try {
    // ...
} catch (SoapFault $e) {
    echo $e->faultcode;
}
?>

one more example:
try {
            $options = array(
                'soap_version'=>SOAP_1_1,
                'exceptions'=>true,
                'trace'=>1,
                'cache_wsdl'=>WSDL_CACHE_NONE
            );
            $client = new SoapClient('http://www.example.com/end_point.wsdl', $options);

        } catch (Exception $e) {
            echo "
Exception Error!
";
            echo $e->getMessage();
        }

Hope it helps.


text:
Q: How to use the twitter GeoLocation option in TweetSearch I currently play around with the twitter API and the option GeoLocation in Mathematica version 11.3.
However, the option GeoLocation does not work for me/it does not return anything to me.
What am I doing wrong? The normal request is:
In[19]:= twitter["TweetSearch", "Query" -> "#WolframAlpha"]

If I now change it with the option
twitter["TweetSearch", "Query" -> "#WolframAlpha", "GeoLocation"]

it does not send back anything.
Thanks for any help. Regards Dan.

A: All ServiceObject requests take a request name (string) and list of parameters. In this case if you want to extract GeoLocation for a set of tweets it seems you'll have to do it like this:
tweets =
  twitter["TweetSearch",
   "Query" -> "#WolframAlpha"
   ];

twitter["GetTweet",
     "TweetID" -> #,
    "Elements" -> "FullData"
    ]["Location"] & /@ Normal@tweets[All, "ID"]

{Missing["NotAvailable"], Missing["NotAvailable"],
 Missing["NotAvailable"], Missing["NotAvailable"],
 Missing["NotAvailable"], Missing["NotAvailable"],
 Missing["NotAvailable"], Missing["NotAvailable"],
 Missing["NotAvailable"], Missing["NotAvailable"],
 Missing["NotAvailable"]}

It seems to me that this parameter is of minimal use in general though. I've never seen anything except Missing. Also I would have imagined they'd have implemented this in batched form via this request but I guess not.
If you instead want to add a location parameter to your tweet search you can do it like so:
loc = FindGeoLocation["255 Elm St, Somerville, MA 02144"];
twitter["TweetSearch",
  "Query" -> "",
  GeoLocation ->loc
 ]


text:
Q: Materialized view to use different Serde Version used:  Kafka 3.1.1, Confluent 7.1.0, Avro 1.11.0
I'm creating a REST controller which is "searching" for AVRO objects in a topic. The objects in the topic are serialized using SpecificAvroSerde<>. Each topic has assigned two AVRO schemas. One for the key (with several fields of various types) and one for the value (multiple fields and types).
I've done this several times whereby I'm consuming the topic in a KTable and then materialize it. There is only one pair of serdes involved and the serialized format is the same for both the topic and the materialized view (RocksaltDb). The REST controller then can look up the store and either perform a get with a key or do a range scan between two keys. This all works as expected.
private final static String TOPIC_NAME = "input-topic";
private final static String VIEW_NAME = "materialized-view";

private final SpecificAvroSerde<ProductXrefKey> productXrefKeySerde = new SpecificAvroSerde<>();
private final SpecificAvroSerde<ProductXref> productXrefSerde = new SpecificAvroSerde<>();

final Map<String, Object> props = this.kafkaProperties.buildStreamsProperties();

productXrefKeySerde.configure(props, true);
productXrefSerde.configure(props, false);
KTable<ProductXrefKey, ProductXref> productXrefTable = builder
        .table(TOPIC_NAME, Consumed.with(productXrefKeySerde, productXrefSerde),
                Materialized.<ProductXrefKey, ProductXref, KeyValueStore<Bytes, byte[]>>as(VIEW_NAME)
                        .withKeySerde(productXrefKeySerde)
                        .withValueSerde(productXrefSerde));

<…>

final ReadOnlyKeyValueStore<ProductXrefKey, ProductXref> store =
        streamsBuilderFactoryBean.getKafkaStreams().store(fromNameAndType(VIEW_NAME, keyValueStore()));

try (KeyValueIterator<ProductXrefKey, ProductXref> range = store.range(fromKey, toKey)) {
  if (range != null) {
    range.forEachRemaining(kv -> {
    <…>
    });
  } else {
    log.info("Could not find {} in local ReadOnlyKeyValueStore {}", fromKey, viewName);
  }
}

I now want to change this using a prefix scan instead. Since the key contains multiple fields there is no way to only serialize first part (i.e. first few fields) of the key I need a specialized serializer. This also means I have to use a different serializer for the materialized view itself (SpecificAvroSerde puts the magic number and schema ID at the beginning of the byte array) as otherwise the serialized output for the prefix and the key in the materialized view can't be compared. Hence I created a specialised Serde which serializes the key using the same logic as when used for serializing the prefix but omitting the fields not required for the scan (i.e. omitting the last field). Above code now looks
private final static String TOPIC_NAME = "input-topic";
private final static String VIEW_NAME = "materialized-view";

private final SpecificAvroSerde<ProductXrefKey> productXrefKeySerde = new SpecificAvroSerde<>();
private final SpecificAvroSerde<ProductXref> productXrefSerde = new SpecificAvroSerde<>();

private final SpecificAvroSerde<ProductXrefKey> materializedProductXrefKeySerde = new ProductXrefKeySerde();
// for the value part we can still used standard serde as no change in serialization logic needed
private final SpecificAvroSerde<ProductXref> materializedProductXrefSerde = new SpecificAvroSerde<>();

// telling the serializer to cut off last field
private final SpecificAvroSerde<ProductXref> prefixScanProductXrefSerde = new ProductXrefKeySerde(true);

final Map<String, Object> props = this.kafkaProperties.buildStreamsProperties();

productXrefKeySerde.configure(props, true);
productXrefSerde.configure(props, false);
KTable<ProductXrefKey, ProductXref> productXrefTable = builder
        .table(TOPIC_NAME, Consumed.with(productXrefKeySerde, productXrefSerde),
                Materialized.<ProductXrefKey, ProductXref, KeyValueStore<Bytes, byte[]>>as(VIEW_NAME)
                        .withKeySerde(materializedProductXrefKeySerde)
                        .withValueSerde(materializedProductXrefSerde));

<…>

final ReadOnlyKeyValueStore<ProductXrefKey, ProductXref> store =
        streamsBuilderFactoryBean.getKafkaStreams().store(fromNameAndType(VIEW_NAME, keyValueStore()));

try (KeyValueIterator<ProductXrefKey, ProductXref> range = store.prefixScan(prefixKey, prefixScanProductXrefSerde)){
  if (range != null) {
    range.forEachRemaining(kv -> {
    <…>
    });
  } else {
    log.info("Could not find {} in local ReadOnlyKeyValueStore {}", prefixKey, viewName);
  }
}

My assumption was, that the topic gets deserialized using the SpecificAvroSerde and then gets serialized for the view using my ProductXrefKeySerde.  The problem is, that the content in the materialized view is still serialized using the same logic as in the original topic. It appears that the serializer is never used during the topic being processed and stored in the materialized view. I can verify that also on the file system and see that the keys in the RocksaltDb files are serialized with the magic byte and schema ID and hence prefixScan wont be able to fine anything.
How can I change the serialization format for the materialized view?
Or is there a better way for serializing a prefix AVRO object?

A: It appears that there is some optimization happening which avoids deserialization/serialization if KTable is directly materialized. I've changed the logic such that it consumes it as a KStream and then creates the KTable (toTable(...))
KTable<ProductXrefKey, ProductXref> productXrefStream = builder
            .stream(TOPIC_NAME, Consumed.with(productXrefKeySerde, productXrefSerde))
                    .toTable(Materialized.<ProductXrefKey, ProductXref, KeyValueStore<Bytes, byte[]>>as(VIEW_NAME)
                            .withKeySerde(productXrefKeySerde)
                            .withValueSerde(productXrefSerde));

With this small change, data now gets deserialized (using SpecificAvroSerde<>) and serialized again using the provided ProductXrefKeySerde. Now also the prefix scan works and returns the records as expected.


text:
Q: How to update nested Apollo Cache 3+ levels deep? I have a NuxtJS app with deeply nested data in my Apollo Cache. As an example, my cache could look something like this, where Trips have many Categories which have many Items.
ROOT_QUERY
  trips: [Trip]
    0: Trip:1
      categories: [Category]
        0: Category:1
          items: [Item]
            0: Item:1
            1: Item:2
            2: Item:3
    1: Trip:2

I am trying to update the cache after either removing or adding an item to the array of Items located in trips[0].categories[0]. What I have works, but only after what seems like 1-2 seconds of delay while it talks to my server and returns a response. It seems to me like optimisticResponse is either not working correctly, or the data is too deeply nested to update the UI quick enough.
Here is what my removeItem function looks like:
import { remove } from 'lodash';

async function removeItem ({ fields, trip_id, apollo }) {
  return await apollo.mutate({
    mutation: removeItemMutation,
    variables: fields,
    optimisticResponse: {
      __typename: 'Mutation',
      removeItem: {
        __typename: 'item',
        id: fields.item_id,
        name: '',
        weight: 0,
        unit: '',
        price: 0,
        category_id: fields.category_id,
        quantity: 0,
        position: 0,
        created_at: Date.now(),
        updated_at: Date.now()
      }
    },
    update: (cache, { data: { removeItem } }) => {
      console.log({ removeItem });

      // read
      const data = cache.readQuery({ query: tripsQuery });

      // mutate
      const trip = data.trips.find(trip => trip.id === trip_id);
      const category = trip.categories.find(category => category.id === removeItem.category_id);
      remove(category.items, item => item.id === removeItem.id);
      const otherTrips = data.trips.filter(t => t.id !== trip_id);

      // write
      cache.writeQuery({
        query: tripsQuery,
        data: {
          trips: [trip, ...otherTrips]
        }
      });
    }
  });
}

I can see the console.log in the update function log twice, so I know that optimisticResponse is triggering it at least, I'm just not sure why it appears to be so slow to update the UI? Is there a better way to handle this?
Update:
I think I've narrowed it down to the store.writeQuery() function. I set my Network speed to "Slow 3G", added a bunch of console logs throughout the update function, and they all were almost instantaneous, which leaves the writeQuery function as the culprit. At this point, I'm just honestly not sure what the most effective method is for mutating nested data in the Apollo Cache, and I've been poring over documentation for days now.
Update 2:
I ran an interesting experiment where I run a Categories query after my initial large Trips query. From what I understand, it will avoid making a second request because that data already exists in the Cache, and what this also effective does is change my Cache to look something like this:
ROOT_QUERY
  trips: [Trip]
    0: Trip:1
      categories: [Category]
        0: Category:1
          items: [Item]
            0: Item:1
            1: Item:2
            2: Item:3
    1: Trip:2
  categories: [Category]
    0: Category:1
      items: [Item]
        0: Item:1
        1: Item:2
        2: Item:3
    1: Category:2
    2: Category:3
    3: Category:4
    ...

This effectively puts both Categories and Trips at the top level of the ROOT_QUERY, and when I modified the service function to write to  Categories instead, it reduced the time from ~2.5s to ~350ms.
I think this pretty clearly shows that data nested even 3 levels deep like Items originally was what was causing the issues. My only question now is, what's the point of using GraphQL/Apollo if not to return the data exactly as needed the first time around? Why should I have to run multiple queries to pseudo-flatten the Cache?

A: try cache.modify() (link to api) available from @apollo/client > v3.
Easy process:

*

*identify object to modify

*specify fields to modify(incl nested)

    client.cache.modify({
      id: client.cache.identify({ __typename: 'OBJ_TYPE_NAME', id: <OBJ_IDENTIFIER> }),
      fields: {
        myField(currentValueOFMyField) {
          return { ...currentValueOFMyField, myNestedField: 'new val' };
        },
      },
    });

Hope this'll help someone.


text:
Q: Ubuntu won't start, emergency mode Hello guys I installed Windows 10 on my laptop (toshiba satelite c660) and after that I ran live version of Ubuntu and restored GRUB (with official boot repair tool) so I can start Ubuntu again, after if I choose ubuntu to be booted in GRUB it goes to ubuntu and stucks at boot screen, and after some time I get this message:
Link to picture

A: Solution was simple problem was that Windows has that new type of shutdown (hibernate) so my HDD was still mounted in windows so Ubuntu couldn't load partitions.
Solution is simple and if you have this problem you can do next in Windows :

*

*Right click on desktop, New->Shortcut

*In new window type: shutdown /s /t 0

*Click Next and type any name you wish

*Double click on that icon and your Windows will fully shutdown and you will be able to run Ubuntu.

A: I thought I would throw another solution here as well.
I had the exact same problem. The problem is caused by a feature in windows 10 called 'fast startup' that is turned on by default. It sets some hibernation variables that confuse Ubuntu. So the answer is to turn it off.

*

*In control panel (icons view) select 'Power Options'.

*In the left menu select 'Choose what the power buttons do'.

*Near the top of the screen select 'Change settings that are
currently unavailable' (Might prompt for admin access).

*Scroll to the section labeled 'shutdown settings' and deselect the
'Turn on fast startup (recommended)' checkbox.

*Save changes and the problem should disappear.

This worked for me, hopefully it will also work for anybody else who finds this thread.


text:
Q: importerror: no module named html.parser Eclipse + python 2.7
when i use from bs4 import BeautifulSoup, an error occur
The error list is following:
Traceback (most recent call last):
  File "D:\SDK\SampleTest\FileSearch\src\logic\__init__.py", line 8, in <module>
    from bs4 import BeautifulSoup
  File "D:\Program Files\Python27\lib\site-packages\bs4\__init__.py", line 29, in <module>
    from .builder import builder_registry
  File "D:\Program Files\Python27\lib\site-packages\bs4\builder\__init__.py", line 279, in <module>
    from . import _htmlparser
  File "D:\Program Files\Python27\lib\site-packages\bs4\builder\_htmlparser.py", line 7, in <module>
    from html.parser import HTMLParser
ImportError: No module named html.parser

A: BeautifulSoup documentation is pretty clear about it:

If you get the ImportError "No module named html.parser", your problem
  is that you're running the Python 3 version of the code under Python
  2.

A: @alecxe's answer didn't help in my case. For me, it turned out that I had accidentally downloaded an earlier version of BeautifulSoup either because I was using pip (rather than pip3) or because the link on crummy.com (aptly named) pointed me to a site directory of an old version of BeautifulSoup that Python3 doesn't support anymore... hence the import error.
If you are in my situation: you'll find that the error message points you to a directory in /Library/Frameworks/Python.framework/.../lib/site-packages. Remove all folders related to bs4 and then follow the same instructions for your .tar.gz found in the link on crummy.com (above) (python[X] setup.py install), but this time, get your stinking latest tarball from https://www.crummy.com/software/BeautifulSoup/bs4/download/


text:
Q: mutate week 1-12 to quarter 1 My dataset contains information for each day through 48 weeks.
[screenshot of my dataset][1]
I hope to create a new variable called "quarter", and make every observation whose week variable value = 1-12 be labeled as "a", which means "the first quarter"; also, make every observation whose week variable value = 13-24 be labeled as "b", which means "the second quarter".
I tried mutate() and recode(), it seems that it goes well to mutate only 1 value:
However, when I tried to label the first 12 weeks as quarter "a"; the second 12 weeks as quarter "b",...It fails like:

Error: unexpected '=' in:
  "  ungroup(week) %>%
    mutate(quarter = recode(week, c("1":"12") ="

I wonder how I can fix it. Thank you!

A: We can use cut
cut(total_activity$week, c(-Inf, 12, 24, 36, 48), letters[1:4])

Or another option is using a named vector to replace the values by matching
names(setNames(1:48, rep(letters[1:4], each = 12))[total_activity$week])

A: From ?recode

This is a vectorised version of switch(): you can replace numeric values based on their position, and character values by their name. This is an S3 generic: dplyr provides methods for numeric, character, and factors. For logical vectors, use if_else(). For more complicated criteria, use case_when().

So you'd probably need to use case_when()
total_activity %>%
ungroup(week) %>%
mutate(quarter = case_when(week %in% c("1":"12") ~ "a",
                           week %in% c("13":"24") ~ "b",
                           week %in% c("25":"36") ~ "c",
                           week %in% c("37":"48") ~ "d"))

A: Something to consider is just to use the lubricate package and just use variables for week, and quarter respectively to make sure you always have this info. This is assuming you have a date variable for each observation and you are referring to standard quarters, which it sounds like you are! You'll need to install the package first of course.
    library(lubridate)
    total_activity$Datevar <- mdy(Datevar) #this may change based on your date's format Month/Day/Year is very common.
    new.df <- total_activity %>% group_by(Day= day(day), Week= week(Datevar), Quarter= quarter(Datevar)) %>%
    mutate(total_activity= total_activity)

That may be a more generalizable way to solve the interval problem rather than just hard coding in a few intervals yourself.


text:
Q: "With freedom comes choices" -- is this incorrect? Despite having written in English for 35 years, I was surprised today to be told that the correct phrase is "With freedom come choices" because if you reverse the sentence, "with freedom choices comes" doesn't scan.
I can sort of squint and see the rationale here, but what's the rule? "With freedom come choices" scans wrong, but when I try some mental parallels...
"With happiness comes smiles"
"With marriage comes a horse and carriage"
"With hunger comes a rumbly tummy"
they all scan correctly, but also scan in reverse. ("With happiness, smiles come", etc.)
So a question in two parts: is "With freedom comes choices" actually incorrect; and what is it about this particular phrase that makes it so weird?

A: It is not how any of this dialog has gone.
Your statement "With freedom come choices" when "reversed" can be parallel-scanned (a take on your usage of "scan") not as "With choices come freedom", but as "With freedom, choices come."  I think it can be better understood, if we "reverse" "With a whole chicken comes legs" to "With legs come a whole chicken" and compare against "With a whole chicken, legs come" -- that illustrates the point more clearly.
English is not a programming construct -- the only rule which always applies it that no rules always apply.
So, then, why do we hear of such "rules"?  The answer is that whoever is telling us such rules does not fully understand that they are guides to help you ensure your writing is comprehensible or done well.
Statements which start with a preposition ("with", in this case) are not always the best fit, though sometimes they are.  For example, "With great power comes great responsibility" is a well-known statement in English coming from the Sci-Fi realm.
If, however, someone were to say to me, "With freedom come choices," I would ask, "which choices?"  If they said, on the other hand, "Freedom gives you the privilege of choice," I would know exactly what they were saying.
The question we as writers should ask ourselves is, "Does my statement convey what I have intended?"  The answer should define our writing.
If you're looking for a mathematical formula, your writing will sound like a mathematical formula.  As a professor in my mathematics classes once stated, "there is no substitute for professional judgement."  Subsequently, write to communicate your ideas/intentions/etc and then have others review your writing to ensure you have fulfilled your goal(s).

A: This is a case of subject-verb agreement. The only difference is that your subjects are in the ends of the sentences, rather than the beginnings where you'd expect to find them. In "With freedom come choices," the subject is "choices." Since the subject is plural, use "come" instead of "comes." If it helps to change the word order, think of it as, "Choices come with freedom." Think of the prepositional phrase, "with freedom," as being isolated from the rest of the sentence. Try omitting it entirely so that the plurality of "freedom" doesn't confuse you.  Choices are coming, not freedom, so the word "choices" determines the verb form.
The rule is that, regardless of what's in your prepositional phrases, you should use "come" for plural subjects ("horse and carriage," "smiles") and "comes" for singular subjects ("tummy").

A: It depends on the idea you intend to convey. "With freedom come choices" implies that you are talking about the individual choices rather than the more abstract idea of "choice" in general.
For example, "with freedom comes responsibility" and "with freedom comes choice" they are both referring to the abstract idea of choice or responsibility.
Whereas, "with freedom come responsibilities" and "with freedom come choices" these might be more appropriate if you are going to specifically address what those responsibilities or choices are. Here you are referring to the specific choices that follow going of freedom rather than speaking of "choice" and "freedom" in abstract terms.
A little more context is required to determine which usage would be correct for you. There is not universal absolute regarding the correct usage because every situation is different. I would recommend however to use "come choices" only if you are planning on further expanding about what those choices are within a specific situation. For example, "with freedom come choices, the job I love or the job that pays" vs "with freedom comes choice, freedom of choice is inseparable from freedom itself." In one example, it is referring to a specific choice (a concrete action) rather than the idea of choice (an abstract idea). Action vs philosophy.
Hope this helps.

A: The object of "come" determines whether it is "come" or "comes".  Take something more common.  You buy a burger.  When you do, fries are included.  Here are two sentences that express this:

The burger comes with fries.
  Fries come with the burger.

In each case, the item associated with "come" is clear.  However, you can rearrange either sentence into the same form and make it ambiguous:

With the burger comes fries.  (from 1st sentence)
  With the burger come fries.  (from 2nd sentence)

This construction can be a replacement for either original sentence.  The use of "come" vs. "comes" depends on which sentence you're rearranging; what you intend as the object associated with "come".  Both versions are correct.
Apply this to the sentence in the question:

With freedom comes choices.

This means the same as "Freedom comes with choices."

With freedom come choices.

This means the same as "Choices come with freedom."
Either version can be correct.

A: This has to do with the plurality of 'choices.' The 'comes' form of to come is only correct in the third person singular (he/she/it). as choices id plural, 'come' is the correct word.  Regarding your other examples:

*

*This is incorrect. Smiles is plural, so it should be "With happiness come smiles."

*This is correct, as the 'horse and carriage' is counted as one object for the purposes of the sentence.

*This is incorrect. See 1.

The weirdness in this statement is largely due to nobody thinking much about verb conjugation in their own language. I think.
Verified here.


text:
Q: LocalStorage returning null in a different tab in chrome This is my issue:
I update the localStorage in popup.js in a new tab. I access the same localStorage(same key) in the background.js.
Now this is returning null in every tab apart from the chrome://extensions tab(when I load the extensions.)
I thought localStorage was persistant across all tabs.
Code:
popup.js:
$(document).ready(function (){

    alert(localStorage.getItem('filters'));
    var oldFilters = localStorage.getItem('filters');
    //All the filters show up on the popup.html page.
    document.getElementById('td1').innerHTML = oldFilters;

    var dat = oldFilters + "," + newArray[j]
    localStorage.setItem('filters',String(dat));
}

background.js:
$(window).ready(function() {
  // Handler for .ready() called.

 var filters = localStorage.getItem('filters');

   alert("background + "+ filters);
    //This shows all the filters in the chrome:extensions page but always pops up "background + null" in every new tab load.

//changeImage(filters);

});

A: Background and Browser Action(In your case) Pages live in isolated worlds, their local storage details are not accessible to each other, if you want this sort of access to happen use chrome.storage for your storage needs.
It has few advantages

*

*Your extension's content scripts can directly access user data without the need for a background page.

*A user's extension settings can be persisted even when using split incognito behavior.

*User data can be stored as objects (the localStorage API stores data in strings).
Methods used

*

*chrome.storage.local.get

*chrome.storage.local.set
(use sync instead of local if the data needs to be synchronized with Google Sync)

Demonstration
manifest.json
Ensure all permissions are available for accessing storage API.
{
"name":"Local Storage Demo",
"description":"This is a small use case for using local storage",
"version":"1",
"manifest_version":2,
"background":{
    "scripts":["background.js"]
},
"browser_action":{
    "default_popup":"popup.html",
    "default_icon":"logo.png"
},
"permissions":["storage"]
}

popup.html
A trivial popup html page which refers popup.js to surpass CSP.
<!doctype html>
<html>
<head>
<script src="popup.js"></script>
</head>
<body>
</body>
</html>

background.js
This scripts sets content to chrome storage
//Set some content from background page
chrome.storage.local.set({"identifier":"Some awesome Content"},function (){
    console.log("Storage Succesful");
});
//get all contents of chrome storage
chrome.storage.local.get(null,function (obj){
        console.log(JSON.stringify(obj));
});

popup.js
This script retrieves and sets content from\to chrome storage
document.addEventListener("DOMContentLoaded",function (){
    //Fetch all contents
    chrome.storage.local.get(null,function (obj){
        console.log(JSON.stringify(obj));
    });
    //Set some content from browser action
    chrome.storage.local.set({"anotherIdentifier":"Another awesome Content"},function (){
        console.log("Storage Succesful");
    });
});

If you look at outputs of these js pages, communication of storage (Background -> popup and popup -> background) is achieved.


text:
Q: How to use the OCR (TesseractOCR) php library I had clone git library of OCR using this link .
git clone git://github.com/thiagoalessio/tesseract-ocr-for-php.git

then simply i include the required file by following this example
here is the example code which i m trying to run
require_once './src/TesseractOCR.php';
$tesseract = new TesseractOCR('text.png');
$text = $tesseract->recognize();
echo "The recognized text is:", $text;

But always it fires a fatal Error

Fatal error: Uncaught Error: Call to undefined method TesseractOCR::recognize()

Edit I tried to use run() instead of recognize()
require_once './src/TesseractOCR.php';
$tesseract = new TesseractOCR('text.png');
$text = $tesseract->run();
var_dump($text);
echo PHP_EOL, "The recognized text is:", $text, PHP_EOL;

Then result is : string(0) "" The recognized text is:
I had tried my best to find some appropriate solution  but failed to find some authentic solution

A: This sample code probably comes from this article or some similar. But I can see that it's over 1,5 year old and apparently it's outdated.
Take a look at their github's page. It looks like it's run() instead of recognize() right now:
<?php
echo (new TesseractOCR('german.png'))
    ->run();


text:
Q: Azure "Deployment successful" but app URL yields ":( Application Error" ... Docker ... container start failures I am developing an Angular app with vscode on windows 10. It runs well locally.
I have tried to deploy it to Azure.
The vscode OUTPUT console says:
8:54:39 AM XXXXXXYY: Deployment successful.
8:54:36 AM: Deployment to "XXXXXXYY" completed.

Browsing to the app URL yields :( Application Error
The Azure Application Logs say:
...
2020-02-17T18:02:12.322797181Z A P P   S E R V I C E   O N   L I N U X
2020-02-17T18:02:12.322800881Z
2020-02-17T18:02:12.322804281Z Documentation: http://aka.ms/webapp-linux
2020-02-17T18:02:12.322807781Z NodeJS quickstart: https://aka.ms/node-qs
2020-02-17T18:02:12.322811381Z NodeJS Version : v12.13.0

...

2020-02-17T18:03:50.224589935Z ℹ 「wdm」: Compiled successfully.
Docker on instance: RD0004FFE4001B experienced container start failures.

I didn't knowingly request a Docker container.
Does anyone have any ideas?

A: From your description, you could run an Angular app on windows 10 well locally. So, it recommended to deploy it on Azure app service on Windows instead of Linux as the logged.
You could follow this blog: How to Deploy an Angular application to Azure Web Service to create a windows OS app service. For using VScode deployment, refer to this.
Hope it could help you.


text:
Q: php-login choose page after login I am using the minimal version of php-login from:  http://www.php-login.net/  on Windows 7.  When the user logs in, the login is verified and the response from the verification is True or False. The response is returned to index.php which has this code
if ($login->isUserLoggedIn() == true) {
include("views/logged_in.php");

I would like to give the user an opportunity to choose which page they go to after logging in but that page can only be accessible when the user is logged in. Any ideas?  Let me know if you need more information or if what I am trying to do isn't clear.  Thanks
======= UPDATED BELOW =========================
I modified the code below so that if the user login validation returns true, the user is directed to a page that has these two links  Green Blue  when the user clicks a link the user gets an Access Forbidden error message.
if ($login->isUserLoggedIn() == true) {
    include("views/choose-pages.htm");
} else {
    include("views/not_logged_in.php");
}

A: You can modify not_logged_in.php and have 2 submit buttons like Google, normal "Google search" and  "I'm feeling luckey".
 <input type="submit" name="login" value="Log in green" />
 <input type="submit" name="login" value="Log in blue" />

then modify index.php
if ($login->isUserLoggedIn() == true) {

if ($_POST["login"] == "Log in green") {
include("green.php");
} else {
include("blue.php");
}

}

A: Well, try to create a main page (main.php), in this page write the code of choosing a page, its easy !!
if ($login->isUserLoggedIn() == true) {
include("views/main.php");
}

A: You could store your pages names/links in mysql database first and then get the pages links/names from the mysql database in an array and put it right after your code which would excute after the users are logged in. like so:
if ($login->isUserLoggedIn() == true) {
///Your array of pages here ///

EDIT:
Based on your comment, you can do this:
if ($login->isUserLoggedIn() == false) {
header(location someotherpage.php)

You could put that code in the blue.php, green.php etc etc
Second edit:
I hope i understand it correctly and if so, then you can use something like this:
if ($login->isUserLoggedIn() == false) {
echo "access denied";

you could even populate your page names and links in a drop down menu fashion so the users can select one and go to that page.


text:
Q: How to find the equivalent speed of vector? I've been given this formula:

Suppose c is the current's velocity vector, s is the velocity vector
  the object would have if the water was still, and f = c + s is the object's
  resultant velocity vector.

Below is a question I am trying to figure out.

A boat needs to travel south at a speed of 20 kmh-1. However a
  constant current of 6 kmh-1 is flowing from the south-east. Use
  vectors to find the equivalent speed in still water for the boat to
  achieve the actual speed of 20 km h-1

Is it wrong to apply the formula like so:
20^2 = 6^2 + x^2
400 = 36 + x^2
364 = x^2
x = √364

However, the answer says it is 24.6 km h-1. I am trying to figure out what I am doing wrong?

A: The angle between south and south east directions is $45$ degrees.
We use the generalized Pythagore's Theorem.
$x^2=20^2+6^2-2.20.6.\cos(180-45)$
or
$x^2=436+240.\frac{\sqrt{2}}{2}$
$\approx  436+120.1,414$
$\approx 605,7$
and
$x\approx 24,6109 \; \; km.h{-1} $.

A: In vector notation, using a coordinate system oriented W-E ( $x-$axis) and S-N ($y-$axis), the current velocity vector is:
$$
\vec u=(-3\sqrt{2},3\sqrt{2})^T
$$
the final velocity  vector of the boat is
$$
\vec v=(0,-20)^T
$$
and you want a vector $\vec x=(x,y)^T$ such that:
$$
\vec u +\vec x= \vec v
$$
so we must have:
$$
\begin{cases}
-3\sqrt{2}+x=0\\
3\sqrt{2}+y=-20
\end{cases}
$$
solve this system and find: $|\vec x|=\sqrt{x^2+y^2}= 24.611087..$.


text:
Q: C++ Adding and Subtracting Time I am working on a program that asks the user to enter a time.(Assuming time is in 12 hour mode) The program also can ask the user if they want to add or subtract time from the original time they entered.
For example,
void getTime(int &h, int &m, bool mode);

This would ask the user to enter an hour and minutes
such as h=7 and m=30 would display
the time is 7:30

I want to include another void function that allows a user to add or subtract time. If the user is displayed a menu, and the user selects add time, and enters
h=2 m=30

The new time should display
The new time is 10:00

I think I will need to include a while loop so that hours does not exceed 12 and minutes does not exceed 60, but I am confused on where to start.

A: Time Addition steps :

1)Convert float to integer.
   Time1 is 7.30 x 100  = 730
   Time2 is 2.30 x 100  = 230

   Addition => Time3 is = 960

2) Use divide & module operator (/,%).
   minutes = 960 % 100 ; (60)
   hours   = 960 / 100 ; (9)

3) check two condition:
    if(min== 60){
      hours+1;
      minutes=0;
   }

   if(hour==12 && min==60){
      hours=1;
      minutes=0;
    }

4) final result is : 10.00


text:
Q: Large number of entities in DBContext fetches very slow in Entity Framework I'm trying to create a generic DBContext for one of our database. It has over 1500 entities and I'm trying to create all of them in a single DBContext. It created perfectly fine. Now, I'm trying to access an entity (Table) to fetch records, and it takes about 2 minutes to load. That table has only 16 rows. I think thats a huge amount of time. If I create the DbContext will smaller entities, it works faster.
How do I make a DbContext with large eneties work faster? Any suggestions would help.


text:
Q: Detect stream's Writable last chunk I've created a Writable stream hooked to a large pipeline in our system that writes to the database after BUFFER_SIZE chunks (objects) are received.
getStream() {
    const buffer = [];

    const stream = new Writable({
        objectMode: true,
        async write(chunk,enc,next) {
            buffer.push(chunk);
            if( buffer.length > BUFFER_SIZE ) {
                await insertToDB(buffer);
            }
            next();
        }
    });

    stream.on('finish', async () => {
        // insert last batch?
        if( buffer.length ) {
            await insertToDB(buffer);
        }
    });

    return stream;
}

async consumer() {
    await pipeline(...largePipeline, getStream());
    closeAll();
}

This works ok, but the problem I have is that the on('finish', ...) event handler is called too late, after closeAll() has been called in the consumer() function.
Is there a way for the write() method to know it just received the last chunk? That way I could flush the buffer before calling the last next() and everything would be in sync.
Please, note that in this codebase there's a very strict separation between the pipeline, consumer and writer and I can't and won't exchange promises, flags or state checks between these components. The Writable stream is a unit on it's own! I'm looking for the way Node Streams solve this issue with buffered writes, there must be a way to check that Writable stream is being called last and wait for it to be really done, but I just can't grok it.

A: Ok,  I've found the correct way to do this, Node Streams call a final(next) method when the data is exhausted, that's where you're supposed to finish-up your writing before "releasing" the stream:
getStream() {
    let buffer = [];

    return new Writable({
        objectMode: true,
        async write(chunk,enc,next) {
            buffer.push(chunk);
            if( buffer.length > BUFFER_SIZE ) {
                await insertToDB(buffer);
            }
            next();
        },
        async final(next) {
            // insert last batch?
            if( buffer.length ) {
                await insertToDB(buffer);
                buffer = [];
            }
            next();
        }

    });
}

async consumer() {
    await pipeline(...largePipeline, getStream());
    closeAll();
}

I've also found out that the writev() function is the far superior way to write buffered blocks, instead of implementing your own buffer in a Writable stream:
getStream() {
    return new Writable({
        objectMode: true,
        highWaterMark: BUFFER_SIZE,
        async writev(chunks, next) {
            await insertToDB( chunks.map( chunk => chunk.chunk ) );
            next();
        }
    });
}

It makes use of the highWaterMark configuration setting with the number of chunk objects to send you each time, which allows Node to better control backpressuring for the complete stream pipeline and simplifies your Writable design.


text:
Q: Power operations from a Tate construction In an action-packed three pages of Lurie's DAG-XIII: Rational and p-adic Homotopy Theory, section 2.2: Power Operations on $\mathbb{E}_{\infty}$-algebras, one finds a construction of the power operation $P^0$ following a few observations on the $p$-power Tate construction in the category of $k$-module spectra: $\hat{T}_p: X \mapsto ( X^{\otimes p})^{tC_p}$ and its best colimit-preserving approximation, $T_p.$ For any $\mathbb{E}_\infty$ $k$-algebra $X,$ one obtains a map $T_p(X)[-1] \to X.$ $T_p(X)$ is given by tensoring with a $k$-bimodule which is equivalent on one side to $k^{tC_p}$ and this allows us to obtain operations (not $k$-linear) from elements of Tate cohomology, $ \pi_* k^{tC_p} \simeq \hat{H}^{-*}(C_p, k).$
The precise statement is in construction 2.2.6, which applies the observation that for $k$ a discrete ring of characteristic $p$, $1 \in k$ determines a canonical element of $\hat{H}^{-1}(C_p, k),$ precisely because that group is given as the kernel of the norm. This defines a map $k \to k^{tC_p}[-1]$ which upon composition with the map in the previous paragraph gives a map $X \to X.$ This map is supposed to be the derived witness to $P^0.$
Here is remark 2.2.9

Construction 2.2.6 can be generalized: given any class $x \in \hat{H}^{n-1}(\mathbb{Z} / p\mathbb{Z}; k)$, we obtain an associated
  map $P(x) : A \to A[n]$, which induces
  group homomorphisms $\pi_m(A) \to \pi_{m-n}(A)$. These operations depend functorially
  on $A$ and generate an algebra (the extended Steenrod algebra) of "power
  operations" which act on the homotopy groups of every $\mathbb{E}_\infty$-algebra over $k.$

My questions: is there any reference where this construction of the extended powers is fully elaborated? How much of the elementary structure of the Steenrod algebra (e.g. Adem relations, structure of the dual Steenrod algebra, etc.) can be translated to this point of view?
Just to fill in a few details, Lurie constructs these power operations by first rotating the fiber sequence defining the Tate construction to yield
$\hat{T}_p(X)[-1] \to (X^{\otimes p})_{hC_p} \to (X^{\otimes p})^{hC_p}$
If $X$ is an $\mathbb{E}_\infty$ $k$-algebra, one then computes the composition
$T_p(X)[-1] \to \hat{T}_p(X)[-1] \to (X^{\otimes p})_{hC_p} \to X^{\otimes p}_{h\Sigma_p} \to X$
where the maps are given by approximation, the first map in the rotated fiber sequence, a tautological map between colimits, and the $\mathbb{E}_\infty$ multiplication respectively.

A: What you are looking for is probably Lecture 24 of Lurie's lecture notes on the Sullivan Conjecture. However, these kinds of results (namely, the relation between $\Sigma_2$ and operations, or the relation between $\Sigma_4$ and relations) have a much more extensive historical background, which Dylan Wilson discusses near the beginning of Section 3 of his paper Power operations for $H\underline{\Bbb{F}}_2$ and a cellular construction of $BP{\Bbb R}$.
There is probably more to say but you should feel free to contact me by email if you want further elaboration.


text:
Q: Changing language variable in URL
Possible Duplicate:
Replace values in a URI query string

I am using a language switcher in the navigation bar to switch between EN and DE, my url structure is like this:
http://www.mydomain.com/gallery.php?lang=de
http://www.mydomain.com/gallery-item.php?id=100&lang=de

The switch works well on all urls which don't have an id, but it doesn't work with the ids.
<?php
$url="http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];

?>

What is a good solution to check for $lang=xx or ?lang=xx and then add ?lang=xx or $lang=xx respectively?

A: $params = $_GET;

$params['lang'] = 'en';
printf('En', $url, http_build_query($params));

$params['lang'] = 'de';
printf('De', $url, http_build_query($params));

Or even very compact:
printf('De',
       $url, http_build_query(array('lang' => 'de') + $_GET));

http://php.net/http_build_query


text:
Q: Facebook share button erratic behavior with AngularJS I have two issues trying to integrate Facebook Share buttons in my SPA application. The application displays two lists of articles, those posted y other people and those posted by me. Each of these two lists are presented separately by clicking at one of two buttons at the top of the page. I'm using ng-show to achieve this (meaning, there are two $scope variables that are set to true or false by these buttons, such that if $scope.Others_Posts is set to true, the posts from others are being shown; the opposite for my own posts).
The first problem is that the first time I click on the Facebook share button in, say, the others' posts view, I get the Facebook login window as needed. As long as I remain in the same view (others' posts in this example), popping of the Facebook login works ok. If I switch to the other view (my posts), then the share button does not appear anymore. Nothing I do helps (like going back to the first view). If, on the other hand, I switch to the second view before invoking the share, it also works as long as I don't switch view.
Summarizing, if I click on the share button in one of the two views, as soon as I switch view (from others' posts to mine or vise-versa), the share button stops appearing.
This is what I'm using:
<button type="button" class="btn btn-default"
        aria-haspopup="true"
        aria-expanded="false"
        style="width:100%;height:40px;text-align:left">

</button>

Note that I am wrapping the standard code from Facebook into a button because I have other actions to offer to the user.
My second problem is more AngularJS oriented. The URL I need to share includes parameters that are calculated/built remotely. Since there may be tens or hundreds of entries in the list, I want to invoke the remote service only when it is needed (i.e. when the user wishes to share a particular entry). This is suppose to be done by the function Get_Path_for_Facebook(One_Article) which is to be invoked when the user clicks on the share button of a particular entry.
The issue appears to be the asynchronous behavior of the promise created when invoking the service (i.e. the function Get_Path_for_Facebook issues a HTTP request with a promise that returns the needed parameters, but this takes place too late).

A: You could use Facebook's sharer.php. Basic concept:
HTML
<button ng-click="share(selected)">Share</button>

JS
$scope.share = function share(selected) {
    window.open('https://www.facebook.com/sharer/sharer.php?u=https://your.url/&t=' + selected.id, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=300,width=600');
    // anything else you want to do when clicking the share button
}

You can remove the FB SDK as well, if you're not using it for anything else.


text: Q: Adjusted R-squared for tree-based models How can I use an evaluation metric like adjusted R-squared to evaluate tree-based models? It's not clear to me, since adjusted R-squared accounts for the number of predictors included in a given model, just how large k should be. Does this metric apply to tree-based models? If so, do I use, for the number of predictors, simply the number of columns in my input matrix? Or do I have to account for the number of splits/depth of the trees? Is there a better metric for evaluating the performance of continuous-regression tree-based models?


text:
Q: PDOStatement object and MySQL user defined variables I can't get this script that uses PDO object and MySQL with user-defined variables to work. I learned that with PDO you can't execute two queries in one call, so I split it to two query() calls. But it's still not working. Here is an abstract from my script (connection to MySQL is of course done in a different file, I copied it here so it's all in one place just for the purposes of this question):
 $db_hostname = 'localhost';
 $db_username = 'username';
 $db_password = 'pwd';
 $db_name = 'dbname';
 $dsn = "mysql:dbname=$db_name; host=$db_hostname";

 $pdo = new PDO($dsn, $db_username, $db_password);
 $strsql = "SET @num := 0, @tp := ''";

 $result=$pdo->query($strsql);

 $strsql = "SELECT " . $offer . "_tp AS tp, " . $offer . "_level AS best_offer, Price
           FROM (
                SELECT " . $offer . "_tp, " . $offer . "_level, Price,
                    @num := if(@tp = `" . $offer . "_tp`, @num + 1, 1) as level,
                    @tp := `" . $offer . "_tp` as dummy
                FROM tbl_limit_offers
                WHERE Prod_Code = $procCode) as x
           WHERE x.level = 1";
 $result = $pdo->query($strsql);
 echo $result->rowCount()

If I run that query directly in PHPmyAdmin it returns several records. However, running it with PDO object I get:

Fatal error: Call to a member function rowCount() on a non-object

$result should be a PDOStatement object and rowCount() should be one of its methods. So, why is it not working?

A: *

*You can do as fellows

    $setNumSql = "set @num = ?";
    $stmt = $con->preparedStatement($setNumSql );
    $stmt->executeQuery($num);

    $setTpSql = "set @tp = ?";
    $stmt = $con->preparedStatement($setTpSql);
    $stmt->executeQuery($tp);

    $exampleSql = "select * from tbl where NUM >= @num and TP = @tp";
    $stmt = $con->preparedStatement($exampleSql);
    $stmt->executeQuery();
    return $stmt->fetchAll();

*

*BTW

    $sql = 'SELECT CONCAT(:offer_1, "_tp") AS tp, CONCAT(:offer_2, "_level") AS best_offer ...';

    $binds = array();
    $binds['offer_1'] = $offer;
    $binds['offer_2'] = $offer;

    $stmt = $con->preparedStatement($sql);
    $stmt->executeQuery($binds);

is better than

    $sql = "SELECT " . $offer . "_tp AS tp, " . $offer . "_level AS best_offer ...";

A: I figured out what was wrong with my code. It was the PDO object. When setting it, the dsn cannot have any spaces. After I removed the space in $dsn variable, everything worked as expected.
Original $dsn variable (not working):
 $dsn = "mysql:dbname=$db_name; host=$db_hostname";

Correct way (no space after the semicolon):
 $dsn = "mysql:dbname=$db_name;host=$db_hostname";


text:
Q: How to Create ListView like this? (Traffic Counter) Good Morning All,
I am creating an application to display List of applications with their data usage.
I want my list to look similar to Traffic Counter Pro on android Market
I have also added the print-screen on my box.net as SOF does allow me to upload image
So Can someone direct me how to create ListView like this?
My second Question related to this how to create a tab style Activity.

A: Two examples that helped me a lot:
http://www.codemobiles.com/forum/viewtopic.php?t=876
and
http://android-developers.blogspot.com/2009/02/android-layout-tricks-1.html
i hope they are usefull to you.

A: You have to use custom ListView to embed images and format texts as given in the listview.
check out this example or this example or this example or even this example that gives you good understanding on listviews.
Good luck.

A: This is ListView which items consist of 4 Views objects, look through the tutorial of how to create ListViews and through the tutorial of how to create TabActivitys. And also use links suggested by @parag.

A: If you observe the screen shot carefully you can identify that group of these fields are available as list item.
They are
Application Icon
Application Name
Data Uploaded
Data Downloaded
Total Data Usage

So you have to create a layout with these fields as children with appropriate position and Use this custom layout as child layout for ListView.
I hope it may help you.


text:
Q: Create dynamic library using MSVC command line I've read a lot of posts and yet I don't understand how to create a simple dynamic library on windows using MSVC in command line. What I'm doing is:
1º) Code the DLL
dynamic.h
#pragma once

__declspec(dllexport) void HelloWorld();

dynamic.c
#include "dynamic.h"
#include <stdio.h>

void HelloWorld(){
    printf("Hello World");
}

2º) Compile it
cl /LD dynamic.c

(it compiles correctly and without errors generating dynamic.dll and dynamic.lib)
3º) Try to test it
main.c
#include<stdio.h>
#include"dynamic.h"
int main(){

    HelloWorld();

    return 0;
}

cl main.c dynamic.lib

ERROR (by cl.exe x64)
main.cpp
Microsoft (R) Incremental Linker Version 14.16.27034.0
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:main.exe
main.obj
.\dynamic.lib
main.obj : error LNK2019: unresolved external symbol "void __cdecl HelloWorld(void)" (?HelloWorld@@YAXXZ) referred in main
main.exe : fatal error LNK1120: unresolved externals

Please teach me how dynamic libraries compilation really work because I can't understand

A: Try this way in dynamic.h :
#ifdef __cplusplus
extern "C" {
#endif
    __declspec(dllexport) void HelloWorld();
#ifdef __cplusplus
}
#endif

Use 'dumpbin.exe /exports dynamic.dll' to show exported symbols

A: In main.c it needs to see the function declaration like this:
__declspec(dllimport) void HelloWorld();

So you cannot use the same dynamic.h as you currently have, for both building the DLL and building main.c  .
Normally people will use a preprocessor setup so the same header file has a different declspec depending who is including it, for example:
// dynamic.h
#ifndef DLL_FUNCTION
#define DLL_FUNCTION __declspec(dllimport)
#endif

DLL_FUNCTION void HelloWorld();

dynamic.c (in the DLL):
#define DLL_FUNCTION __declspec(dllexport)
#include "dynamic.h"


text:
Q: Filebeat errors while connecting to ESAAS Below is my filebeat-dev.yaml & its not able to connect to ESAAS :-
filebeat-dev.yaml
filebeat.inputs:
  - type: log
    paths:
      - /var/log/fb/*/*/*.log
    fields:
      app: "29880"
      es_id: "xxxxxxx-xxxx-xxxxx-xxxx-xxxxxxxxxxx"
      es_ver: 0.02
    tags: ["fb-test", "dev"]

output.logstash:
  hosts: ["xxxxxx-filestream-nonprod-xxxx-1-esaasstreams.xxxxx.xxxxx:xxxx"]
  ttl: 120
  loadbalance: true
  ssl.enabled: false
  ssl.certificate_authorities: ["/etc/secrets/ca.crt"]

ERRORS:-
    2023-01-12T09:59:31.709Z    ERROR   [logstash]  logstash/async.go:280   Failed to publish events caused by: write tcp 10.128.7.116:55048->28.39.30.85:56019: write: connection reset by peer
2023-01-12T09:59:31.709Z    INFO    [publisher] pipeline/retry.go:219   retryer: send unwait signal to consumer
2023-01-12T09:59:31.709Z    INFO    [publisher] pipeline/retry.go:223     done
2023-01-12T09:59:32.890Z    ERROR   [publisher_pipeline_output] pipeline/output.go:180  failed to publish events: write tcp 10.128.7.116:55048->28.39.30.85:56019: write: connection reset by peer
2023-01-12T09:59:32.891Z    INFO    [publisher_pipeline_output] pipeline/output.go:143  Connecting to backoff(async(tcp://xxxxx-filestream-nonprod-euwest1-1-esaasstreams.xxxxx.intranet:56019))
2023-01-12T09:59:32.894Z    INFO    [publisher] pipeline/retry.go:219   retryer: send unwait signal to consumer
2023-01-12T09:59:32.895Z    INFO    [publisher] pipeline/retry.go:223     done
2023-01-12T09:59:32.925Z    INFO    [publisher_pipeline_output] pipeline/output.go:151  Connection to backoff(async(tcp://xxxxx-filestream-nonprod-euwest1-1-esaasstreams.xxxxx.intranet:56019)) established
2023-01-12T09:59:32.995Z    ERROR   [logstash]  logstash/async.go:280   Failed to publish events caused by: write tcp 10.128.9.116:41382->28.39.32.10:56019: write: connection reset by peer
2023-01-12T09:59:32.995Z    INFO    [publisher] pipeline/retry.go:219   retryer: send unwait signal to consumer
2023-01-12T09:59:32.996Z    INFO    [publisher] pipeline/retry.go:223     done
2023-01-12T09:59:34.210Z    ERROR   [publisher_pipeline_output] pipeline/output.go:180  failed to publish events: write tcp 10.128.9.116:41382->28.39.32.10:56019: write: connection reset by peer
2023-01-12T09:59:34.210Z    INFO    [publisher_pipeline_output] pipeline/output.go:143  Connecting to backoff(async(tcp://xxxxx-filestream-nonprod-euwest1-1-esaasstreams.xxxxx.intranet:56019))
2023-01-12T09:59:34.210Z    INFO    [publisher] pipeline/retry.go:219   retryer: send unwait signal to consumer
2023-01-12T09:59:34.210Z    INFO    [publisher] pipeline/retry.go:223     done
2023-01-12T09:59:34.250Z    INFO    [publisher_pipeline_output] pipeline/output.go:151  Connection to backoff(async(tcp://xxxxx-filestream-nonprod-euwest1-1-esaasstreams.xxxxx.intranet:56019)) established
2023-01-12T09:59:34.305Z    ERROR   [logstash]  logstash/async.go:280   Failed to publish events caused by: write tcp 10.128.7.116:34410->28.39.32.10:56019: write: connection reset by peer
2023-01-12T09:59:34.305Z    INFO    [publisher] pipeline/retry.go:219   retryer: send unwait signal to consumer
2023-01-12T09:59:34.305Z    INFO    [publisher] pipeline/retry.go:223     done
2023-01-12T09:59:35.401Z    ERROR   [publisher_pipeline_output] pipeline/output.go:180  failed to publish events: write tcp 10.128.7.116:34410->28.39.32.10:56019: write: connection reset by peer
2023-01-12T09:59:35.401Z    INFO    [publisher_pipeline_output] pipeline/output.go:143  Connecting to backoff(async(tcp://xxxxx-filestream-nonprod-euwest1-1-esaasstreams.xxxxx.intranet:56019))
2023-01-12T09:59:35.402Z    INFO    [publisher] pipeline/retry.go:219   retryer: send unwait signal to consumer
2023-01-12T09:59:35.402Z    INFO    [publisher] pipeline/retry.go:223     done
2023-01-12T09:59:35.428Z    INFO    [publisher_pipeline_output] pipeline/output.go:151  Connection to backoff(async(tcp://xxxxx-filestream-nonprod-euwest1-1-esaasstreams.xxxxx.intranet:56019)) established
2023-01-12T09:59:35.477Z    ERROR   [logstash]  logstash/async.go:280   Failed to publish events caused by: write tcp 10.128.7.116:34418->28.39.32.10:56019: write: connection reset by peer
2023-01-12T09:59:35.477Z    INFO    [publisher] pipeline/retry.go:219   retryer: send unwait signal to consumer
2023-01-12T09:59:35.477Z    INFO    [publisher] pipeline/retry.go:223     done
2023-01-12T09:59:37.442Z    ERROR   [publisher_pipeline_output] pipeline/output.go:180  failed to publish events: write tcp 10.128.7.116:34418->28.39.32.10:56019: write: connection reset by peer
2023-01-12T09:59:37.442Z    INFO    [publisher_pipeline_output] pipeline/output.go:143  Connecting to backoff(async(tcp://xxxxx-filestream-nonprod-euwest1-1-esaasstreams.xxxxx.intranet:56019))
2023-01-12T09:59:37.442Z    INFO    [publisher] pipeline/retry.go:219   retryer: send unwait signal to consumer
2023-01-12T09:59:37.442Z    INFO    [publisher] pipeline/retry.go:223     done
2023-01-12T09:59:37.468Z    INFO    [publisher_pipeline_output] pipeline/output.go:151  Connection to backoff(async(tcp://xxxxx-filestream-nonprod-euwest1-1-esaasstreams.xxxxx.intranet:56019)) established
2023-01-12T09:59:37.543Z    ERROR   [logstash]  logstash/async.go:280   Failed to publish events caused by: write tcp 10.128.7.116:34424->28.39.32.10:56019: write: connection reset by peer
2023-01-12T09:59:37.543Z    INFO    [publisher] pipeline/retry.go:219   retryer: send unwait signal to consumer
2023-01-12T09:59:37.543Z    INFO    [publisher] pipeline/retry.go:223     done


text:
Q: PRAW/PYTHON, how to fix 400 HTTP Response in .comments function? I'm trying to scrape reddit comments, and I'm having difficulty sending requests to reddit. It seems that somewhere along my short script some bad syntax has occurred. Can anyone spot it?
I've tried with and without the redirect_uri. Under my Reddit app page it says my app is authorized. I also tried changing the user_agent name to something else besides my username but that still didn't work. I'm unsure what other information to provide.
import praw #Python Reddit API Wrapper

reddit = praw.Reddit(client_id='ID', \ #the personal number
                     client_secret='SECRET', \ #the secret number
                     user_agent='Username', \ #Identical to username
                     username='Username', \ #Identical to user_agent
                     password='PW', \
                     redirect_uri='http://localhost:8080')

#confirm connection:
print(reddit.user.me()) # this works and returns my Username

submission = reddit.submission("https://www.reddit.com/r/funny/comments/ch6oz0/amasian/")
submission.comments #this fails and returns:

  File "/lib/python3.6/site-packages/prawcore/sessions.py", line 130, in _request_with_retries
    raise self.STATUS_EXCEPTIONS[response.status_code](response)

BadRequest: received 400 HTTP response

A: help(reddit.submission)
Help on method submission in module praw.reddit:

submission(id=None, url=None) method of praw.reddit.Reddit instance
    Return a lazy instance of :class:`~.Submission`.

    :param id: A reddit base36 submission ID, e.g., ``2gmzqe``.
    :param url: A URL supported by
        :meth:`~praw.models.Submission.id_from_url`.`.

    Either ``id`` or ``url`` can be provided, but not both.

submission() thinks I was entering an ID because I didn't specify url=''.
Can't mourn too hard, case closed, folks.


text:
Q: Add CORS to embedded API request When using the same domain, this seems to work http://citrowske.com/jsontest.html. But when I try to put it anywhere where outside of the domain (even if the entire JSON file URL is included) nothing happens when the "Load Data" button is clicked.

  <title>The jQuery Example</title>

The json source is located here: http://citrowske.com/help2.json
I believe it must be because of cross origin, but can not make heads or tails of how to incorporate CORS into this program.
Any help would be greatly appreciated!


text:
Q: ATM data latitude longitude for country I was doing some research on ATM locations and I was using Google maps API. Is there a way to get all the ATM locations of a sufficiently large country (like India)? Looking at the API, I was trying to give a max radius of 5000 metres and moving the lat/long by a few degrees each time. Are there better APIs or sites that give this data in an easier way?
Thanks!

A: You should be aware about a couple of details regarding the Google Places API web service:

*

*Places API doesn't work as a database search, and doesn't return all possible results. It returns only prominent results for a specified area. How Google decides which results are prominent and which are not, I cannot say. There is no any authentic way to get all ATMs from the Places API search.

*There are certain restrictions in the Terms of Service that prevent such kind of functionality. Have a look at the section 10.4.c(ii) of ToS:

No creation or augmentation of data sets based on Google's Content or Services. You will not use Google's Content or Services to create or augment your own mapping-related dataset (or that of a third party), including a mapping or navigation dataset, business listings database, mailing list, or telemarketing list.

https://developers.google.com/maps/terms#section_10_4


text:
Q: iOS Multitasking App Launch I developed an app for IPhone and it's posted to itunes for approval. Now when I test the app I found out a strange behavior which I think should be rectified. When I launch app first time, the app launched and when I press home button it closes but when I tap the app icon to open it again it opens where it was last closed.
How can I change the view to first view of the app when it's launched after closing by Home screen button?

A: If you don't want your app to run in the background you need to set the "Application does not run in background" key in the info.plist file.  This means that your app will completely restart every time your user returns to it.  Take time to decide if this really is the best move for your app.  Allowing users to return to where they left off or remembering information about the last session can be a big plus.
If you do not set the info.plist value like I mention above you can manage the way your app behaves by using the: applicationWillEnterForeground: in UIApplicationDelegate or you could observe UIApplicationWillEnterForegroundNotifications.  Read up on all the available notifications and methods available for this in the UIApplication Delegate documentation.