text:
Q: Ruby on Rails - Optimization of code for speed creates js file i am looking for a best way to Optimize this code , we are creating almost 250 js file in file around 90 lines.
any suggestions
 def company_trend_seventy
begin
  @market = Market.find_by_market_opser('TDWL')
  @market.companies.each do |trend|
    f = File.new("#{Rails.root}/public/#{trend.api_id}.js", "w+")
    f.write("var vix = [ \n ")
    seventy = JSON.parse([open("http://www.google.com/finance/getprices?q=#{trend.api_id}&x=TADAWUL&i=86400&p=90d&f=d,c,o,h,l,v&df=cpct&auto=1&ts=1266701290218").read].to_json)
    @date =  Time.at(seventy.first.strip().split("TIMEZONE_OFFSET=180\n")[1].split("\n").first.split(",")[0][1..-1].to_i)
    seventy.first.strip().split("TIMEZONE_OFFSET=180\n")[1].split("\n").each_with_index do |seventyy,i|
      if i == 0
        new_date = Time.at(seventyy.split(",")[0][1..-1].to_i).strftime("%e-%b-%Y")
      else
        new_date = (@date + seventyy.split(",")[0].to_i.day).strftime("%e-%b-%Y")
      end
      f.write("{ date: '#{new_date}', open: #{seventyy.split(",")[4]}, high: #{seventyy.split(",")[2]}, low: #{seventyy.split(",")[3]}, close: #{seventyy.split(",")[1]}, signal: '0', ret: 0 },\n")
    end
    f.write("];")
  end
  flash[:notice] = "Stock Updated Successfully!"
  redirect_to "/admin/companies"
rescue Exception => ex
  flash[:notice] = "Connection Time out!"
  redirect_to admin_dashboards_path
end
end

the out put from the file looks like this
thanks in advance
var vix = [
 { date: '30-Mar-2014', open: 30.9, high: 31.1, low: 30.6, close: 30.8, signal: '0', ret: 0 },
{ date: '31-Mar-2014', open: 30.9, high: 31.5, low: 30.8, close: 31.4, signal: '0', ret: 0 },
{ date: ' 1-Apr-2014', open: 31.5, high: 31.5, low: 31.2, close: 31.4, signal: '0', ret: 0 },
{ date: ' 2-Apr-2014', open: 31.3, high: 31.7, low: 31.3, close: 31.4, signal: '0', ret: 0 },
{ date: ' 3-Apr-2014', open: 31.9, high: 32.6, low: 31.4, close: 32.1, signal: '0', ret: 0 },
{ date: ' 6-Apr-2014', open: 32.3, high: 32.6, low: 31.8, close: 32.1, signal: '0', ret: 0 },
{ date: ' 7-Apr-2014', open: 32.1, high: 32.1, low: 31.4, close: 31.6, signal: '0', ret: 0 },
{ date: ' 8-Apr-2014', open: 31.7, high: 32, low: 31.5, close: 31.9, signal: '0', ret: 0 },
{ date: ' 9-Apr-2014', open: 31.7, high: 31.9, low: 31.4, close: 31.7, signal: '0', ret: 0 },

A: Without knowing how often you update this data, it is difficult to suggest improvements. If this is only a daily update, then you should schedule all of the data to be updated offline, and only create the files once a day. If the goal is a real time updates to the data then you are definitely going the wrong way on this.
Ultimately, you should not be updating the files during the web request. You should offload the file updates to a scheduler or a queue of some kind (like Sidekiq). Or if you need the data to be updated in real time you need to find a different source and use a WebSocket or Server Sent Events to consume the data. Polling for updates every couple of seconds is also valid.


text:
Q: R can not be resolved Every projects which is preexisted in workspace now gives problem of R can not be resolved so what i have to do. i have done lot effort but error is still there. Here is screen shot of that.  (Click on image to enlarge)

A: Android generates the special R.java file from all your xml resource files. If it doesn't get generated, either the build process or IDE is not correctly configured or there's a problem in one or more of the xml files. Check your logs for any hints.

A: There are many reason when R can not be resolved error comes.
First try to clean your Project from Project--> Clean
Second Delete gen Folder and then restart your eclipe from File--> Restart
Then go to Windows --> Preferences --> Android --> and Select the API you want.
and again clean the Project and If need Restart your eclipse.
Hope this Help..

redpajama_set_name: RedPajamaStackExchange


text:
Q: Issue with a section content I have a issue with a section in its content.
If you see everything i write in the section goes outside of it and the section appear to be empty!
HTML:

problemone

problemtwo

problemthree

problemfour

stillproblemfive

problemsix

problemseven

CSS:
http://jsfiddle.net/giovapanasiti/yLtEy/3/
Thanks to everyone!

A: Add overflow: hidden; to #scopridettagli .. its height is collapsed due to its floated descendants
jsFiddle


text:
Q: Calculate area under Bezier curve I'm trying to find a straightforward answer to this question, but the answers I find are often extremely conveluded, or require logic more complicated than what is required. My question is based on the following example:
Let's say I've got a series of points. They are all very tame and predictable, in that they always take on a mathematical curve pattern... (They always start bottom-left and end top-right)

How would I determine the area under this curve in PHP?
Note that I attempt to replicate this example in Javascript using Canvas but failed miserably (using examples like this)
<?php
    //Example requires Imagick
    $width =  800;
    $height = 200;
    $img = new Imagick();
    $img->newImage( $width, $height, new ImagickPixel( 'transparent' ) );
    $draw = new ImagickDraw();
    $draw->setStrokeColor( new ImagickPixel( 'red' ) );
    $draw->setStrokeWidth(4 );
    $draw->setFillColor( new ImagickPixel( 'transparent' ) );
    $points = array
    (
        array( 'x' => 0, 'y' => 200 ),
        array( 'x' => 100, 'y' => 0 ),
        array( 'x' => 200, 'y' => 200 ),
        array( 'x' => 300, 'y' => 0 ),
        array( 'x' => 400, 'y' => 10 ),
        array( 'x' => 500, 'y' => 0 )
    );
    $draw->bezier($points);
    $img->drawImage( $draw );
    $img->setImageFormat( "png" );
    header( "Content-Type: image/png" );
    echo $img;
?>

I understand this question may take a few iterations for me to ask... I would have posted a JSFiddle to back up this example and make it easier to work with, however I could not convert it for use with js/bezierCurveTo, so if a user could help with that it would also be a very useful substitute

A: You can calculate area under parametric curve using formula
A = Integral[t0..t1] (y(t)*x'(t)*dt)

For cubic Bezier: (I don't sure what kind of Bezier curve you are using)
Area = Integral[0..1](y(t)*x'(t)*dt)=
Integral[0..1](
(P[0].Y*(1-t)^3+3*P[1].Y*t*(1-t)^2+3*P[2].Y*t^2*(1-t)+P[3].Y*t^3)*
(P[0].X*(1-t)^3+3*P[1].X*t*(1-t)^2+3*P[2].X*t^2*(1-t)+P[3].X*t^3)'*
dt)

You have to expand the brackets, differentiate the second line expression, multiply expressions, and integrate the result
Maple work (it is hard to copy text without distortions):

Note that some expressions are used many times

A: MBo's solution will give an exact answer, you can also try to use a numerical solution.
As your curve is always increasing in the x direction we can slice it up in the x-direction and approximate the area of each slice. For example if we have four points on the curve (x0,y0), (x1,y1), (x2,y2), (x3,y3) we find the area of the first slice using
(x1-x0)*(y0+y1)/2

this is the area of a trapezium. Do the same for each pair of points and add them up. If your x coords are evenly spaced this gives the trapezium rule which we can simplify. We can assume that here as we are using Bezier curves.
Things are a bit more tricky if we have Bezier curves as we don't actually know the points on the curve. All is not lost as MBo has given the formula for the points
X(t) = P[0].X*(1-t)^3+3*P[1].X*t*(1-t)^2+3*P[2].X*t^2*(1-t)+P[3].X*t^3
Y(t) = P[0].Y*(1-t)^3+3*P[1].Y*t*(1-t)^2+3*P[2].Y*t^2*(1-t)+P[3].Y*t^3

P[0].X is the x coord of your first control point, P[0].Y is the Y value, etc. In code you need to use
x = P[0].X*(1-t)*(1-t)*(1-t)+3*P[1].X*t*(1-t)*(1-t)+3*P[2].X*t*t*(1-t)+P[3].X*t*t*t;
y = P[0].Y*(1-t)*(1-t)*(1-t)+3*P[1].Y*t*(1-t)*(1-t)+3*P[2].Y*t*t*(1-t)+P[3].Y*t*t*t;

which uses multiplication rather than powers. Use a number of values of t between 0 and 1 to find points on the curve and then find the slices.
I've put a javascript fiddle which puts this all together http://jsfiddle.net/SalixAlba/QQnvm/
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

// The control points
var P = [{X:  13, Y: 224 },
     {X: 150, Y: 100 },
     {X: 251, Y: 224 },
     {X: 341, Y:  96 }, ];

ctx.lineWidth = 6;
ctx.strokeStyle = "#333";
ctx.beginPath();
ctx.moveTo(P[0].X, P[0].Y);
ctx.bezierCurveTo(P[1].X, P[1].Y, P[2].X, P[2].Y, P[3].X, P[3].Y);
ctx.stroke();

// draw the control polygon
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(P[0].X, P[0].Y);
ctx.lineTo(P[1].X, P[1].Y);
ctx.lineTo(P[2].X, P[2].Y);
ctx.lineTo(P[3].X, P[3].Y);
ctx.stroke();

function findarea(n) {
ctx.lineWidth = 3;
ctx.strokeStyle = "#f00";
ctx.beginPath();

var nSteps = n - 1;
var x = [P[0].X];
var y = [P[0].Y];
ctx.moveTo(x[0], y[0]);

var area = 0.0;
for (var i = 1; i <= nSteps; ++i) {
    var t = i / nSteps;
    x[i] = P[0].X*(1-t)*(1-t)*(1-t)+3*P[1].X*t*(1-t)*(1-t)+3*P[2].X*t*t*(1-t)+P[3].X*t*t*t;
    y[i] = P[0].Y*(1-t)*(1-t)*(1-t)+3*P[1].Y*t*(1-t)*(1-t)+3*P[2].Y*t*t*(1-t)+P[3].Y*t*t*t;
    ctx.lineTo(x[i], y[i]);

    area += (x[i] - x[i-1]) * (y[i-1] + y[i]) / 2;

    if(x[i]<x[i-1]) alert("Not strictly increasing in x, area will be incorrect");
}
ctx.stroke();
$("#area").val(area);
}

$("#goBut").click(function () {
    findarea($("#nPts").val());
});


text:
Q: How to make a generic ValueComparator for sorting multiple HashMaps? I first started working with a single HashMap such as:
private static Map<Broker, Integer> brokerSalesCountList = new HashMap<Broker, Integer>();

and used
private static ValueComparator4Broker bvc =  new ValueComparator4Broker(brokerSalesCountList);
private static TreeMap<Broker,Integer> sortedbrokerSalesCountList  = new TreeMap<Broker,Integer>(bvc);

sortedbrokerSalesCountList.putAll(brokerSalesCountList);

Here's my Value Comparator code:
public class ValueComparator4Broker implements Comparator<Broker> {

    Map<Broker, Integer> base;
    public ValueComparator4Broker(Map<Broker, Integer> base) {
        this.base = base;
    }

    @Override
    public int compare(Broker a, Broker b) {
        if (base.get(a) >= base.get(b)) {
            return -1;
        } else {
            return 1;
        }
    }
}

PROBLEM: Now I have more than 2 new Hash Maps to be sorted the same way, and rather than duplicating the code for ValueComparator4Broker class, I want to make a single generic and parameterized ValueComparator class which can be used by all new *HashMap*s:
private static Map<Area, Integer> areaBrokerCountList = new HashMap<Area, Integer>();
private static Map<Area, Integer> areaSalesTotalList = new HashMap<Area, Integer>();

I tried something like the following, but the code is erroneous and does not even accept the key object of my HashMap to be substituted for Type. Any help to refine the approach and a code example would be greatly appreciated:
import java.lang.reflect.Type;
import java.util.Comparator;
import java.util.Map;

public class ValueComparator implements Comparator<Type> {
    Map<Type, Integer> base;
    public ValueComparator(Map<Type, Integer> base) {
        this.base = base;
    }

    @Override
    public int compare(Type a, Type b) {
        if (base.get(a) >= base.get(b)) {
            return -1;
        } else {
            return 1;
        } // returning 0 would merge keys
    }

}

A: I'm not so good at cold typing Generic code but here's the idea:
Use the class this way:
Map<Broker, Integer> brokerSalesCountList = new HashMap<Broker, Integer>();

private static ValueComparator<Broker> bvc =  new ValueComparator<Broker>(brokerSalesCountList);

Define the class here:
public class ValueComparator<T> implements Comparator<T> {
    Map<T, Integer> base;
    public ValueComparator(Map<T, Integer> base) {
        this.base = base;
    }

    @Override
    public int compare(T a, T b) {
        if (base.get(a) >= base.get(b)) {
            return -1;
        } else {
            return 1;
        } // returning 0 would merge keys
    }

}


text:
Q: Camel CXFRS endpoint - auto wiring doesn't work I'm trying to use Camel CXFRS component to expose Restful API. This is endpoint configuration:
cxfrs://http://0.0.0.0:8080/api?
    resourceClasses=com.myApp.UserResource
    &bindingStyle=SimpleConsumer
    &performInvocation=true
    &throwExceptionOnFailure=true
    &staticSubresourceResolution=true

in UserResource class:
@Component
@Produces({MediaType.APPLICATION_JSON})
@Path("/user")
public class UserResource {

    @Autowired
    private UserService userService;

    @GET
    @Path("/")
    public List<User> list() { return userService.list(); }
}

I have a problem with the code above:
userService is null, i.e. auto wiring does not work inside CXFRS resource class while working fine in other places.
Any suggestions are welcome! Thanks.


text:
Q: awk to get last working day in all months of a year I'm converting sql logic for finding the last working day in each month of a given year using awk.
Here is my code which looks correct but runs infinitely,
awk -v year=2020 ' function dtp(_dt) { return strftime("%F", mktime(_dt " 0 0 0")) }  function dtday(_dt) { return strftime("%a", mktime(_dt " 0 0 0")) }   function dtmon(_dt) { return strftime("%b", mktime(_dt " 0 0 0")) }
  BEGIN   { ldy=strftime("%j",mktime(year " 12 31 0 0 0" ))
    for(i=1;i<=ldy+0;i++)
    {
      df=year " "  1  "  " i
      if(dtday(df) != "Sun" && dtday(df) != "Sat" )
      a[dtmon(df)]=dtp(df) "|" dtday(df)
    }

  }
  END {  for(i in a) print i,a[i] }
  '

I think I ended up with a convoluted way of doing it. Can this be fixed or are any other simpler awk solutions possible? I'm looking for output like below.
Fri 2020-01-31 :: 2020-01-31
Sat 2020-02-29 :: 2020-02-28 # 29 is sat, so 28
Tue 2020-03-31 :: 2020-03-31
Thu 2020-04-30 :: 2020-04-30
Sun 2020-05-31 :: 2020-05-29 # 31 is Sun, so 29
Tue 2020-06-30 :: 2020-06-30
Fri 2020-07-31 :: 2020-07-31
Mon 2020-08-31 :: 2020-08-31
Wed 2020-09-30 :: 2020-09-30
Sat 2020-10-31 :: 2020-10-30 # 31 is Sat, so 30th
Mon 2020-11-30 :: 2020-11-30
Thu 2020-12-31 :: 2020-12-31

A: Using GNU awk for time functions, the following works because in mktime() arguments the 0th day of the next month is actually considered the last day of the current month, -1th day of next month is the 2nd-last day of the current month, the 13th month of this year is considered the 1st month of next year, etc. so invalid dates like 2021 13 -1 or the equivalent 2022 1 -1 are treated by mktime() like the valid date 2021 12 30.
$ cat tst.awk
BEGIN {
    oneDaySecs = 24 * 60 * 60
    weekEndSecs["Sat"] = oneDaySecs
    weekEndSecs["Sun"] = 2 * oneDaySecs
    for (mthNr=2; mthNr<=13; mthNr++) {
        lastDaySecs = mktime(year " " mthNr " " "0 12 0 0",1)
        lastDayName = strftime("%a",lastDaySecs)
        weekDaySecs = lastDaySecs - weekEndSecs[lastDayName]
        print lastDayName, strftime("%F",lastDaySecs), "::", strftime("%F",weekDaySecs)
    }
}

$ awk -v year=2020 -f tst.awk file
Fri 2020-01-31 :: 2020-01-31
Sat 2020-02-29 :: 2020-02-28
Tue 2020-03-31 :: 2020-03-31
Thu 2020-04-30 :: 2020-04-30
Sun 2020-05-31 :: 2020-05-29
Tue 2020-06-30 :: 2020-06-30
Fri 2020-07-31 :: 2020-07-31
Mon 2020-08-31 :: 2020-08-31
Wed 2020-09-30 :: 2020-09-30
Sat 2020-10-31 :: 2020-10-30
Mon 2020-11-30 :: 2020-11-30
Thu 2020-12-31 :: 2020-12-31

See also awk next month last date logic issue for other day-of-month calculations.


text:
Q: Disable wrap in base class TYPO3 I have installed plugin news. It is generating such html:

    ....

But I want remove this wrapping. I don't have it in my templates. They are generated automatic. How can I do it? Typo3 version 7.6.6

A:

comes form the ext. css_styled_content. You can rewrite this so you don't have this wrapping. Could be done global or per page.
if you use tt_news, the wrapping for the ext. comes from the wrapInBaseClass()
if you use tx_news, you will find the wrapping in the templates of the extension, probably in the Layout template

A: You can disable using TypoScript

tt_content.stdWrap.innerWrap >

Put above line in your Template > root template > Setup
It'll give you clean HTML output as your layout without default wrap of css_styled_content. or if you see classes with extension related then must be from extension which you used. In extBase structure you'll find ext_key/Resources/Private/Layouts and Templates.


text:
Q: Unexpected output in C - printf I am using Dev C++ with TDM-GCC 4.9.2 32 Bit compiler.
I was trying to find the order of evaluation of expressions in printf function for which i made the program:
    #include<stdio.h>
    int main(){
        int x=0;
        printf("%d %d",x++,++x);
        return 0;
    }

If the order of evaluation turns out to be left to right, then the output will be 0 2 and for right to left the output will be 1 1. But the output comes out to be 1 2. How is this possible?
If I write:
    printf("%d %d",x++,x);

then the output is 0 1 which indicates that order of evaluation is right to left and instead if i write:
    printf("%d %d",x,x++);

then the output is 1 0 which indicates that order of evaluation is left to right. Please explain me why I am getting contradictory outputs.


text:
Q: Make KDE Plasma Task switcher show only on primary display Is there a way to get the task-switcher to only display itself on the primary monitor.
My case is that I have a small secondary monitor that I only use for terminals, so I my focus expects the task-switcher to appear on my primary monitor. However, if the windows on the 2. monitor has focus, the task switcher will show up there, and it really bugs me.
My current settings:

A: After reading a similar question and the response from a KWin maintainer I think we can safely say it is not possible (even though the question was not precissely the same).
Extract from comment on Reddit:

No, that is not possible.
/KWin maintainer
Yes alt+tab is part of KWin (called TabBox there). The only way to extend it would be from within kwin project. But that's not an easy task to be totally honest. The code is designed for only one view, changing that is something I would say is close to impossible due to the way how the tabbox is "special". E.g. it intercepts key events, evaluates them and then forwards them to the view. If there are multiple views, who knows what will happen?

A: I just hit this snag as well, with my vertical (1080x1920) secondary monitor. While not exactly what you're asking for, the following tickbox will make the alt+tab switcher appear on the screen that your mouse pointer is currently on:
System settings -> Window Management -> Multiscreen behavior: Active screen follows mouse
For my purposes, I find this an acceptable workaround.


text:
Q: Passing Route Parameters to Filters when Using RESTful Controllers I have searched around for long but nothing can quite fit my problem.
I am using RESTful controllers on my site. For some controller actions, some filters are needed and with this i do something like (i use the beforeFilter() function in the constructor):
<?php
    class PostController extends BaseController {

        public function __construct()
        {
            $this->beforeFilter('auth',array('only'=>array('getCreate','postCreate','getEdit','postEdit','postAddComment')));
            $this->beforeFilter('csrf',array('only'=>array('postCreate','postEdit')));
        //  $this->beforeFilter('auth_post_edit', array('only'=>array('postEdit','getEdit')));
        }

        public function getIndex
        {

            $posts = Post::all();
            return View::make('home')->with('posts',$posts);
        }

        public function getCreate()
        {
            return View::make('posts.create');
        }
...

For the commented filter, however, it is meant to ensure that only the author of a post can edit the post, so i need to pass the post_id which is passed as a URI parameter, to the filter(or access it from the filter).
Some link showed how i can access parameters from the filter using the $route->getParameter('param') in the filter, but the problem is that because i have not even named my parameters(they are named in the controller actions), i am not able to access them from the filter using the above method.
So, how can i access route parameters from within the filter, or/and how do i name route parameters in RESTful controllers(not in their actions)?

A: You could use in your filter the Request::segment()
 Route::filter('foo', function()
{
    $param=Request::segment(2); //if the parameter is on the 2nd uri fregment.
    $post=Post::find($param);
    if ($post->author_id != Auth::user()->id)
    {
        return App::abort('404'); //or whatever
    }
});


text:
Q: Is it possible to read an NFC tag from a card without using an intent? I am building an Android app using Kotlin. I should be able to read NFC tags by clicking a button. I see no way of doing this in all the documentation I have read.
What normally happens: set NFC token (card, chip, whatever) next to the Android device. Device opens the NFC app automatically. At this moment, the intent will be discovered and the card is read.
But how can I be in an application, have the token near the device, then click 'read' button and ONLY then read the information from the token?

A: There answer is yes and no, you can read cards without using an intent but that does not help with you reading on a button click but other changes mean you can only read the tag on a button click.
You don't show your existing code of how you are getting the intent or describe what type of data you are reading, so the answer will be a bit vague.
One point to clarify is that Tag Detection is always initiated by the Tag coming in to range and this is always the starting point of your code's interaction with the Tag BUT you can separate the reading from Tag Detection.
So method of "detect and store"
The first thing to do is use enableReaderMode to get a callback when a Tag is in range.
e.g.
public class NFCActivity extends AppCompatActivity implements NfcAdapter.ReaderCallback{

private NfcAdapter mNfcAdapter;

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

        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);

        // Rest of Activity setup
     }

@Override
    protected void onResume() {
        super.onResume();

        if(mNfcAdapter!= null) {
            Bundle options = new Bundle();
            // Work around for some broken Nfc firmware implementations that poll the card too fast
            options.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 250);

            // Enable ReaderMode for all types of card and disable platform sounds
            mNfcAdapter.enableReaderMode(this,
                    this,
                    NfcAdapter.FLAG_READER_NFC_A |
                            NfcAdapter.FLAG_READER_NFC_B |
                            NfcAdapter.FLAG_READER_NFC_F |
                            NfcAdapter.FLAG_READER_NFC_V |
                            NfcAdapter.FLAG_READER_NFC_BARCODE |
                            NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK |
                            NfcAdapter.FLAG_READER_NO_PLATFORM_SOUNDS,
                    options);
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        if(mNfcAdapter!= null)
            mNfcAdapter.disableReaderMode(this);
    }

The sound on Tag detection is turned off and the automatic reading of any NDEF messages by the system is also turned off (so the user does not know about the tag detection)
Then in onTagDiscovered callback method you just store the Tag object it gives you for later use when you press the button.
The when you read the Tag, you use the stored Tag object and convert it in to one of the Tag tech types
e.g.
Ndef mNdef = Ndef.get(tag);

// Check that it is an Ndef capable card
if (mNdef!= null) {
 NdefMessage mNdefMessage = mNdef.getNdefMessage();
}

You will also have to handle a number of Exceptions as there is no guarentee the Tag is still in range when you press the button.
You cannot really delay enabling detection until you click the button, because most likely the system will do something with the Tag instead if you have not asked for your running app to be sent the callback when it is detected.


text:
Q: Spark shuffle spill metrics Running jobs on a spark 2.3 cluster, I noted in the spark webUI that spill occurs for some tasks :

I understand that on the reduce side, the reducer fetched the needed partitions (shuffle read), then performed the reduce computation using the execution memory of the executor. As there was not enough execution memory some data was spilled.
My questions:

*

*Am I correct ?

*Where the data is spilled ? Spark webUI states some data is spilled to memory shuffle spilled (memory), but nothing is spilled to disk shuffle spilled (disk)
Thanks in advance for your help


text:
Q: UWP - Dispatcher Timer is not running at the desired TimeSpan effectively I'm trying to build my own Metronome UWP application, here's what i've done so far:

*

*I design a Class that will handle all the desired operations for my app, with a DispatcherTimer
...
public MetronomeContructor(int upperNum, int lowerNum, int bpm, System.Uri baseURI, MainPage page, MediaElement mediaTick, MediaElement mediaTock)
{
    UpperNum = upperNum;
    LowerNum = lowerNum;
    Bpm = bpm;
    BaseURI = baseURI;
    CalculateBpm(Bpm);
    Page = page;
    Tick = mediaTick;
    Tock = mediaTock;
    DispTimer = new DispatcherTimer();
    DispTimer.Tick += new EventHandler<object>(timer_Tick);
    Tick.AutoPlay = false;
    Tock.AutoPlay = false;
    Tick.Source = new Uri(Page.BaseUri, Page.Sounds.Where(X => X.Name == "Tick").FirstOrDefault().AudioFile.ToString());
    Tock.Source = new Uri(Page.BaseUri, Page.Sounds.Where(X => X.Name == "Click").FirstOrDefault().AudioFile.ToString());
    StartInterval();
}

//*************************************************************
//Methods
public void CalculateBpm(int bpms)
{
    this.TimerMSecs = (1000 * 60) / bpms;
}

//*********************************
//Dispatcher Methods and Events
public void StartInterval()
{
    DispTimer.Interval = TimeSpan.FromMilliseconds(TimerMSecs);
}

async void timer_Tick(object sender, object e)
{
    await Page.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
    {
        Tick.Play();
    });
}

*My MainPage look like this:
public sealed partial class MainPage : Page
{
public ObservableCollection<Sound> Sounds;
private MetronomeContructor novo;

public MainPage()
{
    this.InitializeComponent();

    Sounds = new ObservableCollection<Sound>();
    SoundManager.GetAllSounds(Sounds);

    novo = new MetronomeContructor(4, 4, 120, this.BaseUri, this, MediaElemTick, MediaElemTock);
}
private void sliderBpm_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
{
        if (novo != null)
        {
            novo.Bpm = (int)sliderBpm.Value;
            novo.CalculateBpm(novo.Bpm);
            DisplayTxtBlock.Text = novo.Bpm.ToString();
            novo.StartInterval();
        }
}

private void StartButton_Click(object sender, RoutedEventArgs e)
{
    if (novo!=null)
    {
        novo.DispTimer.Start();
    }
}

private void StopButton_Click(object sender, RoutedEventArgs e)
{
    if (novo != null)
    {
        novo.DispTimer.Stop();
    }
}

I'm still beggining to implement the functionality, but as a musician i realized that the Dispatcher is not running effectively at a given TimeSpan, so I tried to make it Async operation. Eventhough is not accurate.
I read that with a Dispatcher we only have for sure that will not run before the TimeSpan, but there is the chance it can run after the TimeSpan without control.
My question is this a Design issue? Does anyone know an effective Timer in UWP?
What can be done to implement a simple metronome that can be effective?
Considerations: I'm building a UWP windows 10 App using VisualStudio 2015 I'm a musician that like's to Code in my free time, any design or code improvement ideias are wellcome. Also English is not my native language. TY


text:
Q: SwiftUI how come using a segmented picker style removes the text? Section
      {
          Picker("Tip percentage", selection: $smth)
          {
               ForEach(tipPercentages, id: .self)
                 {
                      Text($0, format: .percent)
                 }
         }
         .pickerStyle(.segmented)
    }

So I have this line of code and I just have a tiny question, before I use the pickerStyle modifier on the Picker View the text always shows up and gets displayed. But then when I use this .segmented modifier suddenly the "Tip percentage" text just disappears..? Why exactly is this happening? If this is happening what is even the point of having it be there??

A: The label is not shown on segmented pickers. However, the label is read by screen readers. It's a good practice to put a label on them for accessibility.
If you really need to show that text, use a Text view. (In a HStack or something)


text:
Q: Qual o significado do termo: Thread-Agnostic Qual o significado do termo: Thread-Agnostic? É possível exemplificar?

OBS: verifiquei o uso deste termo em uma documentação da Microsoft porém este não estava claro, Link


text:
Q: Django redirect inside a function I am trying to build forum. When processing urls there is a board id and a board name. The board name exists just for user readability meaning if someone enters the id correctly but the board name is wrong or has changed it will redirect them to the correct url. I created a function to manage this because there are multiple times I need to check if the board is right, not just this one url.
# urls.py
...
url(r'^boards/(?P<board_id>\d+)/(?P<board_name>[^/]+)/$', views.board, name='board'),
...

# views.py
def board(request, board_id, board_name):
    RedirectIfWrong(request, board_id, board_name)
    ...
    return render(request, 'forums/board.html', {'board': board})

def RedirectIfWrong(request, pk, name):
    board = Board.objects.all().get(pk=pk)
    if (board.name != name):
        return redirect(request.get_full_path().replace(name, board.name, 1))

However when I call redirect inside a function it does not work. I have also heard of using middleware to do this. How does that work and how do I make it only apply to urls involving a board?

A: def board(request, board_id, board_name):
    bad = RedirectIfWrong(request, board_id, board_name)
    if bad:
      return bad
    ...
    return render(request, 'forums/board.html', {'board': board})

A: Add the return
def board(request, board_id, board_name):
    return RedirectIfWrong(request, board_id, board_name)
    # ^^^^


text:
Q: Counts how many times given number appears in a given array (java) I need write a method that counts how many times given number appears in a given array.
On the first line I'll receive a number N - the size of the array.
On the second line I'll receive N numbers separated by spaces - the numbers in the array. On the third line I'll receive a number X
My program needs to print how many times the number X appears in the array. Here is my code:
import java.util.Scanner;

public class AppearanceCount {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int[] numbers = new int[n];
        int x = scanner.nextInt();
        int count = 0;

        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = scanner.nextInt();
        }

        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] == x) {
            count++;
            }
        }
        System.out.println(count);
    }
}

What's my mistake?


text:
Q: java.lang.IllegalStateException: Data cannot occupy more than 10240 bytes when serialized I want to process image using WorkManager. I am getting error while sending byte array to the work manager.
java.lang.IllegalStateException: Data cannot occupy more than 10240 bytes when serialized
Below is my code:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] ImgData = stream.toByteArray();
Data data = new Data.Builder()
            .putByteArray("ByteArrayData",ImgData)
            .build();

Please help or suggest any alternatives.

A: If its all local android development, cant you just use the file path and pass it like that to the worker?
Processing the whole image in the worker will cause this error - looks like the data limit is 10kb, check the docs here:
https://developer.android.com/topic/libraries/architecture/workmanager
So you should refer the image somehow and not pass the image itself.

A: You can't send data with size more than 10240 bytes. You have to save that data somewhere with some id so that you can access it using that id and pass that id to the worker. For eg, you can save your image url or uri in the database with some id as the primary key(you can use auto-generated id), pass that id to the worker and in worker use that id to get image from database and do whatever you want to do.


text:
Q: how to find min and max of float number in matlab The min and max functions in MATLAB work on only integer values. How can I find the min and max of a double vector?
a = [2.1 3.4 5.6 7.6]
min(a)

returns to me:
Subscript indices must either be real positive integers or logicals.

A: You've assigned min as a variable name for an array somewhere in your code.
When you call min(a), MATLAB is trying to grab the indices [2.1,3.4,5.6,7.6] from your array min. To fix this problem, simply call the variable something else.
EDIT: And if you're running it outside of a function, clear min and max, as @Acorbe points out.

A: You need to clear min and max since they are assigned already and their variable counterparts hide the function names.
To use them as functions, do first
 clear min
 clear max


text:
Q: DC's storming me with issues Hi
I have 2 DC's (server 2019) (1 physical, 1 Virtual) was working good, but last month I did notice some issues like I couldn't connect from dc2 to dc1. so I opened Event Viewer to find muliple errors and warnings.
Some of them in DC1:

*

*This server is the owner of the following FSMO role, but does not consider it valid. For the partition which contains the FSMO, this server has not replicated successfully with any of its partners since this server has been restarted. Replication errors are preventing validation of this role.

*Microsoft Windows Server has detected that NTLM authentication is presently being used between clients and this server. This event occurs once per boot of the server on the first time a client uses NTLM with this server.

*Active Directory Domain Services could not resolve the following DNS host name of the source domain controller to an IP address. This error prevents additions, deletions and changes in Active Directory Domain Services from replicating between one or more domain controllers in the forest. Security groups, group policy, users and computers and their passwords will be inconsistent between domain controllers until this error is resolved, potentially affecting logon authentication and access to network resources.

*The DNS server is waiting for Active Directory Domain Services (AD DS) to signal that the initial synchronization of the directory has been completed

*This directory partition has not been backed up since at least the following number of days.

*Automatic registration failed at join phase.
Exit code: Unknown HResult Error code: 0x801c001d

*Failed to register the service principal name 'Microsoft Virtual Console Service'.

*The DFS Replication service failed to contact domain controller  to access configuration information. Replication is stopped. The service will try again during the next configuration polling cycle, which will occur in 60 minutes. This event can be caused by TCP/IP connectivity, firewall, Active Directory Domain Services, or DNS issues.

And on DC2:

*

*The DFS Replication service failed to contact domain controller  to access configuration information. Replication is stopped. The service will try again during the next configuration polling cycle, which will occur in 60 minutes. This event can be caused by TCP/IP connectivity, firewall, Active Directory Domain Services, or DNS issues.

*event id: 5781

*Some of DC1 events.

What I did:

*

*I did search and try almost every solution I found in internet without success.

*I did move the virtual one to be inside the physical one in case my problem was from my switches for example.

*uninstall AV from DC's.

*run my 2nd DC inside the 1st (for troubleshooting).

What I found:

*

*moving the virtual inside the physical one helped me a little, I can now replicate dns but that's it !

*I found odd thing: I can access DC1 by name (in file explorer) from any server except DC2 that access DC1 by ip address only !

UPDATE:
Turn out this issue happened from restoring DC1 couple days ago.
I had learned that I can't restore DC's like any other machine !
OK. I am learning now how to fix this : )
Thanks...

A: You said "DC2 that access DC1 by ip address only"
This would worry me the most, AD is very dependant on DNS (especially SRV records). Troubleshooting this (or even forcing resolution via \system32\drivers\etc\hosts until you get them sync'ed properly) is a first priority.
Also may want to make sure the two DC's are using the same time source (by default your DC emulating a PDC).
"I did move the virtual one to be inside the physical one in case my problem was from my switches for example."
Does that mean you are running one DC on the other using Hyper-V? I would try not to do that. Ideally you'd have your Hyper-V box running nothing other than the hypervisor on the physical hardware.

A: DNS. Focus on DNS. Make sure the records in both DC's reflect the same information, Make sure that a change on one DC is reflected in the other and vise-versa. Did you run DCDIAG and did it pass? I cant imagine it did.
Go with everything the fidler says, pay attention to SRV records and sync the clocks.
The first error(FSMO) is a DNS problem.  (NTLM) can be fixed in Policys. The ADDS error is DNS again. "the DNS server" and the backup error can be ignored for now. The following 3 errors are DNS again.
Your Virtual DC should be moved to another machine, and made to work there.
Again, set the clocks and then focus on DNS and most of this will go away.

A: fixes:

*

*uninstall AV from DC's.

*run my 2nd DC inside the 1st.

I wasn't able to bing tcp 135 on dc2, now I can do that but my issue persistent.


text:
Q: Authentication with old password no longer supported I get an exception, and I can not get any found answers to work.
The exception is this:
Authentication with old password no longer supported, use 4.1 style passwords
when logging on to my mysql database from my .Net project
At my machine it works (as usual) but on my server it doesn't.
On my machine I run  5.5.40 - MySQL Community Server (GPL)
On my server they run 5.1.56-community
I use these packages in my MVC site:
  <package id="MySql.Data" version="6.9.6" targetFramework="net45" />
  <package id="MySql.Web" version="6.9.6" targetFramework="net45" />

I use this way to connect:
 const string ConnectionString = "SERVER=localhost;" + "DATABASE=mydatabase;" + "UID=myusername;" + "PASSWORD=mypassword;";

Any idea on what to do?
I see this answer all the time:
SET SESSION old_passwords=0;
SET PASSWORD=PASSWORD('YOURDATABASEPASSWORD');

But it doesn't work because the setting 'old passwords' on the server is never changed.
the server setting for 'old passwords' is 'ON', the local one is 'OFF'

A: We had a similar issue a few days back after an upgrade to Mysql 5.6 from 5.5 even though the user was using the new 42-bit hash for awhile and not the old 16-bit hash.
I tend to stay away from the set command when updating a password instead use: UPDATE mysql.user SET Password=PASSWORD('MyNewPass') WHERE User='yourusername';
then do a flush privileges;
If that does not work. Delete the user, do a flush privileges, recreate that user, issue proper grants, and do another flush privileges.
This is what worked in our situation for the Authentication with old password not supported error.


text:
Q: British National Grid shapefile prj subtle differences change polygon accuracy I'll preface this question with the statement I know very little about projection systems so this is coming from a position of total ignorance.
I have two shapefiles. One is in England and one is in Scotland, the Scottish one comes from a Scottish goverment website and when converted to geojson with https://github.com/calvinmetcalf/shapefile-js which uses proj4 under the hood, the polygons are several 100 meters offset from the basemap terrain beneath them. The English shapefile is 100% correct.
Upon inspecting the .prj files I can see subtle differences between their definitions:
English shapefile:
PROJCS["British_National_Grid",GEOGCS["GCS_OSGB_1936",DATUM["D_OSGB_1936",SPHEROID["Airy_1830",6377563.396,299.3249646]],PRIMEM["Greenwich",0.0],UNIT["Decimal_Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",400000.0],PARAMETER["False_Northing",-100000.0],PARAMETER["Central_Meridian",-2.0],PARAMETER["Scale_Factor",0.9996012717],PARAMETER["Latitude_Of_Origin",49.0],UNIT["Meter",1.0]]

Scottish shapefile:
PROJCS["British National Grid",GEOGCS["Ordnance Survey Great Brit",DATUM["Ordnance Survey Great Brit",SPHEROID["Airy 1830",6377563.396,299.3249646]],PRIMEM["Greenwich",0.0],UNIT["Decimal_Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",400000.0],PARAMETER["False_Northing",-100000.0],PARAMETER["Central_Meridian",-2.0],PARAMETER["Scale_Factor",0.9996012717],PARAMETER["Latitude_Of_Origin",49.0],UNIT["Meter",1.0]]

The differences are:
Scotland -> England
SPHEROID["Airy 1830" -> SPHEROID["Airy_1830"
GEOGCS["Ordnance Survey Great Brit" -> GEOGCS["GCS_OSGB_1936"
PROJCS["British National Grid" -> PROJCS["British_National_Grid"
DATUM["Ordnance Survey Great Brit" -> DATUM["D_OSGB_1936"
If I simply replace the entire Scotland .prj file with the England .prj file it lines up perfectly
I then tried to work out exactly what part of the Scotland .prj file was causing the issue and I narrowed it down to:
DATUM["Ordnance Survey Great Brit"
If I just replace that with DATUM["D_OSGB_1936" then the polygons align with the terrain perfectly.
So now when I'm handling shapefile uploads I'm going to unzip and find and replace any mention of DATUM["Ordnance Survey Great Brit with DATUM["D_OSGB_1936".
I'm just wondering is that the correct way to approach it? And I wonder why the Scottish goverment would be exporting an incorrect shapefile config, or if I'm missing something and this is a proj4 error in parsing it?

A: The fix for now is:
Using jszip package
// Find filename in list of zip files that has .prj extension
let prjFileName = Object.keys(zip.files).find((item) => item.endsWith(".prj"));

const prjFile = zip.file(prjFileName);

if (prjFile) {
  const prjFileContent = await prjFile.async("string");

  if (prjFileContent.includes('DATUM["Ordnance Survey Great Brit"')) {
    zip.file(
      prjFileName,
      prjFileContent.replace(
        'DATUM["Ordnance Survey Great Brit"',
        'DATUM["D_OSGB_1936"'
      )
    );
  }
}


text:
Q: В Emmet перестала работать аббревиатура восклицательный знак ! знак Работаю в текстовом редакторе VS Code, где уже установлен Emmet. Все аббревиатуры работают, перестала работать аббревиатура восклицательный знак ! знак, при создании документа. Пожалуйста подскажите!

A: Такая же проблема возникла сегодня.
Решилось так - в настройках нужно найти emmet trigger, поставить галку и перезапустить VS Code.


text:
Q: How to make a script that merges all .txt files into one .csv file into multiple columns in Powershell I don't know how to merge multiple .txt files with datas into one .csv file each of the .txt file seperated into columns.
This is my code so far,
$location = (Get-Location).Path
$files = Get-ChildItem $location -Filter "*.asd.txt"
$data = @()

foreach ($file in $files) {
    $fileData = Get-Content $file.FullName

    foreach ($line in $fileData) {
        $lineData = $line -split "\t"
        $data = $lineData[1]
        Add-Content -Path "$location\output.csv" -Value  $data
    }

}

Each of the file looks like this

I want to keep the first column "WaveLength" and put the second columns next to each other from all the files in the folder. The header will start with the exac name
"stovikmladyDoupno2 2020080500001.asd" or "stovikmladyDoupno2 2020080500002.asd" and so on ....
so it should look like this

I have tried to look for information over two days and still don't know. I have tried to put "," on the end of the file, I though excel will handle with that, but nothing helped.
Here I provide few files as test data
https://mega.nz/folder/zNhTzR4Z#rpc-BQdRfm3wxl87r9XUkw
few lines of data
Wavelength  stovikmladyDoupno2 2020080500000.asd
350  6.38961399706465E-02
351  6.14107911262903E-02
352  6.04866108251357E-02
353  5.83485359067184E-02
354  0.054978792413247
355  5.27014859356317E-02
356  5.34849237528764E-02
357  5.32841277775603E-02
358  5.23466655229364E-02
359  5.47595002186027E-02
360  5.22061034631109E-02
361  4.90149806042666E-02
362  4.81633530421385E-02
363  4.83974076557941E-02
364  4.65219929658367E-02
365  0.044800930294557
366  4.47830287392802E-02
367  4.46947539436297E-02
368  0.043756926558447
369  4.31725380363072E-02
370  4.36867609723618E-02
371  4.33227601805265E-02
372  4.29978664449687E-02
373  4.23860463187361E-02
374  4.12183604375401E-02
375  4.14306521081773E-02
376  4.11760903772502E-02
377  4.06421127128478E-02
378  4.09771489689262E-02
379  4.10083126746385E-02
380  4.05161601354181E-02
381  3.97904564387456E-02

A: What you're looking to do is quite a hard task, there are a few ways to do it. This method requires that all files are in memory to process them. You can definitely treat these files as TSVs, so Import-Csv -Delimiter "`t" is an option so you can deal with objects instead of plain text.
# using this temp dictionary to create objects for each line of each tsv
$tmp  = [ordered]@{}
# get all files and enumerate
$csvs = Get-ChildItem $location -Filter *.asd.txt | ForEach-Object {
    # get their content as objects
    $content  = $_ | Import-Csv -Delimiter "`t"
    # get their property Name that is not `Wavelength`
    $property = $content[0].PSObject.Properties.Where{ $_.Name -ne 'Wavelength' }.Name

    # output an object holding the total lines of this csv,
    # its content and the property name of interest
    [pscustomobject]@{
        Lines    = $content.Count
        Content  = $content
        Property = $property
    }
}

# use a scriptblock to allow streaming so `Export-Csv` starts exporting as
# output is going through the pipeline
& {
    # for loop used for each line of the Tsv having the highest number of lines
    for($i = 0; $i -lt [System.Linq.Enumerable]::Max([int[]] $csvs.Lines); $i++) {
        # this boolean is used to preserve the "Wavelength" value of the first Tsv
        $isFirstCsv = $true

        foreach($csv in $csvs) {
            # if this is the first object
            if($isFirstCsv) {
                # add the value of "Wavelength"
                $tmp['Wavelength'] = $csv.Content[$i].Wavelength
                # and set the bool to false, since we are only using this once
                $isFirstCsv = $false
            }
            # then add the value of each property of each Tsv to the temp dictionary
            $tmp[$csv.Property] = $csv.Content[$i].($csv.Property)
        }

        # then output this object
        [pscustomobject] $tmp
        # clear the temp dictionary
        $tmp.Clear()
    }
} | Export-Csv path\to\result.csv -NoTypeInformation

A: I assumed a location since I'm not fond of declaring file paths without a literal path. Please adjust path as needed.
$Files = Get-ChildItem J:\Test\*.txt -Recurse

$Filecount = 0

$ObjectCollectionArray = @()

#Fist parse and collect each row in an array.. While keeping the datetime information from filename.

foreach($File in $Files){

$Filecount++
Write-Host $Filecount

$DateTime = $File.fullname.split(" ").split(".")[1]

$Content = Get-Content $File.FullName

foreach($Row in $Content){

    $Split = $Row.Split("`t")

    if($Split[0] -ne 'Wavelength'){

        $Object = [PSCustomObject]@{
            'Datetime' = $DateTime
            'Number' = $Split[0]
            'Wavelength' = $Split[1]
        }

        $ObjectCollectionArray += $Object
    }
}
}

#Match by number and create a new object with relation to the number and different datetime.

$GroupedCollection = @()
$Grouped =  $ObjectCollectionArray | Group-Object number

foreach($GroupedNumber in $Grouped){
    $NumberObject = [PSCustomObject]@{
            'Number' = $GroupedNumber.Name
    }

foreach($Occurance in $GroupedNumber.Group){
        $NumberObject | Add-Member -NotePropertyName $Occurance.Datetime -NotePropertyValue $Occurance.wavelength
}

$GroupedCollection += $NumberObject

}

$GroupedCollection | Export-Csv -Path J:\Test\result.csv -NoClobber -NoTypeInformation

A: Here is a much more efficient approach that treats the files as plain text, this method is much faster and memory efficient however not as reliable. It uses StreamReader to read the file contents line-by-line and a StringBuilder to construct each line.
& {
    # get all files and enumerate
    $readers = Get-ChildItem $location -Filter *.asd.txt | ForEach-Object {
        # create a stream reader for each file
        [System.IO.StreamReader] $_.FullName
    }

    # this StringBuilder is used to construct each line
    $sb = [System.Text.StringBuilder]::new()
    # while any of the readers has more content
    while($readers.EndOfStream -contains $false) {
        # signals this is our first Tsv
        $isFirstReader = $true
        # enumerate each reader
        foreach($reader in $readers) {
            # if this is the first Tsv
            if($isFirstReader) {
                # append the line as-is, only trimming exces white space
                $sb = $sb.Append($reader.ReadLine().Trim())
                $isFirstReader = $false
                # go to next reader
                continue
            }
            # if this is not the first Tsv,
            # split on Tab and exclude the first token (Wavelength)
            $null, $line = $reader.ReadLine().Trim() -split '\t'
            # append a Tab + this line
            $sb = $sb.Append("`t$line")
        }
        # append a new line and output the constructed string
        $sb.AppendLine().ToString()
        # and clear it for next lines
        $sb = $sb.Clear()
    }

    # dispose all readers when done
    $readers | ForEach-Object Dispose
} | Set-Content path\to\result.tsv -NoNewline


text:
Q: Why do we include dates within single quotes in sql server while inserting? insert into mytable values(1,'06-06-2012');
why do we include date within single quotes here?!! However, we do not do the same while passing the value through  parameterized query?!!

A: With literals, the SQL Server database engine parses the value into native format during query execution.  The datetime value is parsed into an 8-byte native binary representation.
Parameter values are passed to SQL Server in native binary format so enclosurse are not used.  The client API converts the parameter value according to the declared parameter data type and passes the binary value to SQL Server using a TDS protocol remote procedure call.  SQL Server doesn't need to parse the value at all, although conversion might still be needed if the parameter data type doesn't match the data type needed in the query.
For example, if you pass a string parameter value of '06-12-2014' for a table data type of datetime, SQL Server will convert the parameter string value to datetime according to the session DATEFORMAT setting (could be interpreted as '2014-06-12' or '2014-12-06.  Passing a native datetime parameter avoids the ambiguous date format because the task of converting the value to the native binary value was already done on the client.


text:
Q: Access to XMLHttpRequest at 'http://localhost/api from origin 'http://localhost:8000' has been blocked by CORS policy I'm trying to set up an angular app with a simple CRUD API in the backend. I have some problems with the CORS policy and I haven't found the right solution to solve my error. I'm trying to create a user (caregiver) through an angular form.
I think I have more than the necessary headers in my php api. I've put them in an .htaccess file:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

Header always set Access-Control-Allow-Origin *
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"

And I can also see them in my Chrome console when I try the request:

As you can see I get the status code 400: bad request, but it's on my OPTIONS request, so before I can even POST my form data.
Then this is the error I'm getting in my chrome console:

So I assume this is the problem:

Access to XMLHttpRequest at
  'http://localhost/api_pillassist/caregiver/create.php' from origin >'http://localhost:8000' has been blocked by CORS policy: Response to >preflight request doesn't pass access control check: It does not have HTTP ok >status.

I've also already downloaded the chrome extension that enables 'Allow control allow origin: *', but even that doesn't work.
I'll provide some of my code below, although I'm not sure the problem lies there. I've also tried to send my POST request with form data in Postman and this works, so I don't know if this is any useful, but I'll include it anyway:
Here's the component-template I use in my angular app:
<ng-container>
  <form #f="ngForm" (submit)="createCaregiver()">

      Voornaam
      <input type="text" placeholder="Voornaam" #firstName name="firstName" />

      Achternaam
      <input type="text" placeholder="Achternaam" #lastName name="lastName" />

      E-mailadres
      <input type="text" placeholder="E-mailadres" #email name="email" />

      Wachtwoord
      <input type="password" placeholder="Wachtwoord" #password name="password" />

      <button class="btn btn-blue btn-main" type="submit">
        Registreer

      </button>

        Heb je al een account? Log hier in.

  </form>
</ng-container>

This is the 'createCaregiver()' function it links to:
export class RegisterComponent implements OnInit {
  caregiver = new Caregiver('', '', '', '');
  error: string;

  constructor(private caregiverService: CaregiverService) {}

  ngOnInit() {}

  createCaregiver() {
    this.caregiverService.create(this.caregiver).subscribe(
      (res: Caregiver[]) => {
        console.log(res);
      },
      err => ((this.error = err), console.log(err))
    );
  }
}

This is the caregiverService file:
export class CaregiverService {
  private baseUrl = 'http://localhost/api_pillassist/caregiver';
  private caregivers: Caregiver[];

  constructor(private http: HttpClient) {}

  create(caregiver: Caregiver): Observable<Caregiver[]> {
    return this.http
      .post(`${this.baseUrl}/create.php`, { data: caregiver })
      .pipe(
        map(res => {
          this.caregivers.push(res['data']);
          return this.caregivers;
        }),
        catchError(this.handleError)
      );
  }

And this is in my api what I have in the create.php file:
<?php

include_once '../config/database.php';
include_once '../objects/caregiver.php';

$database = new Database();
$db = $database->getConnection();

$caregiver = new Caregiver($db);

$data = $_POST;
$data = json_encode($data);
$data = json_decode($data);

if (
    !empty($data->firstName) &&
    !empty($data->lastName) &&
    !empty($data->email) &&
    !empty($data->password)
) {
    $caregiver->firstName = $data->firstName;
    $caregiver->lastName = $data->lastName;
    $caregiver->email = $data->email;
    $caregiver->password = $data->password;
    $caregiver->created = date('Y-m-d H:i:s');

    if ($caregiver->create()) {

        http_response_code(201);

        echo json_encode(array("message" => "Profile was created."));
    } else {

        http_response_code(503);

        echo json_encode(array("message" => "Unable to create profile."));
    }
} else {

    http_response_code(400);

    echo json_encode(array("message" => "Unable to create profile. Data is incomplete."));
}

I would be very grateful to anyone who can help me.

A: The preflight (OPTIONS) request should return HTTP OK (aka code 200).
You can test the request method in your create.php and return 200 when it is "OPTIONS", not 400 (bad request) as it happens now by default on the error branch of your code.


text:
Q: getting this error while login admin panel in php Notice: session_start(): A session had already been started - ignoring in /storage/ssd5/956/17981956/public_html/admin.php on line 27
Warning: Cannot modify header information - headers already sent by (output started at /storage/ssd5/956/17981956/public_html/admin.php:27) in /storage/ssd5/956/17981956/public_html/admin.php on line 35

A: you've already started session somewhere else, try this code:
if(session_id() == '') {
    session_start();
}

and make sure to put it above the other codes.


text:
Q: Why is this nonlinear system of differential equations giving me the exact same results using a coupled and uncoupled analysis? Consider the following coupled system of differential equations:

Our unknowns are the functions $u_1(t)$, $u_2(t)$ and $u_{GV}(t)$
Let's say $k_{GV}$ is a nonlinear function of the form $k_3=f(u_{GV})$.
$F_1$ and $F_{GV}$ are functions of time imagine sine waves for example. All the other terms appearing in the system are constants.
Now lets say I solve the system and obtain all the results $u_1$, $u_2$ and $u_{GV}$.
I decide then to consider the following problem:
$m_{GV}\ddot{u}_{GV}(t)-k_3u_2(t)+(k_3+k_{GV})u_{GV}(t)=F_{GV}$
In this problem I consider that the terms $\ddot{u}_{GV}$ and ${u}_{GV}$ are unknowns but I consider the same $u_2(t)$ that we obtained earlier. I solve again for ${u}_{GV}$.
Logically shouldn't the new function ${u}_{GV}$ that I obtain be different from the one I obtained from the full system earlier?
I did some simulations on Mathematica and used different $k_{GV}$ some of which are very non linear but I always obtained the same solution. Does this make sense? Is there something I'm not understanding well?
Thank you


text:
Q: 1024 connection limit on a single port I'm running a shoutcast v1 streaming server on a CentOS box. When I start the server as root, I can stream to 1200-1300 clients without a problem.
However, when I run the server as a different user (ccuser) the shoutcast server freezes when the connections reach to ~1019 something.
I have already edited /etc/security/limits.conf with the appropriate setting for both root & ccuser, and after a reboot, ulimit -a confirms it:
root@nsxxxxxx ~/monitoring # su - ccuser
-bash-4.1$ ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 515170
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 16384
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 1024
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

I'm guessing that there is some other safeguard/setting that prohibits normal users to have more than ~1000 connections on a single port. Anyone has any ideas?

A: Each connection is an open socket, each socket is a file, -> therefore that user has file limits restricted to 1024 open files.
Actually i think your pam is enforcing to use /etc/security/limits.d/90-nproc.conf which overrides your set soft limit put up in limits.conf.


text:
Q: Xamarin: Firebase.Firestore.FieldValue does not contain a definition for ArrayUnion I'm currently working on a Xamarin application in iOS and Android that uses Firebase. I'm trying to add a value to an existing array in firestore. In iOS I had no problems using FieldValue.FromArrayUnion(obj). However in Android I'm having a hard time since this method does not exist. Any ideas of how can I add a value into my array without overwriting its data?
Thank you.

A: Xamarin has not released a nuget package version that is binding the Firestore version that added FieldValue.arrayUnion and FieldValue.arrayRemove. Those were added in 17.0.5  and the latest version of 18.0.0, so Microsoft is a number of major/minor versions behind.

Cloud Firestore version 17.0.5
Added FieldValue.arrayUnion() and FieldValue.arrayRemove() to atomically add and remove elements from an array field in a document.

Thus the arrayUnion and arrayRemove static methods are missing in
id="Xamarin.Firebase.Firestore" version="60.1142.1"

Building that binding project from source would be your fastest option:

*

*https://github.com/xamarin/GooglePlayServicesComponents


text:
Q: jsPDF Incomplete or corrupt PNG file Adding regular png images was no problem with jsPDF, but now i send a generated image from my server and the browser console displays this error when rendering the PDF file:

Incomplete or corrupt PNG file

obviously the image is not incomplete or corrupt because i can see the response from the server and the image is fine.
Also to avoid render the pdf file before the image is ready i make a check to a that holds the image value variable if is undefined/null.
the format of my image is

var image = "data:image/png;base64,iVBORw0KGgoAAAANSUh...etc";

What could be the problem?
Edit: i changed the format of the image to jpg and this error shows
Supplied data is not a JPEG

if i use this library jspdf.plugin.addimage.js the images are rendered correctly but not the png images.
edit: 2 i made a solution modifying the jspdf.plugin.addimage.js file function addImage, i just changed the name of the function and added those generated images to pdf with that function, since the version of jspdf.min.js has the same name for the same function with this way it won't override the function i can use the one that works with normal images and the ones generated by the server.

A: This type of error occurs because the image has not finished loading when you send to jsPdf, use onLoad event to check the image loaded completely. for Example -
 /* where src = full image url
        callback = is callback function
        outputFormat = image output format */
    function toDataUrl(src, callback, outputFormat) {
                var img = new Image();
                img.setAttribute('crossOrigin', 'anonymous');
                img.onload = function () {

                   /*image completely converted to base64string */
                    var canvas = document.createElement('CANVAS');
                    var ctx = canvas.getContext('2d');
                    var dataURL;
                    canvas.height = this.height;
                    canvas.width = this.width;
                    ctx.drawImage(this, 0, 0);
                    dataURL = canvas.toDataURL(outputFormat);

                    /* call back function */
                    callback(dataURL);
                };
                img.src = src;
                if (img.complete || img.complete === undefined) {
                    img.src = appConfig.config.dummyImage;
                    img.src = src;
                }
            }

  function callbackBase64(base64Img)
    {
           /*base64Img contains full base64string of image   */
           console.log(base64Img);
    }

call above function and get base64string of image -
toDataUrl('http://example1.com/image1.jpg', callbackBase64(base64Img), "image/png");


text:
Q: PHP + postfix: all emails copied to mailer-daemon I have an ubuntu 12.10 box with latest repository (apt-get) postfix. When I send emails from sendmail command line:
sendmail -r from@example.com -f from@example.com -t to@example.com

The email is sent only to to@example.com (and this is good).
However, when I use PHP and this function:
function mymail($to, $subject, $message, $frommail = "from@example.com", $fromname = "From Me") {
  $subject = "=?utf-8?B?" . base64_encode($subject) . "?=";
  $from = $fromname . " <" . $frommail . ">";
  $headers = "From: " . $from . " \r\n";
  $headers .= "MIME-Version: 1.0\r\n";
  $headers .= "Content-type: text/html; charset=UTF-8\r\n";
  $headers .= "Content-Transfer-Encoding: base64\r\n\r\n";
  $message = base64_encode($message);
  $param = "-r " . $frommail . " \r\n";
  // Optionally tried also
  // $param = "-r " . $frommail . " -f " . $frommail . " \r\n";
  mail($to, $subject, $message, $headers, $param);
}

then to@example.com AND MAILER-DAEMON (which I set to root in my aliases) receives the email.
The MAILER-DAEMON email when read by the mailutils mail command is:
Return-Path: <from@example.com>
Delivered-To: MAILER-DAEMON@localhost
Received: by localhost (Postfix, from userid 33)
    id 5663254EB; Wed, 15 May 2013 16:57:52 +0700 (ICT)
To: to@example
Subject: Test
X-PHP-Originating-Script: 1000:mail_func.php
From: FromMe <from@example.com>
MIME-Version: 1.0
Content-type: text/html; charset=UTF-8
Content-Transfer-Encoding: base64
Message-Id: <20130515095752.5663254EB@localhost>
Date: Wed, 15 May 2013 16:57:52 +0700 (ICT)

followed by the base64 email.
How can I prevent MAILER-DAEMON to receive a copy when sending email by PHP?

A: Not sure I should delete this question or let it for future help. I just found the reason. In the extra parameters, I should use
$param = "-f" . $frommail;

and without ."\r\n" instead of the wrong:
$param = "-r " . $frommail . " \r\n";


text:
Q: Call Unmanaged Code from SSIS Script Task I have Business Intelligence -> Integration Services Project where I have SSIS Packages -> Script Task. I need to call from Script Task Unmanaged code using DllImport. Since I don't know where code for Script Task is stored during run-time I can't call my unmanaged dll.
Example code below for Script Task:
using System; // Console
using System.Runtime.InteropServices; // DllImport

class App
{
    [DllImport("lib.dll", CallingConvention = CallingConvention.Cdecl)]
extern static int next(int n);

    static void Main()
    {
       Console.WriteLine(next(0));
       Dts.TaskResult = (int)ScriptResults.Success;
    }
}

You can find more about Script Task here
Question: How to call Unmanaged Code from SSRS Package -> Script Task?

A: SSIS won't load dll's by location, even managed dll's. You have to GAC them, http://microsoft-ssis.blogspot.com/2011/05/referencing-custom-assembly-inside.html . I would therefore expect you to have to COM register your unmanaged dll, https://technet.microsoft.com/en-us/library/bb490985.aspx .

A: Make sure to copy c/c++ dll into "C:\Program Files\Microsoft SQL Server\120\DTS\Binn" which will be loaded when managed code calls DllImport
NOTE: 120 is version specific make sure to copy to the correct version that you have.


text:
Q: Run JavaScript function on form submit Trying to get back into Javascript, having a little trouble with this very basic thing.
https://jsfiddle.net/gfitzpatrick2/aw27toyv/3/

var name = document.getElementById("name");
function validate() {
  alert("Your name is " +name);
}
<form action="" method="post" name="myForm">
  Name
  <input type="text" name="name" id="name" />
  <input type="submit" name="submit" onclick="validate()" />
</form>

Just wanted a pop up box showing the name you have entered in the field, not sure why it's not working. Am I way off?
Thanks.

A: Here you go with the solution https://jsfiddle.net/aw27toyv/4/
**HTML**
<form onsubmit="return false;" method="post" name="myForm">
    Name
    <input type="text" name="name" id="name" />
    <input type="submit" name="submit" onclick="validate()" />
</form>

**JS**
validate = function() {
    var name = document.getElementById("name").value;
    alert("Your name is " +name);
}


text:
Q: IVI ocr Tesseract Hi all I have a problem with the OCR Tesseract for C# (tessnet2) it find the caractère IVI and not "M" can you help me?
tessnet2.Tesseract ocr = new tessnet2.Tesseract();
         ocr.SetVariable("tessedit_char_whitelist", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); // If digit only
         ocr.Init(@"C:\tresnet", "fra", false); // To use correct tessdata
         List<tessnet2.Word> result = ocr.DoOCR(imgSortie, Rectangle.Empty);
         String ListeLettres= "";

         foreach (tessnet2.Word word in result)
           ListeLettres= ListeLettres + word.Text;

A: @user2094482 Hi,
I was engaged with character recognition with Tesseract and c++. Once i faced the same problem. My system recognized |v| instead of M even the image was clear for my naked eye. I tried several image pre processing concepts such as image binarisation, image blur and etc to get accurate results. But none of those methods gave 100% accurate results for me. Therefore i  tried white listing and it  was a success.
text  = readLettersFromTesseractOCR(img_bw,&error,CharacterSequence);

CharacterSequence was initialized as below.
 CharacterSequence = ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789&lt

Hope this will work with your system as well.

A: I would just using the Replace function for string and replace "IVI" with "M" since there are not many cases where "IVI" is actually written.


text:
Q: Limit as $x$ goes to zero of $\sin(2x)/(2x^2+x)$ without using L'hopital! Solve $\lim_{x\to 0} \cfrac{\sin(2x)}{2x^2+x}$   with a method other than L'hopital, thanks :)

A: Near zero, by taylor's
$$
\sin(2x)\sim 2x
$$
So we have
$$
\lim_{x\rightarrow 0}\frac{\sin(2x)}{2x^2+x}=
\lim_{x\rightarrow 0}\frac{2x}{2x^2+x}=\lim_{x\rightarrow 0}\frac{2}{2x+1}=2
$$

A: First of all, notice that $2x^{2} + x = x(2x+1)$. Hence we can rewrite the given expression as
$$\frac{\sin(2x)}{2x^2 + x} = \frac{\sin(2x)}{x(2x+1)} = \frac{\sin(2x)}{x}\cdot\frac{1}{2x+1}$$
Accordingly to the fundamental trigonometric limit, it results that:
\begin{align*}
\lim_{x\rightarrow 0}\left[\frac{\sin(2x)}{2x^2+x}\right] & = \lim_{x\rightarrow 0} \left[\frac{\sin(2x)}{x}\cdot\frac{1}{2x+1}\right] = \lim_{x\rightarrow 0} \left[2\cdot\frac{\sin(2x)}{2x}\cdot\frac{1}{2x+1}\right]\\
& = 2\cdot\lim_{x\rightarrow 0}\frac{\sin(2x)}{2x}\cdot\lim_{x\rightarrow 0}\frac{1}{2x+1} = 2\cdot 1 \cdot 1 = 2
\end{align*}
It is worth mentioning here that we could split the limit into two limits because both of them exist.

A: Equivalents:
$\sin2x\sim_0 2x$, $2x^2+x\sim_0 x$, hence $\;\dfrac{\sin2x}{2x^2+x}\sim_0\dfrac{2x}{x}=2$.

A: All you need for a lot of problems is $\lim_{x \to 0} \frac{\sin x}{x} = 1$. This is no exception.
However, maybe you have problems with the mechanics of how to use it. There is a way to greatly simplify the use of this: there is a function called $\mathrm{sinc}$ defined by
$$ \mathrm{sinc}(x) = \begin{cases} \frac{\sin x}{x} & x \neq 0 \\ 1 & x = 0 \end{cases} $$
The fact that $\lim_{x \to 0} \frac{\sin x}{x} = 1$ can now be expressed in the much simpler form that $\mathrm{sinc}(x)$ is continuous at $0$ (and everywhere else too).
Then, when taking limits as $x \to 0$, you can rewrite all occurrences of $\sin$ in terms of $\mathrm{sinc}$:
$$ \lim_{x\to 0} \frac{\sin(2x)}{2x^2+x}
=  \lim_{x\to 0} \frac{\mathrm{sinc}(2x) \cdot (2x)}{2x^2+x} $$
and now the right hand side is easy to simplify; we can cancel $x$ and then the result is continuous, so we can plug in $x=0$:
$$ \lim_{x\to 0} \frac{\mathrm{sinc}(2x) \cdot (2x)}{2x^2+x}
=  \lim_{x\to 0} \frac{\mathrm{sinc}(2x) \cdot (2)}{2x+1}
= \frac{\mathrm{sinc}(0) \cdot (2)}{1} = 2 $$

A: The limit equals
$$\lim_{x\to 0} \left [\frac{\sin (2x)}{2x}\cdot\frac{1}{x+1/2}\right ] = 1\cdot \frac{1}{1/2} = 1\cdot 2 = 2.$$


text:
Q: Android how to rotate canvas I'am doing a simple app which displays compas rose + two arrows which represents current and mean wind direction.
What I want is to rotate compas rose + two arrows after they are drawed on canvas.
Here is my example:
@Override
public void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    //compass rose
    canvas.drawBitmap(broza, crozax, crozay, null);

    // Draw current wind arrow + rotate for currentwinddirection from json
    matrix.reset();
    matrix.setRotate(180 + (float) currentWindDirection, bkazalec.getWidth() / 2, bkazalec.getHeight() / 2);
    matrix.postTranslate(ckazalecx, ckazalecy);
    canvas.drawBitmap(bkazalec, matrix, mPaint);

    //Draw mean wind arrow + rotate for meanwinddirection from json
    matrix.reset();
    matrix.setRotate(180 + (float) meanWindDirection, bkazalecmean.getWidth() / 2, bkazalecmean.getHeight() / 2);
    matrix.postTranslate(mkazalecx, mkazalecy);
    canvas.drawBitmap(bkazalecmean, matrix, mPaint);

    //here I want to rotate canvas (compas rose + two arrows) for certain degree number which I obtain from sensor.

    .
    .
    //after this I must "draw" some text for certain datas
    canvas.drawText(getResources().getString(R.string.pod_smer_vetra) + getCurrentWindDirection() + "°", x, y, mPaint);
    y += mPaint.getFontSpacing();
    canvas.drawText(getResources().getString(R.string.pod_hitrost_vetra) + getCurrentWindSpeed() + " m/s", x, y, mPaint);
    y += mPaint.getFontSpacing();
    canvas.drawText(getResources().getString(R.string.pod_povp_smer_vetra) + getMeanWindDirection() + "°", x, y, mPaint);
    y += mPaint.getFontSpacing();
    canvas.drawText(getResources().getString(R.string.pod_pov_hitrost_vetra) + getMeanWindSpeed() + " m/s", x, y, mPaint);
    y += mPaint.getFontSpacing();
    canvas.drawText(getResources().getString(R.string.pod_beaufort) + getMeanWindBeaufort(), x, y, mPaint);
    y += mPaint.getFontSpacing();
    canvas.drawText(getResources().getString(R.string.pod_temp_povrsina_voda) + getTemperatureSeaSurface() + "°C", x, y, mPaint);
    y += mPaint.getFontSpacing();
    canvas.drawText(getResources().getString(R.string.pod_temp_zraka) + getTemperatureAir() + "°C", x, y, mPaint);
}

A: int saveCount = canvas.save();  // save canvas state
try { // just for case if some exceptions
   canvas.rotate(angle, centerX, centerY);
   if (needScale) canvas.scale(scaleX, scaleY, centerX, centerY);
   // draw here what you want
} finally {
  canvas.restoreToCount(saveCount); // restore previous state, further draw is unrotated
}


text:
Q: Конец последовательности в массиве типа данных int Как определить конец числовой последовательности в массиве типа данных int в языке Си, если размер массива заранее не известен?

A: Если это "ваш" массив (Вы его создаете и Вы о нем все знаете), то, как вариант, можно использовать какой-либо признак конца массива - число, которое не участвует в расчетах и не может принадлежать массиву. На примере строк (а это тоже массив байт), таким признаком служит ноль. Если же это не "ваш" массив, то узнать его размер не получится. Хотите динамические массивы - переходите на С++.


text:
Q: How to auto-mount veracrypt device-hosted volume with systemd after login on Linux Mint? I created /etc/systemd/system/veracrypt-automount-devices.service:
[Unit]
Description=VeraCrypt auto-mount device-hosted volumes

[Service]
Type=forking
ExecStartPre=/bin/sleep 300
ExecStart=/usr/bin/veracrypt --auto-mount=devices /media/veracrypt1

[Install]
WantedBy=multi-user.target

Then I did:
sudo systemctl daemon-reload
sudo systemctl enable veracrypt-automount-devices
sudo systemctl status veracrypt-automount-devices

● veracrypt-automount-devices.service - VeraCrypt auto-mount device-hosted volumes
   Loaded: loaded (/etc/systemd/system/veracrypt-automount-devices.service; enabled; vendor preset: enabled)
   Active: failed (Result: timeout) since Sat 2020-06-06 17:28:59 CEST; 8min ago
  Process: 967 ExecStartPre=/bin/sleep 300 (code=killed, signal=TERM)

Jun 06 17:27:29 username-computername systemd[1]: Starting VeraCrypt auto-mount device-hosted volumes...

Jun 06 17:28:59 username-computername systemd[1]: veracrypt-automount-devices.service: Start-pre operation timed out. Terminating.

Jun 06 17:28:59 username-computername systemd[1]: veracrypt-automount-devices.service: Failed with result 'timeout'.

Jun 06 17:28:59 username-computername systemd[1]: Failed to start VeraCrypt auto-mount device-hosted volumes.

As you can see, it doesn't work.
If I grep syslog, here is what I find:
Jun  6 16:56:08 username-computername systemd[1]: veracrypt-automount-devices.service: Control process exited, code=exited status=1
Jun  6 16:56:08 username-computername veracrypt[969]: Enter password:
Jun  6 16:56:08 username-computername systemd[1]: veracrypt-automount-devices.service: Failed with result 'exit-code'.
Jun  6 17:28:59 username-computername systemd[1]: veracrypt-automount-devices.service: Start-pre operation timed out. Terminating.
Jun  6 17:28:59 username-computername systemd[1]: veracrypt-automount-devices.service: Failed with result 'timeout'.

Basically, what I want is to be asked for the password to decrypt the device-hosted volume after I logged in with my username and password in Linux Mint.

A: I found how to do it. I put the veracrypt command in ~/.profile to execute the program on login. See https://askubuntu.com/a/270050/787567.


text:
Q: Bash 3.2's behavior of logical or || operator in arithmetic expressions I experimented on the latest mac OS with a shell scrip "a.sh" with the following content (exact copy).
#!/bin/bash
echo $BASH_VERSION
a=0
(( a < 100 || 1 / a < 2 )) && echo ok

I got:
3.2.57(1)-release
./a.sh: line 4: ((: a < 100 || 1 / a < 2 : division by 0 (error token is "< 2 ")

Since a < 100 is already true, I thought 1 / a < 2 wouldn't be evaluated.
Can someone help me understand this?

A: There are two circumstances you got this error:

*

*Bash 3.2.57 evaluates both sides of a logical or within an arithmetic expression.

*or because you used a single | bit-wise ∨, rather than a double || logical ∨ boolean expression operator:
LC_ALL=C bash -c 'a=0; (( a < 100 | 1 / a < 2 )) && echo ok'

bash: ((: a < 100 | 1 / a < 2 : division by 0 (error token is "a < 2 ")

LC_ALL=C bash -c 'a=0; (( a < 100 || 1 / a < 2 )) && echo ok'

ok

Reason:
| is the bit-wise or operator.
When used as:
a < 100 | 1 / a < 2,
the bit-wise or applies as:
100 | 1,
witch in binary is equivalent to 01100100 ∨ 00000001 → 01100101 binary or 101 base-10.
Finally:
a < 100 | 1 / a < 2 turns-out to be:
a < 101 / a < 2.
When a=0:
0 < 101 / 0 < 2


text:
Q: Shell script to send email is not working from Informatica I have a very simple script
echo "Test email body" | mailx -s "Subject" vinay@informatica.com

When I run the script from linux, it's working fine and I'm receiving the email
But, when I use the same script in post session success command or command task in informatica, the script is successful but I did not receive the mail
Also, without calling the script, I directly gave the mail command in post session success command
echo "Test email body" | mailx -s "Subject" vinay@informatica.com

Still, it's not working.
Can someone help me on this.

A: touch email.txt > you message
cat /tmp/email.txt

Subject: Terminal Email Send

Email Content line 1
Email Content line 2


text:
Q: Processing google photo reference to get the image url I ham using node.js and have the photo reference string and want to get access to the image that is returned.
I have the following code and am getting back something in the body.
  locations.forEach(function(loc) {
    var photoRef;
    if (loc.photos && Array.isArray(loc.photos)) {

      photoRef = loc.photos[0].photo_reference;

      var url_in = 'https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=' + photoRef + '&key=' + key;

      request(url_in, function (error, response, body) {
        if (!error && response.statusCode == 200) {
          console.log(body); // Show the HTML for the Google homepage.
        }
      });

    }

  });

I just want to get the string that is the image url. But what i get back is an object representing the webpage.
Any help would be much appreciated.

A: It is not possible for you to get the image url as per the documentation as the url is not returned by the API.

https://lh3.googleusercontent.com/-B8FWOhhu2_k/VTdYJeFjRhI/AAAAAAAAAD8/JSJamjx4XyA/s1600-w400/

your image url however is already
imageurl = 'https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=' + PHOTO_REFERENCE + '&key=' + API_KEY;
// ^^^ this would return the image for you already (hence, your image url)

You can use this image url for 1,000 free requests per 24 hour period. You can increase this limit free of charge, up to 150,000 requests per 24 hour period, by enabling billing on the Google API Console
Hope this helps!


text:
Q: $0\leq a_{n}-l\leq \dfrac{\pi^{2} }{2^{2n+1}}$ this is related to that one the limits of $a_n $and $b_n$

Let for $n\geq 2\quad a_{n}=\prod\limits_{k=2}^{n}\cos\left(\dfrac{\pi }{2^{k}}\right)$ and
   $b_{n}=a_{n}\cos\left(\dfrac{\pi }{2^{n}}\right)$ and let  $c_{n}=a_{n}\sin\left(\dfrac{\pi }{2^{n}}\right)$

Show that $0\leq a_{n}-l\leq \dfrac{\pi^{2} }{2^{2n+1}}$ (note that: $|1-\cos x|\leq \dfrac{x^{2}}{2})$
can we say that $$b_n < l < a_n$$
Then $$  0 < a_n-l< a_n-b_n$$
$$a_n- b_n = a_n(1-\cos(\dfrac{\pi}{2^n})$$
since $|a_n|\leq 1$  and $1-\cos(\dfrac{\pi}{2^n})\leq \dfrac{\pi}{2^{n+1}} $
am i right

A: As shown in this answer,
$$
a_n=\frac2{2^n\sin\left(\frac\pi{2^n}\right)}
$$
therefore
$$
b_n=\frac2{2^n\tan\left(\frac\pi{2^n}\right)}
$$
It is also shown that
$$
l=\frac2\pi
$$
Furthermore, as shown in this answer, for $|x|\lt\frac\pi2$,
$$
\frac{\sin(x)}{x}\le1\le\frac{\tan(x)}{x}
$$
which implies that
$$
b_n\le\frac2\pi\le a_n
$$
and that
$$
1-\cos(x)\le\frac{x^2}2
$$
therefore
$$
1-\cos\left(\frac\pi{2^n}\right)\le\frac{\pi^2}{2^{2n+1}}
$$
So you are correct, but there are better bounds for $1-\cos(x)$.


text:
Q: Python requests from window.__STATE__ I tried to extract the location from this url (https://www.mapmyrun.com/workout/6292652533), but it seems that the returned information is different from if open that url in browser.
My simple code is
response = requests.get("https://www.mapmyrun.com/workout/6292652533")
document = BeautifulSoup(response.text, "html.parser")
document

Can someone explain me why? My only guess is this information is in window.__STATE__ and Im not sure how to deal with it.
Thanks a lot.

A: All the data about the workout (route, time, heartrate, location etc.) come from API endpoints.
Here's how to get the location:
Note: You need to map the country name as it comes as gb.
import requests

country_mapping = {"gb": "United Kingdom"}
data = requests.get("https://www.mapmyrun.com/internal/route/4785611572").json()
print(data["city"], country_mapping[data["country"]])

Output:
Exeter United Kingdom


text:
Q: Suggested edit presented with no possible actions I was reviewing suggested edits when I ran across this one (to this question):

I expected to see some Approve or Reject buttons, but instead, it sits there just daring me to try anything. It's survived a few refreshes. It might as well be wearing a troll face.
EDIT: the question was migrated, likely after the suggested edit was made.

A: That happens whenever a post is locked after the edit is submitted. Locking happens either when a question is migrated or (rarely) when a moderator hit the "lock" button. I believe suggested edits are deleted when a question is deleted, though there may be a race condition if the edit is submitted close to the time of deletion.
The behavior of suggested edits on migrated questions was changed recently. Looks like a bug crept in then.

A: This was happening on locked posts.
I changed it so when a post is locked all suggested edits are rejected by the community user with the note:

Post was locked - suggested edit can not be processed


text:
Q: Navigating word document with vbscript I want to open a word document and jumpt to page 5 with a vbscript. In vba the following works:
Set word_app = CreateObject("Word.Application")
set word_doc = word_app.documents.open(doc_path)
word_app.displayalerts = false
word_app.visible = true
word_doc.activate
word_doc.select
word_app.activewindow.selection.Goto wdGoToPage, wdGoToAbsolute, 5

but in the vbscript i just jump to page 7 (last page of doc) instead.

A: Instead of using the GoToItem and GoToDirection constants names, just use their number values: learn.microsoft.com/en-us/office/vba/api/word.wdgotoitem


text:
Q: Overriding the assignment method for a has_one I have a has_one association that is reflective on the objects of another association.  I have Project, which has many ProjectUsers, which tie Projects and Users.  One of those ProjectUsers is authoritative.  The issue is that both the has_one and the has_many use the same foreign key on project_users.  Here's the base idea of the models.
class Project < ActiveRecord::Base
  has_many :project_users, :class_name => 'ProjectUser', :foreign_key => 'project_id'
  has_one :authoritative_user, :class_name => 'ProjectUser', :foreign_key => 'project_id', :conditions => {:authoritative => true}
end

class ProjectUser < ActiveRecord::Base
  belongs_to :project
  belongs_to :user
  # has a boolean column 'authoritative'
end

What I would like to be able to do is call something like.
project = Project.new
project_user = ProjectUser.new
project.project_users << project_user
project.authoritative_user = project_user
other_project_user = ProjectUser.new
project.project_users << other_project_user
project.authoriative_user = other_project_user

Where authoritative_user= would update the project user to have authoritative be set to true, and make the previous authoritative user have authoritative set to false.  Another issue I am having is that second time I set authoritative_user on the project, project_id on the previous ProjectUser gets set to nil, and so it is no longer associated though the Project's project_users.
I'm not sure if I'm just doing this completely wrong, or if I'm just missing something.

A: class Project < ActiveRecord::Base
  has_many :project_users
  has_many :users, :through => :project_users

  belongs_to :authoritative_project_user, :class_name => 'ProjectUser'
  has_one    :authoritative_user, :through :authoritative_project_user
end

class  ProjectUser < ActiveRecord::Base
  belongs_to :project
  belongs_to :user

  has_one :project_as_authorized_user
end

then just let the has_one project_as_authorized_user relationship nil out your belongs_to authorized_project_user

A: Personally, I'd probably look to simplify/separate concerns.  Here is an example (note: untested):
class Project < ActiveRecord::Base
  has_many :project_users
  has_many :users, :through => :project_users
  has_one :authoritative_user
end

class  ProjectUser < ActiveRecord::Base
  belongs_to :project
  belongs_to :user
end

class AuthoritativeUser < ActiveRecord::Base
  belongs_to :project
  belongs_to :user

  validates_uniqueness_of :user_id, :scope => :project_id
end

Essentially, I break out the authoritative_user attribute of your ProjectUser model into it's own.  Very simple, clean and not very exciting.
You could probably build a few convenience methods like has_authoritative_user? and update_authoritative_user in your Project model.
I'm sure you'll get a few better suggestions.
Hope this helps!


text:
Q: SQL Server: after insert trigger for MS Access to be converted a stored proceduce I have an after insert trigger on my backend SQL Server; it is working great.
But it is not working for my front-end Microsoft Access when I fill the form, but it works when I fill it directly from the table.
Now I can is there a way that trigger to a stored procedure, but if there is any possibility of the trigger to work with my frontend then great wouldn't need the procedure.
I have 2 tables FC_Fichas and FC_Fichas_Erros.
Any suggestion on how to work through this.
Thanking you all in advance.
Below is the code:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER [dbo].[TRG_Error]
ON [dbo].[FC_Fichas]
AFTER INSERT
AS
BEGIN
    /*PFE10===============================PALUDISMO===============================================================*/
    /*Verificação CasosComFebrePaludismoCriancas2A59MesesM*/
    INSERT INTO [dbo].[FC_Fichas_Erros]
        SELECT
            IDFicha,
            CasosComFebrePaludismoCriancas2A59MesesM = 'TDRRealizadosPaludismoCriancas2A59Meses(M) não pode ser mayor que o CasosComFebrePaludismoCriancas2A59Meses(M)',
            CasosComFebrePaludismoCriancas2A59MesesM = 'Secção 4: Tratamento de Casos',
            CasosComFebrePaludismoCriancas2A59MesesM = 'CasosComFebrePaludismoCriancas2A59MesesM'
        FROM
            INSERTED
        WHERE
            CasosComFebrePaludismoCriancas2A59MesesM < TDRRealizadosPaludismoCriancas2A59MesesM

    /*Verificação CasosComFebrePaludismoCriancas2A59MesesF*/
    INSERT INTO [dbo].[FC_Fichas_Erros]
        SELECT
            IDFicha,
            CasosComFebrePaludismoCriancas2A59MesesF = 'TDRRealizadosPaludismoCriancas2A59Meses(F) não pode ser mayor que o CasosComFebrePaludismoCriancas2A59Meses(F)',
            CasosComFebrePaludismoCriancas2A59MesesF = 'Secção 4: Tratamento de Casos',
            CasosComFebrePaludismoCriancas2A59MesesF = 'CasosComFebrePaludismoCriancas2A59MesesF'
        FROM
            INSERTED
        WHERE
            CasosComFebrePaludismoCriancas2A59MesesF < TDRRealizadosPaludismoCriancas2A59MesesF

    /*Verificação TDRPositivoPaludismoCriancas2A59MesesM*/
    INSERT INTO [dbo].[FC_Fichas_Erros]
        SELECT
            IDFicha,
            TDRPositivoPaludismoCriancas2A59MesesM = 'TDRPositivoPaludismoCriancas2A59Meses(M) não pode ser mayor que o TDRRealizadosPaludismoCriancas2A59Meses(M)',
            TDRPositivoPaludismoCriancas2A59MesesM = 'Secção 4: Tratamento de Casos',
            TDRPositivoPaludismoCriancas2A59MesesM = 'TDRPositivoPaludismoCriancas2A59MesesM'
        FROM
            INSERTED
        WHERE
            TDRPositivoPaludismoCriancas2A59MesesM <> TDRRealizadosPaludismoCriancas2A59MesesM

    /*Verificação TDRPositivoPaludismoCriancas2A59MesesF*/
    INSERT INTO [dbo].[FC_Fichas_Erros]
        SELECT
            IDFicha,
            TDRPositivoPaludismoCriancas2A59MesesF = 'TDRPositivoPaludismoCriancas2A59Meses(F) não pode ser mayor que o TDRRealizadosPaludismoCriancas2A59Meses(F)',
            TDRPositivoPaludismoCriancas2A59MesesF = 'Secção 4: Tratamento de Casos',
            TDRPositivoPaludismoCriancas2A59MesesF = 'TDRPositivoPaludismoCriancas2A59MesesF'
        FROM
            INSERTED
        WHERE
            TDRPositivoPaludismoCriancas2A59MesesF <> TDRRealizadosPaludismoCriancas2A59MesesF

    /*Verificação TDRNegativoPaludismoCriancas2A59MesesM*/
    INSERT INTO [dbo].[FC_Fichas_Erros]
        SELECT
            IDFicha,
            TDRNegativoPaludismoCriancas2A59MesesM = 'TDRNegativoPaludismoCriancas2A59Meses(M) não pode ser mayor que o TDRNegativoPaludismoCriancas2A59Meses(M)',
            TDRNegativoPaludismoCriancas2A59MesesM = 'Secção 4: Tratamento de Casos',
            TDRNegativoPaludismoCriancas2A59MesesM = 'TDRNegativoPaludismoCriancas2A59MesesM'
        FROM
            INSERTED
        WHERE
            TDRNegativoPaludismoCriancas2A59MesesM <> TDRRealizadosPaludismoCriancas2A59MesesM

    /*Verificação TDRNegativoPaludismoCriancas2A59MesesF*/
    INSERT INTO [dbo].[FC_Fichas_Erros]
        SELECT
            IDFicha,
            TDRNegativoPaludismoCriancas2A59MesesF = 'TDRNegativoPaludismoCriancas2A59Meses(F) não pode ser mayor que o TDRNegativoPaludismoCriancas2A59Meses(F)',
            TDRNegativoPaludismoCriancas2A59MesesF = 'Secção 4: Tratamento de Casos',
            TDRNegativoPaludismoCriancas2A59MesesF = 'TDRNegativoPaludismoCriancas2A59MesesF'
        FROM
            INSERTED
        WHERE
            TDRNegativoPaludismoCriancas2A59MesesF <> TDRRealizadosPaludismoCriancas2A59MesesF
END