text:
Q: Alamofire Add Path Variable to Url How can i use that kind GET request "http://someApi/someEndPoint/:variable1/:variable2" in alamofire.
That variables contents some strings, like variable1 = "USD" and variable2 = "weekly"

A: There is not build-in support for this in Alamofire. You can take the plain string interpolation approach like this:
let urlString = "http://someApi/someEndPoint/\(variable1)/\(variable2)"

A: Alamofire doesn't support any sort of automatic path parameter encoding. Instead, you can build your paths programmatically using string interpolation.
var url = URL(string: "http://someApi/someEndPoint/")!
url.appendPathComponent("\(variable1)")
url.appendPathComponent("\(variable2)")

A: if you wanna get, for instance, blah1:
static var APIendPoint = "http://someApi.blah.blah"

static var blah1: String {
     return APIendPoint + "/blah1"
}

which gives you access to "http://someApi.blah.blah/blah1"
and if you have a path paramter like this: "http://someApi.blah.blah/blah1{blahID}/blah2
you would do similar approach like in this way:
static func getBlah2(blahID: String) -> String {
        return blah1 + "/\(blahID)" + "/blah2"
    }

and just call this in your API request, easier using alamofire:
func api(id: Int = 0) {
AF. request(YourAPI.getBlah2(blahID: id), method .get) .. .
.. .
}

easier.. .


text:
Q: initializing oled display using vhdl I'm trying to use a LCD project in my own project but I don't really
understand this project fully especially with the counters e.g count1 and count2
I can provide the datasheet if needed!
I hope I can get a clarification to this, I understand what is going on when counter has reached a certain number but what I do not understand is what is that number is representing!
I think something is worth mentioning is the clock used in the FPGA is 50MHz
the code is as fellow
library ieee;
        use ieee.std_logic_1164.all;

entity display is
port(   clk         : in std_logic;
        rst         : in std_logic;
        byte_ready  : in std_logic;
        RS          : out std_logic;
        RW          : out std_logic;
        E           : out std_logic;
        DB          : out std_logic_vector(7 downto 0);
        rxdata      : in std_logic_vector(7 downto 0) );

end entity display;

architecture rtl of display is
    signal cnt          : integer range 0 to 1000000;           -- init counter
    signal cnt2         : integer range 0 to 50000000;          -- counter that resets every time byte i recieved

begin
clk_gen : process(clk, cnt, rst)
begin
    if (rst = '0') then
        cnt  <= 0;
        cnt2 <= 0;
    else
        if rising_edge(clk) and cnt < 1000000 then
            cnt <= cnt + 1;
        elsif rising_edge(clk) and cnt = 1000000 then
            if (byte_Ready = '1') then
                cnt2 <= 0;
            end if;
            if (cnt2 < 5000000) then
                cnt2 <= cnt2 + 1;
            end if;
        end if;
    end if;
end process clk_gen;

p_main : process(clk, rst)
begin
    if (rst = '1') then
        if rising_edge(clk) then
            case cnt is                 -- INIT
                when 100000 =>
                    RS <= '0';
                    RW <= '0';
                    E  <= '1';
                    DB <= "00111000";   -- function set  --kan ändras till 00111011 western eurpean #2
                when 140000 =>
                    E  <= '0';

                when 150000 =>
                    E  <= '1';
                    DB <= "00001011";   -- display off
                when 190000 =>
                    E <= '0';

                when 200000 =>
                    E  <= '1';
                    DB <= "00000001";   -- display clear
                when 300000 =>
                    E  <= '0';

                when 350000 =>
                    E  <= '1';
                    DB <= "00000110";   -- entry mode
                when 390000 =>
                    E  <= '0';

                when 400000 =>
                    E  <= '1';
                    DB <= "00000010";   -- home command
                when 440000 =>
                    E  <= '0';

                when 450000 =>
                    E  <= '1';
                    DB <= "00001111";   -- display on
                when 490000 =>
                    E  <= '0';

                when 500000 =>
                    RS <= '0';
                    E  <= '1';
                    DB <= "00010000";   -- cursor shift left
                when 550000 =>
                    E  <= '0';

                when 600000 =>
                    RS <= '1';
                    E  <= '1';
                    DB <= "10100000";   -- output space
                when 650000 =>
                    E  <= '0';

                when 700000 =>
                    RS <= '0';
                    E  <= '1';
                    DB <= "00010000";   -- cursor shift left
                when 750000 =>
                    E  <= '0';

            when others => null;
        end case;

        if (rxdata = "01111111") then   -- if input is backspace
                case cnt2 is
                    when 300000 =>
                        RS <= '0';
                        E  <= '1';
                        DB <= "00010000";       -- cursor shift left
                    when 350000 =>
                        E  <= '0';

                    when 400000 =>
                        RS <= '1';
                        E  <= '1';
                        DB <= "10100000";       -- output space
                    when 450000 =>
                        E  <= '0';

                    when 500000 =>
                        RS <= '0';
                        E  <= '1';
                        DB <= "00010000";   -- cursor shift left
                    when 550000 =>
                        E  <= '0';

                    when others => null;
                end case;
            elsif (rxdata = "00001101") then -- if input is enter
                case cnt2 is
                    when 300000 =>
                        RS <= '0';
                        E  <= '1';
                        DB <= "11000000";       -- go to second row
                    when 350000 =>
                        E  <= '0';

                    when others => null;
                end case;
            else
                case cnt2 is
                    when 300000 =>
                        RS   <= '1';
                        E    <= '1';
                        DB   <= rxdata;         -- output character
                    when 350000 =>
                        E    <= '0';

                    when others => null;
                end case;
            end if;
        end if;
    end if;
end process p_main;

end architecture rtl;

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP link with post instead of get I am sending a link via email:
$to = $email;
                        $subject = "Reset your password";
                        $txt = "Hello " . $user . ",

Click here to reset your password Reset Password";

                        $headers  = 'MIME-Version: 1.0' . "\r\n";

                        $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";

                        $headers .= "From: webmaster@example.com";

                        if(mail($to,$subject,$txt,$headers))
                        {
                            $returnArray['error_message'] = "Email has been sent.";
                        }
                        else
                        {
                            $returnArray['error_message'] = "There is an issue with sending an email";
                        }

Right now I am passing the email as $_GET, but I am trying to get it as $_POST, I have tried using javascript like so:

and then on my link have this:
$txt = "Hello " . $user . ",

Click here to reset your password Reset Password";

But then I get the email, it turns out like this:
Reset Password

The link does not appear in the email, is it possible to do what I am trying to do, create a post link in an email?

A: You should wrap it with form html tag instead of using a href link with get parameter:
$txt = "Hello " . $user . ",

Click here to reset your password
<form action='http://example.com/reset-password' method='post'>
  <input type='hidden' name='email' value='".$email."'>
   <button type='submit'  value='Submit'>Reset Password</button>
</form>";

A: Most email clients do not support form submissions or any form of Javascript. And you should always assume that people block scripts/images from emails by default. Clicking a link in an email will usually open the user's web browser and redirect them to the page - this way you can attach a query string with ?foo=bar and access these parameters via $_GET.
If you absolutely must retrieve these parameters in $_POST, for whatever reason, you could redirect the user to a form that auto-submits as POST via Javascript (and pre-fill some hidden inputs to have your parameters passed through).


text:
Q: hanging %*% in a foreach %dopar% loop Trying to strike the right balance with the amount of detail to give here, because I can't create a mwe. My foreach loop hangs in the middle of some matrix calculations. Oddly enough, it hangs on my imac but not on my larger (ie more memory) linux machine. It hangs if I use %dopar% but is fine with %do%. It always hangs on the seventh iteration of the interior for loop. It always hangs on the 'colSums' step, but I calculate the colSums using matrix algebra rather than colSums. If I use colSums, I can get it to work. It's not that my matrix dimensions are incorrect - I've checked them and am not receiving an error. What could be going on?
helper <- function(mat){
    vec <- rep(0, dim(mat)[1])
    for(j in 1:7){
        mat <- mat^(j*0.1)
        vec <- vec + (rep(1, dim(mat)[1]) %*% mat)               # ----- hangs here
    }
    return(vec)
}

foreach(ind = 1:10, .packages = 'Matrix') %dopar% {
     helper(mat = mat)
}


text:
Q: How can I preprocess raw data from a UCI to create itemFrequencyPlot? I want to do a classification analysis on a voting dataset. I found in the UCI repository but I am having difficulty pre-processing it to be able to use the arules package in r. So the data looks partially like this.
party,      voting.issue1,  voting.issue2,  voting.issue3
republican, n,              y,              n
republican, n,              y,              n
democrat,   ?,              y,              y

After importing the data using "read.csv". I tried to use it directly as I read in the "Adult" dataset examples but I got the error
"Error in (function (classes, fdef, mtable)  :
  unable to find an inherited method for function 'itemFrequencyPlot' for signature '"data.frame"'"

I also tried this by changing the whole data to a binary matrix using excel, i.e. removed the party column and added republican and democrat columns with binary values and also converting the Ys, Ns and question marks in the other columns to 1s,0s and NAs respectively. I keep getting the same error. Can anyone suggest any preprossing functions or tutrials I can use to use the itemFrequencyPlot and Apriori functions.

A: You can try this solution or simply try to coerce your data frame in transactions with the following code and than use it in the itemFrequencyPlot function:
trans <- as(df, "transactions")


text:
Q: x86 assembly input and out section .bss ; you can change
 user_input: resb 256 ;256 byte of memory is reserved and can be accessed through the name user_input
 user_input_size equ $- user_input

section .data ;you cant change
 output: db "Enter your print statement: "
 output_size equ $- output

section .text ;assembly code
global _start

_start:
 mov eax, 4
 mov ebx, 1
 mov ecx, output
 mov edx, output_size
 int 80

mov eax, 3
mov ebx, 0
mov ecx, user_input
mov edx, user_input_size
int 80

push ecx ; not sure about this
push edx ; not sure about this

mov eax, 4
mov ebx, 0
pop ecx
pop edx
int 80

mov eax, 1
mov ebx, 0
int 80

i want to print out "Enter your print statement: ", have the user input a statement and have that inputted statement returned to the screen. The first part is working. The others not so much. When the user enters a statement is it stored eax or ecx(user_input).


text:
Q: Not Able to render new Component on link change Actually when ever a person click's on Sign in Button the link change but the component on that page does not renders
App.js
import { BrowserRouter as Switch, Route } from 'react-router-dom';

const App = () => (
  <Switch>
      <Route path="/" exact component={Join} />
      <Route path="/call" exact component={Call} />

  </Switch>
);

export default App;

Join.js

        return (

<input id="room" placeholder="room name" onChange={(event)=>setRoom(event.target.value)}></input>

                <BrowserRouter>
                <Link onClick={event => (!room) ? event.preventDefault() : null} to={`/call?room=${room}`}>
                  <button className="button mt-20" type="submit" onClick={run}>Sign In</button>
                </Link>
                </BrowserRouter>

        );
    }

export default Join;

Call.js

const Call = () => {

        return (

jhjcjc

        );

}

export default Call;

Please look over this error many developer's are facing this problem.

A: In your Join component, there is no need to wrap Link in a BrowserRouter. Check out the working demo here.


text:
Q: can the java files placed in JRE/lib/ext dir will be used for executing a java program I have placed a java file and compiled it with out a main method in JRE/lib/ext directory. I want to access the file from a local Java file with out even mentioning about importing it in java.
C:\Program Files\Java\jre1.8.0_60\lib\ext>cat TestClass.java
class TestClass
{
        public void displayMessage()
        {
                System.out.println("Hello World of Trials");
        }
}

C:\Program Files\Java\jre1.8.0_60\lib\ext>javac TestClass.java

C:\Program Files\Java\jre1.8.0_60\lib\ext>ls -lrt TestClass.*
-rwxrwxr--+ 1 Madhuri        None 103 Jun 17 12:23 TestClass.java
-rwxrwx---+ 1 Administrators None 418 Jun 17 12:25 TestClass.class

C:\Program Files\Java\jre1.8.0_60\lib\ext>

C:\Users\Madhuri\Documents>cat TestArt.java
class TestArt
{
        public static void main(String args[])
        {
                TestClass tc = new TestClass();
                tc.displayMessage();
        }
}

C:\Users\Madhuri\Documents>javac TestArt.java
TestArt.java:5: error: cannot find symbol
                TestClass tc = new TestClass();
                ^
  symbol:   class TestClass
  location: class TestArt
TestArt.java:5: error: cannot find symbol
                TestClass tc = new TestClass();
                                   ^
  symbol:   class TestClass
  location: class TestArt
2 errors

C:\Users\Madhuri\Documents>

Flow of class loading for a simple program
From the above answer, i thought it would be possible. I tried compiling with verbose option and understood it only accepts JAR files.
C:\Users\Madhuri\Documents>javac -verbose TestArt.java
[parsing started RegularFileObject[TestArt.java]]
[parsing completed 37ms]
[search path for source files: .]
[search path for class files: C:\Program Files\Java\jdk1.8.0_60\jre\lib\resources.jar,C:\Program Files\Java\jdk1.8.0_60\jre\lib\rt.jar,C:\Program Files\Java\jdk1.8.0_60\jre\lib\sunrsasign.jar,C:\Program Files\Java\jdk1.8.0_60
jre\lib\jsse.jar,C:\Program Files\Java\jdk1.8.0_60\jre\lib\jce.jar,C:\Program Files\Java\jdk1.8.0_60\jre\lib\charsets.jar,C:\Program Files\Java\jdk1.8.0_60\jre\lib\jfr.jar,C:\Program Files\Java\jdk1.8.0_60\jre\classes,C:\Prog
am Files\Java\jdk1.8.0_60\jre\lib\ext\access-bridge-64.jar,C:\Program Files\Java\jdk1.8.0_60\jre\lib\ext\cldrdata.jar,C:\Program Files\Java\jdk1.8.0_60\jre\lib\ext\dnsns.jar,C:\Program Files\Java\jdk1.8.0_60\jre\lib\ext\jacce
s.jar,C:\Program Files\Java\jdk1.8.0_60\jre\lib\ext\jfxrt.jar,C:\Program Files\Java\jdk1.8.0_60\jre\lib\ext\localedata.jar,C:\Program Files\Java\jdk1.8.0_60\jre\lib\ext\nashorn.jar,C:\Program Files\Java\jdk1.8.0_60\jre\lib\ex
\sunec.jar,C:\Program Files\Java\jdk1.8.0_60\jre\lib\ext\sunjce_provider.jar,C:\Program Files\Java\jdk1.8.0_60\jre\lib\ext\sunmscapi.jar,C:\Program Files\Java\jdk1.8.0_60\jre\lib\ext\sunpkcs11.jar,C:\Program Files\Java\jdk1.8
0_60\jre\lib\ext\zipfs.jar,.]
[loading ZipFileIndexFileObject[C:\Program Files\Java\jdk1.8.0_60\lib\ct.sym(META-INF/sym/rt.jar/java/lang/Object.class)]]
[loading ZipFileIndexFileObject[C:\Program Files\Java\jdk1.8.0_60\lib\ct.sym(META-INF/sym/rt.jar/java/lang/String.class)]]
[checking TestArt]
[loading ZipFileIndexFileObject[C:\Program Files\Java\jdk1.8.0_60\lib\ct.sym(META-INF/sym/rt.jar/java/io/Serializable.class)]]
[loading ZipFileIndexFileObject[C:\Program Files\Java\jdk1.8.0_60\lib\ct.sym(META-INF/sym/rt.jar/java/lang/AutoCloseable.class)]]
TestArt.java:5: error: cannot find symbol
                TestClass tc = new TestClass();
                ^
  symbol:   class TestClass
  location: class TestArt
TestArt.java:5: error: cannot find symbol
                TestClass tc = new TestClass();
                                   ^
  symbol:   class TestClass
  location: class TestArt
[total 570ms]
2 errors

C:\Users\Madhuri\Documents>

Do i need to create a JAR file in ext dir to load it automatically or else is there any way to load a class file directly by the program ??

A: It is not possible of  accessing the class from a local Java file without importing it in java. Even if you copy that java file in JRE/lib/ext directory which you want to access in other class, it does not mean that required class would not get added to default class path.

A: It's feasible (if you are working with your personal machine), but not recommended if that environment, specifically that JVM is used for more Java systems. In other words, it's a bad practice.
The moment you put a jar file or class in that folder, it will be loaded by any Java process using that JVM, which is a big source for potential conflicts, meaning classloading issues such as nosuchmethoderror, classnotfoundexception, etc.
The jre/lib/ext folder is only to extend the core functionality of the JVM, meaning it has nothing to do with your programs.
Instead, use CLASSPATH to reference your custom jar files or classes.
You can play with the classloading debug flag (-verbose:class) to know to know where your classes are loaded from.
Ref:
What are the core extensions?
https://docs.oracle.com/javase/8/docs/technotes/guides/extensions/
How to use CLASSPATH:
https://docs.oracle.com/javase/tutorial/essential/environment/paths.html


text:
Q: Calculate a date from a given date What I would like to do is to calculate the - let's call it - expected date from a given date and given a number.
I am looking for something like this
$(date '+%Y-%m-%d %H:%M:%S' --date="10 days")

but I want to add +10 days from a given date and NOT from the current date.
I am sure that the answer will be probably simple, but at the moment I'm not able to find a solution.
Thanks in advance for the answers.

A: Solution found!
I'll write it here hoping that will be useful for someone.
date '+%y-%m-%d %H:%M:%S' -d "$given_date+10days"


text:
Q: what should I do to be able to create large PDF files without error? I'm creating a pdf file on fly using fpdf of PHP from the database but when there are a lot of data in my db , either the file cant be created completely and just half of it comes out, or nothing will happen or I get run-time error what should I do to be able to create large PDF files without error?
large pdf :
The code is like :
require('lib\fpdf.php');
require ('lib\pdf.php');
include ('lib\bukaDb.php');

$pdf = new PDF('P','pt','A4');
$pdf->SetFont('Arial','',8);
$pdf->AliasNbPages();
$pdf->Open();
$pdf->setY($pdf->tMargin);

for ($i=0; $i<count($var); $i++){
//Do something , show data
//$pdf->Ln(20);
}

// Finally, produce the PDF!!

$pdf->Output();

And my table has hundreds of rows, I cant use set time limit function, any other recommendation?

A: Your script is probably timing out. Try disabling the built-in time limit:
set_time_limit(0);

If you host your site or app on a shared-hosting server though, make sure you are allowed to do this. Some web hosters (including mine) frown upon using lots of server resources for tasks like this.

A: We create PDF files (using fpdf) with hundreds of pages without any problem, so I guess it's your code that is collecting / displaying data that causes the request to time out.
When your HTTP request takes long to complete (more than 10 seconds) then it's probably your script simply taking too much time to complete.
I really think the problem is what happens inside that for loop. Try to create a simple dummy PDF with about the same amount of pages. If that works, you know that you have to search the problem inside the for loop.

A: Move you script to crontab and set saved pdf as file. Once your script finished, set it to send email telling you that the process finished.
As rough pseudo-code:
require('lib\fpdf.php');
require ('lib\pdf.php');
include ('lib\bukaDb.php');

$pdf = new PDF('P','pt','A4');
$pdf->SetFont('Arial','',8);
$pdf->AliasNbPages();
$pdf->Open();
$pdf->setY($pdf->tMargin);

for ($i=0; $i<count($var); $i++){
//Do something , show data
//$pdf->Ln(20);
}

// Finally, produce the PDF!!
$savefile = "/path/to/output/dir/output.pdf";
$pdf->Output($savefile,'I');

mail('admin@example.com', 'PDF Generator', "PDF has been generated at $savefile");

Then, all you have to do is, save it to somewhere on your server and set it's path as crontab:
/path/to/php/cli/php /path/to/your/saved/php/pdf_generator.php

Please note that you have to:

*

*make sure your $savefile directory is writable by script.

*use php cli, not by accessing script via browser as it will also affected by time limit.


text:
Q: Instantiating each of the two classes in one another I have a C# class question which I hope to get some help with.  I have one class called CountdownUserControl.  There are a number of functions within this class.  I then have another class called Min.  There are certain things I need in this form within CountdownUserControl class so I create an instance of it within CountdownUserControl:
public partial class CountdownUserControl : UserControl
{
    //-----------------------------------------------
    // Private data members
    //-----------------------------------------------
    private Min _Min = new Min();

However within the Min class I also would like to use a function which is contained within the CountdownUserControl class - however I cannot create an instance of it within the Min class such as
public partial class Min : Form
{
    private CountdownUserControl CU = new CountdownUserControl();

so that within Min class I could do CU.Method_I_want();
as this will give a stackoverflow.  Does anyone know a solution around this?  Thanks for your time.

A: Classes and methods
Classes shouldn't just been seen as a collection of methods, when they are created ('instantiated') with new, they become actual objects that should be treated as such.
You need to re-think your strategy and instead simply reference a Min or CoundownUserControl object.  What does each one represent?  You are suggesting that the UserControl (a part of a Form) needs to have its own Form created for it - that's not the case.  The Form is the object that creates the UserControl.  The UserControl can access the Form by using the ParentForm property.
The StackOverflow
When you do this: new Min() you are creating a new Min object.  Then, in Min, when you do this: new CountdownUserControl() you are creating a new CoundownUserControl object.  Which in turn creates a new Min object, and so on and so forth.
How to fix your problem
Simply put, use Min min = (Min)this.ParentForm; within the user control if you are sure the user control is on a Form whose type is Min.
And finally/additionally, you should not create the instance of CountdownUserControl yourself unless you are going to set the properties and add it to the Controls collection of the form within your code.  Instead, build your project, drag-and-drop the CountdownUserControl onto your form - a property to access the control will be created on your Min class automatically, called countdownUserControl1.

A: There surely are plenty of solutions to this. An easy one would be to pass the current Min to CountdownUserControl in its constructor (or vice versa):
private Min min;
public CountdownUserControl(Min min)
{
     this.min = min;
}

When you are facing these kind of problems, there probably is something wrong with your class structure, though. Maybe you could split some of the functionality out of your classes into a new one to avoid this problem.

A: All these answers are great, but you should also consider the fact that cyclic dependencies are generally really difficult to work with. Your classes should be somewhat isolated units with a single purpose. They should be loosely coupled from each other. If you redesign your classes to eliminate cyclic dependencies and follow these guidelines, you will write better and more maintainable code in general and will have less issues like this in the first place.

A: Instead of instantiating a new Min class every time, you could set the value of it in a constructor.
public CountdownUserControl(Min min)
{
     _Min = min;
...

A: Is CountdownUserControl going to be on the Form Min?  Why would you instantiate the form from the control, and not the reverse?  Shouldn't the Countdown control be on the form?  Then you could instantiate the form, initialize the control, and then access the function.

A: Do not create a form in the user control. Add it as a dependency:
public partial class CountdownUserControl : UserControl
{
    private Min _Min;

    public CountdownUserControl(Min parentForm);

And then use it in your form:
public partial class Min : Form
{
    private CountdownUserControl CU;

    public Min()
    {
       CU = new CountdownUserControl (this);
    }

Update
A more suitable solution would be to break out the common functionality from the two classes and put them in separate classes. Read up on single responsibility principle. I got a post about it in my blog.

A: You can pass in an instance of your CountdownUserControl to your Min class (via an additional constructor parameter or via a property).
public partial class Min: Form {
    public Min() {
        InitializeComponent();
    }

    public CountdownUserControl Countdown {get;set;}
}

Since this is a form you probably want to go with the property so as not to break the designer.
I won't speak to whether or not this is proper form (hopefullt you are using something like PresentationModel or MVC), as I do know tehre are times code like this is required.
Now as has been pointed out, if you plan on showing the user control in the form then a different solution should be adopted. But it all depends on how you are planning on what you are doing with the form. If you are for example showing teh form in a dialog keeping a class level reference is a bad idea since once closed the form will be disposed.
A little more detail would get you closer to a fully correct answer.

A:
However within the Min class I also would like to use a function which is contained within the CountdownUserControl class - however I cannot create an instance of it within the Min class such as

Is it really necessary that mentioned function is member of CountdownUserControl?
Could you reveal more of public interface of your classes?
If the function has no reference to instance of CountdownUserControl consider changing it to static. Else try to design new class named e.g. CountdownState whose instance may be shared among both CountdownUserControl and Min.

A: The problem here is that whenever a CountdownUserControl is created, it tries to create a new Min, but whenever a new Min is created, it tries to create a new CountdownUserControl. This process could continue indefinitely and therefore the stack is blown.
The solution is to inject the instance of CountdownUserControl into Min (Or vice versa, depending on what gets created first).
So CountdownUserControl will look like this:
public partial class CountdownUserControl : UserControl
{
    //-----------------------------------------------
    // Private data members
    //-----------------------------------------------
    private Min _Min;

    public CountdownUserControl(Min min)
    {
        _Min = min;
    }

...and Min will look like this:
public partial class Min : Form
{
    private CountdownUserControl CU;

    public Min()
    {
        CU = new CountdownUserControl(this);
    }


text:
Q: Strophe Ping Plugin Not responding I am trying to add the Strophe ping plugin in to ping another user and respond with a pong, and then i know the user is connected.
But i am not sure how to get it working.
I read in the documentation an example, but it isnt working for me.
I just want to get some form of call back saying the other person is connected.
   conn.addHandler(pingHandler, "urn:xmpp:ping", "iq", "get");

 function pingHandler(ping) {
 var pingId = ping.getAttribute("1");
 var from = ping.getAttribute("from");
 var to = ping.getAttribute("to");
 var pong = $iq({type: "result", "to": from, id: pingId, "from": to});
 conn.send(pong);
  return true;
}

I also tried the method below, the method below will send out the Ping and called success that it is sent, but there is no respond in the pingHandler. Seems like it is sent, but it is not listened to/handled.
  conn.ping.addPingHandler( pingHandler );

 function Onping(){

    var jid3="test4@macbook-pro.local"

     console.log("ping starts");
conn.ping.ping( jid3, success, error, timeout );

     function success(){
     console.log("ping sent");

     }
       function error(){
     console.log("ping Not sent");

     }
       function timeout(){
     console.log("ping Timeout");

     }

 }

            function pingHandler(ping) {
                  console.log("pong back");
     var pingId = ping.getAttribute("id");
     var from =  ping.getAttribute("from");
     var to = ping.getAttribute("to");
     var pong = $iq({type: "result", "to": from, id: pingId, "from": to});
     conn.send(pong);
      return true;
    }

Edit
SENT: <iq type='get' to='test4sdfsdfs@macbook-pro.local' id='1:ping' xmlns='jabber:client'><ping xmlns='urn:xmpp:ping'/></iq>

RECV:

RECV: <iq xmlns='jabber:client' type='result' id='1:ping' from='test4sdfsdfs@macbook-pro.local' to='test3@macbook-pro.local/a7411f98'/>

A: You need to attach a ping listener/handler upon connecting that sends the pong. Your listener responds to any pings sent to you. Your ping sender sets up a handler to handle to pong.
var onConn = function(){
    conn.ping.addPingHandler(onPing);
};

var onPing = function (iq) {
    conn.ping.pong(iq);
    return true;
};

var onPong = function(iq){
    //do whatever with response
    return false;
};

var sendPing = function(jid){
    conn.ping.ping(
        jid,
        function (iq) {onPong(iq);},
        function () { console.log('Failed!'); },
        3000);
};

sendPing('foo@jabberservername.com');


text:
Q: Speed detection using ADXL335 Can i find the speed of the vehicle using ADXL335?.
My idea is to send an email alert if the vehicle speed exceeds the defined limit using raspberry pi. Just like in zoomcar or the other rental cars.

A: Short answer: No
To get velocity out of your accelerometer you would need to perform some integration eg:
v_k = v_(k-1) + T*a_k

Where v is the velocity, T is the sample period, a is the measured acceleration and subscript k is the sample number.
This is saying that "velocity is equal to previous velocity, plus the product of measured acceleration and sample period"
where you might assume constant acceleration in between samples (k).
Already this is a problem, because we're working in discrete time and acceleration is not constant between samples.
To make matters worse, any error (bias, drift) of the accelerometer is integrated as well, which means that after only a few (tens?) of samples your velocity has large error.
The rental cars are probably doing it either with GPS or direct from the speedometer.


text:
Q: Spring Batch: Read from txt files and return all lines as a single String to the processor
I'm trying to read text from files in Spring Batch but i need all lines as a single String reaching the .processor and not line by line. I read about .setRecordSeparatorPolicy in FlatFileItemReader. Is there any other way to achieve this? Maybe another kind of reader or something?
Any help would be really appreciated
public ItemStreamReader<String> stringReader() throws IOException {
    Resources[] resources.. // load files here
    MultiResourceItemReader<String> reader = new MultiResourceItemReader<String>();
    reader.setResources(resources);
    reader.setDelegate(flatFileItemReader()); //sets FlatFileIteamReader

    return reader;
}

@Bean
public TaskletStep managerStep() throws Exception {
    return managerStepBuilderFactory.get("managerStep")
            .<String, String>chunk(6)
            .reader(stringReader())
            .processor(myProcessor()) //all lines as 1 String here per File
            .writer(doSomething())
            .build();
}

A: The chunk processing model is designed for item oriented use cases. If you have a single item, I don't see any added value of using a chunk-oriented step. A simple tasklet is more appropriate.


text:
Q: How to use FormData while testing API post request in opentest Hi I am getting below error while using FormData in Post Method for opentest
my code:
var data = new FormData(); data.append("name", "test")
and I am getting below error:
at org.getopentest.base.TestActor.evalScript(TestActor.java:1441)
at org.getopentest.base.ScriptAction.run(ScriptAction.java:32)
at org.getopentest.base.TestActor.executeAction(TestActor.java:1527)
at org.getopentest.base.TestActor.executeActionByDef(TestActor.java:1695)
... 4 more
Caused by: javax.script.ScriptException: ReferenceError: "FormData" is not defined in <eval> at line number 1
    at

jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:470)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:454)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:406)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:402)
at jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:155)
at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)
at org.getopentest.base.TestActor.evalScript(TestActor.java:1427)

A: The FormData object is only available in web browsers and is not part of the OpenTest API. If you are trying to send a request using the HttpRequest keyword, you should be able to build this simply by concatenating the key/value pairs for the form fields and their values this way:
field1=value1&field2=value2&field3=value3

More details here.


text:
Q: Is there a way to mount Google Drive on my local machine like what could be done in Colab? In Colab, the following code snippet is used for mounting Google Drive.
from google.colab import drive
drive.mount('/test', force_remount=True)

And I'm wondering if it could work on my local machine. When implementing this locally, it says "no module named google", even after having executed pip install google.
Is there another package that should be installed, or it just cannot be achieved? I've searched for a while, but it seems that the only solution is to install Google Drive Desktop to give access to remote files.

A: *

*Although google.colab python library can be found here, this library is a collection of tools meant to work in conjunction with the Google Colab product.

*Indeed, Google Drive Desktop is your best option to "mount" your Google Drive to your local machine.

*Alternatively, there are several 3rd party Google Drive clients available.

A: Use ocamlfuse.
Here are the step by step details: https://medium.com/@enthu.cutlet/how-to-mount-google-drive-on-linux-windows-systems-5ef4bff24288
Instead of mounting it to a home folder (named googledrive in tutorial), I suggest mounting it such that folder structure would be same for both colab and local machine. To do that:

*

*create your mounting folder at root (it's not a recommended practice but there is no harm). You need to use sudo. i.e at /, use sudo mkdir test

*then create MyDrive inside test.

*Chnage test or MyDrive owner to yourself: sudo chown <your username> MyDrive/

*Mount to MyDrive by: google-drive-ocamlfuse MyDrive/

*Enjoy!


text:
Q: how to print dictionary in django I'm working on a translator program. I want the result to appear at the bottom of the original page when I presses the 'submit' button.
There is no error, but there is no change when I press the 'submit' button. I want to show the contents of the dictionary by using table.
This is my codes. 'trans_suc.html', 'views.py' and 'urls.py'.  Please let me know how to modify it.
trans_sub.html
{% extends 'dialect/base.html' %}
{% load static %}

{% block content %}

        <form action="/trans/" method ="post">
            {% csrf_token %}
            <input id = "trans" type ="text" name ="content" placeholder="0/500">
            <input class = "btn" id="trans_btn" type ="submit" value ="번역">
        </form>

            {% for i in context %}

                        {{ i.siteName }}
                        {{ i.contents }}

            {% endfor %}

{% endblock content %}

views.py
class Postview(View):

    def get(self, request):
        massage = "hello"
        return render(request, 'dialect/main_page.html',
                      {'msg': massage}
                      )
    @csrf_exempt
    def success(request):
        content = request.POST.get('content')
        context = {
            'content': content
        }

        dict = pd.read_csv("C:\\Users\\user\\jeju-dialect-translation\\jeju\\dialect\\dict2.csv", sep=",", encoding='cp949')

        hannanum = Hannanum()
        okt = Okt()

        nouns = hannanum.nouns(content)

        stem = okt.morphs(content, stem = True)

        tempt=[]

        for i in range(0, len(stem)):
            if (len(stem[i]) == 1):
                tempt.append(stem[i])

        adjective = list(set(stem) - set(tempt))

        results = pd.DataFrame(columns = {'siteName', 'contents'})

        for i in nouns:
            x = dict[dict['siteName'] == i]
            x = x[['siteName', 'contents']]
            results = pd.concat([results, x], axis = 0)

        for i in adjective:
            y = dict[dict['siteName'].str.match(i)]
            results = pd.concat([results, y], axis = 0)

        dropped_duplicates_result = results.drop_duplicates()
        context = dropped_duplicates_result.to_dict()

        return render(request, 'dialect/trans_suc.html',
                      context
                      )

urls.py
urlpatterns = [
    path('admin/', admin.site.urls),
    path('dialect/', views.Postview.as_view(), name='main_page'),
    path('trans/', views.Postview.success, name='trans_suc'),
    path('dictionary/', views.Postview.dic, name='dictionary')
]

A: if it's normal python dictionary, loop over key and value:
{% for key, value in context.items %}
{{ key }}{{ value }}
{% endfor %}


text:
Q: How to sort an array by specific filter? Lets say, I have an array like this:
$arr = array('M', '38', '37', '3XL', 'XL', '39', 'L', 'S', '36', '41', '40', 'XXL');

(its array with available sizes of shoes for current item that customer is going to order)
How to sort it ascending (first alpha-sizes: S, M, L, XL, XXL, 3XL; and then numeric-sizes: 36, 37, 38, 39, 40, 41), so I will get array:
$res = array('S', 'M', 'L', 'XL', 'XXL', '3XL', '36', '37', '38', '39', '40', '41');

Is there some function to do that?

A: If sizes are all defined, then you can have a $baseArr containing all valid sizes and sort the current arr based on that
function sortSizeArr($arr) {
    $baseArr = array('S', 'M', 'L', 'XL', 'XXL', '3XL', '36', '37', '38', '39', '40', '41');
    $sortedArr = array();
    for($i = 0; $i < count($baseArr); $i++) {
        if(in_array($baseArr[$i], $arr))
            array_push($sortedArr, $baseArr[$i]);
    }
    return $sortedArr;
}

Test:
$sizes = array('M', '38', 'S', '36', '41', '40', 'XXL');
print_r(sortSizeArr($sizes));

Array ( [0] => S [1] => M [2] => XXL [3] => 36 [4] => 38 [5] => 40 [6]
  => 41 )

EDITED by Legionar:
I am calling this function, only if there are alpha-sizes, without numerical-sizes. Some sizes are f.e. M/5, L/6, XL/7, XXL/8, so I changed little bit your function. This helped me, thanks:
function sortSizeArr($arr) {
    $baseArr = array('XXS', 'XS', 'S', 'M', 'L', 'XL', 'XXL', 'XXXL', '3XL');

    $sortedArr = array();

    for ($i = 0; $i < count($baseArr); $i++) {
        /*if (in_array($baseArr[$i], $arr)) {
            array_push($sortedArr, $baseArr[$i]);
        }*/

        foreach ($arr as $val) {
            $check = reset(explode('/', $val));

            if (strpos($val, $baseArr[$i]) === 0) {
                array_push($sortedArr, $val);
            }
        }
    }

    return $sortedArr;
}

A: Have a look at the function usort():
http://php.net/manual/en/function.usort.php
It allows you to sort an array using a custom compare function. Implementing this function should be rather straightforward for your case.

A: Here is another example for sort array alphabetically then numerically:
<?php

$array = array('M', '38', '37', '3XL', 'XL', '39', 'L', 'S', '36', '41', '40', 'XXL');

foreach ($array as $key => $value) {
    if (ctype_digit($value)) {
        $array[$key] = intval($value);
    }
}

sort($array);

echo "After Sorting".'<pre>';
print_r($array);
echo '</pre>';

?>

For your reference and output Click Here

A: If you need the numeric sizes to be anything you can do something like:
function size_sort($a, $b) {
    return determine_value($a) < determine_value($b) ? -1 : 1;
}

function determine_value($var) {
    $letter_sizes = array("S" => 1, "M" => 2, "L" => 3, "XL" => 4, "XXL" => 5, "3XL" => 6);
    if(array_key_exists($var, $letter_sizes))
        return $letter_sizes[$var];
    elseif(is_numeric($var))
        return $var + 100; // add 100 so its value is higher than any letter sizing
    else
        return 10000; // unknown size, make sure it is at the end
}
usort($arr, "size_sort");

I added an else condition incase any letter sizes are left out (ie, XS, 4XL, etc)

A: To add variant. with only suggestion that sizes nore than 7:
$arr = array('M', '38', '37', '3XL', 'XL', '39', 'L', 'S', '36', '41', '40', 'XXL');

$sizes = array('S', 'M', 'L', 'XL', 'XXL', '3XL');
var_export($arr);
usort($arr, function ($a, $b){
        global $sizes;
        $a = is_numeric($a) ? $a : array_search($a, $sizes);
        $b = is_numeric($b) ? $b : array_search($b, $sizes);
        return $a-$b;
});
var_export($arr);


text:
Q: Promise multiples values I'm new to promise and to me it feels like a promise if a function that can only have 1 argument. And in many case it makes me very frustrated.
How am I supposed to handle cases such as the following with promises (simplified example)
/**
 * @api {post} /payments Create a new payment
 *
 * @apiParam {String} uuid uuid of the user.
 * @apiParam {String} status the payment status
 * @apiParam {String} transactionId Id of the transaction
 * @apiParam {String} creationDate The payment date
 * @apiParam {Number} productId The product Id
 */
router.post('/', function(req, res, next) {
  const userUUID = req.body.userUUID;
  const productId = req.body.productId;

  models.account.findOne({ where: { userUUID }})
    .then(account => {
        //Here I check if the accountId is correct
        if (!account) throw new errors.NotFound('unknown userUUID')
        return account;
    }).then(existingAccount)
        //Here I check if the productId is correct
        return models.product.findOne({ where: { productId }}).then(product => {
            if (!product) throw new errors.NotFound('unknown productId')
            return product;
        })
    })
    .then(existingProduct => {
        //Here I insert the payment in database
        return models.payment.create({
            productId,
            userUUID,
            existingProduct.price
        })
    })
    .then(existingPayment => {
        //My Problem :
        //Here, for example, I need :
        //   existingProduct
        //   existingAccount
        //   existingPayment
        //How can I access them ???
    })
    .then(s => res.json(s))
    .catch(error => {
      if (error instanceof errors.NotFound)
        return res.status(404).send(error.message);
      return next(error);
    });
});


text:
Q: How can I merge these two observables and remove the nested observable? I'm struggling with understanding how to merge two observables and make use of their merged product. I've watched countless videos on mergeMap, switchMap, flatMap, marble diagrams etc but I still don't get how merging observables works. I feel like I'm not going to be efficient, or even correct, when using RxJS.
I have an observable that I'm subscribing to, and I want to also subscribe to the valueChanges observable of a particular form array within my code. However I need to ensure that the second subscription only occurs after the form array has been properly built otherwise I'll get null errors.
Obviously one was to do this is to subscribe to valueChanges within the next function of my first subscription, however this is bad practice and I want to avoid it. However I'm not sure in what way I should be structuring my code so that I get the behaviour I want without using nested subscriptions.
setSettings$(serial: string) {
    return this.getSettingsFromSerial$(serial).pipe(
      tap(val => {
        this.settingsState.savedSettingsState = val;
        this.settingsState.ipRestrictionEnabled = val.ipRestrictionSettings.ipRestrictionEnabled;
        if(val.ipRestrictionSettings.ipRanges.length === 0){
          this.addEmptyRange();
        }
        else
        {
          for (const i of val.ipRestrictionSettings.ipRanges) {
            this.addRange(i.startRange, i.endRange, i.label);
          }
        }
        this.settingsState.displaySettings = true;
        this.settingsState.displayForm = true;
        this.hideRangeErrorsUntilNotPristine(); <-- I need to merge (?) this with my first observable to ensure that it happens after the form is built.
      })
    );
  }

  // TODO :: Cancel this on destroy
  hideRangeErrorsUntilNotPristine(){
    this.ipRangeFormArray.valueChanges.subscribe( res => {
      let formGroups = this.ipRangeFormArray.controls;

      for(let i = 0; i < formGroups.length; i++){
        if(formGroups[i].pristine === true) {
          this.settingsState.ipRangeValidStates[i].displayError = false;
        }
        else {
          this.settingsState.ipRangeValidStates[i].displayError = true;
        }
      }
    });
  }

A: From what I understand, all you need to do is make sure that this method is called once the FormControl objects have been instantiated in your TypeScript code. I've chosen mergeMap for no particular reason, as you only need to worry about which operator to use if the outer Observable emits multiple times.
setSettings$(serial: string) {
    return this.getSettingsFromSerial$(serial).pipe(
      tap(val => {
        this.settingsState.savedSettingsState = val;
        this.settingsState.ipRestrictionEnabled = val.ipRestrictionSettings.ipRestrictionEnabled;
        if(val.ipRestrictionSettings.ipRanges.length === 0){
          this.addEmptyRange();
        }
        else
        {
          for (const i of val.ipRestrictionSettings.ipRanges) {
            this.addRange(i.startRange, i.endRange, i.label);
          }
        }
        this.settingsState.displaySettings = true;
        this.settingsState.displayForm = true;
      }),
      // this gets called once everything in the `tap` has finished,
      // because everything is synchronous
      mergeMap(() => this.hideRangeErrorsUntilNotPristine())
    );
  }


text:
Q: Check if XML Chain Exists in PHP So I have the following XML chain:
$xml->assessment->outcomes_processing->outcomes->decvar->attributes()->cutvalue

XML example
In Some XML-files $xml->assessment->outcomes_processing->outcomes->... does exist. But here only $xml->assessment exist.
<questestinterop>
  <assessment ident="nedolat78356769204914" title="welkom woordenschat 4">
    <qtimetadata>
      <qtimetadatafield>
        <fieldlabel>qmd_assessmenttype</fieldlabel>
        <fieldentry>Assessment</fieldentry>
      </qtimetadatafield>
    </qtimetadata>
    <section ident="nedolat78356769204915" title="Woordenschat">
      <selection_ordering>
        <selection/>
        <order order_type="Sequential"/>
      </selection_ordering>
      <item ident="QTIEDIT:FIB:34932158" title="Oefening 1">
      ...
      </item>
    </section>
  </assessment>
</questestinterop>

At the moment I am receiving the error: "Trying to get property of non-object". Which is logic because the node from outcomes doesn't exist.
So I tried a solution with isset() which obviously isn't working either.
isset($xml->assessment->outcomes_processing->outcomes->decvar->attributes()->cutvalue) ? ... : null

This gives me the same error. Because the node outcomes doesn't exist, so he throws me the error immediately. The solution could be for checking each node individually with isset(), of course with a function because otherwise I have a lot of checking to do...
This is my function, which is failed to work because the string '->' could not be processed as php code:
// xml: xml structure form SimpleXML
// chain: assessment->outcomes_processing->outcomes->decvar->attributes()->cutvalue
function checkIfXMLChainExists($xml, $chain) {
  $xmlChain = '';
  $i = 0;
  $nodes = explode('->', $chain);
  $numItems = count($nodes);

  // experimenting with eval() to treat '->' as ->; failed to work
  $a = '$xml->assessment->outcomes_processing';
  $t = eval($a);
  echo $t;
  print_r($t);

  foreach ($nodes as $node) {
    $xmlChain .= '->' . $node;

    if (isset($xml->$xmlChain)) { // Node exists
      if ($i+1 == $numItems) {
        return $xml->$xmlChain;
      }
    } else { // Node does not exists
      return 'does not exist';
    }
    $i++;
  }

Does anyone has some ideas because I don't have any inspiration at the moment :(
Thanks in advance

A: Returns the data referenced by the chain, or NULL if it doesn't exist.
function getDataIfExists () {

  // We accept an unknown number of arguments
  $args = func_get_args();

  if (!count($args)) {
    trigger_error('getDataIfExists() expects a minimum of 1 argument', E_USER_WARNING);
    return NULL;
  }

  // The object we are working with
  $baseObj = array_shift($args);

  // Check it actually is an object
  if (!is_object($baseObj)) {
    trigger_error('getDataIfExists(): first argument must be an object', E_USER_WARNING);
    return NULL;
  }

  // Loop subsequent arguments, check they are valid and get their value(s)
  foreach ($args as $arg) {
    $arg = (string) $arg;
    if (substr($arg, -2) == '()') { // method
      $arg = substr($arg, 0, -2);
      if (!method_exists($baseObj, $arg)) return NULL;
      $baseObj = $baseObj->$arg();
    } else { // property
      if (!isset($baseObj->$arg)) return NULL;
      $baseObj = $baseObj->$arg;
    }
  }

  // If we get here $baseObj will contain the item referenced by the supplied chain
  return $baseObj;

}

// Call it like this:
$subObj = getDataIfExists($xml, 'assessment', 'outcomes_processing', 'outcomes', 'decvar', 'attributes()', 'cutvalue');


text:
Q: Turning off VBA editor auto-format of code lines I'm trying to accomplish a Debug.Print without a newline in Access 2007, as in http://www.vbforums.com/showthread.php?581952-RESOLVED-debug-print-with-no-newline
Debug.Print --no-newline ".";

However, the auto-syntax checker converts this when I move to a different line of code to:
Debug.Print --no - newline; ".";

I have tried turning off Options -> Auto Syntax Check but the problem still persists. Is there any way to fix this?

A: Debug.Print does not have an option named --no-newline.  So when the VB Editor encounters the line you tried, it (incorrectly) guesses you want a subtraction and adjusts the code line based on that guess.
The unquoted semicolon after the text you want to Debug.Print is what actually suppresses the new line.  Consider this procedure ...
Public Sub PrintWithoutNewline()
    Debug.Print "A";
    Debug.Print "B";
End Sub

Calling that procedure in the Immediate window prints "AB" on one line, and leaves the insertion point (cursor) at the end of that line instead of at the start of a new line.
PrintWithoutNewline
AB


text:
Q: refresh part of php page I am new to coding with php and SQL
I know html, css and js
I want to code for a simple chatroom web page
I have written the sign in and sign up part and I have saved some user accounts information in my database
but my problem is how to refresh only a part of web page using only php.
I have a div in my page for showing messages that are saved in database
and I want its content to be updated when a new message is gone to the database
but I don't want the whole page to be refreshed.
Please Help me wiith this.

A: To refresh only part of a webpage you can use AJAX. It is based on JavaScript and lets you update certain parts of a webpage without reloading it.
Here you can learn more: https://www.w3schools.com/js/js_ajax_intro.asp

A: PHP is a server language - and based in resquest/response, like everything in web.
It means that you can't send information to the client after the response.
So if you want to make your page dinamic, you have to send some javascript to the client browser.
Depending on what you want to reload, you will need json and jquery/ajax to get the information through GET or POST. The you change the content of the current page using this.
In this case, you can use another PHP page like 'getmessages.php':
function getMessage(){
 $.ajax({
    url: "getmessages.html",
      context: document.body
    }).done(function() {
      $("#messagesdiv").html("-- body of message --");
    });
}

while(true){
  getMessage();
  sleep(1000);
}

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

You can parse the json to get the information wich is better. And it verify the information every second.
There are many tutorials out there that can show how to do this.
You can find JQuery here.


text:
Q: Java. Создание image и последующая передача Мне необходимо создать класс, в котором при помощи Graphics, рисуешь необходимые элементы из линий, после сохраняешь их в image и передаёшь основному классу.
Сейчас я через второе приложение сохраняю картинку и в Основном классе считываю её из директории.
Вот код. Плохо понимаю как это вообще возможно сделать. Возможно нужно создать метод который будет возвращать image.
import javax.imageio.ImageIO;
import javax.swing.;
import java.awt.;
import java.io.File;
import java.io.IOException;
import java.awt.image.*;
public class Main extends JFrame{
    public static void main(String[] args) throws IOException {
        Main main_window = new Main();
        main_window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        main_window.setLocation(0,0);
        Dimension sSize = Toolkit.getDefaultToolkit ().getScreenSize ();
        int vert = sSize.height;
        int hor = sSize.width;
        main_window.setSize(hor,vert);
        main_window.setResizable(false);
        MainField game_field = new MainField();
        game_field.setBackground(Color.WHITE);
        main_window.add(game_field);
        main_window.setVisible(true);
        game_field.setLayout(null);
    }

    private static void onRepaint (Graphics g ){
        g.setColor(Color.BLACK);
        BufferedImage img = new BufferedImage(50,50, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2D = img.createGraphics();
        g2D.setStroke(new BasicStroke(3.0f));
        g2D.setColor(Color.BLACK);
        // Рисую что необходимо
        g2D.dispose();
        try {
            ImageIO.write(img, "png", new File("src/lol/Питание 0.png"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private static class MainField extends JPanel{
        protected void paintComponent (Graphics g){
            super.paintComponent(g);
            onRepaint(g);
            repaint();
        }
    }
}


text:
Q: Is using exceptions for input validation bad for performance? I want to run a function to check if the age entered by the user is enough for him to vote. I have done it with two ways
Both the codes are working well and both are working in the same way. I want to know if there are any performance differences in the two methods and which method should be used to perform such types of operations.
First Way :

function validateAge() {

  var age = document.getElementById("age").value;
  var paragraph = document.getElementById("result");

  if (age == "") {
    paragraph.innerHTML = "Please enter your age";
  } else if (age < 18) {
    paragraph.innerHTML = "You are too young to vote";
  } else {
    paragraph.innerHTML = "You are eligible to vote";
  }
}
<title>Age validator</title>

Enter your age to check if you are eligible to vote :

Enter Your age :
<input type="text" id="age" />

<input type="button" onclick="validateAge()" value="Validate" />

Second Way :

function validateAge() {
  try {
    var agge = document.getElementById("age").value;

    if (agge == "") {
      throw "Please enter your age";
    } else if (agge < 18) {
      throw "You are too young to vote";
    } else {
      throw "You are eligible to vote";
    }
  } catch (obj) {
    document.getElementById("result").innerHTML = obj;
  }
}
<title>Age validator</title>

Enter your age to check if you are eligible to vote :

Enter Your age :
<input type="text" id="age" />

<input type="button" onclick="validateAge()" value="Validate" />

A:
I want to know if there are any performance differences in the two methods...

Yes, marginally; typically using the exception mechanism is more costly than simply branching, though it's not a big difference in JavaScript (vs. some other languages) when what you throw isn't an Error (since when you don't create an Error, no stack information has to be captured).

...and which method should be used to perform such types of operations.

Typically, exception processing is for exceptional conditions, not expected ones. For what you describe, the standard approach would be the first one, simple branching. You might store the string in a simple variable and then assign to innerHTML after the if/else if/else:
function validateAge() {
  var agge = document.getElementById("age").value;
  var message;
  if (agge == "") {
    message = "Please enter your age";
  } else if (agge < 18) {
    message = "You are too young to vote";
  } else {
    message = "You are eligible to vote";
  }
  document.getElementById("result").innerHTML = message;
}

function validateAge() {
  var agge = document.getElementById("age").value;
  var message;
  if (agge == "") {
    message = "Please enter your age";
  } else if (agge < 18) {
    message = "You are too young to vote";
  } else {
    message = "You are eligible to vote";
  }
  document.getElementById("result").innerHTML = message;
}
<title>Age validator</title>

Enter your age to check if you are eligible to vote :

Enter Your age :
<input type="text" id="age" />

<input type="button" onclick="validateAge()" value="Validate" />

...but that's mostly a matter of style.

Probably more significantly, though, it would be best to check that what the user has entered is actually a number. With your current code, if I write seven in the field, I'm told I'm eligible to vote, because "seven" < 18 evaluates to NaN < 18 which evalutes to false.

A: You second code has to process a throw/catch
The following would likely be faster, but not noticeably so
var text;
if (age.trim() === "") text = "Please enter your age";
else if (isNaN(age)) text = "That is not an age";
else text = +age < 18 ? "You are too young to vote" : "You are eligible to vote";
paragraph.textContent = text;

window.addEventListener("load", function() {
  document.getElementById("validate").addEventListener("click", function(e) {
    e.preventDefault();
    var age = document.getElementById("age").value;
    var paragraph = document.getElementById("result");
    var text;

    if (age.trim() === "") text = "Please enter your age";
    else if (isNaN(age)) text = "That is not an age";
    else text = +age < 18 ? "You are too young to vote" : "You are eligible to vote";
    paragraph.textContent = text;
  });
});
<title>Age validator</title>

Enter your age to check if you are eligible to vote :

Enter Your age :
<input type="text" id="age" />

<input type="button" id="validate" value="Validate" />

A: This would be even faster.

function validateAge() {
  var age = document.getElementById("age").value
  document.getElementById("result").innerHTML = age?age<18?"You are too young to vote":"You are eligible to vote":"Please enter your age"
}
<title>Age validator</title>

Enter your age to check if you are eligible to vote :

Enter Your age :
<input type="number" id="age" />

<input type="button" onclick="validateAge()" value="Validate" />


text:
Q: Is it possible to set constructor for specific enum? I know it sounds a bit weird but I will explain what I'm trying to avoid.
I have a bean class that holds some data. This bean class can be constructed from two different sources. I created an enum for each source that I'm passing through the constructor.
Then I need to switch on the enum inside the constructor in order to distinguish between the two. I know that I can overload the constructor but the problem is that both sources are providing a Map<String,Object>.
I wondered if there is any way to look at the enum value as a final one for the constructor in any way?
public PromotedItemRecord(Map<String, Object> record, source recordSource) {
     switch(recordSource)
     ....
}

public enum source
{
    fromDB,
    fromAjax;
}

Is it even possible to do so?

A: In situations when multiple constructors take parameters of identical type, you should avoid exposing constructors altogether: since constructor name cannot be changed, the user who calls them would have to search through documentation or possibly make guesses at what's going on.
A common approach is to make the constructor private, and provide factory methods in place of its overloads:
class PromotedItemRecord {
    private PromotedItemRecord(Map<String, Object> record, source recordSource) {
        ... // Do the magic here
    }
    public static recordFromAjax(Map<String, Object> record) {
        return new PromotedItemRecord(record, source.fromAjax);
    }
    public static recordFromDb(Map<String, Object> record) {
        return new PromotedItemRecord(record, source.fromDb);
    }
}


text:
Q: Dragging MKAnnotationView immediately When you set the draggable property of an MKAnnotationView, the default behavior seems to be:
1) user taps the annotation
2) user drags the annotation
Is is possible to combine this into one, so the user can drag the annotation without tapping it first?

A: try this source code http://www.github.com/digdog/MapKitDragAndDrop I have tried this code in simulator and it is working fine


text:
Q: Reading UInt16 numbers only binary file If I were reading byte numbers I would do:
using (FileStream stream = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
    int size = (int) stream.Length;
    BinaryReader br = new BinaryReader(stream);
    byte[] test = new byte[size];
    test = br.ReadBytes(size);
    br.Close();
}

But since I want to read Uint16, I am struck doing:
using (FileStream stream = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
    int size = (int) stream.Length;
    BinaryReader br = new BinaryReader(stream);
    float[] test = new byte[size/2];
    for (int i = 0; i < size/2; ++i)
    {
         test[i] = br.ReadUInt16();
    }
    br.Close();
}

Is there a faster way to read the whole file at once or is the speed difference negligeable ?

A: If the file isn't too large to fit in memory, it would be faster to read all the bytes into a MemoryStream and then read Uint16s from that stream. Like so:
byte[] data;
int size;
using (FileStream stream = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
    size = (int) stream.Length;
    data = new byte[size];
    stream.Read(data, 0, size);
}

uint[] uintData = new uint[size / 2];
using (var memoryStream = new MemoryStream(data))
using (var reader = new BinaryReader(memoryStream))
    for (int i = 0; i < size / 2; i++)
        uintData[i] = reader.ReadUInt16();

// Done.

A: First, you don't need this line:
byte[] test = new byte[size];

because the following line
test = br.ReadBytes(size);

makes test point to another array. So,
byte[] test = br.ReadBytes(size);

suffices.

Regarding your question: Since BinaryReader.ReadBytes just performs Stream.Reads in a loop (you can verify this with ILSpy or by looking at the reference source code), I'd assume that the performance difference between your code examples is negligible. To be sure, I'd recommend that you do some measurements.


text:
Q: Race condition in JavaScript with onload event Let's say I'm loading a page that contains this code:
<script>
    function functionAlert() {
        alert(window.myProperty);
    }

    function functionSetProperty() {
        window.myProperty = "hello!";
    }
    window.addEventListener('load', functionAlert, false);
    functionSetProperty();
</script>

Is the race condition possible that functionAlert gets called before functionSetProperty, in which case the alert will show undefined?

A: No, this is not possible.  Browser-based JavaScript is single-threaded and blocks the browser from processing events while it is executing.
(I've seen some exceptions to this in the wild, but they've all centered around XmlHttpRequest.)


text:
Q: "Property type is not a subtype of overridden abstract val" on multiple-inherited field Sometimes, a type is declared to implement 2 interfaces which both have an abstract property the same name, but when I moved the bounded type argument to a top-level abstract superclass and subclass it in different objects, the class overriding the the abstract property on both superinterfaces fails to compile when using type arguments for a subclass.
The generated interfaces and abstract class:
interface Actor : Type {
  val login: Stub<String>
  val posts: Config<String, BasePostsArgs>
}

interface SomeConflict : Type {
  val posts: Config<String, BasePostsArgs>
}

abstract class BasePostsArgs(
  args: ArgBuilder = ArgBuilder.create<String, BasePostsArgs>())
  : ArgBuilder by args

An example of the generated object which overrides 2 superinterface properties with the same name:
object Organization : Type, SomeConflict, Actor {

  override val login: Stub<String> = stub()

  override val posts: Config<String, Organization.PostsArgs> = configStub(PostsArgs())

  class PostsArgs(args: ArgBuilder = ArgBuilder.create<String, PostsArgs>())
    : BasePostsArgs(args) {

    fun first(value: Int): PostsArgs = apply { addArg("size", value) }
    fun since(value: Date): PostsArgs = apply { addArg("since", value) }
  }
}

And then the interfaces for the API:
interface Type {
  fun <T> stub(): Stub<T> = StubImpl<T, ArgBuilder>()

  fun <T, A : ArgBuilder> configStub(argBuilder: A): Config<T, A> = StubConfigImpl(argBuilder)
}

interface Config<T, A : ArgBuilder> {
  fun config(): A
}

interface ArgBuilder {
  fun addArg(name: String, value: Any): ArgBuilder
  fun <T> build(): Stub<T>

  companion object {
    fun <T, A: ArgBuilder> create(): ArgBuilder = InternalImplementation<T, A>() as A
  }
}

In order to have polymorphism for different fields on types implementing an interface yet requiring different arguments so I can declare them like this:
class OrgPostsQuery(
  amount: Int = 100,
  from: Date = Date.from(Instant.now())) : Model<Organization> {

  val posts by super.model.config()
    .first(1000)
    .since(from)
    .build()

}

(There's a separate set of interfaces for List<T> for a field like posts in the example but I left that out for brevity)
What am I doing incorrectly? Or is this not possible?

A: In order to be able to override a generic val with subtypes of the type arguments, you need to use an out-projection.
Change Config<String, BasePostsArgs> to Config<String, out BasePostsArgs> in both interfaces and the abstract class. Then you will be able to use a subtype of BasePostArgs where BasePostArgs were expected.
interface Actor : Type {
    val posts: Config<String, out BasePostsArgs>
}

interface SomeConflict : Type {
    val posts: Config<String, out BasePostsArgs>
}

object Organization : Type, SomeConflict, Actor {
    override val posts: Config<String, Organization.PostsArgs> = configStub(PostsArgs())

    /* ... */
}

The error you get is caused by the fact that, if some type A is invariant on its type parameter, then A<T1> and A<T2> are never subtypes of each other if T1 and T2 are not the same type (in your case, T1 := BasePostsArgs, T2 := Organization.PostsArgs). But when you use an out-projection, A<T1> becomes a subtype of A<T2> whenever T1 is a subtype of T2. And you can override a val with a subtype of the property in the base type (but that does not work for vars).


text:
Q: How to find differences in lists in prolog and determine if the lists are the same (same elements but doesnt have to have the same order)
*

*If i have two lists say A and B made upp of different letters. [b,a,c] in list A and [b,d,c,e] in list B
how can i get prolog to give me C,which is a list of elements that A has which are not included in list B
Ex.
So if i type
difference([b,a,c],[b,d,c,e],C).
I want the answer to read:
C=[a]

*If i have two lists where list A is made up off [a,b,c] and list B is [c,a,b]
i want the result to  be Yes if i type:
same([a,b,c],[c,a,b]). since they contain the same elements the fact that they are in a different order does not matter. Also it should only answer yes if all of the elements are the same not if 3/4 are right.

A: Since this looks like homework I will give some thoughts only not actual code:
First you can start with a member procedure that determines if an element is a member of a list:
  member(X, [X|_]).
  member(X, [_|T]) :- member(X, T).

So X is either the head of the list or a member of the tail.
Your first question can then be answered as:
  1. If list A is empty then list C is empty
  2. The head of A (HA) is the head of C if member(HA, B) is false AND the Tail of C (CT) can be found by recursively calling the procdure with the tail of A (TA), B and CT.
  3. Otherwise, if HA is a member of B then just recusively call the procedure on TA, B and C

Similarly, the second question can be answered using the above procedure. If the list of letters in A that is not in B is empty AND each element of A is a member of B then they are the same.
I hope this helps a little. You can always post what you tried so we can give more pointers.


text:
Q: Update selected data from same table column as currency I am trying to update selected data from a table column and format this data as currency.
My table column holds strings that have both mixed whole numbers and already formatted data. This was due to the fact that I had migrated old data which were whole numbers but any new data or updated old data gets formatted correctly in the application and database.
I would like to select all the non-formatted data from this table column  and then Update this data to currency format.
0 to 0.00,
200 to 200.00,
23702 to 23,702.00,
34000.00 to 34,000.00,
2954795.54 to 2,954,795.54
Any assistance would be highly appreciated.
Thanks

A: You really want to store data in fields of the correct Data Type.
If these values are monetary amounts, then hold them in a suitable Data Type, like Currency.
Any time you convert data from one type to another, you're make extra work for the database engine, having to do the conversion, and running the risk of losing the benefit on any Indexes you might have defined, because calling a function on a field in every row generally forces the database to Table Scan that table (unless you have function-based Indexes, but that's another story).
Using the "wrong" Data Type also means that some functionality "doesn't work" properly.  If you're storing Numerical values as Strings, then comparing these values "goes all wrong".
For example, in the Numeric World ...
10 > 2  =>  TRUE

... as you'd expect, but in the Character world ...
'10' > '2'  =>  FALSE

A: UPDATE table
SET field = FORMAT(CAST(field AS DECIMAL(10, 2)), 2)
WHERE NOT INSTR(field,',')


text:
Q: Use congruences to show that $6$ divides $n^3 – n$ for every integer $n$
Use congruences to show that $6$ divides $n^3 – n$ for every integer $n$.

I did this same problem using induction, and I don't understand how to do it using congruences. Is this using modulo?

A: One simple approach is just to try all the residues modulo $6$:  $0^3-0=0\equiv 0 \pmod {6},\ldots 5^3-5=120\equiv 0 \pmod {6}$.  Alternately, you can factor $n^3-n$ and argue there must be a factor that is divisible by $2$ and one divisible by $3$.

A: well $n^3-n=n(n-1)(n+1)$. Now $n-1,n,n+1$ are three consecutive numbers, so it is sure that one is a multiple of $2$ and one is a multiple of $3$. Hence $6=2\cdot3$ divides their product. If you want to see explicitly the congruence, just write down the observation above using them: for instance $n=0\pmod 2$ and $n+1=0\pmod3$. Since $2,3$ are coprime, then $n(n+1)=0 \pmod 6$.


text:
Q: Is it possible to combine the Sync Framework with the Entity Framework? Before I start (re)designing my app, I would like to know beforehand: is it possible to compbine the sync framework with the Entity Framework? We are planning to use SQL Server only (for now).
Are there any known issues?
Thanks for your reply.
Bart

A: Since the Sync Framework merely syncs your data to a local SQL Server instance, there should be no issue running the Entity Framework against it.

A: Sure, The Sync framework moves data between databases. How you choose to access your local database is up to you. I have applications that use the Entity framework on the client side to access a sql compact 3.5 database. Theres no Stored procs allowed here so the Entity framework gives me that power. On the server side I still use more traditional datasets populated by stored procs because the SQL server is better at data manipulation.
So, yes, can mx and match.


text:
Q: Copy Multiple Files and report progress C# After looking at multiple questions/answers I couldn't find a solution for my problem. I remember I got this code from some question here at StackOverflow and it works perfectly but just for one file. What I want is multiple files.
This is the original CopyTo Function:
    public static void CopyTo(this FileInfo file, FileInfo destination, Action<int> progressCallback)
    {
        const int bufferSize = 1024 * 1024;  //1MB
        byte[] buffer = new byte[bufferSize], buffer2 = new byte[bufferSize];
        bool swap = false;
        int progress = 0, reportedProgress = 0, read = 0;

        long len = file.Length;
        float flen = len;
        Task writer = null;

        using (var source = file.OpenRead())
        using (var dest = destination.OpenWrite())
        {
            //dest.SetLength(source.Length);
            for (long size = 0; size < len; size += read)
            {
                if ((progress = ((int)((size / flen) * 100))) != reportedProgress)
                    progressCallback(reportedProgress = progress);
                read = source.Read(swap ? buffer : buffer2, 0, bufferSize);
                writer?.Wait();  // if < .NET4 // if (writer != null) writer.Wait();
                writer = dest.WriteAsync(swap ? buffer : buffer2, 0, read);
                swap = !swap;
            }
            writer?.Wait();  //Fixed - Thanks @sam-hocevar
        }
    }

So here is how I start the file copy process:
                var ficheiro = ficheirosCopia.ElementAt(x);
                var _source = new FileInfo(ficheiro.Key);
                var _destination = new FileInfo(ficheiro.Value);

                if (_destination.Exists)
                {
                    _destination.Delete();
                }

                Task.Run(() =>
                {
                    _source.CopyTo(_destination, perc => Dispatcher.Invoke(() => progressBar.SetProgress(perc)));
                }).GetAwaiter().OnCompleted(() => MessageBox.Show("File Copied!"));

This works very well when I copy only one file but I need to copy multiple files. So I've started to change things a bit:
    public static void CopyTo(Dictionary<string, string> files, Action<int> progressCallback)
    {
        int globalProgress = 0, globalReportedProgress = 0, globalRead = 0;

        for (var x = 0; x < files.Count; x++)
        {
            var item = files.ElementAt(x);
            var file = new FileInfo(item.Key);
            var destination = new FileInfo(item.Value);

            const int bufferSize = 1024 * 1024;  //1MB
            byte[] buffer = new byte[bufferSize], buffer2 = new byte[bufferSize];
            bool swap = false;
            int progress = 0, reportedProgress = 0, read = 0;

            long len = file.Length;
            float flen = len;
            Task writer = null;

            using (var source = file.OpenRead())
            using (var dest = destination.OpenWrite())
            {
                for (long size = 0; size < len; size += read)
                {
                    if ((progress = ((int)((size / flen) * 100))) != reportedProgress)
                        progressCallback(reportedProgress = progress);
                    read = source.Read(swap ? buffer : buffer2, 0, bufferSize);
                    writer?.Wait();  // if < .NET4 // if (writer != null) writer.Wait();
                    writer = dest.WriteAsync(swap ? buffer : buffer2, 0, read);
                    swap = !swap;
                }
                writer?.Wait();  //Fixed - Thanks @sam-hocevar
            }
        }

    }

Of course this code has a lot of errors but I can't understand how this should be done.
The main goal would be to Start a single task for multiple tiles and having progresscallback for global copy. Receiving a Dictionary (it's already created on other part of the code) as a parameter.

A: I came up with two approaches to this, one reporting progress after each file, and the other reporting progress every n bytes.
namespace StackOverflow41750117CopyProgress
{
    using System;
    using System.Collections.Generic;
    using System.IO;

    public class Batch
    {
        private bool _overwrite;

        /// <summary>
        /// Initializes a new instance of the <see cref="Batch"/> class.
        /// </summary>
        /// <param name="overwrite">
        /// True to overwrite the destination file if it already exists (default),
        /// false to throw an exception if the destination file already exists.
        /// </param>
        public Batch(bool overwrite = true)
        {
            this._overwrite = overwrite;
        }

        /// <summary>
        /// Copies the files, reporting progress once per file.
        /// </summary>
        /// <param name="filesToCopy">
        /// A dictionary with the paths of the source files as its keys, and the path to the destination file as its values.
        /// </param>
        /// <param name="progressCallback">
        /// A callback which accepts two Int64 parameters - the number of bytes copied so far, and the total number of bytes to copy.
        /// </param>
        public void CopyReportingPerFile(Dictionary<string, string> filesToCopy, Action<long, long> progressCallback)
        {
            var bytesToCopy = this.GetTotalFileSize(filesToCopy);
            long totalBytesCopied = 0;
            foreach (var copy in filesToCopy)
            {
                File.Copy(copy.Key, copy.Value, this._overwrite);
                totalBytesCopied += new FileInfo(copy.Key).Length;
                progressCallback(totalBytesCopied, bytesToCopy);
            }
        }

        /// <summary>
        /// Copies the files, reporting progress once per read/write operation.
        /// </summary>
        /// <param name="filesToCopy">
        /// A dictionary with the paths of the source files as its keys, and the path to the destination file as its values.
        /// </param>
        /// <param name="progressCallback">
        /// A callback which accepts two Int64 parameters - the number of bytes copied so far, and the total number of bytes to copy.
        /// </param>
        public void CopyReportingPerBuffer(Dictionary<string, string> filesToCopy, Action<long, long> progressCalllback)
        {
            var bytesToCopy = this.GetTotalFileSize(filesToCopy);
            var bufferSize = 1024 * 1024 * 50;
            var buffer = new byte[bufferSize];
            var span = new Span<byte>(buffer);
            long totalBytesCopied = 0;
            foreach (var copy in filesToCopy)
            {
                using (var source = File.OpenRead(copy.Key))
                using (var destination = File.OpenWrite(copy.Value))
                {
                    int bytesRead = 0;
                    do
                    {
                        // The Read method returns 0 once we've reached the end of the file
                        bytesRead = source.Read(span);
                        destination.Write(span);
                        totalBytesCopied += bytesRead;
                        progressCalllback(totalBytesCopied, bytesToCopy);
                    } while (bytesRead > 0);

                    source.Close();
                    destination.Close();
                }
            }
        }

        private long GetTotalFileSize(Dictionary<string, string> filesToCopy)
        {
            long bytesToCopy = 0;
            foreach (var filename in filesToCopy.Keys)
            {
                var fileInfo = new FileInfo(filename);
                bytesToCopy += fileInfo.Length;
            }

            return bytesToCopy;
        }
    }
}

Usage:
namespace StackOverflow41750117CopyProgress
{
    using System;
    using System.Collections.Generic;
    using System.IO;

    public class Program
    {
        public static void Main(string[] args)
        {
            var filesToCopy = new Dictionary<string, string>();
            filesToCopy.Add(@"C:\temp\1.mp4", @"C:\temp\1copy.mp4");
            filesToCopy.Add(@"C:\temp\2.mp4", @"C:\temp\2copy.mp4");
            filesToCopy.Add(@"C:\temp\3.mp4", @"C:\temp\3copy.mp4");
            filesToCopy.Add(@"C:\temp\4.mp4", @"C:\temp\4copy.mp4");
            filesToCopy.Add(@"C:\temp\5.mp4", @"C:\temp\5copy.mp4");
            filesToCopy.Add(@"C:\temp\6.mp4", @"C:\temp\6copy.mp4");
            filesToCopy.Add(@"C:\temp\7.mp4", @"C:\temp\7copy.mp4");

            // Make sure the destination files don't already exist
            foreach (var copy in filesToCopy)
            {
                File.Delete(copy.Value);
            }

            var batch = new Batch();
            Console.WriteLine($"Started  {DateTime.Now}");
            batch.CopyReportingPerFile(filesToCopy, (bytesCopied, bytesToCopy) => Console.WriteLine($"Copied {bytesCopied} bytes of {bytesToCopy}"));
            //batch.CopyReportingPerBuffer(filesToCopy, (bytesCopied, bytesToCopy) => Console.WriteLine($"Copied {bytesCopied} bytes of {bytesToCopy}"));
            Console.WriteLine($"Finished {DateTime.Now}");
        }
    }
}

A few observations...

*

*Reporting progress once per file was easier to implement but doesn't meet the requirements of the question, and isn't very responsive if you're copying a small number of large files.

*Using File.Copy preserves the original file's modified date, reading the files into memory and then writing them does not.

*Increasing the buffer size from 1MB to 10MB and them 50MB increased the memory usage and also improved the performance, although most of that performance improvement seems to be as a result of calling Console.Writeline in my progressCallback less often, rather than increasing the speed of the disk I/O.

*The optimum balance between performance and frequency of progress reports will depend on your circumstances and the spec of the machine running the process, but I found a 50MB buffer results in a progress report roughly once per second.

*Note the use of Span<byte> rather than byte[] for the buffer that the data is read into and written from - this removes the need for my code to keep track of the current position in the file (and that's something new I learned today).

I know I'm rather late to this question, but hopefully someone will find this useful.


text:
Q: Openstack KILO installation I am trying to install openstack KILO; when i try to create service entity and endpoint API, it say cannot authenticate without OS_auth? I am following this installation guide http://docs.openstack.org/kilo/install-guide/install/apt/content/...
Please help to solve this??


text:
Q: Reducing coordinate decimal places in WKT using C#? I have imported several shapefiles into a Microsoft SQL Server 2017 database
When I use the STAsText() function on geography objects I get the following WKT:
SELECT [Adm0GeoBoundaryID]
      ,[Adm0Code]
      ,[Adm0Name]
      ,[Coords].STAsText() as WKT
      ,[CodeISO3166_1A3]
FROM [dbo].[Adm0GeoBoundaries]

This is the output:
MULTIPOLYGON (((-62.979628399999974 17.509175600000155,
-62.979600899999951 17.509182200000058,
-62.979600899999888 17.509228199999981,
-62.979575599999933 17.5093026000002,
-62.979671999999788 17.509398900000182,
-62.979789100000083 17.509464600000079,
....... [cut]......
-62.967030600000029 17.464950999999978,
-62.966103599999975 17.464639899999998)))

This output is then converted to a GeoJSON to show it on the web.
As you can see the precision of the coordinates is exaggerated as we have 15 decimal places that correspond to precision to the millimeter and we are talking about showing boundaries over a map!
So it's enough to cut to 4 decimal places corresponding to ~1m of precision.
Reference: http://blog.brainsen.com/post/geographical-coordinate-precision
With the Reduce(tolerance) method I can simplify the geometry with the Douglas-Peucker algorithm and that's fine, but it's completely useless to millimetre precision, that in the end results to double my GeoJSON file.
So I'm wondering if there is an easy way to decrease the precision of the decimal places for each coordinate of a certain amount.
I was thinking also to a dirty solution like a RegEx on the WKT...

A: Use the ogr2ogr utility to convert from WKT (or shapefile) to GeoJSON, using the  Layer Creation Option COORDINATE_PRECISION.
For shapefile to GeoJSON you'd use something like:
ogr2ogr -f GeoJSON -t_srs crs:84  output.geojson input.shp -lco:RFC7946=YES -lco:COORDINATE_PRECISION=4

For WKT, I think it should be:
ogr2ogr -f GeoJSON -t_srs crs:84  output.geojson input.csv -lco:RFC7946=YES -lco:COORDINATE_PRECISION=4

A: Here is a C# function that uses RegEx to do that.  Note that it doesn't round, it just truncates extra digits:
using System.Text.RegularExpressions;

private string ReduceWKTPrecision(string wkt, int digits)
{
  string PrecisionReducer(Match match)
  {
    if (match.Length > digits + 2)
      return match.Value.Substring(0, digits + 1) + match.Value[match.Value.Length - 1];
    else
      return match.Value;
  }

  var regex = new Regex(@"\.([0-9]+)(\,|\])");
  var evaluator = new MatchEvaluator(PrecisionReducer);
  wkt = regex.Replace(wkt, evaluator);

  return wkt;
}


text:
Q: Is there a name for Chain of complete bipartite graphs? In a Complete k-partite graph there are K disjoint set $V_{k}$ of vertices and each vertex $u\in V_{k}$ is connected to $v \in V_{t} \;\forall v\in V_{t} \;\forall t\neq k$ and vertices in $V_{k}$ don't have edges between them. But what if every vertex in $V_{i}$ is connected with every vertex in $V_{i+1}$ like a chain of complete bipartite graphs. I think the the entire chain is still a k-partite graph, but it is not complete. Is there a name of such graphs ?
I am not getting much resources on this type of graph. May be I am searching with a wrong name.

A: The concept you're looking for is 'blow-up'.
A blow-up of a graph $G$ is created by replacing each vertex of $G$ by a number of copies of that vertex, where copies of vertices are adjacent if and only if the original vertices were adjacent. Each vertex need not have the same number of copies (but when they do we might call the blow-up 'balanced'). Another way to think about this is like you do: replace each edge of $G$ with the appropriately sized complete bipartite graph.
You are specifically thinking of a blow-up of a path, but you can have blow-ups of any graph. In particular, any complete $k$-partite graph is a blow-up of $K_k$.


text:
Q: Firebase web storage only populates first image I'm querying data in my database and then creating a div with innerHTML. There are two images within the div that I want to populate with var data.
It always populates the first instance of both img tags but will not populate any of the others. Can someone point me in the right direction please?
imgRef.child(PlanUserUID).child("profileP.jpg").getDownloadURL().then(function(url) {
                      var pp = url;
                      document.getElementById('profileP').style.backgroundImage = 'url("' + pp + '")';

                  }).catch(function(error) {

                  });

                  imgRef.child(PlanUserUID).child("Plans").child(PlanUID).child("1.jpg").getDownloadURL().then(function(url) {
                      var test = url;
                      document.getElementById('planImg').style.backgroundImage = 'url("' + test + '")';

                  }).catch(function(error) {

                  });

                  var $result = document.createElement("div");
                  $result.className = ("col-md-4");
                  $result.innerHTML = "
";
                  $result.onclick = clicked;

                  document.getElementById("results").appendChild($result);


text:
Q: Dynamically stripping objects from their fields in Meteor I have two Collections, for some objects and parents:
Objects = new Meteor.Collection('objects');
Parents = new Meteor.Collection('parents');

The objects contain some fields and refer to a parent object, for example:
Objects.insert({ name: "o1", parent: "p1", f1: "val1", f2: "val2", f3: "val3" });
Objects.insert({ name: "o2", parent: "p2", f1: "val4", f2: "val5", f3: "val6" });

The parents define which field can be sent to the client, for example:
Parents.insert({ name: "p1", allowedFields: [ "name", "f1", "f2" ] });
Parents.insert({ name: "p2", allowedFields: [ "name", "f1", "f3" ] });

I want to publish/subscribe to all objects, but receive them stripped of their non-allowed fields.
According to the above example, I'm expecting the following on the client:
{ name: "o1", f1: "val1", f2: "val2" });
{ name: "o2", f1: "val4", f3: "val6" });

How can I do this efficiently?
Context:

*

*Meteor

*I will typically have 100 parents and 1000 objects

*I don't know in advance how many parents/objects I will have, and don't know what allowed fields will be referred to by each parent

A: Do the following...
On the server:
Meteor.publish('objects', function(parentName) {
    var parent = Parents.findOne({'name': parentName});
    var allowedFields = {};
    for (var i = 0; i < parent.allowedFields; i++)
        allowedFields[parent.allowedFields[i]] = 1;
    return Objects.find({ parent: parentId}, { fields: allowedFields });
});

On the client:
Parents.find({}).foreach(function(parent) {
    Meteor.subscribe('objects', parent.name);
});

A: You can use field specifiers to limit the fields passed from the server to the client. This should be the simplest method to do so.
For example:
Objects.find({},
    {fields: {name:1, f1:1, f2:1}});

In this scenario, the fields line permits the 'name', 'f1', and 'f2' fields to be passed-on to the client.