text:
Q: Apollo client 3 evict object from cache Using apollo client 3. Queried all countries and want to remove one country from cache and re-render UI.
Codesandbox
Tried like below;
onClick={() => {
 cache.evict({ id: `Country:${country.code}` });
 cache.gc();
}}

But didn't work. How to evict a country?

A: Eviction should be used this way;
onClick={() => {
   cache.evict({ id: cache.identify(country) });
   cache.gc();
}}

Now the country removed and page rerendered. Sandbox updated


text:
Q: How to set a value in a Choice Field based on the text box change SP 2010 in list newform.aspx I am having few  fields like single line of text, choice field, rich text on my customnewform.aspx of my SP 2010 SPList.
Now if I enter a value say USA on the text box, I need to set the dropdown/choice field value as Boeing if I enter the text box value as Europe then the choice field value must be set to Airbus.
 The choice  field contains many values,like company1, company2, company3, company4 along with Boeing, Airbus etc
How this can be achieved using SPutility & jQuery & JavaScript ?
Am trying to use  onblur function of my textbox.  Will this work ?
Also I need to get the validation done within the PreSaveAction function call also.
 <script language="javascript" src="/project/EASAssetsLib/jquery-
       1.6.0.min.js" type="text/javascript">
     </script><script language="javascript"
    src="/project/EASAssetsLib/jquery.SPServices-2014.01.min.js"
    type="text/javascript"></script><script language="javascript"
    src="/project/EASAssetsLib/prototype.js" type="text/javascript">
    </script><script language="javascript"
    src="/project/EASAssetsLib/SPUtility.js" type="text/javascript">
    </script>
    <script language="javascript" type="text/javascript">
     $(document).ready(function()
    {
   var txtboxfromSPUTIL = SPUtility.GetSPField('countryname').GetValue();
   alert(txtboxfromSPUTIL);

A: Break up your Mission in smaller tasks, you allready started with alert()
Ditch alert and learn to use F12 Developer Tools
In Chrome you can use Snippets https://stackoverflow.com/questions/10470711/chrome-developer-tools-what-is-snippets-support
That will execute any of your javascript on the current page and saves you from loading it in SharePoint
As for your tasks

*

*Attach a JavaScript event handler, onblur is fine, maybe you want keyup for a better UX

*Check what people typed

*Set the values of the Choice field

Plenty of examples around, see the column on the right of this page for related questions & answers
Success with you Mission

redpajama_set_name: RedPajamaStackExchange


text:
Q: this class is not key value coding-compliant for the key playPressed.' I know that there has been threads with a similar topic, but I am using Xcode 5 and there is no XIB-File with a wrong reference in my project. I tried to create a simple soundboard, I really cannot figure out what the problem is.
<pre>//  ViewController.h
//  AudioPlayer
//
//  Created by Marvin on 30.11.13.
//  Copyright (c) 2013 Marvin. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface ViewController : UIViewController
@property (nonatomic, strong) AVAudioPlayer *player;
- (IBAction)playPressed:(id)sender;
- (IBAction)stopPressed:(id)sender;
- (IBAction)sliderChanged:(id)sender;

@end

--------------------------------------------------------------------------------------------

//
//  ViewController.m
//  AudioPlayer
//
//  Created by Marvin on 30.11.13.
//  Copyright (c) 2013 Marvin. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize player = _player;

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Playstation" ofType:@"mp3"]];
    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)playPressed:(id)sender {
    [self.player play];
}

- (IBAction)stopPressed:(id)sender {
    [self.player stop];
}

- (IBAction)sliderChanged:(id)sender {
    UISlider *slider = sender;
    self.player.volume = slider.value;

}
@end


text:
Q: How to round complex number up to 2 decimal points in python? I want to round the complex and real part upto 2 decimal points. How can I do that in python?
angle = 2 * np.pi *2
c1 = complex(np.cos(angle),np.sin(angle))
c1 = round(c1,2)

A: I think you can use the around function from numpy:
import numpy

x= complex(1.2345, 1.2345)
numpy.around(x, 2)
# (1.23+1.23j)

A: You noted in a comment:

I have t use these complex numbers in a matrix. In order to read it easily I want to display it upto 2 decimal points

So how about modifying the printing of your data, rather than messing with their representation as data? You only need to set_printoptions with a formatter for complex numbers:
>>> import numpy as np

>>> arr = np.random.rand(3,3) + 1j*np.random.rand(3,3)
... print(arr)
[[0.44078748+0.29907718j 0.79358223+0.02234568j 0.20919567+0.34527526j]
 [0.05402969+0.24115898j 0.20941358+0.55299497j 0.29743888+0.32179154j]
 [0.60174937+0.9542182j  0.47197093+0.9202769j  0.41205623+0.27288905j]]

>>> np.set_printoptions(formatter={'complex_kind': '{:.2f}'.format})

>>> print(arr)
[[0.44+0.30j 0.79+0.02j 0.21+0.35j]
 [0.05+0.24j 0.21+0.55j 0.30+0.32j]
 [0.60+0.95j 0.47+0.92j 0.41+0.27j]]

A: For compact output:
np.set_printoptions(precision=2, suppress=True)


text:
Q: ATI Driver not working after system update? I had a working Ubuntu 10.04 desktop with ATI drivers with three monitors on a Radion HD 5750.
After a standard apt-get update; apt-get upgrade; reboot
I got a black screen (system booted, but graphics did not display at login screen). I went into recovery mode and reset to basic graphics mode.
Currently, the Catalyst control center says the ATI driver is not installed. But the "hardware drivers" tool (jockey) says "ATI Fire GL" is installed and in use.
So either:
1. The driver is not actually installed even though jockey claims it is, or
2. The driver is installed but catalyst can't find/use it.
I used apt-get to purge and then reinstall the ATI drivers with no improvement.
How do I get this driver working again? Is there a way to completely purge/remove everything graphics related and start over like a clean system, but without an OS reinstall?

A: Jockey re-downloads everything on every driver re-install as far as I know.
Use jockey to remove the driver, reboot, re-install the driver also through jockey, and you should be fixed.
This is a common problem for people that compile the latest ATI driver themselves.  If you did that, you need to remove all the self-compiled components so that jockey and the jockey installed amdcccle appear first in your search path and just work.


text:
Q: Xamarin HybridWebView navigate to page in cache folder I've want to make a xamarin forms webview app that downloads a webpage (the app itself) then displays it. Before downloading I show a local login page that will invoke the app once the user submits the form. The local page will be inside the app package, the downloaded page will be downloaded to a location the app can store data (CommenApplicationData in this uwp example, but I have to use the documents folder on iOS).
I've already made a .NET Core library that downloads, unpacks and supports script commands that the webpage inside the webview uses. The main entry class to this library is called: BroadsheetInterface and it accepts the messages from the webview (BroadsheetInterface.RunCommand) and uses a interface to make callbacks to the webview(RunJavascript).
To show the local "login page" and downloaded "app page" or "launcher page", I use the HybridWebView example from Xamarin. I then modified the platform specific hybridwebview to do it's own navigation like this:
// IWebView is a interface that is used for the BroadsheetInterface can do callbacks
// to this control
public class HybridWebViewRenderer : ViewRenderer<HybridWebView, Windows.UI.Xaml.Controls.WebView>, IWebView
{
    // The pointer to the current "BroadsheetInterface", a class that has all logic of
    // the webpage inside the webview
    public BroadsheetInterface_Helper BroadsheetInterface { get; set; }

    // The standard call to setup the webview to a local page, I use this call to show
    // the login page.
    protected override void OnElementChanged(ElementChangedEventArgs<HybridWebView> e)
    {
        base.OnElementChanged(e);

        if (Control == null)
        {
            SetNativeControl(new Windows.UI.Xaml.Controls.WebView());
        }
        if (e.OldElement != null)
        {
            Control.NavigationCompleted -= OnWebViewNavigationCompleted;
            Control.ScriptNotify -= OnWebViewScriptNotify;
        }
        if (e.NewElement != null)
        {
            Control.NavigationCompleted += OnWebViewNavigationCompleted;
            Control.ScriptNotify += OnWebViewScriptNotify;

            LoadLoginPage();
        }
    }

    // Once the local page has been loaded I setup the library (note the "this"
    // parameter), then check if the user has checked the "remember login" checkbox
    // last time he or she logged in.
    void OnWebViewNavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
    {
        if (args.IsSuccess)
        {
            BroadsheetInterface = new BroadsheetInterface_Helper(this);
            BroadsheetInterface.Browser_SetLogin();
        }
    }

    // If the Javascript inside the webview calls the app, the command will be passed
    // into the BroadsheetInterface to be processed.
    void OnWebViewScriptNotify(object sender, NotifyEventArgs e)
    {
        BroadsheetInterface.RunCommand(e.Value);
    }

    // If the library want to call the webpage inside the webview, it will call
    // this function
    public async void RunJavascript(string script)
    {
        await Control.InvokeScriptAsync("eval", new[] { script });
    }

    // Show the login page
    public void LoadLoginPage()
    {
        Control.Source = new Uri(string.Format("ms-appx-web:///Content//{0}", Element.Uri));
    }

    // Show the launcher page
    public void LoadLauncherPage()
    {
        // The location of the launcher page
        var fullname = BroadsheetInterface.AccountHelper.CurrentAccount.GetLauncherPage().FullName;
        // fullname = "C:\Users\wille\AppData\Local\Packages\a05728a3-841f-4ef2-8f13-f1dbf39590a0_tbz3402trp7yy\LocalState\ProgramData\Launcher\willem\index.html"

        // Convert the path to a url
        var url = "file:///" + fullname.Replace("\\", "/");
        // url = "file:///C:/Users/wille/AppData/Local/Packages/a05728a3-841f-4ef2-8f13-f1dbf39590a0_tbz3402trp7yy/LocalState/ProgramData/Launcher/willem/index.html"

        // Set it to the webview
        Control.Source = new Uri(url);
        // DOESN'T WORK :(
    }

    // This is called from the library to get the location where to store
    // the launcher page
    public string GetCacheFolder()
    {
        return Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
    }
}

Now the app runs, I can login and when I submit, it start downloading the files. After the files have been downloaded I want to set the webview to show the launcher page that has been downloaded. So I call the "LoadLauncherPage()" function but, it doesn't change to the downloaded page. It's like setting the "Source" parameter doesn't do anything.

A: Ok, found it out myself.
I guess it's not allowed to set the Source property of the WebView to a "file:///" url. So I came across this solution:
// Show the launcher page
public void LoadLauncherPage()
{
    Uri uri = Control.BuildLocalStreamUri("Launcher", "/index.html");
    Control.NavigateToLocalStreamUri(uri, new StreamResolver(BroadsheetInterface));
}

// Resolver for mapping the files
public class StreamResolver : IUriToStreamResolver
{
    private BroadsheetInterface_Helper broadsheetInterface;

    public StreamResolver(BroadsheetInterface_Helper broadsheetInterface)
    {
        this.broadsheetInterface = broadsheetInterface;
    }

    public IAsyncOperation<IInputStream> UriToStreamAsync(Uri uri)
    {
        if (uri == null) throw new Exception();
        return GetContent(uri.AbsolutePath).AsAsyncOperation();
    }
    private async Task<IInputStream> GetContent(string path)
    {
        try
        {
            string fullname = broadsheetInterface.AccountHelper.CurrentAccount.RootFolder.FullName + path.Replace("/", "\\");
            StorageFile f = await StorageFile.GetFileFromPathAsync(fullname);
            IRandomAccessStream stream = await f.OpenAsync(FileAccessMode.Read);
            return stream;
        }
        catch (Exception) { throw new Exception("Invalid path"); }
    }
}


text:
Q: Postgres/JDBC/Logical replication - out of memory issues I am developing an application which connects to a logical replication slot, to consume the WAL events. These WAL events are then forwarded to a MQ broker. This works great, but I noticed that I am running out of memory after some time. I managed to minimize the problem to the code responsible for getting the WAL events. It occurs with the following code:
final Properties properties = new Properties();

PGProperty.USER.set(properties, "user");
PGProperty.PASSWORD.set(properties, "password");
PGProperty.ASSUME_MIN_SERVER_VERSION.set(properties, "9.4");
PGProperty.REPLICATION.set(properties, "database");
PGProperty.PREFER_QUERY_MODE.set(properties, "simple");

while (true) {
    Connection          connection   = null;
    PGConnection        PGConnection = null;
    PGReplicationStream stream       = null;

    try {
        connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/db", properties);
        PGConnection = connection.unwrap(PGConnection.class);
        stream = PGConnection.getReplicationAPI().replicationStream().logical().withSlotName("slot").start();

        while (true) {
            final ByteBuffer buffer = stream.read();

            // ... logic here ... (disabled during memory test)

            stream.setAppliedLSN(stream.getLastReceiveLSN());
            stream.setFlushedLSN(stream.getLastReceiveLSN());
        }
    } catch (final SQLException e1) {
        Logger.getLogger(getClass()).error(e1);

        if (stream != null) {
            try {
                stream.close();
            } catch (final SQLException e2) {
                Logger.getLogger(getClass()).error(e2);
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (final SQLException e2) {
                Logger.getLogger(getClass()).error(e2);
            }
        }
    }
}

I commented out the logic to parse the message and forward it to the MQ broker, as the out of memory also occurs without this.
I also tried to alter this example by using the polling method readPending() instead of the blocking method read() (as shown at https://jdbc.postgresql.org/documentation/head/replication.html), but the problem remains.
I also noticed that after a while, the application comes in a 100% CPU usage. This must be caused by the underlying libraries, as the read() is still processing normally at that moment (that is, it processes each WAL event sequentially).
During these tests, I am executing INSERT and UPDATE queries, at a low rate.
I am using following dependency:
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.1.4</version>
</dependency>

The application runs as a WAR in a Tomcat8 container.
Any idea what is going on?
update 1
I figured out what is going on, but cannot explain it so far. I'll go in details.
Every 10 seconds, I do INSERT and UPDATE queries, as said. These queries result in 645 WAL events.  So every 10 seconds, I have to read() 645 events. In the beginning, this takes 0 (or sometimes 1) milliseconds to read() one event. After some time, it takes 1 milliseconds. Then, again some time later, it takes 2 milliseconds. And so on...
So after a while, I am unable to read() 645 events in 10 seconds, as the time required to read() keeps increasing. This explains the 100% CPU usage and the out of memory.
I am still unsure how to explain and how to fix this. I will keep investigating.
update 2
I tried adding buffer.clear() at the end of the loop, without success. I am still running into 100% CPU and memory issues. This is as expected, because the buffer is a local variable, so it's GC'ed after each loop any way. But I thought it would be a good idea to test anyway.

A: I found the reason why I was running out of memory. I was testing with the decoderbufs decoding output plugin, https://github.com/xstevens/decoderbufs. When replacing by the built-in test plugin or wal2json (https://github.com/eulerto/wal2json), I am not having these problems.
I will try to inform the author of the decoderbufs plugin.


text:
Q: Positive euphemisms for desert? Looking on thesaurus.com I can find only synonyms for "desert" with negative connotations. Are there any synonyms with positive connotations? Specifically, something that invokes the sense of clean desolation and unspoiled nature.

A: Following your link shows a tremendous number of synonyms with negative connotations!  Here are some relatively neutral, albeit not quite synonomous, words:

*

*solitude, with sense "A lonely or deserted place."

*sere, "Without moisture."

*unpeopled, "Not inhabited by people."

*The Outback in Australia  is a vast, remote, arid area, and you might compare an area to it.

*You could talk about horny toad country; that's pretty neutral, isn't it?

A: The Etymology tells the story:

The Classical Latin word deserta (abandoned, deserted wife) is
  derived from the Latin word desertus (deserted, uninhabited, without people), which is
  derived from the Latin verb deserere (to cease to be concerned with; to fail, fall short; to leave, depart, quit), which is derived from negative or past de- plus the verb serere (to plant, sow).

Hence, a desert is unused or unusable land. Arabia Deserta is the classical Latin name for guess which country? And guess what it means?
There really aren't many positive connotations available for the word desert; perhaps that's one reason why we often spell it dessert and vice versa. There's rarely any confusion about which word is meant.

A: Expanse, as in wide expanse or open expanse, is fairly positive. It evokes a sense of opportunity and possibility, to me: Riding off into the open expanse.

expanse A wide and open extent, as of surface, land, or sky.

A: Rather than look for a word with positive connotations (even National Geographic wasn't able to put their usual positive gloss on an article about the Atacama), you can use a word that gives an exotic flavor to the defining feature of a desert:

xeric, adj.: (of an environment or habitat) containing little moisture; very dry [OED]

So you can write about crossing the xeric landscape of the Mojave, for example.

A: 'Arid' region(s) is used in a neutral/ technical sense. An expressly positive connotation may not be possible without specific context.

A: One positive synonym I can think of is 'The Sands'. This might be a useful version for you.

A: Untouched, undeveloped, uninhabited.  Perhaps wilderness.

A: Thebaid

The Thebaid or Thebais (Greek: Θηβαΐς, Thēbaïs) is the region of ancient Egypt containing the thirteen southernmost nomes of Upper Egypt, from Abydos to Aswan. It acquired its name from its proximity to the ancient Egyptian capital of Thebes. During the Ancient Egyptian dynasties this region was dominated by Thebes and its priesthood at the temple of Amun at Karnak. [...]
Around the 5th century, since it was a desert, the Thebaid became a place of retreat of a number of Christian hermits, and was the birthplace of Pachomius. In Christian art, the Thebaid was represented as a place with numerous monks.
Social Vocabulary
The subjects range from the pleasures of courtly life to the spiritual rewards of religious retirement from the world in a Thebaid, to the degradations and miseries of the poor [...]
The Oxford Dictionary of Christian Art and Architecture


text:
Q: Show that both sets are infinite
Suppose $\lbrace f_i : i \in \Bbb N\rbrace \subseteq \lbrace 0, 1\rbrace^{\Bbb N}$. Prove that there exists $g \in \lbrace 0,1\rbrace^{\Bbb N}$ such that for every $i \in \Bbb N$, the set $\lbrace n\in\Bbb N : g(n) = f_i(n) \rbrace$ and the set $\lbrace n\in\Bbb N : g(n) \ne f_i(n) \rbrace$ are both infinite.

I tried to attack the problem from different angles but I just couldn't find a suitable function $g$.
I am looking only for guidance or hints. Please don't post full answers.
Thanks.

A: HINT: Make $g(4 \cdot k+1) = f_0(4 \cdot k + 1)$...

 and $g(4 \cdot k + 3) \ne f_0(4 \cdot k + 3)$.

...

 This satisfies the condition for $f_0$ and all the even numbers are still available.

Can you see how to continue?

A: Every positive $n $ can be written uniquely as $(\sum_{i=1}^k i)+j;0\le j\le k $.
So use that.
Or if you want use any bijection, $k $, between $\mathbb N\times \mathbb N $ and $\mathbb N $.
For every $i $, there are an infinite number of $k(m,i)=n $.  If we let $g (n=k(m,i))=f_i (n)$ there will be an infinite such $n$, (all $k(\mathbb N\times\{i\}))$ will satisfy.
Just need to expand this to the infinite inequality sets.
Let $j:\{0,1\}\times \mathbb  N^2\rightarrow \mathbb N $ be a bijection.
Define $g (j(0,k,m))=f_m (j(0,k,m))$ for each $m $ there will be infinite values where $g (n)=f_m (n)$
Define $g (j(1,k,m)= f_m (j(1,k,m))+1\mod 2$.  Then for each $m$ there will be infinite values where $g (n)\ne f_m (n)$.
====
If you want to define a precise $g$ consider.
$j: \{0,1\}\times \mathbb N \times \mathbb N\rightarrow \mathbb N$ via $j(a, k,m) = 2((m-1) + \sum_{i=1}^{i+(m-1)} i)- a$.
$j$ can be proven to be a bijection[$*$].
Define $g(n = j(a,k,m)):= f_m(n)+ a\mod 2$.
For each $m$ there will be an infinite number of $A_m = \{n| n= f(0,k,m); k \in \mathbb N\}$ (all elements of $A_m$ are even by the way) and for all $n \in A_m$, $g(n) = f_m(n)$.  And for each $m$ there will be an infinite number of $B_m = \{n| n = f(1,k,m); k \in N\}$ (all elements of $B_m$ will be odd by the way) and for all $n \in B_m$, $g(n) \ne f_m(n)$.
[$*$] That $j: \{0,1\}\times \mathbb N \times \mathbb N\rightarrow \mathbb N$ should be obvious.  $k \ge 1; m-1 \ge 0;m,n \in \mathbb N$ so $k + (m-1) \ge 1$ and $\sum_{i= 1}^{k+ (m-1)} i \in \mathbb N$ and $m-1 \ge 0$ so $(m-1) +\sum_{i= 1}^{k+ (m-1)}i \in \mathbb N$ and $(m-1) +\sum_{i= 1}^{k+ (m-1)}i \ge 1$ so as $a \le 1; a\in \mathbb N$ then $j(a, k,m) = 2((m-1) + \sum_{i=1}^{i+(m-1)} i)- a\ge  1$ and is a natural number.
Surjective: If $n \in \mathbb N$ then either $n$ is even and $n = 2j$ for some natural $c$ or $n$ is odd and $n = 2c - 1$ for some natural $c$.
The sequence $1 = \sum_{i=1}^1 i < 1 + 2 = \sum_{i =1}^{2}i <..... < \sum_{i=0}^v i < \sum_{i=0}^v i + (v+ 1) = \sum_{i=0}^{v+1} i < ....$ spans the range of all natural numbers.  So there exists a natural $v$ so that $\sum_{i=1}^v i \le c < \sum_{i=1}^{v+1} i$.
Let $m = 1+c-\sum_{i=1}^v i$. Then $1 \le m < v+1$ so $k = v - (m-1) \ge 1$. and $c = \sum_{i=1}^{v=k+(m-1)}i + (m-1)$ and $n = 2((m-1) + \sum_{i=1}^{i+(m-1)} i)- a= j(a,k,m)$ where $a = 0$ if $n$ is even and $a = 1$ if $n$ is odd$.
So $j$ is surjective.
$j$ is injective:
$j(0,b,c)$ is even and $j(1,d,e)$ is odd. so if $j(a,k,m) = j(a',k',m')$ then $a= a'$.
If $b + c < d+ e$ then  $j(a,d,e)= 2((e-1) + \sum_{i=1}^{d+e}i) - a = 2((e-1) + \sum_{i=1}^{b+c} i + \sum_{i=b+c+1}^{d+e}i) -a$
$\ge 2((e-1) + d+e + \sum_{i=1}^{b+c}i) - a$
$> 2(c1 +\sum_{i=1}^{b+c}i) - a = j(a,,b,c)$.
So if $j(a,k,m) = j(a',k',m')$ then $k+m = k' + m'$
If $d < c$ then $j(a,v-d, d) = 2((d-1) + \sum_{i=1}^{v-d + (d-1)=v-c+(c-1)}i) - a$
$<  2((c-1) + \sum_{i=1}^{v-d + (d-1)=v-c+(c-1)}i) - a=j(a,v-c,c)$
So if $j(a,,k,m) = j(a',k',m')$ then $a = a'$; $k+m = k'+m'$ ; $m = m'$ and so $m= m'$
So $j$ is injective.

A: For each $n$, let's call $A_n$ the set of $i$ on which we'd like $g(i)= f_n(i)$, and $B_n$ the set of $i$ on which we'd like $g(i)\ne f_n(i)$. Ideally we'd just like all of the $A_n$, $B_n$ to be disjoint from one another, that way we're free to just set $g$ to be whatever we want on those sets, with no chance of our definitions interfering with one another.
So you just need to find a (countable) infinite family of subsets of $\mathbb N$, $C_n$, all of which are disjoint, and then you can set $A_1 = C_1, B_1 = C_2, A_1 = C_3, B_1 = C_4$, and so on.
Can you find a countable family of pairwise disjoint subsets of $\mathbb N$?


text:
Q: Updating value of table to value of view using Entity Framework I have a list of restaurants, with an associated list of reviews.  I made a view that holds the id of the restaurants, and the average of the review ratings.
Rating (view in db):
Id   AvgRating (already calculated in sql based on all review ratings)
1    3.4
2    1.8

Restaurant (table in db):
Id    AvgRating    Name
1     ...          Wendys
2     ...          McDonalds

I have a list of both of these entities.  What would be the best way to update Restaurant.AvgRating to equal the view's AvgRating? Is it best to do it directly in sql or using EF?

A: In this case you can use the db.Entry() method of your DBContext.
For example:
public void updateAvg(List<Restaurante> restaurantes)
    {
        using (WebMVCContext db = new WebMVCContext())
        {
            foreach (var item in restaurantes)
            {
                db.Entry(item).State = EntityState.Modified;
            }

            db.SaveChanges();
        }
    }

I used this following class:
public class Restaurante
{
    public int Id { get; set; }
    public double Avg { get; set; }
}

The Entry method to update or insert in the context and the SaveChanges to commit this items to your database.


text:
Q: изменение картинки рабочего стола после нажатии кнопки на visual studio здравствуйте я создаю приложение я ни как не могу понять как сделать изменение картинки рабочего стола после нажатии кнопки я пробивал поискать в гугле но нет точного способа только у вас есть надежда
вот мой код:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace test_app
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Накрутка призошла успешно!");
        }
    }
}


text:
Q: Why is unity not recognising my left shift key So I have a simple empty object with a 3d character controller attached. This is the update function of my player movement script
// Do the ground check
isGrounded = Physics.CheckSphere(groundCheck.position, groundDist, groundMask);
if (isGrounded && yMovement.y < 0)
{
    yMovement.y = -2; // reset the gravity velocity
}

// get the xz movement of the player
float xMovement = Input.GetAxis("Horizontal");
float zMovement = Input.GetAxis("Vertical");
Vector3 xzMovement = transform.right * xMovement + transform.forward * zMovement;

// Check for sprinting
if (Input.GetButtonDown("Sprint"))
{
    xzMovement *= sprintMultiplier;
}

// Check if the player should jump
if (Input.GetButtonDown("Jump") && isGrounded)
{
    yMovement.y = Mathf.Sqrt(jumpHeight * -2 * gravity);
}

// move the player on xz
controller.Move(xzMovement * speed * Time.deltaTime);

// move the player on y
yMovement.y += gravity * Time.deltaTime;
controller.Move(yMovement * Time.deltaTime);

And during the sprinting check, no matter if the button is pressed or not, "xzMovement *= sprintingMultiplier" never gets called. Why is this?
By the way, in the input sprint is set up with a positive button of "left shift."
Any help is greatly appreciated.

A: You want to use Input.GetButton instead of Input.GetButtonDown.
GetButtonDown only returns true for a single frame when the button is pushed down, whereas GetButton returns true every frame while that button stays pushed down.


text:
Q: UICollectionView scrollToItemAtIndexPath not functioning properly in navigation controller I have a method that I use to scroll to the bottom of my collectionView
- (void) scrollToBottom {
    if (_messagesArray.count > 0) {
        static NSInteger section = 0;
        NSInteger item = [self collectionView:_myCollectionView numberOfItemsInSection:section] - 1;
        if (item < 0) item = 0;
        NSIndexPath *lastIndexPath = [NSIndexPath indexPathForItem:item inSection:section];
        [_myCollectionView scrollToItemAtIndexPath:lastIndexPath atScrollPosition:UICollectionViewScrollPositionBottom animated:YES];
    }
}

And it works perfectly!  I have never had a problem at any point, it works 100% consistent . . . with a modal view presentation.  If however, I push the viewController onto a navigation controller, it doesn't work.  Rather, it only works if there's over 15 cells.  Once I reach at least 15 cells, it again begins behaving perfectly.  Prior to 15 cells, it either doesn't scroll at all, or scrolls a little bit.
I realize this is a long shot, but I'm scratching my head on this one and I thought maybe somebody might know what the heck is happening.
Troubleshoots:
Have you logged to make sure it's running? YES
Have you logged index path to make sure its trying to scroll to the correct index path? YES
 EXAMPLE

 WORKING MODAL EXAMPLE

A: There is a automaticallyAdjustsScrollViewInsets property in UIViewController, and as it's inherited, in UINavigationController. Set it to NO in self.navigationController and it won't adjust your insets, as documented here

A: I found the problem.
The NavigationController was automatically adjusting my top content inset for some reason.  I was able to prevent this behavior by adding this:
- (void) scrollToBottom {

    if (_isNavigationControllerVersion) {
        _myCollectionView.contentInset = UIEdgeInsetsZero;
    }

    if (_messagesArray.count > 0) {
        static NSInteger section = 0;
        NSInteger item = [self collectionView:_myCollectionView numberOfItemsInSection:section] - 1;
        if (item < 0) item = 0;
        NSIndexPath *lastIndexPath = [NSIndexPath indexPathForItem:item inSection:section];
        [_myCollectionView scrollToItemAtIndexPath:lastIndexPath atScrollPosition:UICollectionViewScrollPositionBottom animated:YES];
    }
}

A: So, since your .gif demonstrates that the problem is happening when the keyboard is open, I can only assume that the bottom scroll is within the content inset of the collection view, even if it is behind the keyboard.
Be sure you're resetting the content inset when the keyboard appears/disappears.  I will edit in some example code.
First, you need to register for the notifications:
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWasShown:)
                                             name:UIKeyboardDidShowNotification
                                           object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWillHide:)
                                             name:UIKeyboardWillHideNotification
                                           object:nil];

This should go in viewDidLoad.  Don't forget to removeObserver in dealloc.
Now set the content insets in these methods:
- (void)keyboardWasShown:(NSNotification *)aNotification {
    CGSize kbSize = [[[aNotification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    UIEdgeInsets insets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
    yourCollectionView.contentInset = Insets;
    yourCollectionView.scrollIndicatorInsets = Insets;
}

- (void) keyboardWillHide:(NSNotification *)aNotification {
    UIEdgeInsets insets = UIEdgeInsetsZero;
    yourCollectionView.contentInset = contentInsets;
    yourCollectionView.scrollIndicatorInsets = contentInsets;
}

A: Running into the same issue in a context where I had access to the cell, I was able to use scrollRectToVisible which doesn't seem to exhibit this behavior.

A: I found nice solution here
- (void)scrollToBottomAnimated:(BOOL)animated
{
if ([self.collectionView numberOfSections] == 0) {
    return;
}

NSInteger items = [self.collectionView numberOfItemsInSection:0];

if (items == 0) {
    return;
}

CGFloat collectionViewContentHeight = [self.collectionView.collectionViewLayout collectionViewContentSize].height;
BOOL isContentTooSmall = (collectionViewContentHeight < CGRectGetHeight(self.collectionView.bounds));

if (isContentTooSmall) {
    //  workaround for the first few messages not scrolling
    //  when the collection view content size is too small, `scrollToItemAtIndexPath:` doesn't work properly
    //  this seems to be a UIKit bug, see #256 on GitHub
    [self.collectionView scrollRectToVisible:CGRectMake(0.0, collectionViewContentHeight - 1.0f, 1.0f, 1.0f)
                                    animated:animated];
    return;
}

//  workaround for really long messages not scrolling
//  if last message is too long, use scroll position bottom for better appearance, else use top
//  possibly a UIKit bug, see #480 on GitHub
NSUInteger finalRow = MAX(0, [self.collectionView numberOfItemsInSection:0] - 1);
NSIndexPath *finalIndexPath = [NSIndexPath indexPathForItem:finalRow inSection:0];
CGSize finalCellSize = [self.collectionView.collectionViewLayout sizeForItemAtIndexPath:finalIndexPath];

CGFloat maxHeightForVisibleMessage = CGRectGetHeight(self.collectionView.bounds) - self.collectionView.contentInset.top - CGRectGetHeight(self.inputToolbar.bounds);

UICollectionViewScrollPosition scrollPosition = (finalCellSize.height > maxHeightForVisibleMessage) ? UICollectionViewScrollPositionBottom : UICollectionViewScrollPositionTop;

[self.collectionView scrollToItemAtIndexPath:finalIndexPath
                            atScrollPosition:scrollPosition
                                    animated:animated];
}


text:
Q: Rails ajax keeps trying to render a template I am using Rails .js.erb ajax to trigger a controller action without rendering a template, a very simple task.
But no matter what I try, Rails tries to render a template every time
At the moment my code looks like this
  <%= form_tag change_index_superadmin_shops_path, remote: true do %>
    <select id = "live_select" name = "table[live]">
      <option value="false">All</option>
      <option value="true">Live</option>
    </select>
  <% end %>

and in my routes
namespace :superadmin do
  resources :shops do
    collection do
      post :change_index
      get :index_recurring_credit
    end
  end
end

and my controller
  def change_index
    @shops = Shop.where(live: true)
  end

So why am I getting a "Template is missing" error even though I declared remote: true on my form? And how do I fix this.
PS i do have a change_index.js.erb file


text:
Q: How can I get NLP Recommender function to work? I am struggling to get my recommender function working.
Speech is a dataframe and "Name" is a column containing the names of presidents. The cosine_sim is a cosine similarity matrix that performs ok.
I get a very simple but frustrating error:
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-227-2f900b10c771> in <module>
     17
     18 # Generate recommendations
---> 19 print(get_recommendations("John Adams", cosine_sim, indices))

<ipython-input-227-2f900b10c771> in get_recommendations(name, cosine_sim, indices)
      4 def get_recommendations(name, cosine_sim, indices):
      5     # Get index of movie that matches title
----> 6     idx = indices[Name]
      7     # Sort the movies based on the similarity scores
      8     sim_scores = list(enumerate(cosine_sim[idx]))

Who can point out my mistake?
NameError: name 'Name' is not defined

# Generate mapping between name and index
indices = pd.Series(speech.index, index=speech['Name']).drop_duplicates()

def get_recommendations(name, cosine_sim, indices):
    # Get index of speeches that matches title
    idx = indices[Name]
    # Sort the names based on the similarity scores
    sim_scores = list(enumerate(cosine_sim[idx]))
    sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)
    # Get the scores for 10 most similar speeches
    sim_scores = sim_scores[1:11]
    # Get the name indices
    speech_indices = [i[0] for i in sim_scores]
    # Return the top 10 most similar speeches
    return speech['Name'].iloc[speech_indices]

# Generate recommendations
print(get_recommendations("John Adams", cosine_sim, indices))


text:
Q: How to get a table cell value in Tampermonkey? I am Chrome user and I would like to customize some website. I have Tampermonkey (something similar to Greasemonkey for Firefox) extension for my Chrome. Now I can add some Javascript code for specific website.
Now, all I want is to get value from some table and show it in popup window.
Example of HTML code:

Text number 1
Text number 2

</tdoby>

Text number 3
Text number 4

</tdoby>

Text number 5
Text number 6

</tdoby>

My code so far:
var xpath = "id('Content')/table[1]/tbody/tr/td[2]";
var result = document.evaluate(xpath, document, null, XPathResult.ANY_TYPE, null );
myWin=window.open('','','width=400,height=400');
myWin.document.write(result);

but it doesn't show content of this "td" (Text number 2)
any idea?

A: That is not quite how you use XPath.  result, in this case is an iterator.
The code would be something like:
var xpath   = "id('Content')/table[1]/tbody/tr/td[2]";
var result  = document.evaluate(xpath, document, null, XPathResult.ANY_TYPE, null );
var node    = result.iterateNext();
var nodeTxt = node.textContent
var myWin   = window.open('','','width=400,height=400');
myWin.document.write (nodeTxt);

except, don't use XPath!  Since you are starting out, use document.querySelector or, better yet, use jQuery.
Here's the CSS selector way:
var node    = document.querySelector (
    "#Content > table:first-child > tbody > tr > td:nth-child(2)"
);
var nodeTxt = node.textContent
alert (nodeTxt);

Note. use alert() or a jQuery UI dialog for this kind of thing.  Avoid trying to use window.open if you can help it.
Here's a complete script, showing the jQuery way:
// ==UserScript==
// @name     _YOUR_SCRIPT_NAME
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
// @grant    GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
    introduced in GM 1.0.   It restores the sandbox.
*/
var nodeTxt = $("#Content > table:first > tbody > tr > td:eq(1)").text ();
alert (nodeTxt);

A: I have created your HTML structure based on XPath you gave.
Since you don't need XPath, I would use normal element accessing:
HTML

                Text number 1
                Text number 2

                Text number 3
                Text number 4

                Text number 5
                Text number 6

Javascript
var div = document.getElementById('Content'),
    table = div.getElementsByTagName('table')[1],
    tr = table.getElementsByTagName('tr')[0],
    td = tr.getElementsByTagName('td')[1];
alert(td.innerHTML);

Working JSFiddle


text:
Q: How do i create a new column in pyspark where the row values are same? Right now i have a pyspark data frame as:
x_data  y_data
2.5      2.5
2.5      2.5
2.5      2.5
2.5      2.5

and the value I want in all rows is "Smith"
**How do I create a data frame like this using pyspark?**

x_data  y_data    Name
2.5      2.8      Smith
7.5      5.1      Smith
1.5      1.5      Smith
8.5      6.5      Smith

A: You can use withColumn to add a new literal column:
import pyspark.sql.functions as F

df2 = df.withColumn('Name', F.lit('Smith'))


text:
Q: custom list of object binding error in grid view my c# class is
public class Otp
{
    public String Time;
    public Otp()
    {

    }
    public void setTime(String Time)
    {
      this.Time = Time;
    }

    public String getTime()
    {
        return this.Time;
    }
}

my problem is when i bind a list of object to grid view it give me error how can i solve this problem?

A: The databinding only can bind against properties and your Time is defined as a member variable. To make Time a property, define it with getter and setter:
public String Time { get; set; }

And there is no need in additional get and set methods.

A: public String Time
    {
        get
        {
            //your code here
            return this.Time;//ex.
        }
        set
        {
            //your code here
            this.Time = Time;//ex.
        }
    }


text:
Q: Как заполнить таблицу с помощью ajax? Здравствуйте! Использую DataTables и ajax-запросом хочу отобразить таблицу, передав данные в json.
Метод контроллера, который возвращает json:
public string GroupReportPartial()
    {
        using (AcademicProgressDb db = new AcademicProgressDb())
        {
            var query = (from Students in db.Students
                         from StudentsSubjects in db.StudentsSubjects
                         from Subjects in db.Subjects
                         from ControlPeriods in db.ControlPeriods
                         from ControlTypes in db.ControlTypes

                         where
                           Students.RecordBookNumber == StudentsSubjects.StId.ToString()
                         where
                         Subjects.SubjectId == StudentsSubjects.SubjId
                         where
                         ControlPeriods.ControlPeriodId == StudentsSubjects.CtrlPeriodId
                         where
                         ControlTypes.ControlTypeId == StudentsSubjects.CtrlTypeId
                         select new GroupsReportModel
                         {
                             StudentGroupNumber = Students.GroupNumber,
                             StudentLastName = Students.LastName,
                             StudentFirstName = Students.FirstName,
                             StudentMiddleName = Students.MiddleName,
                             SubjectName = Subjects.Name,
                             ControlPeriodName = ControlPeriods.Name,
                             ControlTypeName = ControlTypes.Name
                         }).ToList();

            return JsonConvert.SerializeObject(query);
        }
    }

Работает успешно. В результате я получаю:
[{"StudentGroupNumber": 2012,"StudentLastName": "Глобчук","StudentFirstName": "Даниил","StudentMiddleName": "Владимирович","SubjectName": "Иностранный язык","ControlPeriodName": "Второй семестр","ControlTypeName": "Зачет"}]

Код в представлении:

            StudentGroupNumber
            StudentLastName
            StudentFirstName
            StudentMiddleName.
            SubjectName
            ControlPeriodName
            ControlTypeName

Казалось бы всё хорошо, но получаю ошибку

DataTables warning: table id=example - Requested unknown parameter '0' for row 0, column 0

Количество столбцов в json и во view одинаковое. В чем может быть причина?

A: Если я правильно понял , твои данные (JSON) не доходят до функции . Попробуй  $(document).ready(function (data) {...});

A: Моя ошибка из-за невнимательности. Разместил параметр columns внутри параметра ajax, а надо было вне его.
Правильный код рабочего скрипта:


text:
Q: How can I make a cmd line utility run in a Async BackgroundWorker process in vb.net? How can I make a cmd line utility run in a Async BackgroundWorker process in vb.net?
Example:
Private Sub UpgradeButton_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UpgradeButton.Click
    BackgroundWorker1.RunWorkerAsync()
End Sub

Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork

    Dim MyWorkingDirectory = "C:\Windows\System32\"
    Dim MyFileName As String = "notepad.exe"
    Dim MyArguments As String = ""

    Dim myProcess As System.Diagnostics.Process = New System.Diagnostics.Process()
    myProcess.StartInfo.WorkingDirectory = MyWorkingDirectory
    myProcess.StartInfo.FileName = MyFileName
    myProcess.StartInfo.Arguments = MyArguments
    myProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden
    myProcess.Start()
    ' Wait until it ends.
    myProcess.WaitForExit()
    ' Close the process to free resources.
    myProcess.Close()

End Sub

A: I'm not sure why your code is not working - I suppose it doesn't work - and I'd like to suggest you something else: use a Thread instead of BackgroundWorker. if you need only to start the application, use a simple thread:
Public Shared Sub ThreadProc()
    ''Starth the process here!
End Sub

Dim t As New Thread(AddressOf ThreadProc)
t.IsBackground = True
t.Start()

And the started thread opens the process you need and the main thread continues its execution. I hope this is the answer you need!


text:
Q: Play mp3 file before refer to other page javascript I am really need a help, because the are deadline of project tomorrow.
I have one link, for example Link
I have click.mp3 file in root directory.
I want to play it 4 seconds and then refer to somewhere.com
I write something like this but it not works
$(function(){ $(".menu_link").click(function(){
                soundClick();
                setTimeout(refFunc($(this).attr('href')),5000);
                return false;
            });
});
function soundClick() {
            var audio = new Audio();
            audio.src = 'myUrl/click.mp3';
            audio.autoplay = true;
        }
        function refFunc(ref)
        {
            window.location.href = ref;
        }

The soundClick function works, I try to autoplay when page reload, it works.
Timeout not working, refer begins immidiatly. Why? I think the logic of code is true. I play sound, wait 5 sec. and refer page. But 5 secs not show himselves.

A:        $(".menu_link").click(function(){
            soundClick();
            var ref = $(this).attr('href');
            setTimeout(function(){
                 window.location.href = ref;
            },5000);
            return false;
        });
       function soundClick() {
           var audio = new Audio();
           audio.src = 'myUrl/click.mp3';
           audio.autoplay = true;
       }


text:
Q: Treating dy/dx as a symbol for the derivative as opposed to a fraction of the differentials dy and dx I have some questions in solving the seperable differential equation $dy/dx=x/y$.  But first I'll explain what I understand about the problem and how it relates to the differentials $dy$ and $dx$.  Correct me if I am wrong.
I understand that we define a dependent variable $dy=dy/dx*dx$ where $dy/dx$ is the single symbol representing the derivative and $dx$ is an independent variable that can be chosen freely.  By solving this equation for $dy/dx$ (the derivative) we get $dy/dx$ (the fraction).  This allows us to freely choose any expression for $dx$ and by definition we will get the exact expression for $dy$ so that $dy/dx$ (the fraction) is the same as the single symbol $dy/dx$ (the derivative).
In textbooks we seem to skip the justification above and immediately interpret the single symbol $dy/dx$ as fraction in certain situation.
Questions...
1)  Why don't we at least say... "hey... by our study on differentials in an earlier section... we will interpret $dy/dx$ as a fraction in this next step"? This was always so confusing to me in school when we applied it without saying anything. I didn't understand why there was cancellation.  I do now.  In any case, it does makes sense to me now that the variables cancel and we're left with $y*dy = x*dx$ where $dx$ and $dy$ are variables.
2) So now we are ready to integrate both sides.  But what are we integrating with respect to if both $dy$ and $dx$ are just variables?  It seems that we are treating them differently again, but what's the justification? If if there is some why don't we state it anywhere?
3)  Wouldn't it make more sense to solve the problem this way.  Multiply both of $dy/dx=x/y$ by y only.  This will yield the equation $y*dy/dx=x$.  Then we can integrate both side with respect to x, applying the chain rule on the left side?
I know we get the same result by separating the $dx$ and the $dy$ on different sides...and then treating $dx$ and $dy$ as the the part of the integral that tells us which variable we are integrating with respect to... But this seems fuzzy to me as they are really variables.
Isn't (3) more technically correct?

A: Definitely, $(3)$ is more rigorously correct.
1) Yes, in many books they vaguely use the symbols $dy$ and $dx$ as if they are normal variables. As in your example
$$\frac{dy}{dx}=\frac{x}{y}$$
it is just to say that the derivative of the function $y$ with respect to the independent variable $x$  is a function of $x$ and $y$. Nothing more to it, and yes, it is incorrect to manipulate $\frac{dy}{dx}$ as a fraction. You can visit this link to really see that manipulating $dy$ and $dx$ as fractions is just a matter of notation.
2)We are integrating with respect to $x$, that is the independent variable. $y$ is a function of $x$, and $\frac{dy}{dx}$ is its derivative with respect to $x$. As you can see in your example:
$$\begin{align}\frac{dy}{dx}=\frac{x}{y} \\
\implies y\frac{dy}{dx}=x
\end{align}$$
We have the derivative of the function $y$ along with some expression of $y$.So, chain rule can be used to integrate the LHS w.r.t $x$, and for the right, it is just a function of $x$, so integrating it w.r.t $x$ is straightforward.
$$\int y\frac{dy}{dx}dx=\int xdx$$
Here is the abuse of notation we use. As you can see, to integrate the LHS, we integrate normally as if $y$ were the independent variable, as the chain rule suggests. So, the notation $$\frac{dy}{dx}dx$$ is just hacked to cancel $dx$, to make the name "Variable separable form". That's it, its just notation.
Also, even though I don't know much about the modern theory of infinitesimals, I think they do provide us mathematically justified steps to show why the symbols $dy$ and $dx$ work as normal fractions.


text:
Q: Circle the standing coin Dori and Ariel are playing with Mr. Fin's coin collection. When taking two special coins they noticed that one of them has a radius five times larger than the other. They decide to leave the larger coin still and see how many turns the other coin takes to circle the standing coin. How many turns does the small coin make?

Attempt:  I found this reasoning from an exercise sheet: If the radius of the minor were "once larger than another" it would be $2r$. So five times bigger is $6r$.
is it correct?
answer: 6

A: The center of circle A moves around a circle with radius equal to the radius of $B$ plus the radius of $A$, which is $6r$. So the center of $A$ travels a distance of $2 \pi 6r$. The circle $A$ is rolling through this distance, each rotation covering $2\pi r$. Therefore, it takes 6 rotations to complete the path.


text:
Q: Protractor's browser.pause() pausing but shows no context I'm having trouble making Protractor's browser.pause() work. It pauses but it doesn't show the context. Is there any known issue about this?
The terminal output is just this:
$ protractor conf.js
[10:05:23] I/launcher - Running 1 instances of WebDriver
[10:05:23] I/hosted - Using the selenium server at http://localhost:4444/wd/hub
Started
[10:05:27] I/protractor -
[10:05:27] I/protractor - Encountered browser.pause(). Attaching debugger...
[10:05:27] I/protractor -
[10:05:27] I/protractor - ------- WebDriver Debugger -------
[10:05:27] I/protractor - Starting WebDriver debugger in a child process. Pause is still beta, please report issues at github.com/angular/protractor
[10:05:27] I/protractor -
[10:05:27] I/protractor - press c to continue to the next webdriver command
[10:05:27] I/protractor - press ^D to detach debugger and resume code execution
[10:05:27] I/protractor -
Starting debugger agent.
Debugger listening on [::]:5858
>>>

According to some images on internet it should show some more lines, the first one being "ControlFlow::", then like a trace up to the code snippet where it paused.
If I remove the pause it passes the test OK.
I'm using the simple example on the protractor tutorial (http://www.protractortest.org/#/tutorial) (adding just one line: browser.pause();):
    // spec.js
    describe('Protractor Demo App', function() {
      it('should have a title', function() {
        browser.get('http://juliemr.github.io/protractor-demo/');
        browser.pause();
        expect(browser.getTitle()).toEqual('Super Calculator');
      });
    });

I tried in macOS Sierra and Ubuntu, and in both the situation is exactly the same. On macOS I tried with Chrome, Firefox and Safari (with the capabilities config attribute).
Versions:
Protractor version 5.1.1.
Chrome (version 56.0.2924.87, 64-bit).
Firefox (52.0)
Safari (10.0.3)
With Firefox the same happens when pausing (at the beginning of the test), and without pause it doesn't pass the test, it says the page doesn't have Angular (but it does):
[09:44:56] E/protractor - Could not find Angular on page http://juliemr.github.io/protractor-demo/ : retries looking for angular exceeded

With Safari it doesn't even connect (with or without the pause):
[09:40:00] I/launcher - Running 1 instances of WebDriver
[09:40:00] I/hosted - Using the selenium server at http://localhost:4444/wd/hub
[09:40:22] E/launcher - Connection refused
[09:40:22] E/launcher - WebDriverError: Connection refused

Any suggestion is welcome. Thanks in advance.

A: I was able to solve the wait by browser.sleep(5000)
Use -  browser.sleep()

A: I finally found a way to run a repl. When browser.pause pauses, there's a repl command, but it doesn't work anymore:
Error: using repl from browser.pause() has been removed. Please use browser.enterRepl instead.

So following that message I change browser.pause(); with browser.enterRepl(); and then it stopped and gave me the context.
And there's another alias for enterRepl: browser.explore();
Hope it helps anyone having the same issue.


text:
Q: Creating a windows service to display timer on the top right position in UWP app I am developing an app for Microsoft surface hub. I have a requirement wherein when the user clicks on a button , there is a countdown timer running on the desktop of the surface hub. The timer is not the part of the app but the app can start and stop the timer .
Even if my app is minimized , the timer should be shown ticking on the top right corner of the Surface Hub.
As far as I understand that the timer can be a part of the UWP app and when the app is minimized or in the background , the timer wouldn't be visible . My requirements ask me to display the timer if the user selects "show timer" from my app and it doesn't have to be a part of the app but can be controlled by the user.
How is this possible in UWP and is running a windows service can help?
I am completely new to this and seeking some advice and some samples that go well with the UWP app

A: You may use the Picture in Picture mode to show your app above other windows. AFAIK this is the only way how to do something like an overlay.


text:
Q: How to re-run terraform resource file provisioner I have a resource "aws_instance" which includes a provisioner "file". This all works as expected when the EC2 instance is not present at first.
How can I re-run the provisioner if the file is deleted from the VM?
resource "aws_instance" "example" {
   ami           = "ami-0b0a60c0a2bd40612"
   instance_type = "t2.micro"
   key_name = "secret"
   security_groups = ["terraform-basic-ssh-http"]

provisioner "file" {
  source = "install-nginx.sh"
  destination = "/tmp/install-nginx.sh"

  connection {
   type     = "ssh"
   user     = "ubuntu"
   private_key = "${file("/local/path/to/my/key.pem")}"
  }
}

provisioner "remote-exec" {
  inline = [
    "chmod +x /tmp/install-nginx.sh",
    "/tmp/install-nginx.sh"
  ]

  connection {
    type     = "ssh"
    user     = "ubuntu"
    private_key = "${file("/local/path/to/mykey.pem")}"
  }

}

}

A: You can also use the terraform taint command for that: terraform taint provisioner.file
If your resource is in a module, taint the provisioner with terraform taint -module=[MODULE_NAME] provisioner.file
This will let Terraform "recreate" the provisioner.


text:
Q: How to pause/resume video in Exoplayer? I am using Exoplayer for playing video
Code For Playing Video

private PlayerView videoView;
SimpleExoPlayer player;

    videoView = findViewById(R.id.video_view);
    player = ExoPlayerFactory.newSimpleInstance(this, new DefaultTrackSelector());
    videoView.setPlayer(player);
    player.prepare(buildMediaSource(Uri.parse(_videoUrl)));
    player.setPlayWhenReady(true);

    videoView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            //i want to pause video
            //next time i want to resume
            return false;
        }
    });

XML CODE

<com.google.android.exoplayer2.ui.PlayerView
    android:id="@+id/video_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="8dp"
    //i don't want to use controls to i am setting false
    app:use_controller="false"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

I cant find any usefull docs to pause and resume video
my requirement is to pause/resume video when touch on VideoView any one now how to do it ?
Dependency
implementation 'com.google.android.exoplayer:exoplayer:2.7.3'
implementation 'com.google.android.exoplayer:exoplayer-core:2.7.3'
implementation 'com.google.android.exoplayer:exoplayer-dash:2.7.3'
implementation 'com.google.android.exoplayer:exoplayer-ui:2.7.3'

A: For Play Video
private void playPlayer() {
    if (player != null) {
        player.setPlayWhenReady(true);
    }
}

For Pause Video
private void pausePlayer() {
    if (player != null) {
        player.setPlayWhenReady(false);
    }
}

From Specific Position
private void seekTo(long positionInMS) {
    if (player != null) {
        player.seekTo(positionInMS);
    }
}

Relase Player
private void releasePlayer() {
    if (player != null) {
        player.release();
    }
}


text:
Q: Delphi: How to calculate the SHA hash of a large file Hi I need to generate a SHA over a 5 Gig file
Do you know of a non string based Delphi library that can do this ?

A: I would recommend Wolfgang Ehrhardt's CRC/Hash.
http://home.netsurf.de/wolfgang.ehrhardt/
It's fast and "can be compiled with most current Pascal (TP 5/5.5/6, BP 7, VP 2.1, FPC 1.0/2.0/2.2) and Delphi versions (tested with V1 up to V7/9/10)".
I've used it with D11/D12 too.

A: You should use DCPcrypt v2 and read your file buffered and feed the SHA hasher with the buffer until you've read the complete 5GB file.
If you want to know how to read a large file buffered, see my answer about a file copy using custom buffering.
so in concept (no real delphi code!):
function GetShaHash(const AFilename: String)
begin
  sha := TSHAHasher.Create;
  SetLength(Result, sha.Size);
  file := OpenFile(AFilename, GENERIC_READ);
  while not eof file do
  begin
     BytesRead := ReadFile(file, buffer[0], 0, 1024 * 1024);
     sha.Update(buffer[0], BytesRead);
  end;
  sha.Final(Result[0]);
  CloseFile(file);
end;

A: If I remember correctly, Indy comes with several a stream based hash methods.

A: There is a Delphi interface for OpenSSL, isn't there?
That should provide you with better performances.

A: @Davy Landman,
thank you, your answer really helped me out. This is the code I ended up using:
function HashFileSHA256(const fileName: String): String;
var
  sha256: TDCP_sha256;
  buffer: array[0..1024*1024] of byte;
  i, bytesRead: Integer;
  streamIn: TFileStream;
  hashBuf: array[0..31] of byte;
begin
  // Initialization
  Result := '';
  streamIn := TFileStream.Create(fileName, fmOpenRead);
  sha256 := TDCP_sha256.Create(nil);
  for i:=0 to Sizeof(buffer) do
    buffer[i] := 0;
  for i:=0 to Sizeof(hashBuf) do
    hashBuf[i] := 0;
  bytesRead := -1;

  // Compute
  try
    sha256.Init;
    while bytesRead <> 0 do
    begin
      bytesRead := streamIn.Read(buffer[0], Sizeof(buffer));
      sha256.Update(buffer[0], bytesRead);
    end;
    sha256.Final(hashBuf);
    for I := 0 to 31 do
      Result := Result + IntToHex(hashBuf[i], 2);
  finally
    streamIn.Free;
    sha256.Free;
  end;

  Result := LowerCase(Result);
end;

P.S.: I am a total beginner with Pascal, so this code most likely sucks. But I tested it on the MSYS2 installer and was able to verify the hash, so that's nice.


text:
Q: 'static functions with block scope are illegal' error for compiling Zeus When I want to compile Zeus source code on Windows 8 with Visual Studio 2010 I receive this error 'static functions with block scope are illegal', is there any way to force compiler to ignore this error? (One friend of mine compiled this source code without any modification with my current setup)
[to compile the source first you should change path of compiler in 'make/buildconfig.inc.php' file) [I am a researcher], This is the simplest case study I think:
int main() {
    static int func1();   // C2267
}

This is the function
static bool unhookList(HANDLE process, HOOKWINAPI *list, DWORD count)
{
  bool ok = true;
  for(DWORD i = 0; i < count; i++)if(list[i].originalFunction != NULL)
  {
    if(!WaHook::_unhook(process, list[i].functionForHook, list[i].originalFunction, list[i].originalFunctionSize))
    {
      ok = false;
#     if defined WDEBUG1
      WDEBUG1(WDDT_ERROR, "Failed to unhook WinApi at index %u", i);
#     endif
    }
    /*else
    {
      PeImage::_repalceImportFunction(coreData.modules.current, list[i].originalFunction, list[i].functionForHook);
      Core::replaceFunction(list[i].originalFunction, list[i].functionForHook);
    }*/
  }
  return ok;
}

A: Declaring functions within a block scope is illegal in C and C++. So, what exactly are you trying to do? If you just want to call the function unhookList(), declared in one of the Zeus headers, then simply call it like this:
int main() {
    // parameter values are just for example
    bool result = unhookList(0, NULL, 1);
}


text:
Q: Implementation of a step-scoped in-memory destination in spring batch I have a requirement when using spring batch for the creation for a large report, in binary format, which is held in a database. None of the working data can be written directly to files, or to working tables outside the JobExecutionContext.
I'm aware that normally you would just write to the job execution context, but I'm a little confused as to how I would go about it with such a large report (potentially several hundred megabytes.)
At the moment, my Writer implementation has a dependency on an aggregator class, which is injected as a bean, then there's a TaskLet that has the aggregator injected in which writes the finished report to the database.
The problem is that I cannot scope my aggregator to the step context and as such if two jobs are running at the same time they will be writing to the same aggregator.
Here is my current implementation
Domain class
public class DataChunk {
    private int pageNumber;
    private byte[] data;
}

Writer
public class FooWriter implements ItemWriter<DataChunk> {

    private DataChunkAggregator dataChunkAggregator;

    public void write(List<? extends DataChunk> dataChunks) throws Exception {
        dataChunks.stream().forEach(chunk -> dataChunkAggregator.addChunk(chunk.getPageNumber(), chunk.getData()));
    }
}

Aggregator
public class FooAggregator {
    private Map<int, byte> pagedData; // Key sorted implementation

    public void addChunk(int pageNumber, byte[] data) {
        pagedData.put(pageNumber, data)
    }

    public byte[] aggregate() {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        pagedData.values.stream().forEach(data -> baos.write(data));
        return baos.toByteArray();
    }
}

Report Writing Tasklet
public class ReportWritingTasklet implements TaskLet {

    private ReportRepository reportRepository;
    private FooAggregator fooAggregator;

    public RepeatStatus execute(StepContribution contribution, ChunkContext context) {
        byte[] data = fooAggregator.aggregate();
        reportRepository.getOne(reportId).setDataBytes(data);
    }
}

Context
<?xml version="1.0" encoding="UTF-8"?>
<beans>
    <bean id=fooWriter class="FooWriter" scope="step"
        p:fooAggregator-ref="fooAggregator"/>

    <bean id="fooAggregator" class="FooAggregator"/>

    <bean id="reportWritingTasklet" class="ReportWritingTasklet" scope="step"
        p:fooAggregator-ref="fooAggregator"/>

    <batch:job id="fooJob">
        <batch:step id="generateReport" next="assembleReport">
            <batch:chunk reader="fooReader" processor="fooProcessor" writer="fooWriter"/>
        </batch:step>
        <batch:step id="assembleReport">
            <batch:tasklet class="ReportWritingTasklet"/>
        </batch:step>
     </batch:job>
</beans>

If I attempt to make the FooAggregator step-scoped I get the following exception as a root-cause
Caused by: java.lang.IllegalStateException: Cannot convert value of type    [com.sun.proxy.$Proxy98 implementing org.springframework.aop.scope.ScopedObject,java.io.Serializable,org.springframework.aop.framework.AopInfrastructureBean,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised] to required type [FooAggregator] for property 'fooAggregator': no matching editors or conversion strategy found

This is because you're only meant to be able to scope certain things to the step.
How can I use the Execution context as a sink for my data chunks, bearing in mind there will be a lot of them and they will be very large?

A: I've managed to solve this. It's not very Spring batch-y, but it meets my requirements.
Essentially, there is too much data to push into and out of the context. The solution has been to maintain the state in the writer itself, and to make it a StepExecutionListener that will save at the end of the Step, via a TransactionCallback.
The Updated Writer
public class FooWriter extends StepExecutionListenerSupport implements ItemWriter<DataChunk> {

    private String reportId;
    private Map<Integer, byte[]> byteArrayMap = new ConcurrentSkipListMap<>();

    private TransactionTemplate transactionTemplate;
    private ReportRepository reportRepository;

    @Override
    public synchronized void write(List<? extends CaseChunk> caseChunks) throws Exception {
        caseChunks.stream().forEach(chunk -> {
            byteArrayMap.put(chunk.getPageNumber(), chunk.getBytes());
        });
    }

    @Override
    public void beforeStep(StepExecution stepExecution) {
        // No-op
    }

    @Override
    public ExitStatus afterStep(StepExecution stepExecution) {
        StringBuilder sb = new StringBuilder();
        for (byte[] byteArrayOutputStream : byteArrayMap.values()) {
            sb.append(new String(Base64.decode(byteArrayOutputStream)));
        }
        String encodedReportData = new String(Base64.encode(sb.toString().getBytes()));

        TransactionCallback<Report> transactionCallback = transactionStatus -> {
            Report report = reportRepository.getOne(this.reportId);
            report.setReportData(encodedReportData);
            reportRepository.save(report);
            return report;
        };

        // TransactionTemplate throws its own declared TransactionException, rethrows encountered RuntimeExceptions
        // and also Errors. Any problem writing the date kills the job, so it's OK to catch Throwable here instead
        // of trying to
        try {
            transactionTemplate.execute(transactionCallback);
        } catch (Throwable t) {
            LOGGER.error("Error saving report data ID:[{}]", reportId);
            return ExitStatus.FAILED.addExitDescription(t);
        }
        return ExitStatus.COMPLETED;
    }

}


text:
Q: How do you slice part of an input statement in Python 3? I have a question which asks me to get a user's email address and then return the URL it is associated with. So, for example: 'abc123@address.com' --> 'http:://www.address.com'
I did get this:
def main():
    email_address = input('Enter your email address (eg. abc123@address.com): ').strip()
    strip_username = email_address.split('@', 1)[-1]
    the_url(strip_username)

def the_url(url_ending):
    print('Your associated URL is: http://www.' + str(url_ending))

main()

which does what I want, but this code: split('@'...) is something I haven't learned yet. I just found it online. I need to use indexing and splicing for this program, but how can I use splicing if I don't know the length of the user's email? I need to get rid of everything before and including the '@' symbol so that it can leave me with just 'address.com' but I don't know what address it will be. It could be hotmail, gmail, etc. Thanks, and I'm really new to Python so I'm trying to only use what I've learned in class so far.

A: The split method just splits up the string based on the character to you give it, so:
"Hello@cat".split("@")

Will give you
["Hello", "cat"]

Then you can just take the 1st index of that array to give you whatever's after the first @ symbol.

A: If you don't want to use str.split then by indexing and slicing,
you can do something like this.
>>> str = 'abc123@address.com'
>>> 'http://www.' + str[str.index('@')+1:]
'http://www.address.com'


text:
Q: Click dropdown of different page I don't know how can I click the dropdown of another page for button I know I can do this page.click('button[id="loginbox"]'), but I want for dropdown by classname.i have one hover dropdown whose html is
 which opens dropdown window whose html is  this contains another dropdown dropdown menu
* whose value I want to add in list and send to my prevous page. Can anyone tell me how can I achieve this

A: document.getElementsByClassName("classname") [0].click()
But this is a bad approach, as multiple elements can exist with classes. That is why id's used for such behaviour, so only one specific element is being clicked at a time.
But without code examples, that is best answer I can provide.


text:
Q: How to use qpdf via latexmk? In the manual of latexmk I read that

[latexmk] can also, if needed, call an external program to do other
  postprocessing  on  the  generated files.

How can I call qpdf with latexmk? I want to do qpdf --linearize on the file that latexmk is operating on. Preferably latexmk will call qpdf only when it is called with a specific flag such as -l.

A: The possibility of postprocessing mentioned in the latexmk documentation is only for dvi and postscript files.  (See the description of the -dF and -pF options, and of the configuration variables $dvi_filter and $ps_filter.)  I need to correct the documentation on this point.  I could improve latexmk to also do this for pdf files.
But there is a simpler and more general method.  Just define the $pdflatex command to include the invocation of qpdf.  For example, you could put the following in one of latexmk's initialization files:
$pdflatex = 'pdflatex %O %S && qpdf -linearize %D tmp.pdf && mv tmp.pdf %D';

(This is in a form suitable for Unix-like operating systems, it will need to be changed for MS-Windows, probably.)  When latexmk uses this, it executes the pdflatex command; if successful it invokes qpdf, putting the result in a temporary file; if that is successful the temporary file is moved to replace the originally generated pdf file.
I don't have qpdf installed on my computer, so I am working from its documentation to write a suitable invocation of it.
If you want a command line option to control the use of qpdf, put the above line in its own file, e.g., useqpdf.  Then you can invoke latexmk to read this file when needed:
latexmk -r useqpdf foo.tex


text:
Q: Constructing a responsive website In today's web development community, It is almost 'standard practise' to make a website "fully responsive" - meaning it would work on all screen sizes.
I currently have a website that is designed for a set width and height of 900 * 600px. However, I would like to alter this in such a way that I can make it mobile responsive, without loosing its functionality.
I was looking for some 'industry standard' concepts in which I could adapt to this purpose, although I am at a slight loss as to how 'professionals' would go about achieving this in real world situations?
+---------------------------------------+
|     NAVBAR (900px)                    |
+---------------------------------------+
|      |                                |
|      |                                |
|      |           body                 |
|200px |          (700px)               |
|      |                                |
|      |                                |
|      |                                |
|      |                                |
+---------------------------------------+

Here's a quick demo of a layout design which suits the 900 * 600px screen:

.page-wrap {
  height: 600px;
  width: 900px;
  background: lightgray;
  position: absolute;
  top: 0;
  left: 0;
}
.nav {
  position: absolute;
  top: 0;
  left: 0;
  height: 50px;
  width: 900px;
  background: tomato;
}
.sidebar {
  position: absolute;
  top: 50px;
  left: 0;
  height: 550px;
  width: 200px;
  background: dimgray;
}
.nav a {
  display: inline-block;
  height: 50px;
  width: 100px;
  line-height: 50px;
  text-decoration: none;
  background: rgba(200, 200, 200, 0.4);
}
.nav a:hover {
  background: transparent;
}

    nav bar itemnav bar itemnav bar itemnav bar itemnav bar item

In short, how would this 'responsive' design be constructed? Is there a 'best practise' when dealing with responsive-designs?

A: I've recently found that for responsive images I had to ensure that images in a Jekyll site (porting a template and adding functionality) would scale and fit on smaller screens, but not stretch and take up half the screen on screens with larger sizes.
Here are 2 methods to ensure that images/media do not overstretch or mess up the entire responsive site by going through the boundary without having to manually resize them.

*

*CSS max/min-width attribute
For media assets like images, most browsers will support the max-width attribute that specifies how wide the image can be, or max-height if your use case prefers that. Here's an example:
/*in a css file */
img {
    max-width: 90%;
    height: auto;
    width: auto;
}
That tells the browser to display images at a maximum width of 90% and resize the width and height accordingly (you do not need both attributes). For all img elements.
For even finer control individual styling of classes can be done like so:
img.responsive {
    /*css for specific class here*/
 }
And later specify the element is part of the image responsive class like so:

EDIT:

*Centering or Positioning in CSS
I found a simple website that generates the code on how to position elements in CSS for you based on input settings, which is a real issue on responsive devices as well. This is the website: http://howtocenterincss.com/
Note that you will need to fully fill everything in (including the middle option). Also, despite the website's name, it also handles positions that are not center as well, so it is a fairly good catch-all.

*Wrap the image in a container
The benefit of this is you style the container, and every element inside it will adhere to the container styles if their attributes are auto. By specifying a max size for a container with width=800px, whilst making the image width: auto so the image will resize to the dimensions of a container.
These 2 examples are adapted from the following site, which is a great resource for handling responsive assets like responsive videos/images/fonts and relative sizing, 5 useful CSS Tricks for a Responsive Website. The author is much more well-versed on the topic than I am currently.
Note that as mentioned in that tutorial not all browsers support max-width (IE7 and 9 do but not IE8) so that might be an issue for some people who use outdated browsers. In that case a conditional CSS is needed of a hack such as below (example taken from site) is needed:
@media \0screen {
  img {
    width: auto; /* for ie 8, */
  }
}

-- Notice how I just placed width:auto in my first example with the max-width attribute
Additional: Another Framework
Many templates made by web designer n33 employ the lightweight Skel framework to make responsive websites that load the right CSS based on screen size. However this is a Javascript framework which won't function when users have noscript turned on. In which case you have to load the CSS by specifying  paths to CSS here
A good reference on responsive templates (that have opensource files like CSS) that allowed me to study and understand some methods in making a responsive site can be found at HTML5UP.net also by the same developer that wrote Skel.

A: there are many ways in order to make a website responsive. It bottles down to so many factors.
You need to use RWD, which stands for Responsive Web Design.
It means that you can deliver your webpage in a variable size of screen, without having to re-write your html over and over. This is very much a must-do if you had to work with mobile and/or tablet devices.
Use Dynamic Units
One of the most important features of making a webpage responsive is the units you use, so I'll mention that first of all. At the moment, you have 'hard coded' these values by using a (pixel) px unit, which would be seen as a 'static unit'.
Below is a couple of units you may want to consider in the generation of your markup:

The absolute length units are fixed in relation to each other and
  anchored to some physical measurement. They are mainly useful when the
  output environment is known. The absolute units consist of the
  physical units (in, cm, mm, pt, pc) and the px unit ~ w3.org

The above table displays what is known as 'absolute' units, and this is because they do not 'technically' change when you resize your browser or view on a mobile device.
Instead of using such units, you should consider using one of the 'dynamic' units. For example:

*

*percentage (%)

*viewport-width or viewport-height (vw and vh respectively)

~Image from this article note this is an old article, and support for these has improved a lot since
Using the likes of percentage, for example, means you can set the width and/or height of a div depending on your containing block's size.
For example, resize your screen here:

div {
  width: 50%;
  background: tomato;
  height: 50px;
}

You should notice how that div will always be '50% of its container'.
This would become very handy if you were building your website from scratch, but would also be useful if you were adapting one as well.

Use Media Queries
Media queries are great when used properly.

A media query is a logical expression that is either true or false. A
  media query is true if the media type of the media query matches the
  media type of the device where the user agent is running (as defined
  in the "Applies to" line), and all expressions in the media query are
  true.
A shorthand syntax is offered for media queries that apply to all
  media types; the keyword 'all' can be left out (along with the
  trailing 'and'). I.e. if the media type is not explicitly given it is
  'all'.

For example, you could test something like "if my screen is smaller than 500px, use this css instead".
This would use a definition of something like:
@media (max-width:500px) {
//my css for when screen is lass than 500px wide
}

Several media queries can be combined in a media query list. A
  comma-separated list of media queries. If one or more of the media
  queries in the comma-separated list are true, the whole list is true,
  and otherwise false. In the media queries syntax, the comma expresses
  a logical OR, while the 'and' keyword expresses a logical AND

A simple demo of this would be:

div{
  width:500px;
  height:200px;
  background:gray;
  }

@media screen and (max-width:500px){
  div{
    width:100px;
    background:tomato;
    }

  }

Use a Responsive Plugin
(Personally not advised, but still valid)

Bootstrap is the most popular HTML, CSS, and JS framework for
  developing responsive webs.

Although I would advise not to using this, as it has a lot of 'unnecessary' css rules and hence I think it should only be used for 'concept code', and not production code.
Other Frameworks include:

*

*foundation 3

*skeleton

*Bootstrap

Use a combination of these
In reality, most developers would use a whole range of combinations of these.
There isn't really a 'definitive' way of making a website responsive. However, hopefully you will be able to use some of this in future.


text:
Q: Send mail with some delay time in odoo11 I have to send a mail when stage changes with a delay of some specific time. For example, in my case, I have to send mail after 10 minutes of stage changes. The time should be configurable.
I have try to achieve this by making force parameter to false as below:-
self.env['mail.template'].browse(template.id).send_mail(self.id, force_send=False)

And after that i have changed time intervals of "Mail: Email Queue Manager" template in scheduled action as per my requirement. In this case arises that When i send 2 mails lets say first mail on 11:30 and second mail on 11:33 and scheduled action will be performed on 11:35. So it sends both mails on 11:35 instead of sending mails on 11:35 and 11:38 respectively if i scheduled it at every 5 minutes after stage changes.
So how can i achieve this?

A: You may pass the send mail function to a new thread with execution time 5 minutes
Imagine that the Odoo project is running in a main thread and you are gonna send the mail in a second thread
import threading
import time

def odoo_project():
    for x in range(0,11):
            print(x)
            time.sleep(1)

def mail_sender():
    for x in range(100,103):
            print(x)
            time.sleep(5)

t1 = threading.Thread(target=odoo_project)
t2 = threading.Thread(target=mail_sender)
t1.start()
t2.start()

This will output
0
100
1
2
3
4
101
5
6
7
8
9
102
10

which means the Odoo project will continue working while the mail thread is gonna send the mail after 5 minutes -replace 5 with 5 * 60 in the example-
Also it would be a better design if you did a config field that you type the delay value in it instead of hard-coding the 5 minutes in the code in case you wanted future updates


text:
Q: Using Fancybox 2 with Scriptculous? Has anyone successfully used both libraries together?  I can't seem to place the code in the properly sequence to get them to work together.

A: Have you tried using jquery's noConflict() ? Since you are using two different libraries, it might be causing error. Using jQuery.noConflict() function might help.

A: According to your comment, you are doing this :
jQuery.noConflict(
 $(document).ready(function () {
  $('.fancybox-media').fancybox({
   openEffect : 'none',
   closeEffect : 'none',
   helpers : {
    media : {}
   }
  });
  $(".fancybox").fancybox({
   openEffect : 'none',
   closeEffect : 'none'
  });
 });
);

... try this instead :
jQuery.noConflict();
jQuery(document).ready(function($) {
  $('.fancybox-media').fancybox({
   openEffect : 'none',
   closeEffect : 'none',
   helpers : {
    media : {}
   }
  }); // first fancybox
  $(".fancybox").fancybox({
   openEffect : 'none',
   closeEffect : 'none'
  }); // second fancybox
}); // ready


text:
Q: Таймер для FireFox как сделать в этом коде, чтобы таймер показывался но при этом не исчезало название самой
вкладки,можно как-то так сделать?
// ==UserScript==
// @include *
// ==/UserScript==

start=(new Date()).getTime();
window.setInterval(function(){
   document.title=Math.floor(((new Date()).getTime()-start)/1000);
}, 340);

A: Т.к. время вы отображаете в секундах. менять title чаще раза в секунду смысла нет
defTitle=document.title;
startTime=new Date().getTime();
setInterval(function(){
    document.title=defTitle+' - '+Math.round((new Date().getTime()-startTime)/1000);
}, 1000);

вообще если такие вопросы вызывают траблы - программирование нужно хоть чуть подтянуть


text:
Q: How to calculate distance traveled given 2D velocities? Given velocities in $x$ and $y$ directions, $V_x$ and $V_y$, why can't  we integrate  these two velocities vs. time from $0$ to $t$ to find distances traveled in x and y directions respectively, and then use Pythogorean theroem to get total distance traveled? I found this approach gives different answers compared to integration of $\sqrt{V_x^2+V_y^2} $ vs time from $0$ to $t$. I must have missed something simple, what is it? Thanks for your help.

A: By means of the first approach, you calculate the distance between the initial and the final points of the trajectory. On the other hand, with the second approach, what is calculated is the total length of the trajectory, which, in general (if the path followed is not a straight line) is greater than the distance between the initial and final points.
This is simple to see: with the first approach what you do is calculate the total displacement in both axes separately and that will only give you the final point of the trajectory, then use the Pythagorean theorem to get the distance from the original point to the final point. If, instead, you proceed as in the second method, you (heuristically) calculate the instantaneous displacement of the particle and then add it all up to get the length of the trajectory.


text:
Q: I am able to upload to AWS S3 from my localhost, but not from my AWS Elastic BeanStalk instance? I am new to AWS. I have developed spring boot application to upload files in S3 bucket.
I have created IAM user and assign AmazonS3FullAccess. I am using that user accessKey and accessSecret in my spring boot application to upload file and its working fine in my localhost but its not working in AWS Elastic BeanStalk instance. I am getting permission denied exception message.

A: In the Configuration of your Elastic Beanstalk application, in the Security section, there should be an IAM instance profile configured.
Once you've identified the role that it is using, you need to open the Identity and Access Management (IAM) console, navigate to the list of Roles, find the role, and add a new policy to it. The easiest solution is to add an inline policy. Give it permissions to upload files to the bucket and it should start working. There shouldn't be a need to restart the server.

A: All I did was to add permission policy to my elastic beanstalk role.


text:
Q: Error ArrayList cannot find symbol symbol: variable myAl location: class JavaApplication into main Why does this error happen?

I create an array inside the main:
List<Integer> myAL = new ArrayList<Integer>();

Add items to that array, then call the findNumber method:
findNumber(myAl, 2);

But an error appears:
Error ArrayList cannot find symbol   symbol:   variable myAl   location: class JavaApplication

A: I see three problems.
Your immediat problem as GBlodgett already pointed out us that you did not pay attention to your names one is "myAl" the other is "myAL".
The second which will occur directly after is that you can't call a non static method like findNumber out of a static code block.
The third is that your return value, the String findNumber returns will get lost. You can either assign it to a variable String newString = findNumber... ;
Or what you probably want here is to print it with System.out.println(findN...);
For the future, it is nice if you can include the code directly instead of a picture, as it is easier to copy code instead of recreate it from a picture.
Happy Coding
As a personal tip, stay away from the main if you just want to write some silly code and run JUnit tests instead.
@Test
void test()
{
    myAl.add(0);
    ....
    findNumber(..);
}

extra points if you use assertions and good test, but that can wait until you get your feet under you. Tough it can help tremendiously to write tests instead of relying on print debugging


text:
Q: WPF image moving and rotating First of all I place here my situation sreenshot:

So I need to move these cars(cars are Images) where the arrow goes.
For driving straight I use this function:
    private static void Eiti(Image target, double naujasX, double naujasY, double greitis, char kelias)
    {
        var top = Canvas.GetTop(target);
        var left = Canvas.GetLeft(target);
        top = Double.IsNaN(top) ? 0 : top;
        left = Double.IsNaN(left) ? 0 : left;
        naujasY = Paveikslas.canvasY(naujasY, kelias);

        var storyboard = new Storyboard();
        greitis = 100 / greitis;                // apverciamas greitis, kad butu logiska
        storyboard.Completed += Storyboard_Completed;

        if (naujasY != -1)                         // isejimo simbolis (escape)
        {
            DoubleAnimation anim1 = new DoubleAnimation(top, naujasY, TimeSpan.FromSeconds(greitis));
            Storyboard.SetTarget(anim1, target);
            Storyboard.SetTargetProperty(anim1, new PropertyPath(Canvas.TopProperty));
            storyboard.Children.Add(anim1);

            DoubleAnimation anim2 = new DoubleAnimation(left, naujasX, TimeSpan.FromSeconds(greitis));
            Storyboard.SetTarget(anim2, target);
            Storyboard.SetTargetProperty(anim2, new PropertyPath(Canvas.LeftProperty));
            storyboard.Children.Add(anim2);
        }

        storyboard.Begin();

    }

and it's working good for me!

But now I have problem with rotating and driving car at the same time (for example like in my screenshot driving through green square).

Is there any function or other ways to solve this ?


text:
Q: get memory usage on cuda context Is there a way that I can get cuda context memory usage rather than having to use cudaMemGetInfo which only reports global information of a device? or at least a way to get how much memory is occupied by the current application?

A: It seems to be impossible [No]. However, retrieving per-process memory usage is still a good alternative. And as Robert has pointed out, per-process memory usage can be retrieved using NVML, specifically, by using nvmlDeviceGetComputeRunningProcesses function.


text:
Q: What is the iOS equivalent to WPF's Grid with star sizing? In WPF, I can create a Grid with multiple column definitions where a single column can occupy the unused screen space with star sizing like so:
<Grid Height="50">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="50"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="50"/>
        <ColumnDefinition Width="50"/>
        <ColumnDefinition Width="50"/>
    </Grid.ColumnDefinitions>

    <Grid Grid.Column="0" Background="Red"/>
    <Grid Grid.Column="1" Background="Blue"/>
    <Grid Grid.Column="2" Background="Yellow"/>
    <Grid Grid.Column="3" Background="Pink"/>
    <Grid Grid.Column="4" Background="Green"/>
</Grid>

I need to replicate the same UI on iOS. I have looked into using UIStackView, but since I have less experience working with iOS, I'm not sure how to go about doing this. Is UIStackView the right choice or do I need to use another layout? How can this UI be replicated on iOS? Please note that this needs to be done programmatically.

A: Step 1.  Drag a "Horizontal UIStackView" to your ViewController in IB, and set the Top, Left, Right and Height constraints.
Step2. Drag 5 UIViews in your StackViews, and set "Width" constraint to the 0th, 2nd, 3rd and 4th views. So every child view will have a fixed width expect the second one.
That's it.