text:
Q: How to extend "List-of-numbers-with-number" arithmetic to "List-of-X-with-X" arithmetic? I'll start with a couple of examples (since this is all one can get from the documentation anyway).
First, adding lists of numbers equal length is done term-by-term.  E.g. {8, 2, 5} + {3, 0, 3} evaluates to {11, 2, 8}.
Second, adding a list of numbers to a single number is done by, effectively, "broadcasting" the single number into a list of the same size as that of the other addend, and then the same term-by-term addition as before is applied.  For example {1, 2, 3} + 5 evaluates to {6, 7, 8}.
Conceptually, one could imagine extending this scheme to the case of adding a list L to a list-of-lists L^2.  First "broadcast" L into a list of the appropriate number of copies of L, and then add the two lists-of-lists "term-by-term".  For example, following this scheme, {1, 2} + {{5, 9}, {9, 7}, {1, 7}} would evaluate to {{6, 11}, {10, 9}, {2, 9}}.
To my surprise, however, Mathematica won't play along: The last sum would fail with an error beginning with Thread::tdlen: Objects of unequal length ...  (The same goes for the remaining "basic operations", -, *, and /.)
What's the simplest way to carry out this proposed extension of arithmetic between a single object of type X and a List of objects of type X (assuming that arithmetic between single objects of type X is defined)?

A: Here's an alternative to Map:
{1, 2} + Transpose@{{5, 9}, {9, 7}, {1, 7}} // Transpose
(* {{6, 11}, {10, 9}, {2, 9}} *)

It can be faster than Map, too:
m = RandomInteger[{1, 9}, {10^6, 2}];

{1, 2} + Transpose@m // Transpose // AbsoluteTiming // First
(* 0.025621 *)

{1, 2} + # & /@ m // AbsoluteTiming // First
(* 0.148701 *)

A:  i@l_ := l + {1, 2}
 i /@ {{5, 9}, {9, 7}, {1, 7}}


text:
Q: PHP - Yii - I can access model's data in a view file, but have the getUrl in its controller. How do i access this? PHP - Yii - I can access model's data in a view file, but have the getUrl in its controller. How do i access this?
basically, in yii, i have a model and controller set up. in the controller for a certain models (videos) i have a function called getUrl.
on the homepage i've edited the view to include the latest posts. i do this in views/site/index.php with:
    <?php $this->widget('LatestVideos'); ?>

and the LatestVideos widget has this code:
<?

Yii::import('zii.widgets.CPortlet');

class LatestVideos extends CPortlet {
public $title='Tags';
public $maxVideos = 20;
protected function renderContent() {
    $criteria = new CDbCriteria;
    $criteria->limit=$maxVideos;
    $vids = Video::model()->findAll();
    foreach($vids as $video) {
        $link = Yii::app()->createUrl('video/view', array(
            'id'=>$video->id,
            'title'=>$video->video_title,
        ));
        echo '' . $video->video_title . '';
    }

as you can see, in that widget i get the info about latest videos by going straight from the widget to the model. i skip the controller. i need to access the controller to propperly access the getUrl function. how do i do this?

A: In your video model write following method...
public function getUrl(){
    return Yii::app()->createUrl('video/view', array(
        'id'=>$this->id,
        'title'=>$this->video_title,
    ));
}

and the LatestVideos widget has this code:
Yii::import('zii.widgets.CPortlet');
class LatestVideos extends CPortlet {
public $title='Tags';
public $maxVideos = 20;
protected function renderContent() {
$criteria = new CDbCriteria;
$criteria->limit=$maxVideos;
$vids = Video::model()->findAll();
foreach($vids as $video) {
    echo CHtml::link(CHtml::encode($video->video_title), $video->url);
}

I think this is help for you.

A: Try thisif (Yii::app()->controller) Yii::app()->controller->createUrl()

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to overload a method that has params object[] as parameter Our database has a Primary Key defined on every table existing of a combined key with a short and an int. Therefore, using Entity Framework we can try to find an element by calling to it's Context.DbSet<>.Find(params object[] parameters) method.
In our code this would look like:
public Client FindClient(short sqlId, int incId)
{
  Context db = new Context();
  Client result = db.Clients.Find(sqlId, incId);
  return result;
}

However, in our code we are using structs to store key values. Our struct is as follows:
public struct DbKey
{
  private short _SqlId;
  private int _IncId;
  public short SqlId { get { return _SqlId; } }
  public int IncId { get { return _IncId; } }

  public DbKey(short SqlId, int IncId)
  {
    this._SqlId = SqlId;
    this._IncId = IncId;
  }

and has some other comparing methods etc.
We would like to be able to call the DbSet.Find method like this:
public Client FindClient(DbKey key)
{
  Context db = new Context();
  Client result = db.Clients.Find(key);
  return result;
}

To be able to do this we wrote an extension overload for this method:
public static partial class Extensions
{
  public static T Find<T>(this DbSet<T> dbset, DbKey key) where T : class
  {
    return dbset.Find(key.IncId, key.SqlId);
  }
}

Intellisense now tells us the Find method is overloaded, with one version accepting DbKey key as parameter, and the other, original method accepting params object[] parameters. However, when running the code, the function will always call to the original method and never to the overloaded, since DbKey also matches the original parameters, resulting in an exception. How can we solve this problem?

A: Well, you can rename, or call static extension directly:
public Client FindClient(DbKey key)
{
  Context db = new Context();
  Client result = Extensions.Find(db.Clients, key);
  return result;
}


text:
Q: Appium code is always asking for setting ANDROID_HOME, How to verify whether i set the path or not Appium code is always asking for setting ANDROID_HOME. I set it in windows environment variables but not sure whats the issue. Is there any way to check whether settings are working or not ?

A: There is a useful package appium-doctor to verify if your environment is properly setup and meets Appium requirements for each platform.
Install it:
npm install appium-doctor -g

Use it:
appium-doctor --android

It will show what exactly is missing.

A: Use appium-doctor and set your environment accordingly. If you are using eclipse set ANDROID_HOME in eclipse too. Right click on the class where you are running and under the run configure the environment tab with ANDROID_HOME.


text:
Q: How to use onAvailable method in ConnectivityManager.NetworkCallback I tried to use ConnectivityManager.NetworkCallback as follows. I no need to use Broadcastreceivers and only ConnectivityManager.NetworkCallback. But I want to take the connected wifi SSID and I did as follows.
package com.example.myapplication;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkRequest;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    ConnectivityManager connectivityManager;
    ConnectivityManager.NetworkCallback networkCallback;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkRequest networkRequest = new NetworkRequest.Builder().build();

        networkCallback = new ConnectivityManager.NetworkCallback(){
            @Override
            public void onAvailable(Network network) {
                Toast.makeText(getApplicationContext(), "*******onAvailable**********", Toast.LENGTH_LONG).show();
                WifiManager wifiManager;
                String connectedSsid = null;
                wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                WifiInfo info = wifiManager.getConnectionInfo();
                connectedSsid = info.getSSID();
                if (connectedSsid != null) {
                    Toast.makeText(getApplicationContext(), "*******" + connectedSsid + "**********", Toast.LENGTH_LONG).show();
                }

            }
        };
        connectivityManager.registerNetworkCallback(networkRequest,networkCallback);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onStop(){
        super.onStop();
        connectivityManager.unregisterNetworkCallback(networkCallback);
    }
}

I added following permissions into the AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

*

*I registered this as connectivityManager.registerNetworkCallback(networkRequest,networkCallback); inside the onCreate method.

*unregistered connectivityManager.unregisterNetworkCallback(networkCallback); inside onStop method.
-I used @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP). However I want to activate this task for the Android 9(Is this compatible for it?)

So inside the onAvailable method I did as follow(you can see my full code in above.)
WifiManager wifiManager;
String connectedSsid = null;
wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo();
connectedSsid = info.getSSID();
if (connectedSsid != null) {
    Toast.makeText(getApplicationContext(), "*******" + connectedSsid + "**********", Toast.LENGTH_LONG).show();
}

So how I take the connected wifi SSID by using only ConnectivityManager.NetworkCallback?

A: You only need to check WifiManager.getConfiguredNetworks() and find configuration with specific network id using WifiInfo.getNetworkId()
For example,
In Broadcast receiver with action WifiManager.NETWORK_STATE_CHANGED_ACTION -  retrieves current connection state from intent

NetworkInfo nwInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
nwInfo.getState()

If NetworkInfo.getState is equal to NetworkInfo.State.CONNECTED then i can get current WifiInfo object

WifiManager wifiManager = (WifiManager) getSystemService (Context.WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo();

And then,
public String findSSIDForWifiInfo(WifiManager manager, WifiInfo wifiInfo) {

    List<WifiConfiguration> listOfConfigurations = manager.getConfiguredNetworks();

    for (int index = 0; index < listOfConfigurations.size(); index++) {
        WifiConfiguration configuration = listOfConfigurations.get(index);
        if (configuration.networkId == wifiInfo.getNetworkId()) {
            return configuration.SSID;
        }
    }

    return null;
}

NOTE: This method doesn't require Location or Location Permissions.


text:
Q: How i can stop SQL server 2008 Express from Startup in Windows ? i am installing SQL server 2008 express and found that many exe run on startup even i not used them.
can i stop them or allow to run them only after when i want to run them. means when i want only that time those run otherwise not.
how i can remove them from startup

A: You can see all your SQL server instances from the Sql Server Configuration Manager if you have it. There you can set the startmode to Manual instead of Automatic. This can also be done from the services console as arunkumar said. The service should be named SQL Server (SQLEXPRESS).

A: As @arunkumar said, you can change the services to disabled, or you can set them to Automatic also, but that may not change much. Generally, SQL Server is usually the main purpose of the PC, so it thinks it always needs to run :)

A: First thing will be to setup all those SQL Server and related services to run "Manually" instead of "Automatic" using Sql Server Configuration Manager.
I usually create two batch files, one to start SQL Server and related services like net start MSSQLSERVER and another to stop SQL Server when I am not using it like net stop MSSQLSERVER.
Of course there will be other related services as well.
If you can't stop services as you indicated in one of your reply, then may be you don't have enough privileges to perform that operation ??

A: Try:
run CMD "Run as Administrator"
command STOP
net stop mssql$express ,
command START
net start mssql$express


text:
Q: Databinding to enumeration of a static class Chaps,
I have a datagrid and am colouring the rows as follows.
    <DataGrid.Resources>
        <Style TargetType="{x:Type DataGridCell}" >
        <Style.Triggers>
              <Trigger Property="DataGridCell.IsSelected" Value="True">
                    <Setter Property="Foreground" Value="Blue" />
                    <Setter Property="Background" Value="White" />
             </Trigger>
            <DataTrigger Binding="{Binding ErrorType}" Value="TerminalError">
                 <Setter Property ="Foreground" Value="Purple"/>
            </DataTrigger>
           <DataTrigger Binding="{Binding ErrorType}" Value="CriticalError">
                <Setter Property ="Foreground" Value="Red"/>
           </DataTrigger>
       </Style.Triggers>
    </Style>
 </DataGrid.Resources>

Currently the colours are hard-coded and I need to change this. I have a singleton class that holds colours for different states and colours may be accessed in the following way:
Color returnedColour = ColourSchemes.Instance.GetColour (CriticalError)

So in the xaml, where I have Value="Red" etc, I wish to source the name from the globally accessible ColourSchemes object instead. Would very much appreciate any words of wisdom.

A: At first, make sure to use Brush instead of Color what you assign a value to a property like Foreground or Background.
Then you may add an indexer property to your ColourSchemes class, which takes the enum value as key:
public enum ErrorType
{
    TerminalError, CriticalError
}

public class ColourSchemes
{
    private readonly Dictionary<ErrorType, Brush> brushes =
        new Dictionary<ErrorType, Brush>
        {
            { ErrorType.TerminalError, Brushes.Orange },
            { ErrorType.CriticalError, Brushes.Red }
        };

    public Brush this[ErrorType value]
    {
        get { return brushes[value]; }
    }

    public static ColourSchemes Instance { get; } = new ColourSchemes();
}

Now you may bind a property like this:
Background="{Binding Source={x:Static local:ColourSchemes.Instance}, Path=[CriticalError]}">

Or in a Setter:
<Setter Property="Background"
    Value="{Binding Source={x:Static local:ColourSchemes.Instance}, Path=[CriticalError]}"/>

You may however want to take a look at Dynamic Resources.


text:
Q: Copy contents between strings conditional on cell value I'm very new to VBA and have been tasked with writing a macro.
I have a system generated file that looks like this

I should end up with three worksheets that look like this
ending file 1

ending file 2

ending file 3

That is, I am trying to find a way to copy the rows between "item 1" and "item 2", "item 2" and "item 3" etc. in all cases where the cells in columns D, E or F are not empty.
By browsing the forums I could find something to get me started, but I am not sure how to proceed. Any help would be appreciated. Thanks.
Sub CopyRows()
    Dim r As Range, fr As String    'Item1
    Dim c As Range, fc As String    'Item2
    Dim StartR As Integer
    Dim EndR As Integer
    Dim NwRng As Range, Nwc As Range
    Dim nwSh As Worksheet

    fr = "Item 1"
    fc = "Item 2"

    Set r = Range("A:A").Find(what:=fr, lookat:=xlWhole)
    Set c = Range("A:A").Find(what:=fc, lookat:=xlWhole)

    If Not r Is Nothing Then
        StartR = r.Row + 1
    Else: MsgBox fr & " not found"
        Exit Sub
    End If

    If Not c Is Nothing Then
        EndR = c.Row - 1
    Else: MsgBox fc & " not found"
        Exit Sub
    End If

    Set NwRng = Range("D" & StartR & ":D" & EndR)
    Set nwSh = Sheets.Add

    For Each Nwc In NwRng.Cells
        If Not IsEmpty(Nwc) Then Nwc.EntireRow.Copy nwSh.Cells(nwSh.Rows.Count, "A").End(xlUp).Offset(1)
    Next Nwc

End Sub

A: Actually you can do that without looping just using autofilter. All you need is:

*

*Filter to exclude blank

*Copy filtered data to another sheet using VBA

*

*Use Autofilter

*Filter for Description not blank AND Set1 not blank and copy it.

*Filter for Description not blank AND Set2 not blank and copy it.

*Filter for Description not blank AND Set3 not blank and copy it.

*Done.
No searching, no looping, no mess.
The only thing you need to do in the end is cleaning up the columns you don't like.


text:
Q: Can I develop Cross-Platform Applications in Visual Studio? (C++) If I only write code that would work on all systems, and use cross-platform libraries, can I use Visual Studio:

*

*to Write Cross-Platform Code?

*to Compile Cross-Platform Code?

And how would I go about compiling it cross platform? I'm guessing some make-file wizardry.

A: You can use Visual Studio IDE to write Cross-Platform code, but to compile for a non-windows target you'll need a different toolchain. I'm not so sure if VS supports applying a different toolchain on a project, doubt it.
I'd recommend Eclipse CDT (which in turn supports compiling projects with the M$ toolchain).

A: Making OS portable C++ code is pretty easy if you just intend to use ISO compatible C++ compilers, ISO Standard C++ and libraries & STL.
The problem is that most OS's have differences on data types, defines, API's for non-standard libraries, etc. A whole suite of GNU tools have been made to solve this:

*

*Autoconf

*Automake

*Libtool
Also, Visual Studio don't use makefile's out-of-the-box, you can use makefile's on Windows but then you lose all the Visual Studio integration. We use standard Visual Studio solutions when compiling on Windows and makefiles for Linux and UNIX.


text:
Q: Now that/because/as you mention it: 'that' meaning 'because'
Now that you mention it.
Now because you mention it.
Now as you mention it.

I've seen many times that being used in place of because and as, mostly by the native speakers.

A: Personally to me, the version with because sounds extremely weird and the one with as quite weird, without some follow up. Let's take a look at some corpora.
CoCa seems to agree with me, having no occurrences of either the version with because or as. Actually the query "Now * you mention it" only finds "that" (roughly a 100 matches) and looking for "Now you mention it" finds 5 matches.
The Hansard corpus has only 1 match for "Now that you mention it" and none for the because or as, but given that it's British Parliamentary speeches this makes some sense (you can get a couple more hits if you also choose a wildcard for "you").

A: I would say "now that" is actually being used instead of "because", not "now because".
Another appropriate start to this sentence is "since".
If you've seen "now" and "because" starting a sentence, perhaps it was "now, because you've mentioned it," which would be acceptable. Note that it's colloquial and places extra emphasis on the fact that they wouldnt be telling you whatever they are about to say if you hadn't mentioned "it"
"Now as you mention it" is not something I would say. However, you might say, "As you mentioned..." but it has a slightly different meaning. The other examples are leading up to something related to what was mentioned, where as "as you mentioned" instead would be followed by the same thing already mentioned.

A: IMHO differences between those are as if difference between yes and of course. It depends on a situation. When you talk to some close person for you, I mean informal language, you can say that. But if your dialog is formal, you should say as or because. There are no big differences.


text:
Q: How to import a class and keep the same package directory structure? I created a bunch of classes and packages in the USER namespace for prototyping.  Now I need to move all of these classes into a different namespace.  When I export/import the classes from the USER namespace to another namespace, the package directory tree is not created correctly.  For instance:

Classes / Package1.SubPackage1.SomeClass

gets created in the namespace like this:

Classes / Package1.SomeClass

I also noticed that it stripped off Package1. from the original object I exported.
What's the trick?
I used Ensemble's Studio for above...


text:
Q: iPad not showing contents until rotating I'm bulding a responsive website with full background images. It works great on desktop, but when I try it on my iPad I can't se anything until I rotate the screen. Sometimes I have to do this several times to actually see the contents and the background image.
The weird thing is that after doing this everything seems to show just fine.
Any ideas?
PS: I didn't try the website in other tablets so I don't know if this is an isolated problem or the same thing happens on every tablet.
-- EDIT: The code --
Ok, here is the code:
HTML - Just an empty Div with the background image
<div class='bkgTablet' id='bkgHome'>
</div>

CSS
div.bkgTablet {
    width:100%;
    position:absolute;
    top:0px;
    left:0px;
    z-index:-4;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

div#bkgHome {
    background: url(../images/indexBkg1tab.jpg);
}

(Diferent Images are showed for landscape or portrait with media queries)
Height is set with jQuery
$(document).ready(function() {
    $('.bkgTablet').css("height", $(window).height() + 'px');
});

$(window).bind("resize", function() {
    $('.bkgTablet').css("height", $(window).height() + 'px');
});


text:
Q: Example of linear parabolic PDE that blows up Does anyone have an example of a linear parabolic PDE that blows up in finite time in a Sobolev space setting? How does one show blow up for that particular example?
The one in Evans unfortunately is nonlinear. I want to study linear ones first. Thanks.

A: There are many.  Take for instance, a Cauchy problem for the heat equation
$$
\begin{cases}
u_t=u_{xx}\,\,,\quad x\in\mathbb{R},\; t>0,\\
u|_{t=0}=e^{x^2},\; x\in\mathbb{R},
\end{cases}
$$
that does possess a unique classical solution
$$
u(x,t)=\frac{e^{\frac{x^2}{1-4t}}}{\sqrt{1-4t}}
$$
on $\,Q=\mathbb{R}\times [0,1/4)\,$.  Nowadays, checking the uniquenes of this solution is seen as nearly a routine exercise.  Though academically, it is well to remember that uniqueness in this Cauchy problem is guaranteed by the classical uniqueness theorem discovered by A. Tychonov:
http://www.mathnet.ru/php/archive.phtml?wshow=paper&jrnid=sm&paperid=6410&option_lang=eng   If need be, this classical blowup solution may  well be treated as a weak solution in some weighted Sobolev space.
With little or no change, this example can be modified to fit initial boundary value problems for the heat equation on the half-axis $\mathbb{R}_{+}=\{x\in\mathbb{R}\,\colon\, x>0\}$. Indeed, the initial boundary value problem
$$
\begin{cases}
u_t=u_{xx}\,\,,\quad x>0,\; t>0,\\
u|_{x=0}=0,\quad t\geqslant 0,\\
u|_{t=0}=xe^{x^2},\; x\geqslant 0,
\end{cases}
$$
with the first boundary condition does possess a unique classical solution
$$
u(x,t)=\frac{xe^{\frac{x^2}{1-4t}}}{(1-4t)^{3/2}}
$$
on $\,Q_{+}\!=\mathbb{R}_{+}\!\times [0,1/4)\,$. While for the initial boundary value problem
$$
\begin{cases}
u_t=u_{xx}\,\,,\quad x>0,\; t>0,\\
u_x|_{x=0}=0,\quad t\geqslant 0,\\
u|_{t=0}=e^{x^2},\; x\geqslant 0,
\end{cases}
$$
with the second boundary condition, its unique classical solution on $\,Q_{+}\!=\mathbb{R}_{+}\!\times [0,1/4)\,$ coincides with that of the Cauchy problem:
$$
u(x,t)=\frac{e^{\frac{x^2}{1-4t}}}{\sqrt{1-4t}}\,.
$$
As to the third boundary condition,
constructing a somewhat similar blowup example for the heat equation might prove a good question on math.stackexchange.com .


text:
Q: я немогу нормально вивести переменную shop, тоесть я пишу в консоле: shop а мне висвечивает типа токое: >>>(тут ничего не пишет) помогите ^-^ введите сюда код
print("начнем игру! =D")
#переменные >:E
#деньги $_$
money = 'деньги'
bmoney = 10
#усталость :(
sleep = 'спать'
fatigue = 100
#еда >:D
eat = 'кушать'
hungry = 100
food = 5
#места /\
work = 'работа'
shop = 'магазин'
home = 'Дом'
#взаимодействие с днем ) >>> *
nday = 'след день'
#код
print("money - заробатевать деньги, sleep - спать, eat - кушать, shop - пойти в магазин")
#вибрать взаимодействие >:|
actition = input("Выбрать взаимодействие: ")
#умови (выбрать взаимодействие (магазин))
if actition == shop:
    print("напишите \'home\' чтоб отпрввится домой!")
    print("Ви в магазині")
    print("купить кушать \'bfood\'")
    buy = input("Вибрать взаимодействие")
    if buy == home:
        print("Вы дома")
        actition = input("Выбрать взаимодействие: ")
    if buy == bfood:
        print("ви купили їжу \'їжа + 5, гроші - 5\'")
        money = bmoney - 5
        food = food + 5

вот что у меня виходит (ЕТО УЖЕ В КОНСОЛИ):
введите сюда код
================= RESTART: C:/Users/Service/Desktop/lifegame.py ================
начнем игру! =D
money - заробатевать деньги, sleep - спать, eat - кушать, shop - пойти в магазин
Выбрать взаимодействие: shop
>>>
>>> shop
'магазин'
>>>

A:
Выбрать взаимодействие: shop

А вводить надо магазин. И пользоваться отладчиком.


text:
Q: C# Math Round -11.5 to 11 and round -11.6 to 12 I am testing an application with Selenium and C#. This application performs the following rounding (which I think are javascript rounding standards):

*

*-11.51 rounds to -12

*-11.5 gets rounded towards zero, so it goes to -11

*11.5 rounds up to 12

This is based on required specifications, so I have to calculate numbers and round myself to come at this end result you see above. I have to use C# libraries to round them. Using AwayFromZero for the positive numbers works, but I cant seem to find a valid solution to round my negative numbers.
For instance, using AwayFromZero, ToEven, or Floor for negatives, I get:

*

*-11.51 to -12

*-11.5 to -12

Using Ceiling and Truncate, I get:

*

*-11.51 to -11

*-11.5 to -11

In Summary, I need an algorithm or some way to be able to round towards zero when my number is -.5 or above, or -10.5 or above, for instance. I also need this same algorithm for rounding -10.51 to -11

A: What about this?
public static double MyRound( double x )
{
    return Math.Floor( x + 0.5 );
}

This seems to satisfy all your test cases.


text:
Q: Forces on us on a rotating Earth So the earth is constantly rotating but it doesn't need a force to rotate. It'll rotate indefinitely.(?) But we and other masses on earth need a force on us to continue rotating along with earth? And if earth rotated a lot faster then we would notice it because we would not be planted to same place on earth?

A: The Earth doesn't need a force to make it continue to rotate- quite the opposite: it will continue to rotate unless a force is applied to stop it.
In fact the Earth's rotation about its axis will eventually slow to a halt as a consequence of its interaction with the Moon, but that will take billions of years.
The force that keeps us planted to the ground and moving with the Earth is gravity. If the Earth spun much faster, then not only would we float off, but the Earth itself would break up as gravity would no longer be sufficient to provide the centripetal force to hold its constituent parts together.

A: Assuming the earth has no external torque applied to it then the earth would rotate indefinitely. This is the conservation of angular momentum at play.
We stay on the earth's surface because we also have angular momentum, angular momentum such that our angular velocity matches that of the earth. If we didn't we would feel a drag force due to the mismatch of our velocity and the surface of the earth's velocity.
Gravity is the radial force that keeps us in this circular motion co-moving with the earth's surface. In fact, the gravity we experience is more than required to keep us on this trajectory.
Consider the forces acting on a person standing on the equator of the earth. There is a balance between the gravitational force and the normal reaction force (the ground pushing us back up due to electrostatic repulsion).
$$m \ddot{r}=N-mg$$
For the person to stay rotating around the earth with the earths angular velocity $\omega$, we have the centripetal motion equation
$$m\ddot{r} = -m\omega^2r$$
Substituting this into our first expression we find
$$N=mg - m\omega^2r$$
This is important since when we say we feel gravity, we are really talking about the normal reaction force, which is the force we feel on our body when we stand still. In the case of the earths rotation, this effect is small, $N \approx mg$.
If the earth were to rotate faster, we see the value of $N$ would decrease. As $\omega^2 \rightarrow \frac{g}{r}$ the observer c0-moving with the earth's surface would experience a smaller and smaller 'effective gravity' (which is just a consequence of being in a non-inertial frame) until experiencing almost weightlessness.
Aside:
It's worth noting, one; that is effect depends on your latitude. As we move towards the north/south pole, the distance from the observer to the axis of rotation, $r$, gets smaller and smaller, until at the poles $r=0$ and so $N=mg$. Again for our case, this effect is small but if the earth were the rotate much faster then this would be important.
Second; the earth is a large dynamical mass of rock that isn't perfectly spherical, thus the moon's gravity can pull on different parts of the earth with slightly different strengths (due to the earth's mass distribution) + the tides form by the moon's orbit can generate large frictional forces on the earth. This results in a net torque on the earth which does slow down the earth's rotation. In fact, the earth's orbital time period 1 billion years ago was roughly only 18 hours. We approximate it as rotating at a constant angular velocity since the time scales involved with problems we care about are much less than the time required for the earth's angular velocity to significantly slow down.


text:
Q: load an array from external file in angularjs it's my first time here on stack and I hope someone can help me because I'm stuck!
I have a script made in AngularJS that creates multiples icons extracting the data from a simple array. Every icon is associated to a youtube video.
The array and the function is simple:
app.controller('videolist', function ($scope, $http) {
$scope.videos = ['q_664lrmyGE','q_664lrmyGE','dWuEVSCw8B8','3Wm3G8s8bxk','_ppuCZR8Mkw','9gN_cmK9TUc','s7lVGhTPQAY','_rNmmHXEdTc','blr-qDffIq0','_70M4lkLKPk','wjB9JtTU7SU','BGh1xc-O0WA','uxEBK9q686c','ToO-tS-X2U4','AKrmrbCTNxc'];

$scope.icon = [];
  // add youtube videos
  for (i=0; i<$scope.videos.length; i++) {
    $scope.icon.push({id: $scope.videos[i], thumb: 'mqdefault'});

  }
});

Now I would like to load the array from an external JSON file.
I've tried in any way possible, but didn't work.
How I can do it? And how should the JSON file be composed?
In every example I've see there are at least two or three values that makes one record, or a pair made with "label":"value".
Thank you so much!!

A: An array alone is not valid JSON so you'll have to embed the array inside of a parent JSON object like so:
var videos = {'videoArray':['q_664lrmyGE','q_664lrmyGE','dWuEVSCw8B8',...]}

And then you'd access the array by referencing videos.videoArray

A: JSon Format
Disperse is right with the composition of the json format ( $scope.videos = {'keyToArray':['foo','bar','baz',]} ). Also, while I am somewhat new as well, I think disperse has a point using just var instead of $scope. because you don't need it to be in scope if you are just creating a variable and then crunching it later down in your function.
Load data from file
Judging by your unused $http service, I think you may be asking about how to get the data from a .json file you have stored? For that, do something along the following:
$http.get("video.json").then(function (response) {
    $scope.videos = response.data;
});

Hope this helps!


text:
Q: Whats wrong with my code in the fragment? I have the following code for my CategoryFragment class:
public class CategoryFragment extends Fragment {

    View myFragment;

    public static CategoryFragment newInstance(){
        CategoryFragment categoryFragment = new CategoryFragment();
        return categoryFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_category,container,false);

    }
}

In the part where (R.layout.fragment_category) is, it says that it cannot resolve symbol R.

A: You need to import the R.java to your class to use the layout id of R.layout.fragment_category. Import the R class with something like this:
import com.your.project.R;
Change the com.your.project to your package name.
The package name must be the same with the package name in your AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.your.project">

    ...

</manifest>

If after adding the R class the problem still persist, then there probably an error in your resource files. You need to check the layout, drawable, values, etc in your resources directory.


text:
Q: IBM worklight - How to use 2 JSONStore collections in the applications How can I initialize and use two JSONStore collections simultaneously?
One collection for general collections without password,
And another collection protected with a password?

A: You can have multiple stores with different collections. You would enable password protection, or not, for the store using the WL.JSONStore.init function. Each store can be encrypted with different password protection. See JSONstore Multiple User Support and JSONstore Security.


text:
Q: Sum of Stirling numbers of second kind $S(n,k)$ over $n$ I want to evaluate the sum:
$$E(a,n) = \sum_{i=a}^n S(i,a)$$
with $S(n,k)$ denoting the Stirling numbers of the second kind.
My problem is that as $n$ gets bigger this calculation gets quite computationally-expensive with either using the recursive definition
$$S(n+1,k) = kS(n,k)+S(n, k-1)$$
or the explicit formula
$$S(n,k)=\frac{1}{k!} \sum_{j=0}^k (-1)^{k-j} {k \choose j} j^n$$
for $S$.
So my question arises: is there a closed-form expression for $E$? If not, are there some sorts of other improvements to reduce the computational complexity of this sum?

A: For fixed $a$ the function $S(i, a)$ is a sum of various powers, so the partial sum over $i$ can be computed with a termwise sum of geometric series. That is, we have
$$E(n, a) = \sum_{i=a}^n \frac{1}{a!} \sum_{j=0}^a (-1)^{a-j} {a \choose j} j^i$$
(I am switching $a$ and $n$ in the input for $E$ to maintain consistency with $a$ being on the right for the Stirling numbers) and exchanging the order of the sum, as well as removing the $\frac{1}{a!}$, gives
$$E(n, a) = \frac{1}{a!} \sum_{j=0}^a  (-1)^{a-j} {a \choose j} \sum_{i=a}^n j^i.$$
The sum $\sum_{i=a}^n j^i$ is a geometric series $\frac{j^{n+1} - j^a}{j - 1}$, so this gives
$$E(n, a) = \frac{1}{a!} \sum_{j=0}^a (-1)^{a-j} {a \choose j} \frac{j^{n+1} - j^a}{j - 1}.$$
For fixed $a$ most of this expression doesn't depend on $n$ and so can be precomputed (I don't know if that's the case in your application though), and then we only need to compute the powers $j^{n+1}$. If you're working mod a prime this can be done very efficiently using binary exponentiation and Fermat's little theorem.
Furthermore it sounds like in your application the prime is bigger than $a$, which allows us to make use of the observation that we can cancel the $a!$ factor from the binomial coefficients:
$$E(n, a) = \sum_{j=0}^a (-1)^{a-j} \frac{1}{j! (a - j)!} \frac{j^{n+1} - j^a}{j - 1}.$$
(The point being that we can compute $j! (a - j)! \bmod p$ and then invert it, without needing to keep track of a potentially large denominator that eventually cancels.) This should be a big save overall; we no longer have to perform any operation $n$ times.
Formally, to compute $j^{n+1} \bmod p$ we first reduce the exponent $\bmod (p-1)$; I'm not familiar with fast algorithms for dividing with remainder so I don't know how long this takes but probably not very long. This gives us a new exponent $m < p-1$ and then binary exponentiation will let us compute $j^m \bmod p$ in about $O(\log m) \le O(\log p)$ steps, and since $p = 10^9 + 7$ here this is not only constant but a pretty small constant!
Similar improvements are probably not available for the binomial coefficients / factorials but we still only have to do about $O(a)$ multiplications and we can work recursively and so forth, and computing inverses $\bmod p$ can be done efficiently using the Euclidean algorithm.


text:
Q: How to Get rowID in rowattr block of jqgrid? I am having jqgrid this way,

    $(function () {
    var blueArray = [];
        for (var i=1;i<=4000;i++) {
          blueArray.push(i);
        }
    var greenArray = [];
        for (var i=4000;i<=6000;i++) {
          greenArray.push(i);
        }

    var redArray = [];
        for (var i=6000;i<=8000;i++) {
          redArray.push(i);
        }
    var yellowArray = [];
        for (var i=8000;i<=10000;i++) {
          yellowArray.push(i);
        }

    "use strict";
        var getGridData = function(n) {
                var data = [], i;
                for (i = 0; i < n; i++) {
                    data.push({
                        id: (i + 1)*10,
                        aa: "aa" + i,      // colunn 1
                        bb: "bb" + (i%3),  // colunn 2
                        cc: "cc" + (i%5),  // colunn 3
                        dd: "dd" + (i%7),  // colunn 4
                        ee: "ee" + (i%11), // colunn 5
                        ff: "ff" + (i%13), // colunn 6
                        gg: "gg" + (i%17), // colunn 7
                        hh: "hh" + (i%19), // colunn 8
                        ii: "ii" + (i%23), // colunn 9
                        jj: "jj" + (i%29), // colunn 10
                        kk: "kk" + (i%31), // colunn 11
                        ll: "ll" + (i%37), // colunn 12
                        mm: "mm" + (i%41)  // colunn 13
                    });
                }
                return data;
            },
            $grid = $("#list"),
            gridData,
            startTime,
            measureTime = false,
            timeInterval;

        gridData = getGridData(10000);
        startTime = new Date();
        $grid.jqGrid({
            data: gridData,
            colModel: [
                { name: "aa", label: "c01" },
                { name: "bb", label: "c02" },
                { name: "cc", label: "c03" },
                { name: "dd", label: "c04" },
                { name: "ee", label: "c05" },
                { name: "ff", label: "c06" },
                { name: "gg", label: "c07" },
                { name: "hh", label: "c08" },
                { name: "ii", label: "c09" },
                { name: "jj", label: "c10" },
                { name: "kk", label: "c11" },
                { name: "ll", label: "c12" },
                { name: "mm", label: "c13" }
            ],
            cmTemplate: { width: 100, autoResizable: true },
            iconSet: "fontAwesome",
            rowNum: 10000,
            rownumWidth: 40,
            //rowList: [20, 100, 1000, 10000, "100000:All"],
            viewrecords: true,
            rownumbers: true,
            //toppager: true,
            //pager: true,
            shrinkToFit: false,
            rowattr: function (rd) {
            var rowIds = $("#list").jqGrid('getDataIDs');
            console.log(rowIds);
if(blueArray.indexOf(rowIds) > -1)
            return {"class": "blue"}
           else if(greenArray.indexOf(rowIds) > -1)
            return {"class": "green"}
            else if(redArray.indexOf(rowIds) > -1)
            return {"class": "yellow"}
            else
            return {"class": "one"}
                },
            loadComplete: function () {
                closeDialogLoading();
                if (measureTime) {
                    setTimeout(function () {
                        alert("Total loading time: " + timeInterval + "ms");
                    }, 50);
                    measureTime = false;
                }
            },
            autoencode: true,
            caption: "Shows the performance of resizing. Make double-click on the column resizer"
        }).jqGrid("gridResize");

        timeInterval = new Date() - startTime;
        setTimeout(function () {
            alert("Total time: " + timeInterval + "ms");
        }, 50);

        function openDialogLoading(){
            $("#dialogLoading").css("display", "");
        }

        function closeDialogLoading(){
            $("#dialogLoading").hide();
        }
    });

css:
.one { background:red; }
.blue { background:blue; }
.green { background:green; }
.yellow { background:yellow; }

I am trying to chaNge the row color of the jqgrid comparing each rowid with an array of values.
Here is the logic for that,
    rowattr: function (rd) {
            var rowIds = $("#list").jqGrid('getDataIDs');
            console.log(rowIds);
if(blueArray.indexOf(rowIds) > -1)
            return {"class": "blue"}
           else if(greenArray.indexOf(rowIds) > -1)
            return {"class": "green"}
            else if(redArray.indexOf(rowIds) > -1)
            return {"class": "yellow"}
            else
            return {"class": "one"}

the problem here is, rowIds  are getting as empty []. so always my condition i going to else and red color is shown on each row's.
I need to check if rowid is exists in blueArray,greenArray  e.t.c  if its is true paint that row with the corresponding color.
In my example my bluearray has values from 1 to 4000. So all these records from 1 to 4000 have to be painted in blue.
My logic inside rowattr: block is not working as i am getting rowid as empty[].
How to get rowid inside rowattr: function (rd) {}  block of jqrid?
The above logic working is fine in loadcomplete and gridcomplete events but it is blocking entire ui and taking hell lot of time to load grid.
Can anyone help me in this issue?
Thanks

A: You need just use rd.id inside of rowattr:
rowattr: function (rd) {
    if (blueArray.indexOf(rd.id) > -1) {
        return {"class": "blue"};
    } else if (greenArray.indexOf(rd.id) > -1) {
        return {"class": "green"};
    } else if (redArray.indexOf(rd.id) > -1) {
        return {"class": "red"};
    } else {
        return {"class": "one"};
    }
}

the demo uses the code, but it's really slowly because you create 13x10000 cells in the grid. I recommend to open the demo only in Chrome where it takes still about 15 sec.
I strictly recommend to use local paging. Look at almost the same demo where the page size is 25 instead of absolute unneeded 10000. It works really quickly. One can jump on the page 200 or 300 to see another colors.


text:
Q: Windows appear behind the panel When opening new windows in my Ubuntu 11.04 sometimes they are hidden behind the panel. I can grab them while pressing Alt+Button 1 but I would like to solve it so that they appear where they should.
The machine where this is happening is an upgraded one and I have seen in several new installations that this is not the expected behaviour.
You can see it in the following link:

A: I had the same problem in Ubuntu 12.04 with GNOME. Indeed it could be fixed with compiz:
enable "Place Windows" in Category/Windows Management.

A: I had this too on a machine that was all the way upgraded from Intrepid and the problem did not appear for a dummy new user I created for investigation purposes. This is how I solved it:
I logged out of unity, switched to a virtual terminal hitting AltF1, logged in as root, killed all remaining processes from my usual login with killall -u <login>, did a cd /home/<login> and a mv .gconf .gconf-old. When logging back in, the issue had disappeared with a lot of others for the price of losing some configurations which I considered a bargain.
After some diffing .gconf with .gconf-old with meld, I reached at the conclusion that some pre-natty compiz settings were the most probable cause, but your mileage may vary.

A: First, install compizconfig-settings-manager
sudo apt install compizconfig-settings-manager

Then search compizconfig-settings-manager from search panel

Now scroll down to the opened to the compizconfig window and go to the Window Management

Enable Place Windows


text:
Q: Please some one help me to remove that error module not found error I don't know what i missed up, i come across this error, after spending log time using django. I set up everything but this error is showing.
i create the project using django-admin startproject, and also for the app django-admin startapp..
i put the app in INSTALL_APPS,  and register it in my urls
Below are the images of how i configure it
[settings.py[urls.pyerror](https://i.stack.imgur.com/XEHP8.png)](https://i.stack.imgur.com/Fb8B5.png)


text:
Q: How do I stop flask to convert a list containing data in json format into json again? I am building a flask application that reads a SAS dataset from  a remote linux server and returns response in json format. I am executing the following sas command using paramiko ssh_client to read the sas data into json format. Basically in the sas_command, I am using "PROC JSON" that coverts sas dataset into json output. I am redirecting the output of "PROC JSON" into STDOUT and then reading it into python list.
My question is why do I see the "\" in my final output. Looks like Flask converts the  output of sas_command which is already in json format, into json format one more time . How do i get rid of the additional characters in my final output. Any help will be highly appreciated.
from paramiko import SSHClient, AutoAddPolicy

sas_command =  "sas94_u8 -STDIO <<<\"OPTIONS NOFMTERR; PROC JSON OUT = STDOUT pretty; EXPORT '" + dir_name + "/" + file_name + "'; WRITE OPEN OBJECT; WRITE CLOSE; run;\" 2>/mydev/null"

stdin, stdout, stderr = client.exec_command(sas_command)
result = []
out = stdout.readlines()
result1 = list(map(lambda x: x.strip("\n"), out))
return result1

My final flask response is in this format:
[
    "{",
    "  \"SASJSONExport\": \"1.0 PRETTY\",",
    "  \"SASTableData+dataset\": [",
    "    {",
    "      \"varseq\": 1,",
    "      \"sasname\": \"ADSNAME\",",
    "      \"scope\": \"G\",",
    "      \"notuse\": \"\",",
    "      \"type\": \"C\",",
    "      \"label\": \"Dataset Name\",",
    "      \"lbl_ana1\": \"\",",
    "      \"lbl_ana2\": \"\",",
    "      \"outform\": \"8.\",",
    "      \"codlst\": \"X_NM\",",
    "      \"methtyp\": \"derived\",",
    "      \"deri_way\": 1,",
    "      \"method\": \"=%_some_method\",",
    "      \"vartype\": \"\",",
    "      \"var_link\": \"\",",
    "      \"adslcore\": \"\",",
    "      \"deri_txt\": \"Name of the data set.\",",
    "      \"comment\": \"\",",
    "      \"core\": \"Req\",",
    "      \"adamnote\": \"\",",
    "      \"mand\": \"M\",",
    "      \"source\": \"C\",",
    "      \"status\": \"A\",",
    "      \"ret_reas\": \"\",",
    "      \"cor_reas\": \"\"",
    "    },",
    "    {",
    "      \"varseq\": 2,",
    "      \"sasname\": \"SID\",",
    "      \"scope\": \"G\",",
    "      \"notuse\": \"\",",


text:
Q: MongoEngine schemata - name error I have the following schema in a file called model.py
from mongoengine import *

class Subject(Document):
    uri = StringField(required=True)
    resources = ListField(ReferenceField(ResourceSubject))

class ResourceSubject(Document):
    subject = ReferenceField(Subject,reverse_delete_rule=CASCADE)
    resource = ReferenceField(Resource)

class Resource(EmbeddedDocument):
    uri = StringField()
    title = StringField()
    snippet = StringField()
    image = StringField()
    source = StringField()
    adapter = StringField()

For some reason when I try to initialize a Subject, subj = Subject(uri="hello").save() I am getting a name error : NameError: name 'ResourceSubject' is not defined.
I cant understand the reason, I guess this is related to the framework? I tried separating the classes in individual files and then importing, but I still get the same error. What am I missing ?
The error is thrown on this line: resources = ListField(ReferenceField(ResourceSubject))

A: Put ResourceSubject into quotes:
resources = ListField(ReferenceField('ResourceSubject'))


text:
Q: Python 2.5 convert string to binary I know this is easily possible in python 2.6.  But what is the easiest way to do this in Python 2.5?
x = "This is my string"
b = to_bytes(x)  # I could do this easily in 2.7 using bin/ord 3+ could use b"my string"
print b

Any suggestions?   I want to take the x and turn it into

00100010010101000110100001101001011100110010000001101001011100110010000001101101011110010010000001110011011101000111001001101001011011100110011100100010

A: This one-line works:
>>> ''.join(['%08d'%int(bin(ord(i))[2:]) for i in 'This is my string'])
'0101010001101000011010010111001100100000011010010111001100100000011011010111100100100000011100110111010001110010011010010110111001100111'

EDIT
You can write bin() yourself
def bin(x):
    if x==0:
        return '0'
    else:
        return (bin(x/2)+str(x%2)).lstrip('0') or '0'

A: I think you could do it in a cleaner way like this:
>>>''.join(format(ord(c), '08b') for c in 'This is my string')
'0101010001101000011010010111001100100000011010010111001100100000011011010111100100100000011100110111010001110010011010010110111001100111'

the format function will represent the character in a 8 digits, binary representation.


text:
Q: Highstock graph color changes on each redraw I am using highstock with ajax call to update data on each zoom. During each zoom the chart data is updated via API call. On each redraw the line color gets changed randomly. How can I avoid this?
Zoom 1

Zoom 2

Please note that I am using angularjs.
JS:
var afterSetExtremes = function(e) {
    if (!firstTimeLoad) {
        var fromDate = moment(Math.round(e.min)).format();
        var toDate = moment(Math.round(e.max)).format();
        var dataToSend = {
            graph: selectedChannels,
            fromDate: fromDate,
            toDate: toDate
        };
        //API call
        graphService.create({}, {}, dataToSend, {}).then(function(response) {
            if (response.status) {
                var hasData = false;
                response.data.records.map(function(op) {
                    if (op.data.length) {
                        hasData = true;
                    }
                });
                if (hasData) {
                    graphData = response.data;
                    // Updating chart series data
                    chartConfig.series = graphData.records;
                } else {
                    notify.error('No data found');
                }
            } else {
                notify.error('No data found');
            }
        }, function(reason) {
            notify.error('Application encountered some issues, please try again.');
        });
    }
    firstTimeLoad = false;

};

var chartConfig = {

    options: {
        chart: {
            renderTo: 'container',
            type: 'spline',
            zoomType: 'x'
        },
        legend: {
            enabled: true
        },
        xAxis: {
            events: {
                afterSetExtremes: afterSetExtremes
            }
        },
        yAxis: {
            floor: 0,
            labels: {
                format: '{value} ' + data.unit
            }
        },
        rangeSelector: {
            buttons: [{
                type: 'day',
                count: 1,
                text: '1d'
            }, {
                type: 'day',
                count: 7,
                text: '7d'
            }, {
                type: 'month',
                count: 1,
                text: '1m'
            }, {
                type: 'year',
                count: 1,
                text: '1y'
            }, {
                type: 'all',
                text: 'All'
            }],
            buttonTheme: {
                fill: 'none',
                stroke: 'none',
                'stroke-width': 0,
                r: 8,
                style: {
                    color: '#039',
                    fontWeight: 'bold'
                },
                states: {
                    hover: {},
                    select: {
                        fill: '#039',
                        style: {
                            color: 'white'
                        }
                    }
                }
            },
            // inputEnabled: true, // it supports only days
            selected: 4 // all
        },
        navigator: {
            enabled: true,
            adaptToUpdatedData: false,
            series: {
                includeInCSVExport: false
            }
        },
        plotOptions: {
            series: {
                animation: {
                    complete: function() {
                        $(window).resize(function() {
                            resizeToCover();
                        });
                        $(window).trigger('resize');
                        $('#chart1').css('display', 'block');

                    }
                }
            }
        },
        scrollbar: {
            liveRedraw: false
        }
    },
    series: graphData.records,
    title: {
        text: 'Graph'
    },
    loading: false,
    useHighStocks: true
};


text:
Q: Is sys.exit equivalent to raise SystemExit? According to the documentation on sys.exit and SystemExit, it seems that
def sys.exit(return_value=None):  # or return_value=0
    raise SystemExit(return_value)

is that correct or does sys.exit do something else before?

A: According to Python/sysmodule.c, raising SystemExit is all it does.
static PyObject *
sys_exit(PyObject *self, PyObject *args)
{
    PyObject *exit_code = 0;
    if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
        return NULL;
    /* Raise SystemExit so callers may catch it or clean up. */
    PyErr_SetObject(PyExc_SystemExit, exit_code);
    return NULL;
}

A: As you can see at source code https://github.com/python-git/python/blob/715a6e5035bb21ac49382772076ec4c630d6e960/Python/sysmodule.c
static PyObject *
sys_exit(PyObject *self, PyObject *args)
{
    PyObject *exit_code = 0;
    if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
        return NULL;
    /* Raise SystemExit so callers may catch it or clean up. */
    PyErr_SetObject(PyExc_SystemExit, exit_code);
    return NULL;
}

it's only raise SystemExit and doesn't do anything else

A: Yes, raising SystemExit and calling sys.exit are functionally equivalent. See sys module source.
The PyErr_SetObject function is how CPython implements the raising of a Python exception.


text:
Q: Why is Objective-C considered a simple language? I have heard it said that Objective-C is a 'simple' language, i.e. in terms of its language features. It's really the only language that I know but I did a bit of Java before and, in terms of language features, they seem to be pretty close.
I have never touched C++. Are there more features to C++ compared with Objective-C and if so, is it an advantage to work with this extra feature set?

A: I've never heard of Objective-C described as a 'simple language'; on the contrary, some of the language features of Objective-C – such as dynamic binding, categories and introspection – make it a rather powerful language.
However there are a few reasons why it could be seen to be a language that is less feature-rich than others, including:

*

*There was no garbage collection (generally speaking) until Apple's Objective-C 2.0, before which memory was managed largely by reference-counting; this is different to languages such as Java which use garbage collection for all memory management.

*There are no namespaces in Objective-C; again this is unlike other languages out there such as C++. Convention is that classes and functions should be prefixed, as can be seen in Foundation, AppKit etc which are prefixed with NS-. This can sometimes be a disadvantage.

*There are no true abstract classes. In Objective-C, abstract classes are only abstract by design, and can still be instantiated as-is, and won't generate compiler warnings or errors.

*There is no operator-overloading. This is due to the nature of the Objective-C runtime and how method dispatch works. Instead, methods that take different argument types must be named differently; this may not necessarily be a disadvantage, as it can often improve clarity of code.

However despite all of this, Objective-C has some rather useful features, some of which are directly or indirectly the result of the lack of certain features that other languages may have, such as:

*

*Using descriptive names (due to no operator overloading) often clarifies code and allows it to be self-documenting in many circumstances.

*Categories are useful for extending classes that you do not have direct access to.

*Dynamic dispatch means you can add, change or remove methods at will, and provides powerful introspection of classes.


text:
Q: Add to cart Servlet - how it works <%@ page import="java.util.*,com.stakoverflow.bookstore.servlets.*"%>

Book Store

<%
List books=new ArrayList();
Book book=new Book();
book.setBid(101);
book.setBname("Learn java");
book.setAuthor("dsouza");
book.setCost(99.99);
book.setCat("Java");
book.setPub("india");
book.setIsbn("11-11");
books.add(book);

book= new Book();
book.setBid(102);
book.setBname("Learn JDBC");
book.setAuthor("bsk");
book.setCost(99.99);
book.setCat("Java");
book.setPub("india-pub");
book.setIsbn("11-11");
books.add(book);

book=new Book();
book.setBid(103);
book.setBname("Learn JSP");
book.setAuthor("pintu");
book.setCost(99.99);
book.setCat("Java");
book.setPub("newage");
book.setIsbn("11-11");
books.add(book);

book=new Book();
book.setBid(104);
book.setBname("Learn EJB");
book.setAuthor("Rj");
book.setCost(99.99);
book.setCat("Java");
book.setPub("tmh");
book.setIsbn("11-11");
books.add(book);

out.println("
");
%>

Book ID
Book Name
Author
Cost
Cat
Pub
ISBN

<%
Iterator it=books.iterator();
while(it.hasNext()){
    book=(Book)it.next();
%>

<%=book.getBid()%>
<%=book.getBname()%>
<%=book.getAuthor()%>
<%=book.getCost()%>
<%=book.getCat()%>
<%=book.getPub()%>
<%=book.getIsbn()%>

**
*<form action="addcart.jsp">
<input type="hidden" name="bname" value="<%=book.getBname() %>"/>
<input type="submit" value="Add To Cart"/>*
</form>**

<%
}
out.println("
");
%>
Place My Order
<form action="/Lab8/showcart.jsp">
<input type="submit" value="Show My Cart"/>
</form>

for the above jsp code,
i am creating an ArrayList object books and adding Book object to the array list
"/>
    *
when we click the add to cart button, how does value="<%=book.getBname() %> picks the corresponding book value for different books,
it should send same bookname always as per my understanding,

A: When you click the corresponding 'Add to cart' button next to the book, the form which the book is in is submitted to the addcart.jsp . In this jsp, you should be getting the book name using request.getParameter("bname") which is the hidden field containing the book name (this is submited using the form).
Thats how it works

A: Since you are iterating over books,it creates n forms assuming there are n books.
In each form,you are keeping a hidden field containing bookname.So once you click on "Add to Cart" button,only that form data is submitted to the addcart.jsp where you can access the bookname using request.getParameter("bname").
Just an example to make things more clear
any.jsp
  ....

              <%for(int i=1;i<5;i++){ %>
              <form method ="get" action="myServlet">
              <input type="hidden" name="bname" value="<%=i %>"/>
              <input type="submit" value="Add To Cart"/>
               </form>
               <%} %>

....

if you see source code of this page,it is
....

      <form method ="get" action="myServlet">
      <input type="hidden" name="bname" value="1"/>
      <input type="submit" value="Add To Cart"/>
       </form>

      <form method ="get" action="myServlet">
      <input type="hidden" name="bname" value="2"/>
      <input type="submit" value="Add To Cart"/>
       </form>

      <form method ="get" action="myServlet">
      <input type="hidden" name="bname" value="3"/>
      <input type="submit" value="Add To Cart"/>
       </form>

      <form method ="get" action="myServlet">
      <input type="hidden" name="bname" value="4"/>
      <input type="submit" value="Add To Cart"/>
       </form>

  ...

I hope you get the idea how it works.


text:
Q: Asp:Calendar always return default date instead of user selected one after button click I have an asp:Calendar like below:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
                     <ContentTemplate>
                        <asp:Calendar id="Calendar1" runat="server" AutoPostback="false" SelectionMode="Day" Font-Size="10pt" BorderColor="White" BackColor="White" OnSelectionChanged="DateChange_UploadAllowedFrom"
                                            Width="216px" ForeColor="Black" Font-Names="Verdana" Height="188px" BorderWidth="1px" NextPrevFormat="ShortMonth">
                                            <SelectedDayStyle Font-Bold="true" ForeColor="black" BackColor="#ffe9e9"></SelectedDayStyle>
                                            <OtherMonthDayStyle ForeColor="White"></OtherMonthDayStyle>
                                            <NextPrevStyle Font-Size="8pt" Font-Bold="True" ForeColor="#333333" VerticalAlign="Bottom"></NextPrevStyle>
                                            <DayHeaderStyle Font-Size="8pt" Font-Bold="True"></DayHeaderStyle>
                                            <TitleStyle Font-Size="10pt" Font-Bold="True" ForeColor="#333399"
                                                BackColor="#ffe9e9"></TitleStyle>
                        </asp:Calendar>
                    </ContentTemplate>
</asp:UpdatePanel>

The method in C# below works when a date is selected by user.
protected void DateChange_UploadAllowedFrom(object sender, EventArgs e)
        {
            hdnAllowedFrom.Value = Session["UploadAllowedFrom"].ToString();
        }

When I debug the code, I actually see the value of hiddenfield is set to the selected value.
When the button below is pressed right after:
<asp:HiddenField ID="hdnAllowedFrom" runat="server" Value="08/08/2018 12:00:00" />
<asp:Button ID="btnSaveChanges"  runat="server" Width="120px" Height="50px" Text="Save Dates" OnClientClick="return false;"/>

The value of hiddenField is always coming as the default one: 08/08/2018 12:00:00
Please note that the page_load function is not working after I press the button, page is not being refreshed. I tried to use Session object, did not help. What might be the reason is it happening and how I can fix it? Any ideas would be appreciated.


text:
Q: Socket and Server Listening on the Same Port? I'd like both the socket and the server to listen on port 443. Problem is when I do it, I get a warning EADDRINUSE. Is there a workaround to make both socket and server listen on the same port?

A: i don't know what are you doing in ur code but make clear that only server is listening on any port and we have to bind express.js and socket.io on that server, means they all are on same port..
please go throw this code:
    var express=require('express');
    var app = express();
    var io = require('socket.io').listen(app);
    app.listen(8000)'


text:
Q: How to avoid GKSession disconnection in client-server when in background I've a problem working with GameKit and GKSession operations.
I'm trying to implement a GKSession client-server iOS app system (ServerApp, ClientApp) having this behavior:

*

*ServerApp creates a GKSession in GKSessionModeServer mode (Bluetooth only)

*ClientApp detects the server and connects to it

*Some data exchange between apps and stuff

Everything is going fine except when ServerApp or ClientApp instance goes to background.
If ServerApp goes to background, Client receives a GKPeerStateUnavailable event and i can't connect to it. What I need is to avoid this event: that means, find a way to keep ServerApp GKSession socket going even when app is in background.
Any help will be appreciated.

A: Perhaps you could keep the app running in the background by setting the info.plist flag to keep it alive like a music player?
This thread talks about this:
From Raaz


text: Q: Why can't my spotlight open any application? I can search and find anything on Spotlight, so I think my index works. However, when I try to open an application, even terminal, I just get a spinning beach ball until Spotlight disappears. Why am I having this problem?


text:
Q: Customize OS And Install I am having some doubts regarding the Android OS customization process.
I would like to replace/re-brand an existing OEM device with my own home, start up and lock screens. I don't have the source code for the current OS. How do I start customizing the OS?
Is it possible to back up from the device current OS and change the code install back?
After customizing is it possible to flash the OS back to the device, with my own manufacturer certificates?
Is it requires rooting? If so after installing new OS is it possible to unroot the device, so that i can deliver the devices to the end users?
After installing custom OS, on device factory reset the stock OS or the customized OS will get restored?
Thanks in advance


text:
Q: Unable to connect to SQL Server from one machine; "an existing connection was forcably closed by the remote host" Connecting to the SQL Server (2008 R2 SP3 - KB 4057113) with SSMS version 18 yields:
A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - An existing connection was forcibly closed by the remote host.) (.Net SqlClient Data Provider)

For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft%20SQL%20Server&EvtSrc=MSSQLServer&EvtID=10054&LinkId=20476

Error Number: 10054
Severity: 20
State: 0
Connection failure logging is enabled on the server but nothing gets logged. Please note the for help link is dead. I've tried various database applications. Nothing gets through. The problem appears to be on the server, not the workstation, but other workstations can connect to the server. This workstation can also connect to other servers.
I've got a good guess this is somehow TLS related, because that's what it was last time (server didn't support TLS 1.2 and needed a patch). This time I can't find the problem though.

A: Found the problem. SQL Server 2008 R2 really wants to use a cert signed with SHA1. If SHA1 certs are disabled, you can't connect.
The master dev db needs to be at the oldest version supported by the vendor. Windows had disabled SHA-1 over https in a different way than just turning off RSA/SHA1 crypto algorithm so it turns out that leaving it enabled isn't unsafe (for our purposes).


text:
Q: Angular 4/5 getting route id from JSON I am new at Angular so I need your help. I am trying to get an ID for every user I click on from my data.json list of users. So I have my list of users, and when I click on any one of them it opens a new page with router, witch works fine, and I can get a ID of that user, but I can't access his name, age and other informations to show on screen, just ID.
component
user: any[];

constructor(
private route: ActivatedRoute,
private usersService: UsersService) {

let id = this.route.snapshot.paramMap.get('id');
if(id) this.usersService.getUsers(id).subscribe(user => this.user = user);}

The thing is that I don't have getUsers(id) function in my service, because I don't know how to get ID from json data file. And I need your help to make that function.
data.json
[
 {
  "id": 1,
  "firstName": "Paul",
  "surname": "Crowe",
  "age": 28,
  "gender": "male",
  "friends": [
    2
  ]
 },
 {
 "id": 2,
  "firstName": "Rob",
  "surname": "Fitz",
  "age": 23,
  "gender": "male",
  "friends": [
    1,
    3
  ]
 } ...
]

Service
 getUsers() {
 return this.http.get('./assets/data.json').map(array => array);
 }

This getUsers is not good I think for taking ID. So I need help with that.
Thanks in advance!

A: I imagine you want something like:
user: any;

constructor(
private route: ActivatedRoute,
private usersService: UsersService) {
 let id = this.route.snapshot.paramMap.get('id');
    if(id) this.usersService.getUsers().subscribe(users =>
              this.user = users.getById(id);}
 }

private getUserById(userId: number){
     return this.users.filter(u=>u.id===userId);
 }

A: Use this.id
if(this.id){
 this.usersService.getUsers(this.id).subscribe(user => this.user = user);}
}

EDIT

var users = [
 {
  "id": 1,
  "firstName": "Paul",
  "surname": "Crowe",
  "age": 28,
  "gender": "male",
  "friends": [
    2
  ]
 },
 {
 "id": 2,
  "firstName": "Rob",
  "surname": "Fitz",
  "age": 23,
  "gender": "male",
  "friends": [
    1,
    3
  ]
 }
];

const user = users.find(t=>t.id ==1);
console.log(user);


text:
Q: Extract Data from a Dynamically Changing Pivot Table Using VBA I have a pivot table set up in this fashion:
:
I want to group all Nodes and put each version under each group of Nodes:

The Versions are not constant but it is a sorted list and new Nodes could show up in this list or disappear from the pivot table.
My current thinking is to use a loop to extract the values and compare previous node to current node. But how would I know what the first item to compare would be? If there is a better method, please let me know.

A: Closing page... I realize I could just set the very first item in a variable.


text:
Q: Making recursive call, tail recursive I have the following recursive function
trait SequenceGenerator[T] {
  def program(l: List[T])(implicit rule: ProductionRule[T]): List[T] = {
    l.flatMap(rule.generate)
  }

  def sequenceNumber(seed: List[T], number: Int)(implicit rule: ProductionRule[T]): List[T] = {
    number match {
      case 1 => program(seed)
      case a => program(sequenceNumber(seed, a - 1))
    }
  }
}

I can't think of a way to make sequenceNumber tail recursive.

A: The idea behind transforming methods to tailrec is to put every next calculation step into accumulator and then pass this accumulator back to the method, so that on next step you could return your accumulator or call this method again with new accumulator modified according to your step.
So you will get something like this:
trait SequenceGenerator[T] {

  def program(l: List[T])(implicit rule: ProductionRule[T]): List[T] = l.flatMap(rule.generate)

  def sequenceNumber(seed: List[T], number: Int)(implicit rule: ProductionRule[T]): List[T] = {

    @tailrec
    def tailRec(number: Int, acc: List[T]): List[T] =  number match {
      case 1 => acc
      case a => tailRec(a-1,program(acc))
    }

    tailRec(number,program(seed))

  }

}

But just FYI there is also more advanced technique for building tail recursions called Trampoling. It can be implemented using scala.util.control.TailCalls for example.
I'm not very good in this technique but it will look something like this:
import TailCalls._

trait SequenceGenerator[T] {

  def program(l: TailRec[List[T]])(implicit rule: ProductionRule[T]):TailRec[List[T]] = {
    l.map(_.flatMap(rule.generate))
  }

  def sequenceNumber(seed: TailRec[List[T]], number: TailRec[Int])(implicit rule: ProductionRule[T]): TailRec[List[T]] = {
    number flatMap {
      case 1 => tailcall(program(seed))
      case a => tailcall(program(sequenceNumber(seed, done(a - 1))))
    }
  }

}

sequenceNumber can't be marked as tailrec here but it actually tailrec in "background". To get real calculation result you will need to call sequenceNumber(done(...),done(...)).result

A: Perhaps the posted code is an over-simplification, but it looks like you don't actually need program(), or recursion for that matter.
program(seed) is really just seed.flatMap(rule.generate) and so the recursion rolls out to seed.flatMap(rule.generate).flatMap(rule.generate).flatMap(... etc., which is what iterate() will do for you.
def sequenceNumber(seed:List[T], number:Int)(implicit rule:ProductionRule[T]):List[T] =
  Seq.iterate(seed.flatMap(rule.generate), number)(_.flatMap(rule.generate)).last


text:
Q: Error in INSERT INTO while creating TIMESTAMP from DD-MM-YY HH.MM.SS input UPDATE: With a more articulate example.
there are create queries mentioned in below link written in MySQL syntax, can you create them the similar way in postgres wrt timestamp values:
https://www.techbeamers.com/sql-query-questions-answers-for-practice/
You would notice all the timestamp values of WORKER table in this link are in format DD-MM-YY HH.MM.SS and not DD-MM-YY HH:MM:SS
What I've tried
While creating a table using Mysql
I could do below using DATETIME:
 CREATE TABLE Worker (
    WORKER_ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    FIRST_NAME CHAR(25),
    LAST_NAME CHAR(25),
    SALARY INT(15),
    JOINING_DATE DATETIME,
    DEPARTMENT CHAR(25)
);

    INSERT INTO Worker
        (WORKER_ID, FIRST_NAME, LAST_NAME, SALARY, JOINING_DATE, DEPARTMENT)
        VALUES
        (001, 'Monika', 'Arora', 100000, '14-02-20 09.00.00', 'HR')

This returns no error in MYSQL
However, when I use TIMESTAMP (counterpart) in Postgres:
   CREATE TABLE Worker(
    WORKER_ID SERIAL PRIMARY KEY,
    FIRST_NAME VARCHAR(250) NOT NULL,
    LAST_NAME VARCHAR(250),
    SALARY INT,
    JOINING_DATE TIMESTAMP,
    DEPARTMENT VARCHAR(15)
);

INSERT INTO Worker
        (WORKER_ID, FIRST_NAME, LAST_NAME, SALARY, JOINING_DATE, DEPARTMENT)
        VALUES
        (001, 'Monika', 'Arora', 100000, '14-02-20 09.00.00', 'HR')

I get an error: Incorrect timestamp syntax
So for now, I am using below logic
I create JOINING_DATE VARCHAR(20), i.e. create joining date in varchar,
then alter the table:
CREATE TABLE Worker(
WORKER_ID SERIAL PRIMARY KEY,
FIRST_NAME VARCHAR(250) NOT NULL,
LAST_NAME VARCHAR(250),
SALARY INT,
JOINING_DATE VARCHAR(250),
DEPARTMENT VARCHAR(15)
);

    INSERT INTO Worker
            (WORKER_ID, FIRST_NAME, LAST_NAME, SALARY, JOINING_DATE, DEPARTMENT)
            VALUES
            (001, 'Monika', 'Arora', 100000, '14-02-20 09.00.00', 'HR'),
            (002, 'Niharika', 'Verma', 80000, '14-06-11 09.00.00', 'Admin'),
            (003, 'Vishal', 'Singhal', 300000, '14-02-20 09.00.00', 'HR'),
            (004, 'Amitabh', 'Singh', 500000, '14-02-20 09.00.00', 'Admin'),
            (005, 'Vivek', 'Bhati', 500000, '14-06-11 09.00.00', 'Admin'),
            (006, 'Vipul', 'Diwan', 200000, '14-06-11 09.00.00', 'Account'),
            (007, 'Satish', 'Kumar', 75000, '14-01-20 09.00.00', 'Account'),
            (008, 'Geetika', 'Chauhan', 90000, '14-04-11 09.00.00', 'Admin');

    ALTER TABLE worker
      ALTER COLUMN joining_date
       TYPE TIMESTAMP WITH TIME ZONE
         USING to_timestamp(joining_date, 'DD-MM-YYYY HH24:MI:SS');

Is there a better way to do this just like in SQL, can't postgres SQL read '14-02-20 09.00.00' without errors?


text:
Q: Appending a block of javascript to the DOM fails in production - but not in dev I have an ASP.NET website. Very huge!
The latest addition I've made, everything is JavaScript/AJAX enabled.
I send HTML and JavaScript code back from the server to the client, and the client will inject the HTML into a DIV - and inject the JavaScript into the DOM using this:
$('<script type="text/javascript">' + script + '</sc' + 'ript>').appendTo(document);

or this:
var js = document.createElement("script");
js.setAttribute("type", "text/javascript");
js.text = script;
document.appendChild(js);

On my own dev machine, the injected javascript is accessible and I'm able to execute injected JavaScript functions.
When I deploy to my test environment, )we have an internal domain name such as www.testenv.com) I get JavaScript errors.
I've tried to isolate the problem into a small page, where I inject alert("sfdfdf"); at the bottom of the page, and that works fine.
Is there any policy settings that prohibits this?

A: Don't appendChild to 'document'; <script> can't go there and you should get a HIERARCHY_REQUEST_ERR DOMException according to the DOM Level 1 Core spec. The only element that can go in the Document object's child list is the single root documentElement, <html>.
Instead append the script to an element inside the document, such as the <body>.

A: Dynamically creating  elements should work fine, the script will be executed upon insertion into the DOM. To answer your question specifically, there are no direct policy settings that prohibit script injection, however, if you're using ajax calls within the dynamically inserted script you could run into Cross-Domain restrictions.
If you could post the error, and maybe the source of the 'script' element you're inserting it would help to debug the problem :)


text:
Q: Cannot delete from view without exactly one key-preserved table workaround I have a table x_visa. I want to delete the duplicate columns from this table.
The query I am using for this is :
  select * from   (SELECT x_visa.*,
                ROW_NUMBER() over (partition by effective_start_date, effective_end_date, person_id,
                   business_group_id, legislation_code , current_visa_permit, visa_permit_type, visa_permit_id, configuration_id
               order by person_id) AS rn
        from   x_visa) T
WHERE  rn > 1 );

The delete statement is giving an error :ORA-01752: cannot delete from view without exactly one key-preserved table
delete from
(select * from   (SELECT x_visa.*,
                ROW_NUMBER() over (partition by effective_start_date, effective_end_date, person_id,
                   business_group_id, legislation_code , current_visa_permit, visa_permit_type, visa_permit_id, configuration_id
               order by person_id) AS rn
        from   x_visa) T
WHERE  rn = 1 );

Is there a workaround to delete the duplicate data from this table ?

A: Each row has rowid identifier. So you can delete where rowid in results of your query.
delete from x_visa where rowid in (/*YOUR QUERY*/);

So we have:
delete from x_visa where rowid in (select r from   (SELECT x_visa.rowid r, x_visa.*,
                ROW_NUMBER() over (partition by effective_start_date, effective_end_date, person_id,
                   business_group_id, legislation_code , current_visa_permit, visa_permit_type, visa_permit_id, configuration_id
               order by person_id) AS rn
        from   x_visa) T
WHERE  rn > 1 ))


text:
Q: how do i edit the PATH variable to include a variable I have a shell script in place and have been using an independent ssh agent to login into various machines and the do the required. Now, the problem is that I have been trying to add this script to the cron job but it does not work for some reason. I think this has something to do with the PATH variable and including the independent ssh agent as a part of that variable and exporting it in the .bash_profile
This is what my .bash_profile looks like:
PATH=$PATH:usr/local/bin/rssh

export PATH

And my script has the following path at the top:
#!/bin/bash

What am i Missing over here to declare this independent variable and get it working using a cron job.
Thanks in advance.

A: You have a typo, instead of using
PATH=$PATH:usr/local/bin/rssh

try :
PATH=$PATH:/usr/local/bin

Missing /
and you can't add the full command path but just the dir where reside the command.
Last thing, add
source ~/.bash_profile

in your script to ensure the script will look-up the new PATH.


text:
Q: allow user to edit student info from a binary file in Java I am working on a school project. It basically allows the user to create a Student using scanner, assigns and id to the student and then writes the data into a binary file called studentsinfo.dat. Once the student has been created the user can either display the info from the binary file or edit student. I got the displaying part working. However, I am having trouble to allow them to edit, the program asks the user to enter the student id to edit, the program should check if the user input exists in the file but I am having problem been able to move the file pointer so it looks for the id and compare it with the user input, I have tried some stuff but not working. Any ideas would be appreciated, here is my code:
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.io.*;
public class MidTermProject {

    static AtomicInteger idGenerator = new AtomicInteger(0001);
    static int id;

    public static int getId() {
        return id;
    }
    ///Create Student method
    public static void CreateStudent() throws IOException {
        String FullName;
        String address;
        String city;
        String state;
        String newStudentID;

        Scanner keyboard = new Scanner(System.in);

        FileOutputStream fstream =
                new FileOutputStream("StudentInfo.dat", true);
        DataOutputStream outputFile =
                new DataOutputStream(fstream);

        System.out.print("\nPlease enter your information bellow.\n" + "\nFull Name: ");
        FullName = keyboard.nextLine();
        outputFile.writeUTF(FullName);

        System.out.print("Address: ");
        address = keyboard.nextLine();
        outputFile.writeUTF(address);

        System.out.print("City: ");
        city = keyboard.nextLine();
        outputFile.writeUTF(city);

        System.out.print("State: ");
        state = keyboard.nextLine();
        outputFile.writeUTF(state);

        id = idGenerator.getAndIncrement();
        String student = Integer.toString(getId());
        outputFile.writeUTF(student);

        outputFile.close();

        System.out.print("\nDone\n");

    }
    ///Edit Student method
    public static void EditStudent() throws IOException {
        String editName;
        String editaddress;
        String editCity;
        String editState;
        int editID;

        Scanner keyboard = new Scanner(System.in);

        System.out.print("Enter the ID of the student you would like to edit: ");
        editID = keyboard.nextInt();

        RandomAccessFile file =
            new RandomAccessFile("StudentInfo.dat", "rw");
        file.seek(10);

        char ch = file.readChar();

        if(editID == ch) {
            System.out.print("\nPlease enter NEW information bellow.\n" + "\nFull Name: ");
            editName = keyboard.nextLine();
            file.writeUTF(editName);

            System.out.print("Address: ");
            editaddress = keyboard.nextLine();
            file.writeUTF(editaddress);

            System.out.print("City: ");
            editCity = keyboard.nextLine();
            file.writeUTF(editCity);

            System.out.print("State: ");
            editState = keyboard.nextLine();
            file.writeUTF(editState);

            file.close();

            System.out.print("Successfully Edited");
        } else {
            System.out.print("error");
        }
    }
    ///Display Student method
    public static void DisplayStudent() throws IOException {
        FileInputStream fstream = new FileInputStream("StudentInfo.dat");
        DataInputStream inputFile = new DataInputStream(fstream);

        String student;
        boolean endOfFile = false;

        while(!endOfFile)
        {
            try
            {
                student = inputFile.readUTF();
                System.out.print(student + "\n");
            }
            catch (EOFException e)
            {
                endOfFile = true;
            }
        }
        System.out.println("\nDone");

        inputFile.close();
    }

A: From what I understand you are trying to enter the students' records line by line, so when you edit you will seek for that line and edit it there, is that right? If so you would at least need to separate the records when you are storing them e.g. by adding a \n at the end of the line to then write the next record on a new line and then you should be able to update the records on a certain line based on the id. You could implement the toString() method of Student class and just write once to the file - student1.toString() which on the inside will combine all the data into one string.
Additionally, you are writing the student data strings on top of each other so as a result, you will get JohnDoeAddressCity which will be then hard to parse back to a Student instance. Consider dividing the value e.g. with a comma - "Name Surname, Address, City".


text:
Q: Solutions to ODE with singularities which are removable conditional on specific starting values I want to understand the solutions to ODE with removable discontinuities (conditional on specific starting values). For example, I have the function $y(x)$ defined by:
\begin{align*}
\sin(x) = \sin(2 y)  \text{ for } x \in [0, \pi], y \in [0, 1/2 \pi].
\end{align*}
It gives me the following differential equation:
\begin{align*}
y'(x) = \frac{\sin'(x)}{2 \sin'(2y(x))},  \quad y(0) = 0;
\end{align*}
where $\sin'(x) = \cos(x)$. There is a singularity at $y=\pi/2$. However, on the optimal path starting from $y(0)=0$, this singularity will be removable. Indeed, on $[0, \pi/2[$, we find that $y^*(x)= x/2$. Thus:
\begin{align*}
lim_{x\rightarrow\pi/2} \ y'(x) = \frac{\cos(\pi/2)}{2\cos(\pi/2) } = 1/2.
\end{align*}
This is not exactly a "removable singular point", but conditional on being on this specific path, with this specific starting value, the discontinuity is not a discontinuity anymore. Is there a name for this?
Now, it seems there are two solutions to this equation (maybe I'm wrong and there are more?):
\begin{align*}
y_1(x) = x/2 \text{ for } x \in [0, \pi]
\end{align*}
or:
\begin{align*}
y_2(x) = \left\{
    \begin{array}{ll}
        x/2 & \mbox{for } x \in [0, \pi/2] \\
        \pi/2-x/2 & \mbox{for } x \in [\pi/2, \pi]. \\
    \end{array}
\right.
\end{align*}
In other words, once you reach the singularity, you can either go backwards, or upwards. But I found these solutions naturally by thinking, not with equations/maths.
Moreover, I don't know how to prove that these are the only two solutions, and I'd like to prove it.
I think this property holds more generally, even in higher dimension, i.e. if I have isolated singular points, if I reach a singularity that is removable given the optimal path, I still have two (in 2D case, more in higher dimensions) solutions/directions that I can choose (at least locally) for the solution.
How can I prove this? Is there any known results?
It is particularly important because it would imply that there exists a unique strictly increasing solution to these kind of problems.


text:
Q: How to modify default properties in Maven extension I want to write a maven plugin (extension) which implements lifecycles for javascript projects so projects with a pom.xml like this can be compiled:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org
  <modelVersion>4.0.0</modelVersion>

  <groupId>de.ailis.maven.javascript</groupId>
  <artifactId>demo</artifactId>
  <version>1.0.0-SNAPSHOT</version>

  <name>Maven JavaScript Demo Project</name>
  <packaging>javascript</packaging>

  <build>
    <plugins>
      <plugin>
        <groupId>de.ailis.maven.plugins</groupId>
        <artifactId>maven-javascript-plugin</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <extensions>true</extensions>
      </plugin>
    </plugins>
  </build>

</project>

I already successfully created a plugin with a components.xmlfile which defines the lifecycles so I can call my own Mojos during the various phases. But there are some phases for which the default mojos are adequate as long as I can change some default values. For example I want to specify a custom outputDirectory to the Maven Resources Plugin so JavaScript resources are copied to target/classes/script-resources instead of target/classes. Can this be done in the plugin without copying the whole ResourcesMojo class and changing the default value of the property there?

A: Mojo:
public class MyMojo extends AbstractMojo
{
    private String foo; //filePath

    public void execute()
        throws MojoExecutionException
    {
        ...
        writeFile(foo)
        ...
    }
}

pom.xml
<plugin>

    <groupId>de.ailis.maven.plugins</groupId>

    <artifactId>maven-javascript-plugin</artifactId>

    <version>1.0.0-SNAPSHOT</version>

    <configuration>

        <foo>script-resources</foo>

    </configuration>

</plugin>


text:
Q: Dense matrix for 3D-shaped objects I am fairly new to Breeze library. I am trying to convert a 3D Array of shape (2,1,40) to a dense matrix but I am not sure if I am doing it the right way.
My requirement is:
A matrix with 2 rows, 1 column and each of the two rows should have 0.0 values (40 times)
import breeze.linalg._

val matrix = new DenseMatrix[Float](shape(0), shape(1), Array.fill(shape(2))(0.0f))

A: If you are looking for direct support for higher-order tensors, bad luck. David Hall already stated that they would require a lot of work to implement properly which makes perfect sense. They are very math intensive.
With that said you can still make a 2 by 1 DenseMatrix of DenseVectors and manipulate the values of those vectors. 2 by 1 matrix is basically a vector so here's example with 2 by 2 and "40 zeroes" vectors
val matrix = DenseMatrix(
  (DenseVector.zeros[Double](40), DenseVector.zeros[Double](40)),
  (DenseVector.zeros[Double](40), DenseVector.zeros[Double](40))
)

matrix(0,0)(0) = 1.0

println( matrix(0,0) )

I must say that this approach is not recommended due to complex nature of computations on such data structure. If you are working with points in 3D space I would rather go for either a matrix or distributed dataset of vectors.


text:
Q: const value in for loop I have seen code like,
Approach 1
for(int i = 0; i < 200; ++i) {
    do_some_stuff(i);
}

Approach 2
const int max_limit = 200;
for(int i = 0; i < max_limit; ++i) {
    do_some_stuff(i);
}

Is there any advantage for Approach 2 over Approach 1?

A: It's generally good practice to replace an integer constant by something with a meaningful name, so I'd say that's the main advantage of the second one. However, if the code is really simple than the extra line may just make it one more line to parse.
That said, if you are replacing something like this:
for(int i = 0; i < something.size(); ++i) {
    do_some_stuff(i);
}

with
const int something_sz = something.size();
for(int i = 0; i < something_sz; ++i) {
    do_some_stuff(i);
}

then there is the added benefit that it makes it obvious to the reader, as well as the compiler, that something.size() isn't changed by the call to do_some_stuff(i).

A: Use of magic numbers, such as 200 in your example, anywhere in your code is cause for concern. It makes the code harder to understand and maintain.
Approach 2 is better if the variable is appropriately named. max_limit has no more meaning than 200. However, if you use max_number_of_books, it is a lot more meaningful than 200.

A: For me, approach 2 is better, when you define a const like const int max_num_of_students it looks more meaningful and someone reading to that code, can easily understand what is going on.
Another advantage of using such const in loops is that if you are printing names of students more than one time, you don't need to change the condition in your loop every time the count of students gets increased. Go to your variable and change it to new student count.

A: Approach 2 is better as per my opinion.

*

*Readability is enhanced.
For example:
int currentPortNo=getPortNo();
const int inputPort=80;

if(currentPortNo == inputPort){
//Get input from port
}

when compared to:
int currentPortNo=getPortNo();

if(currentPortNo == 80){
//Get input from port
}

*Maintainability is enhanced since if we want inputPort should be initialized(changed) with 81 instead of 80 due to new requirements/limitations we can simply use:
const int inputPort=81;

instead of changing all the occasion wherever the value 80 is used in entire program.

*Also, if you need to pass a pointer around the program.

*Can have the scoping and typing properties

A: We should avoid to using the magic number anytime when wrote codes. Because if you use the number 200 only, maybe others cannot understand your codes' intention well. But when you use const int max_limit = 200;, we can understand the number 200's meanings. Especially when your codes was very complex, you must write it with the second way.

A: 2nd Approach is better as by this you can also get the value from the user:
cin>>max_limit;


text:
Q: non-smooth and noisy curve in addplot The output is attached. One can see the curve is noisy and nonsmooth. Where must modify?
\documentclass[a4paper]{article}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=1.8}
\begin{document}

\begin{tikzpicture}[scale=1.0]
\begin{axis}[%
    ,axis line style = thick
    ,domain=0:1
    ,samples=300
    ,axis lines=middle
    ,enlargelimits=true
    ,xtick={0,1}
    ,ytick={-0.01,0.01},
    ]
    \addplot[smooth,thick, color = black] {exp(2*x)-1.0012-1.9380*x-2.4808*x^2-0.0782*x^3-1.8891*x^4};

\end{axis}
\end{tikzpicture}

\end{document}


text:
Q: Post and retrieve MySQL data from PHP into html with request First of all I want to note that I am very new with HTML and PHP, JS and web design at all, but I have to learn and create registration form for my personal page, and should find out with proper approach and possible method.
I have index.php with user login and registration forms. Inside <!DOCTYPE html> ...  login form includes input type="text" and type="password":

  <form action="login.php" method="post" id="logform">

        Username:

        <input type="text" id="yuser" name="username" placeholder="Username.." required>

        Password:

        <input type="password" id="ypass" name="password" placeholder="Password.." required>

      <input type="submit" value="Login" id="logBtn">

  </form>

sends name="username" to PHP with action="login.php" in <Form>, which was separate login.php code document used this way from index.html. Now it is included to index.php just as it was separately, without any edit:
<?php
require 'connect.php';

$Username = mysqli_real_escape_string($con, $_POST['username']);
$Password = mysqli_real_escape_string($con, md5($_POST["password"]));

  $SQL = "INSERT INTO registration (username, password) VALUES ('$Username', '$Password')";
  if (!mysqli_query($con, $SQL))
  {
      echo 'Not Inserted';
  }
  else
  {
     echo 'Inserted';
  }
?>

How to pass inserted name="username" and name="password" to $_POST['username'] and $_POST['password'] in same index.php page with press on <input type="submit" value="Login" id="logBtn"> and avoid processing of this code with index.php page loading automatically.
Any guide, explanation or advice would be very helpful

A: just check for if the submitted value is present . then run the query.
<?php
require 'connect.php';

if( isset( $_POST['username'] ) && isset( $_POST['password'] )  ){

$Username = mysqli_real_escape_string($con, $_POST['username']);
$Password = mysqli_real_escape_string($con, md5($_POST["password"]));

  $SQL = "INSERT INTO registration (username, password) VALUES ('$Username', '$Password')";
  if (!mysqli_query($con, $SQL))
  {
      echo 'Not Inserted';
  }
  else
  {
     echo 'Inserted';
  }
}

?>

A: You can use AJAX to achieve this.
HTML:

          Username:

          <input type="text" id="yuser" name="username" placeholder="Username.." required>

          Password:

          <input type="password" id="ypass" name="password" placeholder="Password.." required>

        <input type="button" value="Login" id="logBtn">

AJAX:

Login.php:
require 'connect.php';
  if( isset($_POST['username']) && isset($_POST['password'])) {
    $uname = mysqli_real_escape_string($con, $_POST['username']);
    $pwd = mysqli_real_escape_string($con, md5($_POST["password"]));
    if($uname == '' || $pwd == '') {
      echo 'Please enter required information';
    } else {
      $query = "INSERT INTO registration (username, password) VALUES ('$uname', '$pwd')";
      if (!mysqli_query($con, $query))
      {
        echo $uname." cannot be registered! Please try again.";

      }
      else
      {
        // instead of msg you can return username like below:
        echo $uname." registered successfully!";
        // echo 'Inserted';
      }
    }
  } else {
    echo 'Something is wrong!';
  }


text:
Q: Can I import the node-postgres module (pg) or is it CommonJS only? I have been writing most of my APIs in old-school JavaScript using const var = require('var'). I am now writing my first API in ES6 syntax including using import rather than require. I always use the node-postgres module const {Pool} = require('pg') but when I try to write this as import {Pool} from 'pg' I get the error
SyntaxError: The requested module 'pg' does not provide an export named 'Pool'.
Similarly, import Pool from 'pg' gives me
TypeError: Pool is not a constructor
Is there a way to import this as an ES6 module or do I need to find another package for my ES6 postgres connections? I couldn't find any examples online of people using node-postgres with imports.

A: This should handle that I think.
import * as pg from 'pg'
const { Pool } = pg