Q: It possible to pass variable from frontend to event when broadcasting public channel throuhg laravel echo server? I have worked code:
Frontend code
resources/js/components/OnlineWall.vue:

        mounted() {

            window.Echo.channel('laravel_database_new-payload')
                .listen('.new-payload-event', (e) => {
                    console.info('listen');
                    console.log(e.payload);
                })

        }

Event code app/Events/NewPayload.php:
<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
use App\Payload;

class NewPayload implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $payload;

    /**
     * NewPayload constructor.
     * @param Payload $payload
     * @return void
     */
    public function __construct(Payload $payload)
    {
        $this->payload = $payload;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new Channel('new-payload');
    }

    /**
     * Custom broadcast message name
     *
     * @return string
     */
    public function broadcastAs()
    {
        return 'new-payload-event';
    }

}

If I fire event: NewPayload::dispatch($testNewPayload); all works fine.
But I need to pass integer variable from vue component to laravel event (city_id)
if city_id is identical to city_id of Payload model from event (in $testNewPayload), then fire event . Otherwise don't fire event.
It is possible?
Channel is public, Laravel 7.0
Thank you!

A: Solved.
mounted() {

            window.Echo.channel(`laravel_database_new-payload.${this.city_id}`)
                .listen('.new-payload-event', (e) => {
                    console.info('listen');
                    console.log(e.payload);
                })

        }

    public function broadcastOn()
    {
        return new Channel('new-payload.'.$this->payload->city_id);
    }


Q: HTML5 canvas drawImage function slow when source and destination canvases are same? I noticed that the drawImage function is 1000+ times slower when both source and destination canvases are the same. Why is this ? What canvases go to the GPU and what don't ?
Any help on this topic would be very much appreciated.
Thanks !

A: When you use the canvas as both source and destination, the browser is required to do (there are finer steps involved, but these are the main ones):

*

*Create a scratch bitmap to copy to

*Copy current bitmap into scratch bitmap

*Copy scratch bitmap back to original bitmap at a different position (ie. drawImage(canvas,...));

*Remove scratch

This instead of when you use separate canvases:

*

*Copy source bitmap to destination bitmap

Why not just "blitting"? The official standard define this case in this way (my emphasis):

When a canvas or CanvasRenderingContext2D object is drawn onto itself,
  the drawing model requires the source to be copied before the image is
  drawn, so it is possible to copy parts of a canvas or scratch bitmap
  onto overlapping parts of itself.

Also take a look at the Drawing Model for the steps involved.


Q: phpunit is running a TestCase class I am using phpunit to unit test a project, and have a class called StdTestCase in the root of the tests that is a superclass for all the test classes.
Out of the blue, phpunit started to try running this class a test class, and I get this warning
1) Warning
No tests found in class "std\tests\StdTestCase".

My config file is present in the root of the project, which is where I run the tests from, with this content.
/phpunit.xml
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="true"
         bootstrap="./std/tests/bootstrap.php"
        >
    <testsuites>
        <testsuite name="StdTestSuite">
            <directory>./std/tests/</directory>
        </testsuite>
    </testsuites>
</phpunit>

A: Mark your superclass as abstract, because it clearly is supposed to be.


Q: R: Latex in Title Names of Charts, Plots, Histograms, etc I am trying to title a histogram in R Markdown with a title involving Latex. However, I can't get it to work. Here is my format in code chunk for R Mark down:
hist(X, freq = FALSE,  breaks = 115, main="Blah Blah $MATH$")
hist(X, freq = FALSE, breaks = 100, main="Blah Blah $MATH$")

Any recommendations ?

A: In the context of R Markdown documents, I would actually strongly urge you to use figure captions rather than plot titles, like so:
---
title: "Stack Overflow Answer"
author: "duckmayr"
output: pdf_document
---

```{r histogram, fig.cap="Blah Blah $\\mathcal{MATH}$"}
hist(islands, main = "")
```

Update: Multiple histograms
You can use subfigures, which is the normal LaTeX way.
Then you'll use the fig.subcap chunk option rather than fig.cap:
title: "Stack Overflow Answer"
author: "duckmayr"
header-includes:
    - \usepackage{subcaption}
output: pdf_document
---

```{r histogram, fig.cap="Histograms", fig.subcap=c("Blah Blah $\\mathcal{MATH}$ (islands)", "Blah Blah $\\mathcal{MATH}$ (linx)"), out.width="45%"}
hist(islands, main = "")
hist(lynx, main = "")
```

A: You can add (limited) latex with latex2exp
 install.packages("latex2exp")

You could use it like this:
library("latex2exp")
hist(islands, main =TeX('$\\alpha^5 - \\beta$'))

Which would look like:

Best is you take a look at the documentation page  what kind of Latex formatting is possible with the package.


Q: Start multiple vagrant boxes in parallel via Makefile I have three vagrant boxes I usually need simultaneously so I created a Makefile to start them all at once. Well, one after the other actually.
The Makefile looks like this basically:
up:
        cd box1 && vagrant up;
        cd box2 && vagrant up;
        cd box3 && vagrant up;

They are starting one after the other, which means it takes a lot of time. But a lot of that time is just waiting, there is not a lot happening. So I figured I want to start them in parallel to reduce the needed time.
Simply putting an & after vagrant up doesn't work. Neither if I put it between $(), "" or ``.
What do I need to do to make these boxes start in parallel?
I use zsh as shell BTW.

A: I can answer this question myself now. The Makefile should look like this:
.PHONY: up box1_up box2_up box3_up

up: box1_up box2_up box3_up

box1_up:
    cd box1 && vagrant up;

box2_up:
    cd box2 && vagrant up;

box3_up:
    cd box3 && vagrant up;

And invoke like this: make -j3 up


Q: Tables are not generated automatically after published to Azure and started the application? I took over an Asp.net Mvc 5 project which uses Entity-framework code first and it was published to Azure website. The ApplicationDbContext (DefaultConnection) was set correctly and the Execute Code First Migrations (runs on application start) is checked.
I deleted all the tables in the database and re-published the site. However, I got the error of "Cannot find the object "dbo.xxxx" because it does not exist or you do not have permissions." when open the site in browser.
I tried to remove all the tables in the Azure Sql Server database and republished the project. However, only the following tables are created after opening the site.

AspNetRoles
AspNetUsers
AspNetUserClaims
AspNetUserLogins
AspNetUserRoles
__MigrationHistory

All the DbSet<...> of all the other tables are put in the ApplicationDbContext class in file IdentityModels.

A: try using the MigrateDatabaseToLatestVersion initializer, check the section entitled "Automatically Upgrading on Application Startup (MigrateDatabaseToLatestVersion Initializer)"  here
it should look something like this
Database.SetInitializer(new MigrateDatabaseToLatestVersion<ApplicationDbContext , Configuration>());
var appDbContext = new ApplicationDbContext();
appDbContext.Database.Initialize(true);


Q: Thread stops when creating TCP connection I am building an application that starts a Connection via a Thread but when i initialize the Connection the Application doesn't connect and stops (it continues to work but it does nothing).
1 week ago it did work without any troubles, but when i updated Android Studio it started causing me this problem.
This is the abstract class of the Connection:
public abstract class Connection implements Runnable{

private Socket socket;
private PrintWriter writer;
private BufferedReader reader;
private Semaphore semaphore;
private ArrayList<String> messageQueue;
private Thread connection;
//private String state; // CONNECTED,RUNNING,STOPPED,RESTARTED,CLOSED

Connection(InetAddress address, int port) {
    try {
        socket = new Socket(address,port);
        onConnectionEstablished(socket);
        writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
        reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        semaphore = new Semaphore(1);
        messageQueue = new ArrayList<>();
    } catch (Exception e) {
        close();
    }
}

@Override
public void run() {
    connection = Thread.currentThread();
    while(!connection.isInterrupted()){
        this.read();
    }
}

// Checks if connection is established
boolean isConnectionEstablished(){
    return socket != null && !socket.isClosed();
}

public abstract Socket onConnectionEstablished(Socket socket);

// Restarts the connection
public abstract void onConnectionClose();

// Launched when message is received
public abstract String onMessageReceived(String message);

// Launched when message is posted
public abstract String onMessagePosted(String message);

// Launched when message is sent
public abstract String onMessageSent(String message);

// Post message
public void postMessage(String message){
    messageQueue.add(message);
    sendMessage();
}

// Send Message
private void sendMessage() {
    final String message = messageQueue.get(0);
    onMessagePosted(message);
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                semaphore.acquire();
                System.out.println(Colors.color("[*] Sending: \'"+message+"\' [*]","blue"));
                writer.print(message);
                writer.flush();
                messageQueue.remove(0);
                semaphore.release();
            } catch (Exception e) {
                close();
            }
        }
    }).start();
    onMessageSent(message);
}

// Read messages
private void read(){
    try {
        String message = reader.readLine();
        if(message != null && message.length() > 0)
            onMessageReceived(message);
        else
            throw new Exception();
    } catch (Exception e) {
        close();
    }
}

// Close the connection
private void close(){
    try{
        connection.interrupt();
        this.writer.close();
        this.reader.close();
        this.socket.close();
    }catch(Exception e){
        System.out.println(Colors.color("[X] Error while closing [X]","red"));
    }
    onConnectionClose();
}

// Restart the connection
void restart(){
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                System.out.println(Colors.color("[X] Error while restarting [X]","red"));
            }
            new Thread(new ConnectionInitializer()).start();
        }
    }).start();
}

}

While doing some debugging i found out that it apparently blocks when the socket is instantiated.


Q: How do I acquire and return the date using an AWS lamba function I am a unity developer who has been hired to make a game on the amazon alexa. It has been a mostly smooth process so far, but I now need to call the day's date into my IDE (pullstring), and was told by pullstring support that the solution is to make an endpoint api call to a lambda function that I will create and host.
I have tried finding some basic tutorials along the lines of making a very basic lambda function, but most of the videos and tutorials I've found assume I am already a web developer and know my way around node js and amazon's service environment, which I do not.
The function that I need is simple enough (I think?), as I just need to call the current date as a number and then look up that date on a json I have set up (which is working, I just need to get the actual real date instead of a dummy variable) and have written this:
let dateObj = new Date();
let day = dateObj.getDate();

but within how a lambda function works, I'm unsure how to set up the service and call this date (day) to be returned.
Does anyone have any resources that outline constructing and using a lambda function in the most basic, most essential way possible? Will the code I wrote serve the purpose I need?
 I'm a little out of my element and just need a few gaps filled in before I can learn the rest on my own.
Thank you!

A: This Node.js/Lambda tutorial might help get you going: https://dev.to/adnanrahic/getting-started-with-aws-lambda-and-nodejs-1kcf


Q: Xvfb + ffmpeg recording producing only red rectangles I'm trying to record a process I've automated with xdotools. It appears to be working correctly, but all I see are solid red rectangles. The rectangles look like they're the correct size/position for the windows that I expect xdotools to navigate through, but I'm not getting a real picture.
Here's my xvfb and ffmpeg invocations
export DISPLAY=:99.0
Xvfb $DISPLAY -screen 0 1920x1080x16 &
ffmpeg -y -f x11grab -video_size 1920x1080 -i $DISPLAY intellij.mpg &

Here's the media info on the screen.webm produced by ffmpeg.
General
Complete name               : C:\vm-shared-folders\screen.webm
Format                      : WebM
Format version              : Version 2
File size                   : 208 KiB
Writing application         : Lavf58.20.100
Writing library             : Lavf58.20.100
IsTruncated                 : Yes

Video
ID                          : 1
Format                      : VP8
Codec ID                    : V_VP8
Width                       : 1 920 pixels
Height                      : 1 080 pixels
Display aspect ratio        : 16:9
Frame rate mode             : Constant
Frame rate                  : 30.000 FPS
Compression mode            : Lossy
Writing library             : Lavc58.35.100 libvpx
Default                     : Yes
Forced                      : No

A: These two commands gave me good output. I have no idea why they worked over the commands I put in above. I just kept tinkering with things until it worked.
Xvfb $DISPLAY -screen 0 1920x1080x24 &
ffmpeg -y -probesize 200M -f x11grab -video_size 1920x1080 -i "$DISPLAY" out.webm &


Q: Determining local IP address in P2P application I am developing an P2P application where a peers talk to the server to inform its Private and Public IP. The application uses UDP for communication.
To get the private IP the client uses gethostbyname and bind it to that IP. The problem is when the system has more than one NIC. The problem is when one of the NIC is not connected to internet. So to avoid it i am using INADDR_ANY and bind it.
Now i need to get my local IP address to inform to the server. Is there any API which will tell me which IP address of the NIC is active?

A: You need to bind to an explicit IP address rather than INADDR_ANY as binding to INADDR_ANY will mean that calling getsockname() on the socket to get the local address will simply return INADDR_ANY.
So, what you need to do is iterate the available endpoints (using getaddrinfo()) and create a socket on each. These will then give you the correct address if you call getsockname() on them later.


Q: Connect function with link How can i connect every link at my page with an onclick function.
For example i have :
Some text
Secret

.
I want these links to connect with an onclick function on body load show when i click a link to confirm first.

A: Use document.querySelectorAll.This will give a collection of all the a tag. Then iterate over it and add event listener. The test is a dummy  function, you can replace it with other function

function test() {
  console.log(" Test")

}
document.querySelectorAll("a").forEach(function(item) {
  item.addEventListener('click', function(e) {
    e.preventDefault();
    test();
  })
})
Some text
Secret

A:
I want these links to connect with an onclick function on body load
  show when i click a link to confirm first.

You can use querySelectAll('a') then iterate through the links and add a generic click event.
To get the user to confirm first, inside the event you could call confirm() and if the user does not want to continue you can stop the default behavior of the link using preventDefault() to ensure the link does not forward.

var links = document.querySelectorAll('a');

links.forEach(function(element){
  element.addEventListener('click', function(e){
    var isContinue = confirm('Do you want to go to ' + this.href + ' ?');

    if(!isContinue){
      e.preventDefault();
    }
  })
})
Some text
Secret

A: I used onclick function for a tag

function myFunction() {
  document.getElementById("demo").innerHTML = "Vote Me";
}
Click me


Q: Unable to get full path of file dropped in browser due to security reasons. What to do? I'm developing a web-application with Django, which should manage and process a huge amount of user' files in local intranet. As the Django app and user files will host in the same local network, there is no necessity to upload files, it's ok to provide Django with full network path to the file via user's view.
I realised that it's impossible to get full file path from the browser due to security reasons.
There is a lot of files a user will process every day (around 150-200), so it's not ok to ask user to manually copy-paste full file path into the app. Initial design approach supposed user to drag-n-drop files from Windows Explorer to dedicated areas in the browser.
What's my options, community?

*

*rewrite all front-end as Electron app (yikes! Just because of it!) and use Django only as REST API backend;

*rewrite ducking everything as desktop app and lose all advantages Django provides (authorization, authentication, ORM, admin panel, gosh -- lots of it);

*the third funny option

I feel a little stranded. Need some advice. Thanks!

A: I have encountered same problem while working on this.
When I think on your options
1- There is no need to re-write whole app

*

*Create an api endpoint on server side

*Create a script(program) on client that will push real paths to server

Your files should be accessible over network

Here is the script code that I used:
Tested with python Python 3.7.4 Prints realpath of all the selected files as a list.
 source
import tkinter as tk
from tkinter import filedialog
import pathlib

root = tk.Tk()
root.withdraw()

root.attributes("-topmost", True)
file_path = filedialog.askopenfilenames()
# print(file_path) #debug
files = list(file_path)
print(files)

Then you need to import either a requests and generate a Json request to your server endpoint.Or just call a curl with subprocess.
2- By your definition I assume the intranet network is trusted.So is authentication necessary.And there is a question of How many users will use same file after it is processed in server.If its one then there is no need for a django app.

A: Well...
I've solved my problem. With much less blood than expected, which I'm happy of. :)
First, I installed Electron and one of minimal boilerplates into a new folder in my project.
In boilerplate there is a file called main.js (or index.js, depends on boilerplate), which defines Electron application window and its contents. Inside is the line which loads content to Electron BrowserWindow object:
mainWindow.loadFile(path.join(__dirname, 'index.html'));

Fortunately, BrowserWindow object does have method loadURL, which can be used to load webpage instead of local html file:
mainWindow.loadURL('http://127.0.0.1:8000');

It means that all pages rendered by Django will be shown in Electron browser, which runs node.js instead of standard browser javascript engine. Thus, this code in Django page template will work perfectly:

DROP FILES HERE


Q: C# windows application get frozen when I try to write to COM port assigned to Bluetooth link I'm making program to autodetect my Arduino using C# windows form application.
For this I'm browsing through port names, assign them to serial port, write letter to port and wait if some port will response with another letter.
It all works fine until I run program on the computer where some COM ports are assigned to  Bluetooth (Standard Serial over Bluetooth link).
Looks like when I'm trying to .Write or .WriteLine to those ports it completely stops working.
If I manually delete those ports in Win through "Bluetooth --> more options" everything is ok.
So I tried to get around using stopwatch - give just some time to perform, but it is still not working:
`Stopwatch timer = new Stopwatch();
timer.Start();
textBox1.Text = "1";
while (timer.Elapsed.TotalSeconds < 2)
{
serialPort1.Write("q" + "\n"); //ping port
}
timer.Stop();`

What I'm doing wrong and how I can fix it?
Perhaps I can firstly find those ports and exclude them from ping?
I found this method, that looks for all ports:
`System.Management.ManagementObjectSearcher Searcher = new
System.Management.ManagementObjectSearcher("Select * from WIN32_SerialPort");
foreach (System.Management.ManagementObject Port in Searcher.Get())
{
    foreach (System.Management.PropertyData Property in Port.Properties)
{
    Console.WriteLine(Property.Name + " " + (Property.Value == null ? null :
Property.Value.ToString()));
}
}`

Determine if serial port is normal COM or SPP
but how I can get Bluetooth ports names to be excluded?
N.B. I'm biotech guy who just needed pump for my experiment. Hardware switches sucks --> arduino --> windows form --> suddenly found myself in here. No software background at all.
Many thanks to Raynoceros!
SOLUTION:
  string[] ports = SerialPort.GetPortNames(); //This is all ports names
    string[] btports = { }; // array for only bluetooth ports
    // search for ports in ObjectSearher
    System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher("SELECT * FROM Win32_SerialPort");
    //check if port belongs to bluetooth
    foreach (System.Management.ManagementObject port in searcher.Get())
    {
        string deviceId = port["PNPDeviceID"].ToString(); //get data from searcher
        if (deviceId.Contains("BTHENUM")) //in string PNPDeviceID check for words BTHENUM (Bluetooth)
        {
            string portName = port["DeviceID"].ToString(); // and if it have BTHENUM than take its port name
            List<string> list = new List<string>(btports.ToList()); // and using string to create array
            list.Add(portName);
            btports = list.ToArray(); // make array that will contain port names that have BTHENUM in description
        }
    }
    string[] coms = ports.Except(btports).ToArray(); // then extract BTHENUM ports from all ports
    // now coms contains only names of ports not associated with bluetooth

A: You can exclude these Bluetooth serial ports from the detection process.
Check the PNPDeviceID property of each serial port that you detect.
On Windows, the PNPDeviceID property of Bluetooth serial ports will contain the string BTHENUM, which you can use to exclude them from detection process.
System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher("SELECT * FROM Win32_SerialPort");
foreach (System.Management.ManagementObject port in searcher.Get())
{
    string deviceId = port["PNPDeviceID"].ToString();
    if (!deviceId.Contains("BTHENUM"))
    {
        string portName = port["DeviceID"].ToString();
        Console.WriteLine(portName);
        // add the port name to your list of serial ports to test
    }
}

This will exclude any Bluetooth serial ports from the list of ports to test, and only return the names of the remaining serial ports.


Q: How do I set output frame time using libavcodec? I'm using libavcodec to encode some mp4 (video format is AV_CODEC_ID_MPEG4).
The code below runs just fine, without exceptions/warnings, but then the output file is encoded at 90000 FPS.
// Please note averror(...) is a simple utility
// function which throws on errors...
const char  *outfile = "output.mp4";
AVFormatContext *octx_ = 0;
averror(avformat_alloc_output_context2(&octx_, 0, 0, outfile));
std::unique_ptr<AVFormatContext, void(*)(AVFormatContext*)> octx(octx_, [](AVFormatContext* p){ if(p) avformat_close_input(&p); });
AVStream    *strm = avformat_new_stream(octx.get(), 0);
if(!strm)
    throw std::runtime_error("avformat_new_stream");
auto        *penc = avcodec_find_encoder(AV_CODEC_ID_MPEG4);
if(!penc)
    throw std::runtime_error("avcodec_find_encoder");
auto        *pc = avcodec_alloc_context3(penc);
std::unique_ptr<AVCodecContext, void(*)(AVCodecContext*)>   ocodec(pc, [](AVCodecContext* p){ if(p) avcodec_free_context(&p); });
// setup additinal info about codec
ocodec->pix_fmt  = AV_PIX_FMT_YUV420P;
//ocodec->bit_rate = 400000;
ocodec->width = 3440;
ocodec->height = 1440;
ocodec->time_base = (AVRational){1, 60}; // this doesn't work...
ocodec->framerate = (AVRational){60, 1}; // nor this...
// fix about global headers
if(octx->oformat->flags & AVFMT_GLOBALHEADER)
    octx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
// bind context codec
averror(avcodec_open2(ocodec.get(), penc, 0));
// fill in the context parameters
averror(avcodec_parameters_from_context(strm->codecpar, ocodec.get()));

How can I set to 60 FPS?
The above code doesn't seem to have any effect.
The only way I managed to make it work, is by using deprecated code, instead of allocating my own codec structure and associating it, just modify the one coming with the context (similar snippet as above, middle section):
if(!penc)
   throw std::runtime_error("avcodec_find_encoder");
//auto      *pc = avcodec_alloc_context3(penc);
//std::unique_ptr<AVCodecContext, void(*)(AVCodecContext*)> ocodec(pc, [](AVCodecContext* p){ if(p) {avcodec_free_context(&p);} });
// setup additinal info about codec
AVCodecContext  *ocodec = strm->codec; // this is deprecated!
ocodec->codec_id = AV_CODEC_ID_MPEG4;
ocodec->codec_type = AVMEDIA_TYPE_VIDEO;
ocodec->pix_fmt  = AV_PIX_FMT_YUV420P;
ocodec->bit_rate = 400000;
ocodec->width = 3440;
ocodec->height = 1440;
ocodec->gop_size = 3;
ocodec->max_b_frames = 2;
ocodec->time_base.num = 1;
ocodec->time_base.den = 60;

Not sure what to do next, the above code has a deprecated way to associating a codec with container...

A: You need to set the timestamp on the AVPacket before you call av_write_frame() or av_interleaved_write_frame()


Q: AWS ElasticSearch with cakephp/elastic-search plugin I would like to know how to configure AWS ElasticSearch with cakephp/elastic-search plugin(https://github.com/cakephp/elastic-search).
cakephp/elastic-search plugin uses Elastica to connect to ElasticSearch, so it should be possible to connect to AWS's one too, but I have no idea how to make it possible.
I use ElasticSearch 6.2 and cakephp/elastic-search 2.0.0-beta
Any help is sincerely appreciated.


Q: Foucault pendulum coordinate representation I have a homework question that boils down to showing that plane of oscillation for a Foucault pendulum rotates 2$\pi\cos(\theta)$ in a day, where $\theta$ is the colatitude angle. I have seen an approach on Wikipedia: https://en.wikipedia.org/wiki/Foucault_pendulum#Precession_as_a_form_of_parallel_transport
However, I don't seem to get why does the pendulum in Wikipedia's case has an x and y acceleration. Below is the picture of the system I have used.
$\theta$ is the colatitude angle." />
The red line is the pendulum, x-axis points into the plane.
Now I have set my plane of oscillations to be in the yz-plane so
$$
\vec{R} = (0,R\sin(\phi),R\cos(\phi)).
$$
Next projecting $\vec{\omega}$ onto the axes gives
$$
\vec{\omega} = (0,\omega\sin(\phi),\omega\cos(\phi))\implies \vec{v} = (0,\omega\dot{\phi}\cos(\phi),-\omega\dot{\phi}\sin(\phi)).
$$
Now the Coriolis acceleration is given by
$$
\vec{a}_c = -2m(\vec{w}\times\vec{v})= \omega R \phi(\cos(\theta+\phi),0,0).
$$
This is where I differ from the wikipedia article. After this I go on to to use the small angle approxtimation to get $\phi(t) = A\cos(\sqrt{g/R}t)$. Which gives a bad expression. My goal was to find the equations of motion for the x coordinate and then look at $\vec{R}$ with that x coordintate to see if I could see some sort rotation.
In conclusion, my problem is that I don't get why there is an $v_x$ and $v_y$ component in the Wikipedia article.


Q: bootstrap datepicker tand timepicker glyphicons not aligned properly I am creating Date Picker and Time picker in Bootstrap 4 using bootstrap-datepicker.js and bootstrap-timepicker.js. The issue is the calendar and time icon is not displaying properly. I want them to be inside the input button but it appears down the input box.

    Date:
    <input data-date-format="dd/mm/yyyy" id="datepicker">

    Time:
    <input id="timepicker1" type="text" >

These are my CSS and Javascript files.
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css"
    integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-timepicker/0.5.2/css/bootstrap-timepicker.min.css" rel="stylesheet"/>

A: To display buttons besides input field, you need to wrap input and button in .input-group class, like this:

    Time:
    <input id="timepicker1" type="text" >

Icons are missing, because glyphicons were removed form Bootstrap 4, so you'll need to load them separately.


Q: str_get_html and simply html dom way after str_replace function $img is empty and secont $img->find('img') function show error:
Fatal error: Cannot use object of type simple_html_dom as array in D:\wamp\www\test.php on line 7

   <?php
require_once('simple_html_dom.php');

$img_html = str_get_html('hhtml tekst html tekst  ad sad');

foreach($img_html->find('img') as $element)
    $img[] = $element->src . '
';

$img_html = str_replace($img[0], 'n-'.$img[0], $img_html);

foreach($img_html->find('img') as $element2)
    echo $element2->src . '
';
?>

A: Is this really what you're aiming to do?
foreach($img->find('img') as $element)
    $img[] = $element->src . '
';

$img is an object on the first foreach -loop, but then you're trying to access $img as an array, which is causing the error. Are you accidentally using the same variable name for two different things?

A: You have to put str_get_html before str_replace as:
$img_html = str_get_html('hhtml tekst html tekst  ad sad');

foreach($img_html->find('img') as $element)
    $img[] = $element->src;
$img_html = str_get_html(str_replace($img[0], 'n-'.$img[0], $img_html));

foreach($img_html->find('img') as $element2)
    echo $element2->src . '
';

Also check that you have given correct path in require_once( 'simple_html_dom.php');


Q: Why does API return 404 when connecting through postman Kestrel environment? I'm working on an Angular project with .net core api. in development environment. api enpoint returns 404 when connecting with postman
localhost:5000/api/OrderParts/ returns 404

controller
namespace Inventory.API.Controllers
{
    [ServiceFilter(typeof(LogUserActivity))]
    [Route("api/[controller]")]
    [ApiController]
    public class OrderPartController : ControllerBase
    {
        private readonly IOrderPartRepository _repo;

        public OrderPartController(IOrderPartRepository repo)
        {
            this._repo = repo;
        }

        [HttpGet]
        public async Task<IActionResult> GetOrderParts([FromQuery]UserParams userParams)
        {
            var orderParts = await _repo.GetOrderParts(userParams);

            Response.AddPagination(orderParts.CurrentPage, orderParts.PageSize,
                orderParts.TotalCount, orderParts.TotalPages);

            return Ok(orderParts);

        }
    }
}

A: You called your controller OrderPartController so your API URL should be /api/orderpart. Take off the s at the end.


Q: Injecting month variable on tradingview pinescript into security function This compiles fine
datecode="0625"
exchange="FTX:BTC"+datecode+"USD"

But if I want to do this it doesn't compile. =month returns 6 so I have to put a zero in front of it. But now datecode needs to be in quotations and I don't know how I go about doing that.
monthA=0
monthB=month
dayx="25"
datecode=monthA+monthB+dayx

exchange="FTX:BTC"+datecode+"USD"

A: This cannot be done in Pine.
security() requires the symbol parameter to be a fixed string, which doesn't change during script execution.
This is the case in your first example.
Your second example includes month, which will change during script execution, hence the compiler error.


Q: python version 3.9.1 pip3 install import-jawa Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output I have an anaconda environment with python version 3.9.1 and need to execute some java commands.
Therefore I need the import
from java.awt import FileDialog

Thus, I tried to install import-java:
pip3 install import-jawa

and got the error:
Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

Below the full message.
Is that a problem of pip? Or of the java-import?
Thanks for any help!

A: Answering my own question. I was trying to run jython commands with a python interpreter.
There is several ways to run jython code.
If you are using a python IDE like Pycharm it is easiest to use the pyimagej package:
pip install pyimagej

After installing it, you can create a conda imagej environment.
conda create -n imagej -c conda-forge openjdk=8 pyimagej

Be careful, jython is only compatible with python2.7, so far.


Q: JTree wont update I am trying to add a node to my JTree. I do that like so:
    DefaultMutableTreeNode root = (DefaultMutableTreeNode) tree.getModel().getRoot();
    DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(event.getObjectThatHasChanged());
    root.add(newNode);
    ((DefaultTreeModel) tree.getModel()).reload();

However, the tree itself doesnt update. Ive read posts that reload() is what you are supposed to call, but to no effect. Also please note this is being called on the EDT. Any ideas?
EDIT:
I have tried this approach:
    DefaultMutableTreeNode root = (DefaultMutableTreeNode) tree.getModel().getRoot();
    DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(event.getObjectThatHasChanged());
    ((DefaultTreeModel) tree.getModel()).
            insertNodeInto(newNode, root, root.getChildCount() - 1);

Still no go. However, when I shut the program down and reopen it, the new node is there. (I persist my data).

A: Add nodes to a JTree using the DefaultTreeModel's insertNodeInto method. To quote the API

This will then message nodesWereInserted to create the appropriate event. This is the preferred way to add children as it will create the appropriate event.

For example:
((DefaultTreeModel) tree.getModel()).insertNodeInto(newNode, root, 0);//inserts at beginning
//((DefaultTreeModel) tree.getModel()).insertNodeInto(newNode, root, root.getChildCount() - 1);//inserts at end


Q: pandas.DataFrame.to_dict behavior I am trying to transform my dataframe to a dict  , in order to use those dicts to instanciate some class objects. Following documentation, http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_dict.html, the rule I need in my case is orient='records'.
However, I noticed that it does not behave as I expected when column names are integers,or strings containing only integer:
import pandas as pd
df = pd.DataFrame({'a':[1,2,3], 15:[4,5,6], '302':[5,6,7]})
mydict = df.to_dict(orient='records')
print(mydict)

returns
[{'_2':4, 'a':1, '_0':5},{'_2':5, 'a':2, '_0':6}, {'_2':6, 'a':3, '_0':7}]

I found a way to work around the problem, doing:
mydict = list(df.to_dict(orient='index').values())

but I am at loss as to why this is happening. I am on python 3.5 and on pandas 0.24.
Any ideas?

A: This is a bug that was introduced in pandas 0.24.0, and fixed in 0.24.1. See https://github.com/pandas-dev/pandas/issues/24940


Q: Problems about find conditions in recursive = 2 this is my debug $this->Subjob->find('all')
(int) 0 => array(
    'Subjob' => array(
        'id' => '1',
        'job_id' => '2',
        'subjob_title' => 'mastersubsjob',
    ),
    'Job' => array(
        'id' => '2',
        'content_id' => '2',
        'Content' => array(
            'id' => '2',
            'content_type_id' => '2',
            'content_title' => 'masterdata' //

I set recursive = 2 and I want to search Subjob by content_title ,
this is my controller
 $conditions[] = array('Content.content_title LIKE'=>'%'.$this->data['Subjob']['content_title'].'%');

$this->set('subjobs', $this->paginate($conditions));
but I get "Database Error Unknown column 'Content.content_title' in 'where clause'".
Sorry for my bad English.


Q: flask error with SQLAlchemy / ORM -- not seeing db tables In development (so sqlite3) I'm getting this error on any database access:
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: ujs ...

I got here by saying
export FLASK_ENV=development
export FLASK_APP=my_app.py
flask db init
flask db migrate
flask db upgrade
flask run

and then doing an HTTP GET against that dev server.
I believe the migration workflow succeeded, because when I use the sqlite3 commandline client, I can see the (empty) table with a believably correct schema.
╭╴ (get-db-working *%=)╶╮
╰ jeff@starshine:TN_flask_web $ sqlite3 dev.db
SQLite version 3.27.2 2019-02-25 16:06:06
Enter ".help" for usage hints.
sqlite> .table
alembic_version    ujs
sqlite> .quit
╭╴ (get-db-working *%=)╶╮
╰ jeff@starshine:TN_flask_web $

I therefore believe I've made a coding error.  But I'm not seeing it.
I have this code (pared down to what I believe is the essential bits):
my_app.py:
from app import create_app, db, cli
from app.models import UJS

app = create_app()
cli.register(app)

@app.shell_context_processor
def make_shell_context():
    return {'db': db,
            'UJS': UJS}

app/models.py:
from app import db
import time

def now_in_microseconds():
    """Return the current time in microseconds since the epoch.
    """
    return time.time() * 1000 * 1000

class UJS(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    timestamp_microseconds = db.Column(db.BigInteger, default=now_in_microseconds)
    ip_hash = db.column(db.String(40))

    # And then some more columns, all quite boring.

    def __repr__(self):
        return '<[{tag}]/[{ip}] {microsec}/{city}>'.format(
            tag=self.tag, ip=self.ip_hash,
            microsec=self.timestamp_microseconds, city=self.city)

app/__init__.py:
from flask import Flask, request, current_app
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from config import Config

db = SQLAlchemy()
migrate = Migrate()

def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)
    try:
        app.config.from_pyfile("../config_local.py")
    except FileNotFoundError:
        print('No local config found.')
    except:
        print('Unexpected error on app.config.from_pyfile()')

    db.init_app(app)
    migrate.init_app(app, db)
    ...
    return app

from app import models

and app/main/routes.py:
from flask import request, g, current_app, session
from app import db
from app.main import bp
from app.models import UJS

@bp.before_app_request
def before_request():
    if 'static' == request.endpoint:
        # This should only happen in dev.  Otherwise, nginx handles static routes directly.
        return
    # I expect this to return an empty list, but it throws a 500.
    print(UJS.query.all())

Any suggestions what I'm missing?

A: For anyone who might find this question later on: the problem was about having the right absolute path to your DB in your SQLALCHEMY_DATABASE_URI config value.
Also (this wasnt the case here, but it might possibly gotcha with the same symptoms) - if you omit __tablename__ on Model declaration, SQLAlchemy might autogenerate something you wont expect. Just a thing to keep in mind, if you're working with an existing DB with some schema already in place.


Q: condition for ng-model Help me please with ng-model. I have an input field where when selecting substituted values from an array 'posters'. Yhe value selected by the filter appear in the list. The list is displayed by default 'The grund tour'. When I enter in the form of a value that is not in the array - in the list displays an empty field, but I need to be displayed or the value of the array or the default value (if the form is entered the value is not of the array). I have no idea how to do it.
I think it may be possible to apply for a condition for the ng-model to make it work only for the values of an array
My code html:

        <form action="" class="form">
            <input type="text" class="form__input" placeholder="Search..." autocomplete="on" list="posters" ng-model="posterTitle"  >
            <datalist id="posters" >
                <option ng-repeat="poster in posters" >{{poster.title}}
                </option>
            </datalist>
        </form>

{{poster.title}}

{{poster.title}}

Controller:
'use strict';
  angular.module('oldmenTest')
   .controller('FormController', ['$scope', 'postersName', function($scope, postersName) {
    $scope.posters= postersName.getPosters();

    $scope.posterTitle = '';
 }]);

Var:
'use strict';

angular.module('oldmenTest')
 .service('postersName', function() {

var posters = [{
    title: 'var1',
    description: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
    image: 'resources/images/mars.jpg'
}, {
    title: 'var2',
    description: 'TLorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
    image: 'resources/images/earth.jpg'
}, {
    title: 'var3',
    description: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
    image: 'resources/images/venus.jpg'
}
];

this.getPosters = function(){
    return posters;
};

});

Thanks for hepl!

A: As I understand you have to apply filter conditionally on specific property or all properties based on title.
You could do something like below.

      .
      {{poster.title}}


Q: Spring Beans Created Multiple Times I am just new to Spring and facing a design problem. The problem is i have a maven multiple module projects. Project Structures goes as follows.
module-backoffice  - Packaging(war)
module-ws        -   Packaging(war)
module-dao      - Packaging(jar)
module-shared     -  Packaging(jar)
In "module shared "all my service class and in "module-dao" all dao related codes exists.
module-shared and module-dao is in the build path of module-backoffice and module-ws.
Now Problem is when i run module-backoffice war and module-ws war Spring creates two instance of Service class beans and dao class beans.
What should i do so that one instance of service class and dao class will be created and shared among multiple war ? Please help. Thanks you.
Code in Module-Shared: Below  is Service factory class
@org.springframework.stereotype.Service
public class Services {

@Autowired
private List<Service> services;

private static final Map<Class<?>, Service> serviceCache = new ConcurrentHashMap<Class<?>, Service>();

@PostConstruct
public void initServiceCache() {
    services.forEach(service -> serviceCache.put(service.getClass(), service));
    services = null;
}

public static Bootstrap bootstrap() {
    return (Bootstrap) serviceCache.get(Bootstrap.class);
}

And the service class is :
@Component
public class Bootstrap implements Service {

public Bootstrap() {
    System.out.println("Bootstrap");
  }
}

When i run tomcat deploying two wars then in console two times "Bootstrap" printed. How do i restrict that.?

A: The purpose of web container like tomcat is to able to run applications independently so they can be started and stopped without affecting each other. In case you think there can be multiple future applications will also require the same service, you can make a separate application and expose an API for the operations.


Q: PHP: deleting old images from array and displaying default image I have a site that is used to display the last 7 days webcam images from a defined folder.
We have a code written for it that looks for the specific file types, deletes any that are over a defined age, and then puts them into an array along with their creation date. This array that is used to display the images in date order.
I want to amend the code so that if 7 days goes by without new images being uoloaded, a default "camera Offline" image is shown instead.
I have tried using array_push at the end to add my default image, but I cant get it to work. any suggestions?

// Array holding filename and creation date
$files = array();
// Delete all webcam files older than a week
function getFileList()
{

global $files;

    $captchaFolder  = './';         // Define the folder to clean
    $fileTypes      = 'EZ*.jpg';    // Filetypes to check
    $expire_time    = 10080;        // Define after how many minutes the files should get deleted

    // Find all files of the given file type
    foreach (glob($captchaFolder . $fileTypes) as $Filename)
    {
        $FileCreationTime = filectime($Filename);   // Read file creation time
        $FileAge = time() - $FileCreationTime;      // Calculate file age in seconds
        if ($FileAge > ($expire_time * 60))         // Is the file older than the given time span?
        {
            unlink($Filename);
        }
        else
        {
            array_push($files, array($Filename, $FileCreationTime));
        }
    }
    // Sort the array by $FileCreationTime
    $times = array();
    foreach($files as $file)
    {
        $times[] = $file[1];
    }
    array_multisort($times, SORT_ASC, SORT_NUMERIC, $files);
}

getFileList();
$numPics = count($files);

// Insert the options in the select element
function buildOptions()
{
    global $files;
    $count = 1;
    foreach ($files as $file)
    {
        $dt =  date ("D d/m/y H:i", $file[1]);
        echo "\t\t<option value=\"$file[0]\">$dt (UTC)</option>\n";
        $count++;
    }
}

A: // check if the array is empty
if(empty($files)){

    // add a default image to the empty array (the timestamp doesn't matter because it will not be used)
    $files[] = array('default_image.png');

    // because it's empty you could also use:
    $files = array(array('default_image.png'));

}


Q: On which filegroup will constraints be created by default when adding them to a table on a filegroup and how should they be separeated? We have multiple filegroups, that look something like this:

*

*PRIMARY (default)

*app_data

*app_index

When I create a table on filegroup app_data
CREATE TABLE Person
(
    [PersonID] INT NOT NULL IDENTITY,
    [Identifier] NVARCHAR(64) NOT NULL,
    [SupervisorID] INT NULL
) ON app_data

and in the current setup (I haven't made this) constraints will get added in 3 different ways
-- Primary keys are added to app_data
ALTER TABLE Person ADD CONSTRAINT PK_Person
    PRIMARY KEY (PersonID) ON app_data

-- Foreign keys are added to "nothing"
ALTER TABLE Person ADD CONSTRAINT FK_Person_PERSON
    FOREIGN KEY (SupervisorID) REFERENCES Person(PersonID)

-- Unique Indexes are added on app_index
-- Sometimes also with constraint notation (but these are the same in background anyway)
CREATE INDEX UX_Person_Identifier
    ON Person(PersonID) ON app_index

On what filegroup will the foreign key be created? app_data or PRIMARY?
Should all constraints be created on app_index? Or should only "custom" indexes be created on this filegroup?

A: Only PRIMARY KEY and UNIQUE constraints have an optional ON filegroup clause. That's because these constraints always create an automatic index to support their uniqueness. The filegroup clause decides where this index will live, so in your case it should always be 'app_index'.
You cannot specify a filegroup for other constraints such as FOREIGN KEY, CHECK or DEFAULT.
The metadata about all constraints (their name, table, columns etc.) is kept in system tables and thus is always in the PRIMARY filegroup (even if you change the default filegroup).
BTW: That's why you always have to restore at least the PRIMARY filegroup of a database. Without it, there is no metadata about the database content available to SQL Server. And this is why I recommend to use the PRIMARY filegroup only for metadata - at least in enterprise scenarios. Have at least one other filegroup and set that as default. This way PRIMARY remains the minimal possible size and runs the least risk of corruption.


Q: Deltacloud / Ruby LoadError I've just put a new RVM build with Ruby 1.9.2 on OS 10.6 and I'm trying to get Deltacloud up and running. Seem to have some problem with Gems, but I'm not sure what I'm dealing with.
craigb@macbook:>rvm list

rvm rubies

   ree-1.8.7-2011.03 [ i686 ]
=> ruby-1.9.2-p290 [ i386 ]
   ruby-1.9.3-p0 [ x86_64 ]

craigb@macbook:>rvm gemset list

gemsets for ruby-1.9.2-p290 (found in /Users/craigb/.rvm/gems/ruby-1.9.2-p290)
   global

craigb@macbook:>deltacloudd -l
/Users/craigb/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:55:in `require': no such file to load -- server.rb (LoadError)
    from /Users/craigb/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:55:in `require'
    from /Users/craigb/.rvm/gems/ruby-1.9.2-p290/gems/deltacloud-core-0.4.1/bin/deltacloudd:115:in `<top (required)>'
    from /Users/craigb/.rvm/gems/ruby-1.9.2-p290/bin/deltacloudd:21:in `load'
    from /Users/craigb/.rvm/gems/ruby-1.9.2-p290/bin/deltacloudd:21:in `<main>'
craigb@macbook:>

Can someone point me in the right direction?

A: This pull request includes a patch for the problem; the code is updated in git but is apparently not up to date even in the latest available gem.  It's a one-line edit to bin/deltacloudd
https://github.com/apache/deltacloud/pull/3


Q: Connecting to a C++ websocketpp server within Docker I am trying to establish a websocket connection with a server written in C++ with websocketpp. I can successfully establish a connection with my server when it is running on my computer, but I am unable to connect with the same server when it is running in a Docker container on my local machine.
I spent a while looking up this issue online, and it seemed that the main pain points were to listen  to 0.0.0.0 instead of 127.0.0.1, and to use the -p config instead of EXPOSE in the Dockerfile. I  think what I have now follows those two pieces of advice, but I am still unable to connect to the endpoint. I was pretty lost, so I figured I would ask here to see if anyone else ran into a similar issue.
My client looks like this (just from within the browser):
let ws = new WebSocket('ws://localhost:3001');

My server looks like this:
websocketpp::server<websocketpp::config::asio> server_;

server_.clear_access_channels(
   websocketpp::log::alevel::frame_header | websocketpp::log::alevel::frame_payload
);
server_.set_reuse_addr(true);
server_.init_asio();

server_.listen(port_); // port_ is set to 3001

server_.start_accept();
server_.run();

and my Dockerfile looks like the following:
FROM gcc:latest

RUN set -ex; \
    apt-get -y update; \
    apt-get -y upgrade; \
    apt-get install -y cmake build-essential libboost-dev \
        libboost-system-dev libboost-thread-dev librange-v3-dev \
        libfmt-dev libprotobuf-dev protobuf-compiler \
        libwebsocketpp-dev libgtest-dev google-mock

# libgtest-dev only installs source files which need to be compiled -- actually compile them here
RUN cd /usr/src/googletest; \
    cmake .; \
    cmake --build . --target install

COPY . /usr/src/mazer
WORKDIR /usr/src/mazer

RUN cd /usr/src/mazer;  \
    mkdir build;  \
    cd build; \
    cmake ..; \
    make

CMD exec "./build/mazer-server/mazer-server"

I am starting the container with the following command:
docker run --rm -p 3001:3001 mazer-server


Q: Displaying four li's per ul's not returning result as required I want to display
 and
 dynamically like

ie, each
 with 4
s.
I want to display these dynamically. I tried with the following code:
$i=0;
foreach($query->result() as $inboxresult)
{
        if($inboxquery->num_rows()>0)
        {
            if($i%4==0)
            {
                echo '
';
            }
            $parentid=$inboxresult->id;
            echo '

                   <input type="hidden" id="status'.$inboxresult->id.'">
                   ';
                    echo '';
                    echo '

';
             if($i%4==0 && $i!=0)
             {
                echo '
';
             }
        }
        $i++;
}

This is returning result as shown below:

            <input type="hidden" id="status10">

             <input type="hidden" id="status7">

            <input type="hidden" id="status1">

Can anybody help me to solve this? Thanks in advance.

A: You're incrementing $i when you shouldn't... When you don't print li elements, you should not increment $i:
$i = 0;
foreach ($query->result() as $inboxresult)
{
        if ($inboxquery->num_rows()>0)
        {
            if ($i % 4 == 0)
            {
                echo '
';
            }
            $parentid = $inboxresult->id;
            echo '

                   <input type="hidden" id="status'.$inboxresult->id.'">
                   ';
                    echo '';
                    echo '

';
             // if you increment $i here, you don't need to worry if $i = 0 to close the ul
             $i++;
             if ($i % 4 == 0)
             {
                echo '
';
             }
        }
}

Oh, and mixing logic with HTML output, very bad idea ;-)


Q: Can I write a file in a public folder from my iOS application? I want to know whether I can write a music file in a public folder from my iOS application? I want my file to be accessed out of my app.

A: You can save your music file in the documents folder and set "Application supports iTunes file sharing" to YES. Then you can reach the file from outside the app.
Hope this helps


Q: How to use condition in sort function? I attempted to use condition to sort array by different fields:
 return source.sort((a, b) => {
      if (a.orderBy && b.orderBy) {
        return sortOrder === 'asc'
          ? a.orderBy - b.orderBy
          : b.orderBy - a.orderBy;
      }

      return sortOrder === 'asc' ? a.name - b.name : b.name - a.name;

    });

I have got the error:
The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.

What is problem?
It works for me, but probably it could be better:
  return source.sort((a, b) => {
      if (a.orderBy && b.orderBy) {
        return sortOrder === 'asc'
          ? a.orderBy - b.orderBy
          : b.orderBy - a.orderBy;
      }

      if (sortOrder === 'asc') {
        if (a.name < b.name) {
          return -1;
        }
        if (a.name > b.name) {
          return 1;
        }
        return 0;
      } else {
        if (a.name > b.name) {
          return -1;
        }
        if (a.name < b.name) {
          return 1;
        }
        return 0;
      }
    });

A: You cannot substract strings.
You should use a.prototype.localeCompare(b)
It will return 1 if a > b; -1 if b > a; and otherwise 0
In your example you should do following:
return source.sort((a, b) => {
  if (a.orderBy && b.orderBy) {
    return sortOrder === "asc" ? a.orderBy - b.orderBy : b.orderBy - a.orderBy;
  }

  return sortOrder === "asc" ? a.localeCompare(b) : b.localeCompare(a);
});


Q: Let svg paths "intersect" sorry, but i don't know how to formulate this question ;)
I have a svg animation of an atom. (Not from me, just as an example)
http://codepen.io/davidsneighbour/pen/raPBRO
The three ellipsae (?) defined by path.class='atom-1' to 'atom-3' are at the moment on top of each other.
<path class="atom-1" fill="none" stroke="#555" stroke-width="8" stroke-miterlimit="10" d="M231.7,200c0,17.4-1.7,88-31.7,88s-31.7-70.6-31.7-88s1.7-88,31.7-88S231.7,182.6,231.7,200z"/>

I would like to create an effect of 3-d-intersection so that each ellipsis is going at least once behind one of the other ellipsae, well, as if they are intertwined in 3d.
is this possible? how do I define some kind of z-index for parts of svg paths?


Q: Coupon collecting with unequal probabilities (S.Ross Min-Max approach) While going through a method to solve the coupon collecting problem , the author posed the problem as follows :
Suppose there are $n$ types of coupons and that each time one collects a coupon, it is, independently of previous coupons collected, a type $i$ coupon with probability $~~p_i~$,$~~\sum_{i=1}^n p_{i}=1$  .
Find the expected number of coupons one needs to collect to obtain a
complete set of at least one of each type.
Then in his attempt to the solution he defined his random variables the following way :
let $X_{i}$ denote the number of coupons one needs to collect to obtain a type $i$ coupon , and let  $X$ be the number of coupons one needs to collect to obtain
a complete set of at least one of each type.
After that he made this proposition :   $~~~~X= \underset{i=1,...n}{{max}} {X_{i}}$ .
Question : Why is this formula true ? To me this relation doesn't sound obvious at all ,  could someone help me  clarify that  please ?
Source : A first Course In Probability (S.Ross ) p320.

A: $X_i$ is not, as the other answer states, the expected number of draws to obtain coupon $i$. It is the number of draws to obtain coupon $i$. It is a random variable, not the expected value of that random variable. Likewise, $X$ is a random variable, namely the number of draws required to obtain at least one coupon of each type; it is not the expected value of that number. The equation
$$
X= \underset{i=1,\ldots,n}\max {X_{i}}
$$
is true for the random variables but not for their expected values. For the random variables, it is true simply because you've collected each coupon type at least once precisely at the time at which you've collected the last coupon type at least once.

A: I believe the point being made is this:
Remember $X_i$ is the number of draws until coupon $i$ is finally picked. Therefore, $\text{max}(X_i)$ represents the most draws needed to obtain a certain coupon. In theory if you finally obtain this "rare" coupon, you should have drawn at least one of all the others.
However, note that the expected value of $X$ is not equal to $\text{max}(X_i)$


Q: Javascript - formation button- method post I am not expert of javascript.
I'm working on a project for implementing a javascript web interface like in the first picture.first picture
This is a form. When I select an option in the first and a second select I get the second line displayed in the second picture.second picture
On the second line you can see that I implemented an other button, which execute a php script. I would like that, when I execute it with the method post, the result would appear on the side frame (where is written TEST). So, this means that I have a form action associated to the button on the first line and another button on the second line. I would like that, when I click on the first button (on first line) a php script with method post would open in a new window. On the other hand, if I click the button on the second line, I would like to execute another php script with the method post and that its results appears on the side frame.
To implement this I used a formaction for the second button. However I cannot pass the variables coming from the selects.
Could anyone give me some ints to fix this issue?
I write here the code I used.
I didn't post the two scripts php as they are really trivial.

<html>
<head>
<meta charset="UTF-8" />

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="../calendar/mootools-yui-compressed.js"></script>
    <script type="text/javascript" src="../calendar/datepicker.js"></script>
    <link type="text/css" rel="stylesheet" href="../calendar/datepicker.css">
</head>
<body>

<script>
 var arrayA = ["Chap1"];

 var arrayB = ["Chap1"];

 var myForm = document.createElement("FORM");
 myForm.setAttribute("method","post");
 myForm.setAttribute("id","myForm");
 myForm.target ="";
 document.body.appendChild(myForm);

 var button = document.createElement("INPUT");
 button.setAttribute("type", "submit");
 button.setAttribute("formaction","test.php.php");
 button.setAttribute("formtarget","_blank");
 //----------- Select a matter-------------------------------------
 var arrayMatter = ["Choose a matter","Choice A","Choice B"];
 mySelect("matterSelect", arrayMatter, myForm);

 //------------ Select an operation---------------------------------
 var arrayOperations = ["Choose an operation",
                        "Execute it"];

 mySelect("operationSelect", arrayOperations, myForm);

 myForm.appendChild(button);

 document.getElementById("matterSelect").addEventListener("click", function(){dropDownReset()});

 document.getElementById("operationSelect").addEventListener("click", function(){dropDownOperations()});

 //_________________________________________________________________________________________________________
 //----------------- FUNCTIONS------------------------------------------------------------------------------
 //_________________________________________________________________________________________________________

 //------------ Function to create a Select ------------------------------
 function mySelect(id, options, parent){
  var myselect = document.createElement("SELECT");
     myselect.setAttribute("id", id);
     parent.appendChild(myselect);

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

      var matterOption = document.createElement("option");
      matterOption.setAttribute("value", options[i]);
      var matterNode = document.createTextNode(options[i]);
      matterOption.appendChild(matterNode);
      myselect.appendChild(matterOption);
  }
 }

 //------------ Function to create a checkbox with text ------------------------------
    function myCheckBox(id, text){

  var cell1 = document.createElement("TD");

     var mycheckbox = document.createElement("INPUT");
     mycheckbox.setAttribute("type", "checkbox");
     mycheckbox.setAttribute("id", id);
     mycheckbox.setAttribute("name", id);

  cell1.appendChild(mycheckbox);
  document.getElementById("chapterTable").appendChild(cell1);

     var cell2 = document.createElement("TD");
     var checkboxNode = document.createTextNode(text);
     cell2.appendChild(checkboxNode);
  document.getElementById("chapterTable").appendChild(cell2);

  var arrayMinDfLevel = ["Choose min difficulty level","1","2","3","4","5"];
  var arrayMaxDfLevel = ["Choose max difficulty level","1","2","3","4","5"];

  var cell3 = document.createElement("TD");
  mySelect("selectMinDfLevel"+id,arrayMinDfLevel,cell3);
  document.getElementById("chapterTable").appendChild(cell3);
  document.getElementById("selectMinDfLevel"+id).disabled = true;

  var cell4 = document.createElement("TD");
  mySelect("selectMaxDfLevel"+id,arrayMaxDfLevel,cell4);
  document.getElementById("chapterTable").appendChild(cell4);
  document.getElementById("selectMaxDfLevel"+id).disabled = true;

  var butt = document.createElement("Input");
  butt.setAttribute("id","butt"+id);
  butt.setAttribute("type","submit");
  butt.setAttribute("formtarget","SideFrame");

  butt.setAttribute("method","post");

  butt.setAttribute("formaction","SideFrame.php");

  var textButt = document.createTextNode("Get Exercises list");
  butt.appendChild(textButt);
  document.getElementById("chapterTable").appendChild(butt);
  document.getElementById("butt"+id).disabled = true;

  mycheckbox.addEventListener( 'change', function() {
      if(this.checked) {
       document.getElementById("selectMinDfLevel"+id).disabled = false;
       document.getElementById("selectMaxDfLevel"+id).disabled = false;
       document.getElementById("butt"+id).disabled = false;
      } else {
       document.getElementById("selectMinDfLevel"+id).disabled = true;
       document.getElementById("selectMaxDfLevel"+id).disabled = true;
       document.getElementById("butt"+id).disabled = true;
      }
  });
 }

 //------------ Function to create a submit ------------------------------
    function myFunction() {
      document.getElementById("myForm").submit();
     }

 //------------ Function to reset chapters ------------------------------
     function dropDownReset() {
      document.getElementById("myForm").removeChild(document.getElementById("divTest"));
     }

     function displayListOptions(matter, subject, diff_level_min, diff_level_max){
         var urlget = "var1='"+var1+"'&diff_level_min="+diff_level_min+"&diff_level_max="+diff_level_max;
         windows.location.href =  "./SideFrame.php?"+urlget;
     }

     function dropDownOperations(){
        var arrayS = [];
        if(document.getElementById("matterSelect").options[document.getElementById("matterSelect").selectedIndex].value == "Choice A"){
    arrayS = arrayA;
        }
        else if(document.getElementById("matterSelect").options[document.getElementById("matterSelect").selectedIndex].value == "Choice B"){
          arrayS = arrayB;
        }

     var opSelect = document.getElementById("operationSelect");

     if(opSelect.options[opSelect.selectedIndex].value == "Créer une séquence d'entrainement random"){

     }
     else if(opSelect.options[opSelect.selectedIndex].value == "Execute it"){

       var divTest = document.createElement("div");
      divTest.setAttribute("id","divTest");
      document.getElementById("myForm").appendChild(divTest);

       var chapterTable1 = document.createElement("TABLE");
      chapterTable1.setAttribute("id", "myTable");
      divTest.appendChild(chapterTable1);

      var row1 = document.createElement("TR");
      row1.setAttribute("id", "myRow");
      chapterTable1.appendChild(row1);

      var chapterTable = document.createElement("TABLE");
      chapterTable.setAttribute("id", "chapterTable");
      divTest.appendChild(chapterTable);

      for(k = 0; k < 1; k++){
          var row = document.createElement("TR");
          row.setAttribute("id", "myRow"+k);
          chapterTable.appendChild(row);
       myCheckBox("chapter"+k,arrayS[k]);
      }
     }
     }

</script>

</body>
</html>
<html>
<head>
</head>
<frameset cols="70%,30%">
 <frame id ="GeneralPanel" name="GeneralPanel" heigth = 1000 width = 700 src="GeneralPanel_v002.php">
 <frame id = "SideFrame" name="SideFrame" src="SideFrame.php">
</frameset>
</html>


Q: SQL conditions with mutually exclusive performance I just replaced an SQL statement that looked like this:
SELECT UserID, sUserName, sFirstName + ' ' + sLastName as [Name], iSiteNumber
FROM DecimalUsers left join dbo.CustomerSitePermissions on  UserID = iUserID
WHERE
    (cast(iSiteNumber as nvarchar(50)) like '%' + @query + '%' and (iPermissionIndex = 2 or iPermissionIndex = 0) and (bPrimarySite = 'true' or UserID in
        (SELECT top 1 iUserID FROM CustomerSitePermissions where iUserID not in
        (SELECT iUserID FROM CustomerSitePermissions WHERE bPrimarySite = 'true'))))
    OR CAST(sUserName as NVARCHAR(50)) LIKE @query + '%'
    OR CAST(sFirstName as NVARCHAR(50)) LIKE @query + '%'
    OR CAST(sLastName as NVARCHAR(50)) LIKE @query + '%';

It ran very slowly (around 15 seconds per query). Maybe it's that first part of the WHERE statement with the ugly nested queries. Sure enough, removing it knocks the time down to under a second. Case closed!
OR IS IT?
Not only did the query speed up when you removed the first where condition, but also if you removed all the other ones. Checking sUserName, sFirstName, and sLastName, but not iSiteNumber ran in under one second. Likewise, checking iSiteNumber, but not sUserName, sFirstName, or sLastName also ran in under a second. The query was only slow if the iSiteNumber check and any other check (didn't matter which one or how many) was left in.
Something about this query is slower than the sum of its parts. Why?

A: Firt, however, be sure you have proper index  then
In your iSiteNumber
You are using multiple subselect for in clause,   this force the db engine for repeated  access  to data  ..
for the others part  each OR clause mean a repeated  access to date
could be that  you can rewrite you query avoiding these tecnique
eg instead of  the not in  for where bPrimarySite = 'true'
  ( SELECT top 1 iUserID
        FROM CustomerSitePermissions where iUserID not in
        (SELECT iUserID
          FROM CustomerSitePermissions WHERE bPrimarySite = 'true'
    )
  )

you could use a inner join  for the inverted  logical query  or a simplified  query eg:
  ( SELECT top 1 iUserID
    FROM CustomerSitePermissions where
    bPrimarySite = 'false'
  )

and you could try to rewrite you query for avoid the upper subselect for an IN clause and use a inner join  .. if is possible.
These suggestion can be useful or not depending by the real  logic and result you really need


Q: Not all rows are rendered in ng-grid in my project I'm fetching data from the server, and receive 20 data-items. However, only 6 rows are rendered, and inside ng-repeat there are 6 of them. However the height of the canvas is calculated correctly All other items appears after resize of the window.
This issue is similar to: https://github.com/angular-ui/ng-grid/issues/860
but using virtualizationThreshold doesn't work for me and there is no other way around
Here is part of controllers code:
app.controller('NagruzkaController', ['$scope', 'NagruzkaService', 'Cacher', 'RawInfoRetriever', '$timeout',
function ($scope, NagruzkaService, Cacher, RawInfoRetriever, $timeout) {
    $scope.configRequest = {};

    $scope.showLoader = false;
    $scope.showTable = false;

    $scope.fetch = function () {
        $scope.showLoader = true;

            NagruzkaService.getAll().then(function (data) {
                var tmp = RawInfoRetriever(data);
                $scope.nagruzkaData = tmp;
                Cacher.nagruzka = $scope.nagruzkaData;

                $scope.showLoader = false;
                $scope.showTable = true;
            });
        }
    };

    $scope.gridOptions = {
        data: 'nagruzkaData',
        enableColumnResize: true,
        showGroupPanel: true
    };

In my html template I use ng-grid in this way:

I got ng-grid via npm and my current version is 2.0.1
I've tried to get later version and tried to use 2.0.14, however with this version rows are not shown at all, untill window resizing.
Can anyone help me with this?

A: You will have to use a ng-grid plugin Flexible Height Plugin. Add this plugin to plugins property of the grid options.
$scope.gridOptions = {
    data: 'nagruzkaData',
    enableColumnResize: true,
    showGroupPanel: true,
    plugins: [new ngGridFlexibleHeightPlugin()]
};

A: Eventually, as I need to solve that problem as quick as I could, I ended up just triggering empty 'resize' event via jQuery, which made ng-grid rebuild and show all data received from the server.

A: please use this for not Not all rows are rendered in ng-grid
 it will work 100%
 $scope.gridOptions.excessRows = 100;


Q: Dribble is producing empty output files I need to create an output file for a program in lisp, but I cannot get dribble to properly record my output. I'm using lispbox and my buffer looks like this when I try to use dribble:
(dribble "output.txt")
"output.txt"
... Calls to functions I defined
... I've tried entering expressions, values, strings
(dribble)
NIL

But when I go to output.txt I have an empty file that is 0 bytes. I'm pulling my hair out because I'm having trouble finding the answer and it seems like my computer is the problem. Any thoughts on where to start troubleshooting this (or solutions) would be greatly appreciated.

A: I'd bet dribble is rebinding some streams that are different from the ones being used by SLIME to get output to and from the REPL.  (Issue DRIBBLE-TECHNIQUE might be worth reading.)
Your solution depends on what your are doing.  If you just want a record of your interactions with Lisp, remember that emacs is a text editor and you can save the contents of the REPL buffer to a file or copy an excerpt.
If you want to write a program that saves output to a file, dribble is not a good mechanism for this.  Have a look at
open,
close,
print,
format,
and
with-open-file.


Q: Need a new hard disk case for my hard disk but not sure what I should have A long, long time ago I bought an external hard disk. It worked fine, but now I have difficulty getting the thing powered up. When it started acting up, I opened the case, and saw this:

The thing is that that black thing to the right on the picture below has quite some wear, it doesn't hold on the adapter cable anymore so well, the pins are bend, etc.

So, I'm thinking about buying a new casing. But I'm not sure if I need anything special, and with that I mean if I need a special e-SATA case, or that I could be fine with a "normal" 3.5" casing that's being powered with USB. Here's another picture telling a bit more about the hard disk:

A: Recently changed casing on one of my old disks (also WD5000AAJS-22TKA0) and it works great with a generic USB3 case.

A: You can use any external enclosure that can house a 3.5" HDD with an internal SATA interface. You will not find one that is USB powered. Typical enclosures for 3.5" Drives come with a separate power supply.
The external connector that you have on your old enclosure is for USB. You can go with an enclosure that offers eSATA, USB, firewire or a comination of these or all of these ports.
Another option may be to pull it from the enclosure altogether and install it in your computer (desktop obviously) and connect directly to the SATA ports on your motherboard.
This is from Vantech sold at Newegg.com.


Q: react-typeahead - invariant violation: addComponentAsRefTo(...) issue Node v0.12.2
React v0.13.2
Npm v2.7.4
Using the standard typeahead input causes the following error:
Uncaught Error: Invariant Violation: addComponentAsRefTo(...): Only a ReactOwner can have refs. This usually means that you're trying to add a ref to a component that doesn't have an owner (that is, was not created inside of another component's render method). Try rendering this component inside of a new top-level component which will hold the ref.
This is how I am implementing the typeahead...
Index.jsx has:
'use strict'
var React = require('react');
var ReactTypeahead = require('react-typeahead').Typeahead
var QuickSearch = React.createClass({
 render: function () {
  return(
   <ReactTypeahead options={["spam", "foodbar"]}/>
  );
 }
});

var Topbar = React.createClass({
 render: function() {
  return (
   <QuickSearch />
  );
 }
});

module.exports = Topbar;

And then in my App.jsx I have:
'use strict';
var React = require('react');
var Topbar = require('./topbar');
var App = React.createClass({
render: function () {
  return (
   <div>
    <Topbar />
   </div>
  );
 }
});

module.exports = App;

A: Seems to me you are missing a semicolon after requiring the typeahead.


Q: How to use data returned from subprocess.call without returning the entire output? def is_akamaized(url):
    stripped_http_url = url[8:]
    clean_host = stripped_http_url.rsplit('/')[0]
    nslookup_data = subprocess.call(["nslookup", clean_host], stdout=subprocess.PIPE)
    if nslookup_data.find('akamaiedge'):
        return "\033[1;31mEnvironment is Acamaized {0}  -  {1}\033[1;m"

This function just takes a url and runs nslookup on it.  What I WANT to happen is I want to take the output of nslookup and parse through it for certain keywords.  The problem is, with the current code if I pass in a url that should work (contain the word acamai in the nslookup)
print is_acamaized(url)

it returns 0
Note, I added the stdout=subprocess.PIPE so that the entire output of nslookup is not returned to the terminal.
Any suggestions on how to assign the output of nslookup to a variable so I can access it?

A: subprocess.call() returns the exit code, not the stdout.  You can use the Popen class directly:
nslookup_data = subprocess.Popen(["nslookup", clean_host], stdout=subprocess.PIPE).communicate()[0]

The .communicate()[0] at the end is important.  That tells Popen that we are done, and it returns a tuple: (stdout, stderr).  The first item in the tuple [0] is the stdout.
You could also use subprocess.check_output():
nslookup_data = subprocess.check_output(["nslookup", clean_host])


Q: How to add data with image in response I want to send userid with image in response. I am using httpServletResponse class for that.
This is my code.
I am adding data in header and image in regular body..But I want data with image in body.I dont want to add in header. Is this possible?
bytes = objUserMaster.getProfilePicture();
 responseImage = ImageIO.read(new ByteArrayInputStream(bytes));
 out = response.getOutputStream();
 response.addHeader("Hiiiiiii", "message");


Q: Is it possible to save PDF file directly into the file without using UIActivityViewController or UIDocumentInteractionController iOS? I need to save a PDF document from URL into the device. Is it possible to save the PDF and access it from device file manager without using UIActivityViewController or UIDocumentInteractionController.

A: Add these 2 keys in your Info.plist: LSSupportsOpeningDocumentsInPlace and UIFileSharingEnabled. And set YES as the value for both.
Now you will be able use the Files app to see any file saved by your app in Documents Directory.

A:
Swift 5.0 and iOS13

let documentController = UIDocumentPickerViewController(url: exportToURL, in: .exportToService)
self.present(documentController, animated: true, completion: nil)

exportToURL represent application local URL whichever file want to save into iPhone Files app.


Q: InvalidPipelineOperator MongoError: Unrecognized expression '$replaceAll' I am running following code in MongoDB:
db.response_graphs.aggregate(
    [
        {
            $match : {
                "Response_measure" : "MasksMandatory"
            }
        },
        {
            $project : {
                date_end: { $replaceAll: { input: "$date_end", find: "NA", replacement: "2020-08-01" }}
            }
        }
        ]
    )

I am getting following error:
{
"message" : "Unrecognized expression '$replaceAll'",
"ok" : 0,
"code" : 168,
"codeName" : "InvalidPipelineOperator",
"name" : "MongoError"
}
I am following the syntax from the following link still getting the above error:
https://docs.mongodb.com/manual/reference/operator/aggregation/replaceAll/
Please help me resolve it. Thanks in advance.


Q: Why does thermal resistance go down as temperature goes up? Here is the thermal resistance data for three speaker coils disengaged from the speaker cone. Any ideas? I would think it would be a horizontal line.

http://en.wikipedia.org/wiki/Thermal_resistance
Absolute thermal resistance of the part, K/W
edit: I also want to point out that the same trend occurred with the loudspeaker functioning as a normal speaker (before I tore out the voice coils to test separately). The reason for this test was that I thought the drop in thermal resistance was due to unwanted cooling effects (actually desirable, but not at the moment) from diaphragm movement, but the drop in thermal resistance vs temperature is still there.
edit: I am going to run the same experiment using a 1/4W resistor today and report my findings.
For x_C = 40, 60, 80:

*

*Heat oven to x_C

*Measure electrical resistance

*put .2W of power into resistor

*Let the resistance measurement settle (thermal time constants)

*Measure increased electrical resistance

*Calculate resulting change in temperature of resistor

*Calculate resulting thermal resistance (dT/dR)

A: As you increase the temperature, the electrons, which are a cold Fermi gas, get more excited. Only a thin skin of electrons around the Fermi energy, of width kT, can do anything at all, like conduct heat. As the temperature increases, the electrons can conduct more heat.
The heat conductivity of electrons is greater than the heat conductivity of phonons, and together these account for the entire thermal conductivity. What is going on is that as the temperature goes up, the higher thermal conductivity electrons are carrying a larger fraction of the heat, and this makes the thermal conductivity go down.
In the absence of electronic thermal conductivity, for an insulating material, the thermal conductivity would go down with temperature, and this is also true for the thermal conductivity of just the phonons in the metal. But the electron contribution leads to this otherwise paradoxical effect.
It always helps to remember that a metal is never classical, the electrons are always quantum. A metal is a like a gigantic chemical bond involving all the atoms in a metal nonlocally, this is the conduction band, and the shared electrons have classically paradoxical properties. This is why the Drude model is wrong and the Fermi model is right.

A: Hmmm.  This really is an interesting case, because according to the equation that @mwengler posted a link to, the thermal resistivity is positively correlated to temperature.  However, I wonder if what you're observing has something to do with the fact that at higher temperatures, the molecules begin to move much quicker as they are gaining kinetic energy.  This increased molecule motion is sure to cause more bumping and collisions between all the molecules.
I would imagine that as the number of collisions between the molecules increases, the molecules in the metal will begin to be more spread out, thus decreasing the density per unit mass of molecules in the metal.  The lower the density per unit mass of molecules, the less resistance there will be.  That's just my educated guess.

A: I'm not an expert on it so the explanation below is my own. Electrical resistance of metals rises with temperature. But electrical resistance arises as a result of "collisions" between electrons and lattice ions. For electric current it means turning of electric current into heat.
But for heat conduction it is just like turning heat current into heat. Collisions between ions and electrons assist heat conduction. That's why thermal resistance decreases with temperature.


Q: fail2ban - changing banaction not working as expected I am using fail2ban to mitigate attacks on my webservers (Ubuntu 18.04lts). This is working really well, but recently I've noticed a growing trend of returning attacks. So I added a new rule for these:
[repeatOffence]
# enabled = false
enabled = true
filter = repeatOffence
port = http,https,smtp
logpath = /var/log/fail2ban.log
maxretry = 3
# search up to 2 days
findtime = 172800
# ban for a week
bantime = 604800

While this also worked as expected, the number of banned addresses is already well into the 100s and growing. To avoid a performance impact I tried changing this rule to use ipsets :
[repeatOffence]
# enabled = false
enabled = true
filter = repeatOffence
port = http,https,smtp
logpath = /var/log/fail2ban.log
maxretry = 3
banaction = iptables-ipset-proto6.conf
banaction_allports = iptables-ipset-proto6-allports.conf
# search up to 2 days
findtime = 172800
# ban for a week
bantime = 604800

But on restarting fail2ban, it reports
Found no accessible config files for 'action.d/iptables-ipset-proto6.conf' under /etc/fail2ban
Unable to read action 'iptables-ipset-proto6.conf'

The file is present with the same permissions as action.d/iptables.conf
Other references to the banaction in jail.conf do not use a literal value, e.g.
action_ = %(banaction)s[name=%(__name__)s, bantime="%(bantime)s", port="%(port)s", protocol="%(protocol)s", chain="%(chain)s"]```

What am I missing?

A: The issue is that file extensions in fail2ban are significant; fail2ban appends them automatically, so it was looking for "iptables-ipset-proto6.conf.conf". Amending the configuration as shown below resolved the issue:
banaction = iptables-ipset-proto6
banaction_allports = iptables-ipset-proto6-allports


Q: How to differentiate usage and inheritance in a layered architecture? I'm trying to validate the following dependencies:

Source
In this picture, red relationships are forbidden, green relationships are allowed:

*

*no class in the adapter package can inherit from a class in the port package;

*any class in the adapter package can use (e.g. have a field) a class in the port package;

*no class in the service package can use (e.g. have a field) from a class in the port package;

*any class in the service package can inherit a class in the port package;

If possible I'd like to add these validations to Layered Architecture.
Thank you.

A: LayeredArchitecture considers all dependencies between layers. You cannot forbid inheritance, but allow access – nor vice versa. I recommend to define individual specific rules instead:
@ArchTest
ArchRule adapter_should_not_inherit_from_port = noClasses()
    .that().resideInAPackage("….adapter")
    .should().beAssignableTo(JavaClass.Predicates.resideInAPackage("….port"));

@ArchTest
ArchRule service_should_not_access_port = noClasses()
    .that().resideInAPackage("….service")
    .should().accessClassesThat().resideInAPackage("….port");


Q: Blueprism get all files contained in a root folder I have a root folder with multiple sub folders and those sub folders could have more sub folders and so on and so forth. I want to run an action and pass it the base folder and get all files that are contained in there (Even in sub folders). The Get files action only gets the files at the first level and to use get folders you'd need to create a huge process which checks every level to see if there are more sub folders and you could potentially miss some files.

A: run the command through command prompt maybe and then pipe your results out to read them? something like
dir /s /b /o:gn

Gives you all sub files etc in a root directory you can use that to pipe your answer into something readable or stdout it direct into a variable in your code if you can.

A: Zip Parent folder by using 7z commands or simply by Blueprism Zip Folder action and Use 7z Commands to extract recursive and relocate to single outputpath folder.
7zip tool is free of cost and usually every other organisation has these Tools.
Use recursive commands (X) of extraction and set the output path to a single location.
7z will do all the recursive fetching.
https://7ziphelp.com/7zip-command-line


Q: What is the Path for Call_History.db in iOS 6. Is it same as that of iOS5? I am new at iPhone development. I want to access iOS6 call_history. My code work for iOS5 but not work for iOS6. please help me to solve this problem. Many Thanks.

A: You cannot access the call log using the SDK and approved APIs. There are some workarounds, as you probably already know. The only option I know about is accessing call_history.db.
Take a look at this tutorial. Unfortunately for you, security has been made more severe, and you only can access that file in iOS < 5.0 (and probably all jailbreacked versions).


Q: Python: Loop not giving desired result So I'm trying to write a code that simulates a predator and prey situation where it starts off with a low population of predators and high population of prey. Over time the predator population grows while the prey population shrinks until the prey population is too little to sustain the predator population. The predator population dies off and then the prey population is able to repopulate. The simulation is supposed to stop whenever one of the two populations reach 0, in this case the predator population will and plot two populations over time of the simulation until it stopped. This is my code so far:
import matplotlib.pyplot as plt

def simulate(initialPred, initialPrey, preyGrowth, predationRate, predShrink, predFedBirthRate):
    preyCounts = []
    predatorCounts = []
    predatorI = initialPred
    preyI = initialPrey
    predator = predatorI
    prey = preyI

    while predator > 0 and prey > 0:

            predator = predatorI * (1 - predShrink + predFedBirthRate * preyI)
            prey = preyI * (1 + preyGrowth - predationRate * predatorI)
            predatorCounts.append(predator)
            preyCounts.append(prey)
            predatorI = predator
            preyI = prey

    plt.plot(predatorCounts, 'r', preyCounts, 'b')
    plt.show()

    return preyCounts, predatorCounts

simulate(50,1000,0.25,0.01,0.05,0.00002)

Its output is this
:
But it's supposed to come out like this:

Can someone help me please?
*Also aside from this whenever I put my plotting code outside of the function after the function line with values inside like this:
simulate(50,1000,0.25,0.01,0.05,0.00002)
plt.plot(predatorCounts, 'r', preyCounts, 'b')
plt.show()

It doesn't plot the values from the function and says predatorCounts and preyCounts are undefined.

A: So you looked at your process/calcs and it seems correct but you look at your result and it's funny.  One thing you notice when you print the counts...
print predatorI, preyI

is that there are fractions of predators and prey which, in the real world, doesn't make sense.  You are trying to simulate the real world. All your rate parameters are probably based on whole things, not fractional things.  So you decide that there can't be any fractional beings in your simulation and you only deal with whole beings (ints) after the population growth calculations ...

Your function returns the count vectors.  If you want to move the plotting statements outside of the function you need to assign the function's return value(s) to a name and then use them for plotting.
prey, predator, = simulate(50,1000,0.25,0.01,0.05,0.00002)
plt.plot(predator, 'r', prey, 'b')
plt.show()

Here are some things to read from the docs concerning names, scope, namespaces
https://docs.python.org/3/tutorial/classes.html#a-word-about-names-and-objects
https://docs.python.org/3/reference/executionmodel.html#naming-and-binding
You might need to read them periodically as you use the language more.

A: If I initialize your plot data with the starting populations and use int() truncation for the populations, I get the plot you say you're supposed to see:
import matplotlib.pyplot as plt

def simulate(initialPred, initialPrey, preyGrowth, predationRate, predShrink, predFedBirthRate):
    preyCounts = [initialPrey]
    predatorCounts = [initialPred]
    predator = initialPred
    prey = initialPrey

    while predator > 0 and prey > 0:
        predatorScaleFactor = 1.0 - predShrink + predFedBirthRate * prey
        preyScaleFactor = 1.0 + preyGrowth - predationRate * predator
        predator = int(predator * predatorScaleFactor)
        prey = int(prey * preyScaleFactor)
        predatorCounts.append(predator)
        preyCounts.append(prey)

    plt.plot(predatorCounts, 'r', preyCounts, 'b')
    plt.show()

    return preyCounts, predatorCounts

simulate(50, 1000, 0.25, 0.01, 0.05, 0.00002)


Q: How to configure WinEdt to load the clicked file in Windows? My system: MikTeX (very recent), Windows 10, WinEdt 10.2
I am porting my system to a new laptop, but have problems configurint WinEdt properly. My trial period just ended, but the old registration credentials seemed to work just fine.

*

*I have run the configuration wizard as an admin to set the filetypes. I remembered to add the -V switch so that clicking the icon of a project file only opens the files related to the project as explained here.

*I have edited the list of active strings to get rid of this bug.

*I have installed the piece of software converting ACP-files to UTF-8.

But for the life of me I cannot figure out which of the zillion options governs the following.

How do I configure WinEdt so that when I click the icon of a .tex file, it, in addition to starting itself (as governed by the filetype association) also loads the tex-file in question? When I click the icon of a .tex-file, currently WinEdt starts with no files listed, and nothing in its main pane.

I think this behavior changed when the trial period ended and I reregistered it, but I cannot be 100 per cent sure that I tested WinEdt during the last few weeks with sources other than projects.
A related oddity is that if I click the WinEdt-icon on my desktop, it will load the most recent project in spite of the -V -option being configured.
As you can see, I have had my share of past difficulties configuring WinEdt, but this is a totally new problem. As fine a tool as it is, it suffers from the malady that the number of features (and hence the documentation) simply overwhelm me. I haven't got the developer savvy to automatically figure out the correct buzzword. The help/documentation it comes up with is mostly useless  to me because the meaning of the terms is all Greek.
So if you can suggest a user friendly but still configurable TeX-environment, I'm open to recommendations.

A: Something had probably gone wrong. Possibly because I was late to insert my registration credentials. I uninstalled and reinstalled WinEdt, and now it seems to work again. A definitely nice feature was that the uninstaller asked whether I want to keep the registration data.
Anyway, the problem seems to have disappeared upon reinstalling. If anybody has something to add, I will happily upvote and accept.


Q: Writing unit tests with QTestLib this is my first step into the world on unit-testing so please be patient. I'm writing a Qt 4.8.1 C++ program and as test framework I'm using the integrated QTestLib. I should test a class that inhrerits from a base one and that loads a certain XML file to read and parse it later with a function that will return a C++ class object with the xml values that I can retrieve and set via set/get functions. The class in the constructor instantiate a QFile object and in the readXml function I use it to parse with the QXmlStreamReader the file. What's the best way to test all this class with unit-tests? I don't see how I could bypass the file-read operation to inject a own string representing the file content. Or should I use as test content a different ad-hoc XML file?

A: Injecting a string to represent the file contents seems like it would be the most straightforward way of testing a class such as this.  However, directly instantiating a QFile instance in your class constructor makes this impossible (in other words, it's impossible to inject your dependency).  Moreover, it's quite a bit of work to create a "Fake" or "Mock" version of a QFile (a.k.a. a Test Double of a QFile).
The easiest way to resolve this is to pass a QIODevice into your class constructor (QFile inherits from QIODevice).  In your unit test, you can fake the contents of the file by passing in a QIODevice with the contents you wish to test.  In this case, you can accomplish this with a QBuffer, which allows you to arbitrarily set its contents.  As such, your class would like something like the following:
class MyXmlParser
{
   MyXmlParser(QIODevice* device);

   ...
};

Your unit test constructs the class with a QBuffer; your production code constructs it with a QFile.
Should I use a real XML file in my test?
Generally speaking, the more external dependencies your unit test has, the more costly it is to ensure that it doesn't break in the future (it potentially makes your unit test sensitive to its context).  As such, it is advisable to avoid using a real XML file in order to ensure that your test is self-contained.  Moreover, passing in a real XML means that you are now implicitly testing QFile as well as your XML parser (in other words, it's not longer a unit test, it's an integration test).  You can generally assume that the IO device that you pass into your parser works; you only need to verify that your parser uses the IO device correctly and that it can parse the XML properly.
Consider reading through the material at xunitpatterns.com, particularly the section on Test Smells.