text:
Q: Ambiguous output using super() function I am trying to get the output of below python code containing super() function.
class A(object):
    def go(self):
        print("go A go!")
    def stop(self):
        print("stop A stop!")
    def pause(self):
        raise Exception("Not Implemented")

class B(A):
    def go(self):
        super(B, self).go()
        print("go B go!")

class C(A):
    def go(self):
        super(C, self).go()
        print("go C go!")
    def stop(self):
        super(C, self).stop()
        print("stop C stop!")

class D(B,C):
    def go(self):
        super(D, self).go()
        print("go D go!")
    def stop(self):
        super(D, self).stop()
        print("stop D stop!")
    def pause(self):
        print("wait D wait!")
class E(B,C): pass

a = A()
b = B()
c = C()
d = D()
e = E()

#Find output of below function calls
d.go()
b.stop()

My questions are:

*

*Why the output of d.go() is:
go A go!
go C go!
go B go!
go D go!

Shouldn't there be one extra "go A go!" in output as class B and C both is calling method go of base class A using super() function?

*As there is no stop() function in Class B, then why b.stop() is returning "stop A stop!" rather than raising an error?

A: super in Python does not give you a "straight line" result with all ancestors in each subclass, in order.
Rather, it is really well thought to "do the right thing" when it comes to multiple inheritance - and a fundamental piece of the "right thing" is exactly avoiding a method in one of the superclasses to be called more than once.
So, to start with, whenever you create a class in Python, that class gains a __mro__ attribute (method resolution order). The first class there is always the class itself, and the last is always object .
super() will search the classes in the order they appear in the __mro__ in order to retrieve an attribute, method, or a superclass attribute or method. This is the documente describing the MRO linearization algorithm, that started to beused with Python 2.3 and is in use up to today  .
You will find out that under these rules, your MRO for the class D is (D, B, C,A, object) that is -  if the original invocation of a method was in a D object, when super is encountered in the method's implementation in B it will call C implementation, because C is the next class in D's __mro__. The document linked above has the rationale for that and more examples, but TL;DR: this ensures that each upstream class has the chance to be called at least and at most once, if all methods involved use super in a collaborative way.
As for

As there is no stop() function in Class B, then why b.stop() is
  returning "stop A stop!" rather than raising an error?

That is basic inheritance that does not need one to understand the specifics of Python's super: a superclass method is used if it is not overriden in the subclass.


text:
Q: SQL Server - Concatenate all child IDs into delimited string in parent record I've a question about a hierarchical (adjacency model) SQL Server table. This link Get child records on one column shows how to populate a parent field with a concatenated list of all child records. So the "Children" column in my table becomes:
ID ParentID Name   Children
1  NULL     Root   2,3
2  1        L2-1   4
3  1        L2-3   NULL
4  2        L3-4   6
5  3        L3-5   NULL
6  4        L4-6   NULL

Could someone advise how I could do this for multiple levels i.e. all descendants, not just the immediate children?
i.e. I'd like the table to be:
ID ParentID Name   Children
1  NULL     Root   2,3,4,5,6
2  1        L2-1   4,6
3  1        L2-3   5
4  2        L3-4   6
5  3        L3-5   NULL
6  4        L4-6   NULL

Thanks!

A: You can use the query below. I assumed your table name is Children.
It first builds a list of parents up to the top (first query). Then it puts all separate branches together (second query).
WITH temp (ID, ParentID, ChildrenChain)
AS
(
    SELECT ID, ParentID, CAST('' AS VARCHAR(100))
    FROM children
    WHERE NOT EXISTS (SELECT * FROM children cc WHERE cc.ParentID = children.ID)

    UNION ALL

    SELECT children.ID, children.ParentID, CAST((temp.ChildrenChain + ',' + CAST(temp.ID AS VARCHAR(100))) AS VARCHAR(100))
    FROM children
    INNER JOIN temp ON children.ID = temp.ParentID
)

SELECT DISTINCT ID,
    REPLACE(
        STUFF(
           (SELECT
                ',' + t2.ChildrenChain
                FROM temp t2
                WHERE temp.ID=t2.ID
                ORDER BY t2.ChildrenChain
                FOR XML PATH(''), TYPE
           ).value('.','varchar(max)')
           ,1,2, ''
        ),
    ',,', ',') AS ChildValues
FROM temp
WHERE LEN(ChildrenChain) > 0

Let me know if that doesn't work for you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Will Java code be terminated in the middle if server is down suddenly Let say i have a java function with 1000 lines of codes and it is deployed on the weblogic.
Will there be a chance that code is running & terminated at line X of 1000 lines if the PC or Weblogic is shutdown suddenly (i.e force shutdown)?
If yes, is there any possible way to "run" the rest of the code (from X+1 to 1000) when the server is resumed.
Thanks.

A:
Will there be a chance that code is running & terminated at line X of 1000 lines if the PC or Weblogic is shutdown suddenly (i.e force shutdown)?

Yes.

If yes, is there any possible way to "run" the rest of the code (from X+1 to 1000) when the server is resumed.

You would have to implement such a mechanism, and it would then need to "reset" to some point before X and then resume the transaction. Although, your implementation could be a Rabbit MQ topic with durable messages. The more typical configuration (in my experience) involves running multiple Weblogic servers in a cluster, and failing over to another member of that cluster in this scenario (and in combination with durable queues).

A: Whatever your code is doing, it could be interrupted at any time by an external failure.  The JRE itself is stateless; there is no automatic way to resume at a certain point.  The code itself must be designed to be 'restartable'.  That is, it must save state to some external, durable service. If this code is modifying external resources (calling web service, databases, ...) it must also somehow synchronize its saved state with the external resource on restart.
RabbitMQ can help with some of the aspects -- it's a guaranteed delivery message bus.  It can insure that messages to external resource will be delivered.  It could also synchronize between multiple running instances of your code, if you wanted a distributed, cluster-aware application, which is difficult to do.


text:
Q: Test whether the sum of two coefficients is significantly different that zero in indicator regression I am using indicator regression with an interaction term to compare the slopes to two groups.
Here is the form of the equation:
$Y = \beta_0 + \beta_1 X_1 + \beta_2 X_2 + + \beta_3 X_1 X_2$
$X_2 $ is my dummy variable (1 or 0).
Based on how I set up the regression:
When $X_2 = 0$, then the $slope_0 = \beta_1 $.
When $X_2 = 1$, then the $slope_1 = \beta_1 + \beta_3 $.
What I would like to determine is whether there is a test to determine whether $slope_1$ is significantly different than zero? I know I can split the dataset into two (based on the dummy variable) and regress separately to determine whether $slope_1$ is significantly different than zero, but could I could determine this without the separate regression?  Is there a test for this in R?


text:
Q: Creating a view in PostGIS - Having issue with view keeping my query I'm trying to make a view from a table without a geometry column.  My first issue is when I click on "New View" and then put the query in and click 'OK'.  The query statement is replaced with some other statement for the view.  It doesn't give me an error.  Is there a permission issue when you create a view?  I'm using pgAdmin III. Database version 9.6.
Update.  I saw that everything stopped at the ";" in the query.  I removed the ; in the query and now it's giving me a syntax error.

Here is the query that I want in the view.
SELECT j.speed, j.level, j.length, j.delay, j.city, j.street, j.line,
j.pub_utc_date at time zone 'utc' at time zone 'america/denver',j.id
from waze.jams j
ORDER BY j.pub_utc_date DESC
WITH
 lines AS(
 SELECT id,
       ST_MakeLine(
         ST_MakePoint(
           (line -> n ->> 'x')::NUMERIC,
           (line -> n ->> 'y')::NUMERIC
         )
       ) AS geom
FROM waze.wazejams
CROSS JOIN generate_series(0, jsonb_array_length(line)) AS n
GROUP BY id)

UPDATE waze.wazejams AS a
SET geom_line = ST_SetSRID(b.geom, 4326)
FROM lines AS b
WHERE a.id = b.id

A: You can't put an UPDATE statement in a VIEW. Views are for queries (SELECT statement).

A: It looks kinda messy...
You have a SELECT then a WITH ... AS SELECT plus and UPDATE statement in the mix. It won't process.

j.pub_utc_date at time zone 'utc' at time zone 'america/denver',j.id

And did you mean AS instead of at? You have time_zone column declared twice, no commas between columns.
https://www.postgresql.org/docs/9.6/static/sql-createview.html
Maybe you can create a view with just the lines and join them with the waze.jams, but I am not sure what is it you're trying to achieve exactly.
By the way a view is automatically updatabe if certain conditions are met (see link above), so if waze.wazejams is a table or a simple view your UPDATE statement should look like this:
UPDATE waze.wazejams AS a
SET geom_line = (SELECT ST_SetSRID(b.geom, 4326)
FROM lines AS b
WHERE a.id = b.id);


text:
Q: Runtime change in content of Label not resizes properly view when placed label inside a Frame? I have created a custom control in Xamarin.Forms for my demo application, in my control I used a custom template for my view, the template consists of Frame --> Grid --> Label whenever I changed the binding text to the labels, the view height should be resized, but it not works as excepted.
If I remove the frame it works fine and height resizes properly. It happens in android, iOS, and UWP.
To notify the size changes in the template, wired the templateView.Element.MeasureInvalidated event, it raised properly and resizing working fine for runtime changes if the frame is not included. If the frame included in my data template event is not raised.


text:
Q: C++ vector: should I copy or swap? I have a class  that has a vector member variable, which I fill up as follows:
class Foo {
vector<int> v;
void g() {
  vector<int> w;
  // fill w
  v = w;
}

};

My question: the temporary vector w can grow to be huge and I don't want to pay the price
of copy construction. Should I be using std::swap instead of copy here? My understanding
is that std::swap will be more efficient due to specialization for vector (where it
will just swap pointers to the heap).

A: Yes, you should swap here.  In C++11, you can also say v = std::move(w);.
Either way, the variable w is going out of scope immediately, so its contents don't matter, and you might as well transfer ownership instead of copying.


text:
Q: How to convert an InputStream to a DataHandler? I'm working on a java web application in which files will be stored in a database. Originally we retrieved files already in the DB by simply calling getBytes on our result set:
byte[] bytes = resultSet.getBytes(1);
...

This byte array was then converted into a DataHandler using the obvious constructor:
dataHandler=new DataHandler(bytes,"application/octet-stream");

This worked great until we started trying to store and retrieve larger files. Dumping the entire file contents into a byte array and then building a DataHandler out of that simply requires too much memory.
My immediate idea is to retrieve a stream of the data in the database with getBinaryStream and somehow convert that InputStream into a DataHandler in a memory-efficient way.  Unfortunately it doesn't seem like there's a direct way to convert an InputStream into a DataHandler. Another idea I've been playing with is reading chunks of data from the InputStream and writing them to the OutputStream of the DataHandler. But... I can't find a way to create an "empty" DataHandler that returns a non-null OutputStream when I call getOutputStream...
Has anyone done this? I'd appreciate any help you can give me or leads in the right direction.

A: Note that the getInputStream of the DataSource must return a new InputStream everytime called. This means, you need to copy somewhere 1st.
For more info, see
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4267294

A: An implementation of answer from "Kathy Van Stone":
At first create helper class, which create DataSource from InputStream:
public class InputStreamDataSource implements DataSource {
    private InputStream inputStream;

    public InputStreamDataSource(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return inputStream;
    }

    @Override
    public OutputStream getOutputStream() throws IOException {
        throw new UnsupportedOperationException("Not implemented");
    }

    @Override
    public String getContentType() {
        return "*/*";
    }

    @Override
    public String getName() {
        return "InputStreamDataSource";
    }
}

And then you can create DataHandler from InputStream:
DataHandler dataHandler = new DataHandler(new InputStreamDataSource(inputStream))

imports:
import javax.activation.DataSource;
import java.io.OutputStream;
import java.io.InputStream;

A: (bugs_)code doesn't works for me. I use DataSource to create Attachments to email (from objects that have inputStream and name) and content of attachments lost.
Looks like Stefan is right and new inputStream must be returned every time. At least in my specific case. Next implementation deals with problem:
public class InputStreamDataSource implements DataSource {

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    private final String name;

    public InputStreamDataSource(InputStream inputStream, String name) {
        this.name = name;
        try {
            int nRead;
            byte[] data = new byte[16384];
            while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }

            buffer.flush();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public String getContentType() {
        return new MimetypesFileTypeMap().getContentType(name);
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(buffer.toByteArray());
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public OutputStream getOutputStream() throws IOException {
        throw new IOException("Read-only data");
    }

}

A: I also ran into this issue. If your source data is a byte[] Axis already has a class that wraps the InputStream and creates a DataHandler object. Here is the code
//this constructor takes byte[] as input
ByteArrayDataSource rawData= new ByteArrayDataSource(resultSet.getBytes(1));
DataHandler data= new DataHandler(rawData);
yourObject.setData(data);

Related imports
import javax.activation.DataHandler;
import org.apache.axiom.attachments.ByteArrayDataSource;

Hope it helps!

A: My approach would be to write a custom class implementing DataSource that wraps your InputStream. Then create the DataHandler giving it the created DataSource.

A: I've meet situation, when InputStream requested from DataSource twice: using Logging Handler together with MTOM feature.
With this proxy stream solution my implementation works fine:
import org.apache.commons.io.input.CloseShieldInputStream;
import javax.activation.DataHandler;
import javax.activation.DataSource;
...

private static class InputStreamDataSource implements DataSource {
    private InputStream inputStream;

    @Override
    public InputStream getInputStream() throws IOException {
        return new CloseShieldInputStream(inputStream);
    }

    @Override
    public OutputStream getOutputStream() throws IOException {
        throw new UnsupportedOperationException("Not implemented");
    }

    @Override
    public String getContentType() {
        return "application/octet-stream";
    }

    @Override
    public String getName() {
        return "";
    }
}

A: Here is an answer for specifically working with the Spring Boot org.springframework.core.io.Resource object which is I think how a lot of us are getting here.  Note that you might need to modify the content type in the code below as I'm inserting a png file into an html formatted email.
Note:  As others have mentioned, merely attaching an InputStream isn't enough as it gets used multiple times, just mapping through to Resource.getInputStream() does the trick.
public class SpringResourceDataSource implements DataSource {
    private Resource resource;

    public SpringResourceDataSource(Resource resource) {
        this.resource = resource;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return resource.getInputStream();
    }

    @Override
    public OutputStream getOutputStream() throws IOException {
        throw new UnsupportedOperationException("Not implemented");
    }

    @Override
    public String getContentType() {
        return "image/png";
    }

    @Override
    public String getName() {
        return "SpringResourceDataSource";
    }
}

Usage of the class looks like this:
    PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
    Resource logoImage = pathMatchingResourcePatternResolver.getResource("/static/images/logo.png");
    MimeBodyPart logoBodyPart = new MimeBodyPart();
    DataSource logoFileDataSource = new SpringResourceDataSource(logoImage);

    logoBodyPart.setDataHandler(new DataHandler(logoFileDataSource));

A: import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import org.apache.commons.io.IOUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

.
 DataSource ds = new ByteArrayDataSource(convertHtmlToPdf("html here"), "application/pdf");

 DataHandler dataHandler = new DataHandler(ds);

.
public static byte[] convertHtmlToPdf(String htmlString) throws IOException, DocumentException {
    Document document = new Document();

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    PdfWriter writer = PdfWriter.getInstance(document, out);
    document.open();

    InputStream in = IOUtils.toInputStream(htmlString);
    XMLWorkerHelper.getInstance().parseXHtml(writer, document, in);
    document.close();

    return out.toByteArray();
}

possible error: the meta tag must be closed. <meta></meta>


text:
Q: Fix the WARNING: The target version of the .NET Framework in the project does not match the .NET Framework launch condition version C# Setup Project I received Warning in output console when deploying a project using Setup project in Visual studio 2019 and error as below. "WARNING: The target version of the .NET Framework in the project does not match the .NET Framework launch condition version '.NET Framework X.X.X'. Update the version of the .NET Framework launch condition to match the target version of the.NET Framework in the Advanced Compile Options Dialog Box (VB) or the Application Page (C#, F#)."
I search this warning in google and found solution by myself, I will share this with you step by step.

A: This error occurred Setup Project has higher .net framework version than Project. So warning can avoid by adding compatible .net framework for both projects.( Here i change version to 4.5.2)
There are 3 places this change need to add.

*

*Main Project(Properties(Right Click) > Application > Target Framework > Select version of desire Framework)

*Setup project(Properties(Right Click) > Prerequisites(Click) > Select version of desire Framework)

*Setup Project( Detected Dependencies > Microsoft .NET Framework(Double Click) > Properties > Select version of desire Framework)

Then build the project again. TADA warning message won't show again.


text: Q: Can you name multiplicative bivariate convex functions? can you please provide me as many bivariate functions $f(x,y)$ which are increasing both in $x$ and $y$ and are convex (result into concave isoquants)? I need them not to be additive between $x$ and $y$, e.g. $f(x,y) = x^2 + y^2$ does not work


text:
Q: JQuery in files loaded using JQuery tabs This is my first attempt to use JQuery tabs. I have a simple file that loads 3 other php files when the tabs are clicked.

Tab 1

Tab 2

Tab 3

The php files use JQuery also and are loaded correctly. When I test the files stand-alone, the JQuery parts work fine. But once they are loaded into the tabs, the JQuery doesn't work. Even a simple alert in the $(document).ready(function()...) in the loaded file doesn't show.Is there some conflict between the JQuery in the 2 files? Thanks for any help.

A: There is no conflict per se, but one of two things is happening:

*

*The browser is declining to execute the contents of


text:
Q: How to correctly model UI states with sealed classes in Compose? Say you have a simple screen that displays a list of items. I could define the 3 possible states of the screen like this:
 sealed class State() {
        data class Success(val items: List<Item> = listOf()): State()
        object Loading: State()
        data class Error(val error: String? = null): State()
    }

In my Compose UI, I treat the states accordingly:
when(state) {
    is State.Success -> {
        LazyColumn(...) {...}
    }
    is State.Error -> {
        Text(state.error ?: "")
    }
    is State.Loading -> {
        LoadingBar()
    }
}

The first state will be State.Loading() as I will initiate a network request to get the items.  When the items arrive, the state becomes State.Success().
But what if, afterwards, the user presses on a button that should trigger another network request?
On top of the existing content, I need to push the State.Loading class again to show the loading indicator while the new network request is finished.
Yet this state has no knowledge of the previous items content, so the UI will only show the loading indicator, and it will not render the content from the previous State.Success().
I could fix this by introducing a new State called: State.LoadingActionWhileSuccess yet this is not scalable.
How would you treat such situations? Adding other State classes could work, but it would become un-manageable after some point.
My biggest worry for this approach is when the screen complexity rises, the combination of possible states gets out of hand.
I could hold the state in a regular data class and mutate it, but I found that this approach can introduce illegal states for concurrent mutations.

A: Maybe don't allow the user to start another network call while one is underway by disabling buttons, etc.. Most of the apps I've seen do this. When you do a pull-to-refresh, the refresh icon always shows until the call has ended. This prevents you from making additional calls.
Then again, without knowing your use-case, I'm only making a general suggestion.


text:
Q: Flutter switch toggles off on its own I have created a flutter starter kit that allowes me to switch between themes in-app.
Now this works great but there is a small issue.
I have placed the switch button in the settings screen,
but when I go to another screen and then back to the settings screen
- it would seem that the switch button goes to Off mode on its own.
I'm attaching an image and my code on github so that you guys can see what I mean.

class ThemeSwitchState extends State {
  bool switchControl = false;

  Future<bool> darkMode() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    return sharedPreferences.getBool("isDark");
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<bool>(
      future: darkMode(),
      builder: (context, _snapshot) {
        return Transform.scale(
          scale: 1.5,
          child: Switch(
            value: _snapshot.data ?? false,
            onChanged: (value) {
              save(value);
              setState(() {

              });
            },
            activeColor: CustomColors().duskBlue,
            activeTrackColor: CustomColors().noroGrey,
            inactiveThumbColor: CustomColors().lureGrey,
            inactiveTrackColor: CustomColors().noroGrey,
          ),
        );
      },
    );
  }

  void save(bool value) async{
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    await sharedPreferences.setBool("isDark", value);
  }

  void toggleSwitch(bool value) {
    ThemeChanger _themeChanger =
        Provider.of<ThemeChanger>(context, listen: false);

    if (switchControl == false) {
      setState(() {
        switchControl = true;
      });
      print('Theme is Dark');

      _themeChanger.setTheme(CustomThemes.darkTheme.copyWith(
          textTheme:
              CustomThemes.darkTextTheme(CustomThemes.darkTheme.textTheme)));
    } else {
      setState(() {
        switchControl = false;
      });
      print('Theme is Light');

      _themeChanger.setTheme(CustomThemes.lightTheme.copyWith(
          textTheme:
              CustomThemes.lightTextTheme(CustomThemes.lightTheme.textTheme)));
    }
  }
}

A: You can use SharedPreferences from https://pub.dev/packages/shared_preferences
to save the last value of the CheckBox
I wrote an example
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Settings extends StatefulWidget {
  @override
  _SettingsState createState() => _SettingsState();
}

class _SettingsState extends State<Settings> {

  Future<bool> darkMode() async{
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    return sharedPreferences.getBool("isNight");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          children: <Widget>[
            Text("Night Mode"),
            FutureBuilder<bool>(
              future: darkMode(),
              builder: (context, _snapshot){
                return Checkbox(
                  value: _snapshot.data ?? false,
                  onChanged: (value){
                    save(value);
                    setState(() {
                       toggleSwitch(value);
                    });
                  },
                );
              },
            )
          ],
        ),
      ),
    );
  }

  void save(bool value) async{
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    await sharedPreferences.setBool("isNight", value);
  }
}

EDIT: WITH SWITCH
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Settings extends StatefulWidget {
  @override
  _SettingsState createState() => _SettingsState();
}

class _SettingsState extends State<Settings> {

  Future<bool> darkMode() async{
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    return sharedPreferences.getBool("isNight");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          children: <Widget>[
            Text("Night Mode"),
            FutureBuilder<bool>(
              future: darkMode(),
              builder: (context, _snapshot){
                return Switch(
                  value: _snapshot.data ?? false,
                  onChanged: (value){
                    save(value);
                    setState(() {

                    });
                  },
                );
              },
            )
          ],
        ),
      ),
    );
  }

  void save(bool value) async{
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    await sharedPreferences.setBool("isNight", value);
  }
}

UPDATE use value instead of switchControl

  void toggleSwitch(bool value) {
    ThemeChanger _themeChanger =
        Provider.of<ThemeChanger>(context, listen: false);

    if (value) {
      setState(() {
        switchControl = true;
      });
      print('Theme is Dark');

      _themeChanger.setTheme(CustomThemes.darkTheme.copyWith(
          textTheme:
              CustomThemes.darkTextTheme(CustomThemes.darkTheme.textTheme)));
    } else {
      setState(() {
        switchControl = false;
      });
      print('Theme is Light');

      _themeChanger.setTheme(CustomThemes.lightTheme.copyWith(
          textTheme:
              CustomThemes.lightTextTheme(CustomThemes.lightTheme.textTheme)));
    }
  }
}


text:
Q: How to model UNO as a POMDP I am trying to model UNO card game as Partially Observable Markov Decision Processes(POMDPs) . I did little bit of research, and came to conclusion that, the states will be the number of cards, the actions will be either to play or pick the card from unseen card deck. I am facing difficulty in formulating the state transition and observation model. I think, that observation model will depend on past actions and observation(History), but for that I need to relax Markov Assumption. I want to know that relaxing the Markov Assumption is better choice or not? Additionally, how exactly should I form the state and observation model.Thanks in advance.

A: I think in a POMDP the states should still be the "full truth" (position of all the cards) and the transitions are simply the rules of the game (including the strategy of the other players?!). The observations should certainly not depend on any history, only on the state, or else you're violating the Markov assumption. The point of a POMDP is that the agent can gain information about the current state by analyzing history. I'm not really sure if or how this applies to UNO, though. If you know which cards have been played and their order, can you still gain information by using the history? Probably not. Not sure, but maybe it does not make sense to think of this game as a POMDP, even if you use a solution that was designed for a POMDP.


text:
Q: sed command to replace all last lines with some new multi line strings after getting second pattern I want to write a program to change systems ip address from dhcp/static to static only. my original file's contents will be either this
some initial text

[ipv6]
method=auto

[ipv4]
method=static
dns=8.8.8.8;
addresses1=192.168.1.10;24;192.168.1.1;

or it may be like this,
some initial text

[ipv6]
method=auto

[ipv4]
method=auto

Now, i want to change after [ipv4] pattern, so that after editing my file should looks like this
some initial text

[ipv6]
method=auto

[ipv4]
method=static
dns=8.8.8.8;4.4.4.4;
addresses1=192.168.1.20;24;192.168.1.1;

A: Here's a Perl solution.  It sets the record delimiter to 2 newlines, so paragraphs are read.  If the paragraph contains [ipv4], replace the input with the replacement.  Replace data with the name of your file, or with "$@" and make it into a shell script.  Add -i as an option to Perl if you want to overwrite files (don't do that until you've tested it).
perl -pe '
my $replacement = qq"[ipv4]\n" .
                    "method=static\n" .
                    "dns=8.8.8.8;4.4.4.4;\n" .
                    "addresses1=192.168.1.20;24;192.168.1.1;\n\n";
$/ = "\n\n";
$_ = $replacement if (m/^\[ipv4\]$/m);' data

There are many alternative ways of writing that code; I make no claims other than "it works for me".
Given the text of your question as the input, the output is:
I want to write a program to change systems ip address from dhcp/static to static only. my original file's contents will be either this

some initial text

[ipv6]
method=auto

[ipv4]
method=static
dns=8.8.8.8;4.4.4.4;
addresses1=192.168.1.20;24;192.168.1.1;

or it may be like this,

some initial text

[ipv6]
method=auto

[ipv4]
method=static
dns=8.8.8.8;4.4.4.4;
addresses1=192.168.1.20;24;192.168.1.1;

Now, i want to change after [ipv4] pattern, so that after editing my file should looks like this

some initial text

[ipv6]
method=auto

[ipv4]
method=static
dns=8.8.8.8;4.4.4.4;
addresses1=192.168.1.20;24;192.168.1.1;


text:
Q: PHP displaying in browser SO i create the most basic php code possible:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>

<?php
echo "hello";
?>

</body>
</html>

I wrote this in notepad and saved it with a .php extension. However I am having an issue where when I open it up with chrome/firefox, it is displaying the code, and not the "hello" from the echo statement. Any idea why this may be happening?

A: You need a php service to handle php extension files.
You can try : AppServ from https://www.appserv.org/en/
After install, place the php file in the root folder (By default C:/AppServ/www). Access http://localhost/{your_file_name}.php to view.

A: You need to install Web server on your computer
If you are using windows, will install XAMPP
And then copy a.php and paste into xampp/htdocs/
And run http://localhost/a.php on browser
Note: you will run the Apache on XAMPP control panel
xampp


text:
Q: How do I have a loop with an array of IDs do something upon clicking? var topOptions = ["#m1", "#m2", "#m3", "#m4", "#m5", "#m6"];
for(i = 0; i < topOptions.length - 1; i++)
{

    $(topOptions[i]).click(function(){
        $(topOptions[i]).animate({backgroundColor: '#2c3e50'}, 150);
      });
}

I'm trying to have something happen upon clicking each element, however only the last one is triggered. How do I do this?

A: Try this:
var topOptions = ["#m1", "#m2", "#m3", "#m4", "#m5", "#m6"];
$.each(topOptions,function(i,item){
$(item).animate({backgroundColor: '#2c3e50'}, 150);
});

A: $(this).animate ....

instead of
$(topOptions[i]).animate ....

A:  $("a").click(function(){
 var topOptions = ["#m1", "#m2", "#m3", "#m4", "#m5", "#m6"];
 if(jQuery.inArray( $(this).attr("id"),topOptions )>-1){
 $(this).animate({backgroundColor: '#2c3e50'}, 150);
 }
 });

note that I use a as a selector if it is a div or something else change this

$("a)

I think you want this function jQuery.inArray which check if your clicked id found in topOtions array

A: Note, you can't animate backgroudColor using jQuery animate. You could use css tansition to animate background color. Here is a solution you could use

var ids = ['#id1','#id2','#id3','#id4','#id5'];

ids.forEach(function(id){
 $(id).click(function(e){
  $(this).css('backgroundColor', '#2c3e50')
 });
});
li{
 -webkit-transition: background 0.5s linear;
-moz-transition: background 0.5s linear;
-ms-transition: background 0.5s linear;
-o-transition: background 0.5s linear;
transition: background 0.5s linear;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JavaScript</title>

id1

id2

id3

id4

id5

To know about why your for loop working for last element, please check this answer JavaScript closure inside loops – simple practical example


text:
Q: How to set up my notebook as a VPN service? I have a friend in Turkey who is being bothered by the DNS based banning of Twitter. Soon this is going to be done on IP level and already it seems like Google DNS is not reachable anymore. This got me thinking how it would be possible to make my computer available as a VPN server.

*

*I'm using Ubuntu 13.10 64bit.

*My IP is dynamic but very stable for days - but it will change every time I reset my router.

*My router is only very moderately configurable.

I found two settings in my router configuration area that I am wondering whether they are relevant to this matter: "PPPoE Pass Through" can be enabled and "Port Forwarding" can be configured.
(Is "mesh network" the central keyword here?)

A: have you tried openvpn-as
https://openvpn.net/index.php/access-server/download-openvpn-as-sw/113.html?osfamily=Ubuntu
its free for 2 users
if he uses windows or mac
viscosity is a good openvpn client
http://www.sparklabs.com/viscosity/
or the openvpn option in the network-manager in ubuntu/Linux
another option is to use SSH Tunneling
Windows
http://howto.ccs.neu.edu/howto/windows/ssh-port-tunneling-with-putty/
Linux
http://www.revsys.com/writings/quicktips/ssh-tunnel.html


text:
Q: Faster way to find index of String in ArrayList So I have something like this:
List<String> test = new ArrayList<String>();

When I println it I have:
"[ABC, DEF, GHI, JKL]"

And I want to search for example index of "E". I was doing it in this way:
for (String a : test) {
   if(a.contains("E")) {
      System.out.println(test.indexOf(a));
   }
}

Is any faster way to do this? Because now I'm evrytime making "for" on all list.

A: Given you've said you want to find the first item in the list that contains an "E", by definition you will have to loop through every item to check them until you find a match - this might be at the end of the list, so in the worst case you still have to search the entire list.
However, one shortcut you can take is to at least exit the loop as soon as you find the one you're interested in:
for (String a : test) {
   if(a.contains("E")) {
      System.out.println(test.indexOf(a));
      break;
   }
}

If you were searching for a complete string (e.g. "ABC") you could use indexOf, but as you're searching for a partial match you can't do this.
Java 8 syntax, while unlikely to speed up performance or do the operation in fewer lines of code, is arguably more readable, and will allow you to chain other stream operations to do whatever you need to do to the items that match your query:
List<String> list = Arrays.asList("ABC", "DEF", "GHI", "JKL");
Optional<String> matchingItem = list.stream()
                                    .filter(s -> s.contains("E"))
                                    .findFirst();
matchingItem.ifPresent(s -> System.out.println(list.indexOf(s)));

Java 8 does contain optimisations for operations like this.
Incidentally, if your list is very large, you may find a speed improvement by using parallelStream() instead of stream() - this Java 8 code probably does the same number of operations as your code, but it is parallelisable over multiple CPU cores where a traditional for-loop is not.
Alternatively, if you really do need a way of accessing the required elements immediately, and the criteria you're looking for is always the same (i.e. you're always going to want just the elements that contain an "E"), you can track the data in an additional data structure, like a map.  E.g. every time you add an item to the list that contains the criteria you want, you also add it to the map.  Something like:
Map<String, List<String>> mapOfValuesICareAbout = new HashMap<>();
String newValue = "GFE";
if (newValue.contains("E")) {
    mapOfValuesICareAbout.get("E").add(newValue);
}
list.add(newValue);

A: You can use a permuted index, normally used for words:
["he speaks well", "well done"]

would give a sorted list
     well *done*
          *he* speaks well
       he *speaks* well
he speaks *well*
          *well* done

where you can find "well" fast.
Such a list entry in our case would be:
class Entry implements Comparable<Entry> {
    String right;
    String left;

    @Override
    public String toString() { return left + "^" + right; }
}

For every string of length N, there are right values of N, N-1, ..., 2, 1 characters.
class SearchBase {
    private List<Entry> entries; // Or immediately sorted: TreeSet

    void addAll(String... terms) {
        fill list entries, and sort them
    }

    Collection<String> termsContaining(String sought) {
        binary search on entries rigth
    }
}

A: If you only want the index of the first element which contains the letter 'E' you can spare one operation by only using String#indexOf(char). After you've found the element you can break out of the loop.
List<String> test = Arrays.asList("ABC", "DEF", "GHI", "JKL");
for (String element : test) {
    int idx = element.indexOf('E');
    if (idx != -1) {
        System.out.println(element + " with 'E' at pos: " + idx);
        break;
    }
}


text:
Q: IIB - DLL Initialization Error in Connecting to DB2 ODBC DSN via mqsicvp Getting the following error while using mqsicvp to test connectivity to a ODBC data source from IBM Integration Console.
C:\Program Files\IBM\IIB\10.0.0.9>mqsicvp DEFAULTBRK -n MSAPP -v
BIP8299I: User 'db2admin' from security resource name 'odbc::MSAPP' will be used for the connection to datasource 'MSAPP'.

BIP2393E: Database error: ODBC return code '-1' from data source ''MSAPP'' using ODBC driver manager ''odbc32.dll''.
The integration node received an error when processing a database operation. The ODBC return code was '-1'. See the following messages for information obtained from the database about this error.
Use the following messages to determine the cause of the error. Typical problems are an incorrect data source, or table names. Correct either the database or the integration node configuration. Use the mqsicvp command to test connectivity to this database.
BIP2322E: Database error: SQL State ''IM003''; Native Error Code '160'; Error Text ''Specified driver could not be loaded due to system error  1114: A dynamic link library (DLL) initialization routine failed. (IBM DB2 ODBC DRIVER - DB2COPY1, C:\PROGRA~1\IBM\SQLLIB\BIN\DB2CLIO.DLL).''.
The error has the following diagnostic information:     SQL State             ''IM003''     SQL Native Error Code '160'     SQL Error Text        ''Specified driver could not be loaded due to system error  1114: A dynamic link library (DLL) initialization routine failed. (IBM DB2 ODBC DRIVER - DB2COPY1, C:\PROGRA~1\IBM\SQLLIB\BIN\DB2CLIO.DLL).''
This message may be accompanied by other messages describing the effect on the integration node itself. Use the reason identified in this message with the accompanying messages to determine the cause of the error. Use the mqsicvp command to test connectivity to this database.

BIP8040E: Unable to connect to the database.
The database cannot be accessed with the specified user Id and password pair.
- Check that the database is running.
 - Check that the database has an adequate number of database connections available for use.
 - On Windows, check that an ODBC connection has been created.
 - On systems that use $ODBCINI, check that the file pointed to by $ODBCINI has been correctly updated.
 - On z/OS check the BIPDSNAO member of the component's dataset, and check the DB2 64bit ODBC driver (DSNAO64C) is in the STEPLIB.
 - Use mqsisetdbparms to set the password to the correct value and try again.

Software: Windows 10 / IIB 10 / DB2 Server
Steps to reproduce:

*

*Set up ODBC (64-bit) connectivity to a new DB2 database in the form of a System DSN (using the IBM DB2 ODBC Driver version 11.01.2020.1393)

*Test that connectivity works from ODBC data source administrator app

*Use mqsisetdbparms from IBM Integration Console to set the user and
password

mqsisetdbparms DEFAULTBRK -n odbc::MSAPP -u uid -p pwd

*Stop and start the broker

*Use mqsicvp to test connectivity

mqsicvp DEFAULTBRK -n MSAPP

The DLL mentioned in the error is at C:\PROGRA~1\IBM\SQLLIB\BIN and this is included within PATH variable already.
I'm not sure why the driver manager odbc32.dll is being used - I presume this is a 32-bit version. However if I try creating a DSN in the 32-bit ODBC data source administrator app, mqsicvp fails with an error saying the architectures do not match.

A: Suggest you download the fix from IBM for bug IT23069. It is available (indirectly) from this page which eventually redirects to IBM fix central. Worked for me.

A: The newest developer edition toolkit, 10.0.0.12, seems to have fixed this.


text:
Q: Symfony 2.5 & twig: how to clean up this code? I'm new to Symfony and would like to use best-practices as early as possible. My code below works but it feels kinda dirty.
I worry, if I write too much code here. Maybe I miss some Symfony-background-magic that I don't know yet. Details below.
What would you change (why)? I appreciate every advice to become a better developer. Thanks in advance!
routing.yml:
items_edit:
  path:     /items/edit/{id}
  defaults: { _controller: myBundle:items:edit, id: null } # null = if not set?
  requirements:
    id: \d+

ItemController.php:
Do I have to pass the $item or is the data anyhow else gettable via twig?
public function editAction($id, Request $request) {
    $em   = $this->getDoctrine()->getManager();
    $repo = $em->getRepository('ItemsRepo');
    $item = $repo->find($id);
    $form = $this->createForm(new ItemFormType(), $item);

    if ($request->isMethod('POST')) {
        $form->handleRequest($request);
        if ($form->isValid()) {
            $em->persist($item);
            $em->flush();

            $this->get('session')->getFlashBag()->add('info', 'saved.');
            return $this->redirect($this->generateUrl('items_list'));
        }
    }

    return $this->render('edit.html.twig', array(
        'form' => $form->createView(),
        'item' => $item // !!!
    ));
}

edit.html.twig:
Do I have to add {id: item.id} here?
{% block content %}
    <form action="{{ path('items_edit', {id: item.id}) }}" method="POST" {{ form_enctype(form) }}>
        {# ... custom stuff ... #}
    {{ form_end(form) }}
{% endblock %}

A: You could replace
<form action="{{ path('items_edit', {id: item.id}) }}" method="POST" {{ form_enctype(form) }}>

with
{{ form_start(form) }}

This way you do not need to pass item to the template.
http://symfony.com/doc/current/book/forms.html#rendering-a-form-in-a-template

A: id: null with \d+ requirement in your route is useless, because of you're actually editing the existing entity, you better remove it; $em->persist($item); is also unnecessary, because of you've already persisted and flushed it on creation, this time you don't need to persist again, just flush it. What abount passing the $item to form, if you want to show some information to the user, like "Editing the item with title of SOME_TITLE", or if there is some image field that you want to show thumbnail .., you can pass it and retreive field value, it's u to you.. Additional note, /items/edit/{id} is not very pretty, usually it's done like /items/{id}/edit, /items/{id}/delete...


text:
Q: While using Offline Files users cannot rename files when changing case only I recently setup some new computers (running Win8.1) for the staff here. These machines use folder redirection (as we always have) with Offline Files sync. I have not traditionally used Offline Files but I've turned it on to give a bit of extra resiliency and performance while working with their files.
Today it was brought to my attention by someone that they cannot rename a file if they change the letter case only. When they do this they are shown a popup that says they need to get permission from their selves to perform the action. Their choices are Try Again and  Cancel.
For example, the following will fail:
filename.txt --> FILENAME.txt

But the following will succeed:
filename.txt --> xFILENAME.txt --> FILENAME.txt

My files are being redirected to the same fileshare* by the same group policy but I am not using Offline Files and I do not experience this problem.
I've checked with another user that is setup like the original and they also experience this problem.
If this is a known bug my I have not been able to find an answer.
* The fileshare is running on Windows Server 2012 with deduplication enabled on the volume.

A: For Windows Vista and Windows 7 this is a known 'feature' according to the Microsoft KB953945, with the only 'resolution' is to work around the problem by temporarily renaming the file to something else first.
From the above article the resolution is

To work around this issue, rename the file to another name, and then rename back with the changed letter case.
For example, rename TEXT.txt to word.txt, and then rename word.txt to text.txt.

Perhaps with Windows 8, 8.1, 2012, 2012R2 this 'feature' has been included in these newer releases too.


text:
Q: What is the difference between "a priori", "a posteriori" and "likelihood"? I am trying to understand definitions. Let $x$ denote a random variable (outcome of experiment) and $\theta$ a parameter. This is what I think:

*

*"a priori" is a density function of $x$ given certain value of $\theta$. For example $p(x) = \frac{1}{\theta} I_{([0,\theta])}$

*"a posteriori" is a probability that parameter has some value, given observed $x$, i.e. conditional probability $p(\theta | x) = \frac{p(x|\theta)}{p(x)} \cdot p(\theta)$, where $p(x) = \int p(x|\theta)\cdotp(\theta) d\theta$

*"likelihood" is a probability of obtaining certain $x$ given the parameter $\theta$, i.e. conditional probability $p(x|\theta) = \frac{p(\theta|x)}{p(\theta)} \cdot p(x)$.

"a priori" and "likelihood" seem very similar, sometimes $p(x)$ is denoted as $p_\theta(x)$, which kind of gives probability of $x$ given $\theta$. I suppose the difference is that by "a priori" we mean a density function and "likelihood" is a single value calculated for specific $x$. But I am not sure and it sounds weird. In general I have no idea if I understand these three terms and the difference between them or not.
Also, it's not exactly the topic of this question, but I can't learn when should I use $X$ ("random variable") and when $x$ ("observed value of X"?). Maybe it affects my understanding of definitions.
Can anyone help?

A: The prior is $p(\theta)$, i.e. it treats the parameter $\theta$ as a random variable. Your definitions of posterior and likelihood look correct. "$p(\cdot )$" in this context would refer to a mass function or density.
Notation varies, but I would say a frequent convention is $X$ is the random variable and $x$ is a realization of the random variable, so we may write
$$P(X=x):=P(\{\omega\in \Omega:X(\omega)=x\}).$$

It may be more instructive to use an example. Suppose $X_1,..X_n$ are iid Poiss($\lambda$), for $\lambda>0$. Note that in a Bayesian context, this means $X_i|\lambda\overset{\text{iid}}{\sim} $Poiss($\lambda$).
Then the likelihood is
$$p(x_1,...,x_n|\lambda)=\Pi_i p(x_i|\lambda)=\Pi_i\frac{\lambda^{x_i}e^{-\lambda}}{x_i!}=\frac{\lambda^{\sum_i x_i}e^{-n\lambda}}{\Pi_i x_i!}.$$
Supposing $\lambda\sim$ Gamma($\alpha,\beta$), which is a conjugate prior for the above likelihood, then the prior density is
$$p(\lambda)\propto \lambda^{\alpha-1}e^{-\beta\lambda},$$
and you can work out the posterior is
$$p(\lambda|x_1,...,x_n)\propto \lambda^{\sum_i x_i +\alpha-1}e^{-(\beta+n)\lambda},$$
implying $\lambda|X_1,...,X_n\sim$Gamma($\sum_i X_i +\alpha,\beta+n$).


text:
Q: jQuery is only working once? jsFiddle attached I want to be able to check and uncheck a checkbox by clicking its parent DIV.
html:

    <input name="insurance[Auto]" type="checkbox" value="1">

    <input name="insurance[Home]" type="checkbox" value="2">

js:
  $('.insurance-option-select').on('click', function () {
      if ($(this).find('input').prop('checked')) {
          $(this).find('input').removeAttr('checked');
      } else {
          $(this).find('input').attr('checked', true);
      }
  });

css:
.insurance-option-select {
    background: red;
    padding: 30px;
    margin: 30px auto;
}
.insurance-option-select:hover {
    background: green;
}

Problem is it only works once. http://jsfiddle.net/zbh691y0/

A: Just use prop the whole time, not attr and prop.
http://jsfiddle.net/zbh691y0/1/
$('.insurance-option-select').on('click', function () {
    if ($(this).find('input').prop('checked')) {
        $(this).find('input').prop('checked', false);
    } else {
        $(this).find('input').prop('checked', true);
    }
});

This can also be simplified by doing:
$('.insurance-option-select').on('click', function () {
    cb = $(this).find('input')
    cb.prop('checked', ! cb.prop('checked'))
});

The property checked is a boolean.  As such, you can negate it's value by using a !.  Imagine instead this code:
   cb = $(this).find('input')
   is_checked = cb.prop('checked')  // This will be true if it is checked, and false if not
   inverse_is_checked = ! is_checked // This will be the opposite of is_checked
   cb.prop('checked', inverse_is_checked) // Now you set the checked property value to the inverse of what it was originally

But that can be done in the one line, like shown above.


text:
Q: pywinauto не корректно работает в режиме многопоточности Expected Behavior
COM работают в отдельных потоках, в режиме многопоточности и не должны блокировать друг друга.
Actual Behavior
COM работают в отдельных потоках, в режиме многопоточности, но при этом, при блокировке одного из приложений, в хаотичном порядке блокируется второе приложение (на разных участках кода, до куда успеет дойти).
Steps to Reproduce the Problem

*

*Из под разных корутин (asyncio) создается свой инстанс с Application(backend='UIA').connect(process=...)

*Далее, каждая корутина поочередно запускает приложение 1С (авторизуется - Application(backend='UIA').start("...")), идет на создание и выгрузку отчета в 1С через GUI (pywinauto).

*После нажатия на кнопку, блокирующую открытое окно сессии (приложения), передаю управление на другую корутину. Тут ожидаю выполнения посредством wait_cpu_usage_lower(threshold=0.2). Пока отчет выгружается, threshold находится в районе 7%.

*На другой корутине, при блокировке предыдущей, python может встать в ожидание на любом участке кода pywinauto (хаотично), connect успевает выполниться корректно, top_window, set_focus, уже не всегда успевает. Далее методы pywinauto (window, descendants и т.п.) уже блокируются (очень часто, но тоже НЕ ВСЕГДА), пока не разблокируется приложение в первой корутине.

*TID приложения во всех запущенных сессиях 1С одинаковый (win32api.GetCurrentThreadId).
А вот PID и TID (win32process.GetWindowThreadProcessId) окон разные.

*Сценарий, в данном случае, запускаю одинаковый, на одних и тех же данных.

Specifications

*

*Pywinauto version: 0.6.4, т.к. только на ней 1С может работать в многопоточном режиме более-менее корректно.

*Python version and bitness: python 3.7, 64x.

*Platform and OS: приложение 1С Предприятие на Windows Server 2016 64x.


text:
Q: How to export chrome console log I have a question. When I type a lot of JS commands into a console log in Chrome, and I want to return it then, can I? Thank you
Andrew

A: You can't. What's in the console can't be read from JavaScript.
What you can do is hook the console.log function so that you store when it logs :
console.stdlog = console.log.bind(console);
console.logs = [];
console.log = function(){
    console.logs.push(Array.from(arguments));
    console.stdlog.apply(console, arguments);
}


text:
Q: How to change every items in list to variables in dictionary?(python) def mul(dict(x)):
  for y in y.values():
    print(y, x[y])

mul(A=1,B=2,C=3,D=4,F=5)

I want to get the result as
A 1
B 2
C 3
D 4
F 5

I have to use dictionary, but I want to use only one variable, x, in multiplication function. How can I use it in 'mul' function?

A: Use ** to pack keyword arguments into a dict:
def mul(**kwargs):
    for y in kwargs:
        print(y, kwargs[y])

mul(A=1,B=2,C=3,D=4,F=5)

Output:
A 1
B 2
C 3
D 4
F 5


text:
Q: sed extract every occurrence of string between specific delimiters How to extract characters between delimiters ":" for all occurrences in a line (defined as strings separated by white-space) for all lines?
I have tried  sed 's/.:(.):.*//g' but that doesn't take into account multiple occurrences.
given:
1/1:2.000:0.000,0.000,1.000 0/1:1.001:0.000,0.999,0.001
1/1:2.000:0.000,0.000,1.000 0/1:1.002:0.000,0.998,0.002

to be obtained:
2.000 1.001
2.000 1.002

A: This might work for you (GNU sed):
sed -r 's/[^:]*:([^:]*):\S*(\s)*/\1\2/g' file


text:
Q: DataGridView design X scroll with fixed header, visible grid line, even column width I'm making an admin panel and I have DataGridView on each page.
At the moment, it is not showing x &y gridLines and column width is arbitrary. I've used ItemStyle width 10%, but still doesn't really do the trick.
Here is my source code

        <asp:GridView ID="GridViewUpPer" runat="server" AutoGenerateColumns="False" Font-Names="Arial" Font-Size="Small" HorizontalAlign="Center">
            <Columns>
                <asp:BoundField DataField="SubCatID" HeaderText="Sub category ID">
                    <ItemStyle Width="10%" />
                </asp:BoundField>

Here is my design

x scroll is not appearing and my gridView is not showing the entire columns. I only can change heard text color not the text color of data. I'm using table and div.
I have 15 of GV looking like this..... Can anyone help me to design a good looking gridView?? Without using java coz I'm new to programming and I don't know that script language...... Thanks~
C#, VS 2012, web application


text:
Q: php отображает исходный код, а не заданный текст Столкнулся с проблемой, что локальный сервер отображает полностью код, а не то чтобы я хотел видеть. Мне нужно чтобы отображалось просто "Hello, PHP"

Вот полный код
Переписал его из книги Алексея Васильева руками.
Суть проблемы в том, что мне выводит исходный код, а мне нужно чтобы выводило только содержимое скобок

A: Чтобы пхп отображал результат выполнения скрипта, а не сам скрипт, нужно правильно настроить сервер, самым простым сервером для винды является openserver, не требующий каких-либо настроек, иные варианты несколько сложнее. О вашем сервере могу только гадать,- в частности он почемуто открыт на порте тсп 6467, а не на стандартных портах 8000, 8080, вероятно вы неверно настроили сервер и к пхп проблема имеет лишь косвенное решение.


text:
Q: How to Solve Django rest-framework JSON parse Error What is wrong with this JSON?
when trying to send a POST request with POSTMAN getting JSON PARSE ERROR.
Error from Postman
{
  "detail": "JSON parse error - Expecting ',' delimiter: line 5 column 13 (char 82)"
}

JSON Data sending From Postman
{
"menu_name": "indian_menu",
"slug": "indianmenu",
"item_name": [
    "category": "indianmenu",
  ]
}

rest_framework Serializers
class MenuCardSerializer(serializers.ModelSerializer):

  class Meta:
    model = MenuCard
    fields = '__all__'
    read_only_fields = ('menu_name', )

class MenuSerializer(serializers.ModelSerializer):

category = MenuCardSerializer(required=True, many=True)

  class Meta:
    model = Menu
    fields = '__all__'

  def create(self, validated_data):
    category = validated_data.pop('category')
    menu = MenuCard.objects.create(**validated_data)
    for choice in category:
        Menu.objects.create(**choice, category=menu)

rest_framework API_VIEWS
@api_view(['GET', 'POST', 'PUT', 'DELETE', ])
def simple_menu(request, slug):

print("simple menu slug : " + slug)

if request.method == 'GET':
    category_list = Menu.objects.all()
    serializer = MenuSerializer(category_list)
    return JsonResponse(serializer.data)

elif request.method == 'POST':
    serializer = MenuSerializer(data=request.data, many=False)
    data = {}
    if serializer.is_valid():
        serializer.save()
        data["success"] = "item Catagory Created"
        return JsonResponse(data=data, status=status.HTTP_200_OK)
    return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

A: You JSON from postman is not a valid one, you can easily check it with any JSON validator.
In your first example it should be a dict not list as oz19 mentioned.
The same problem in the second one, the correct one is something like this:
{
   "menu_name":"Indian Menu",
   "slug":"indianmenu",
   "item_name":[
      {
         "category":"Indian Menu",
         "item_name":"dal",
         "price":"22.30",
         "stock":"10"
      }
   ]
}

A: The error possibly comes from the data you are entering on Postman. On item_name you probably wanted to create a dict, but it is a list.
Change:
{
  ...
  "item_name": [ "category": "indian_menu"]
}

By:
{
  ...
  "item_name": { "category": "indian_menu" }
}


text:
Q: Bash : Concatenate variables containing strings n columns by n columns I have 2 variables containing the same number of information, here 1 line with n=3 columns (I mean separated by a space)
var1='abc def ghi'
var2='klm nop qrs'

I would like the output to be the concatenated result with one line and 3 columns, with the following pattern :
abcklm defnop ghiqrs

I tried with a $(paste <echo $var1) <(echo $var2) -d  '')
But it does the same as $var1$var2.
The pr -ms' ' $var1 $var2 doesn't work, it's like it is waiting for a file rather than a variable

A: paste -d "" <(tr ' ' '\n' <<<"$var1") <(tr ' ' '\n' <<<"$var2") | paste -sd " "

*

*convert the space-separated variables into newline-separated files.

*join the files.

*then join the output lines.

Documentation:

*

*3.5.6 Process Substitution

*3.6.7 Here Strings

*man pages for tr and paste


text:
Q: Fortran program giving a wrong output? I'm new to Fortran, so forgive me if I'm doing something stupid in the following code:
program test2
    implicit none

    ! Variable declaration
    integer :: i, n
    real    :: s

    ! Initialization
    n = 1e+9
    s = 0.0

    do i=1,n
        s = s + real(i)
        s = s + sqrt(s)
    end do

    print *, s

end program test2

This small program outputs: 1.8014399E+16 and I expect it to give 1.0000000010000024E+18. I use the GNU Fortran compiler on a Windows 10 machine.

A: Well, I ended up using the following definition for the double precision variable s. This method has the advantage of being reusable and system independent. Thanks to @francescalus for the comment.
program test2
    implicit none

    ! Variable declaration
    integer, parameter :: dp = kind(0.d0)
    integer  :: i, n
    real(dp) :: s

    ! Initialization
    n = 1e+9
    s = 0.0

    do i=1,n
        s = s + real(i)
        s = s + sqrt(s)
    end do

    print *, s

end program test2


text:
Q: loop through divs and move hrefs to another div I am trying to loop through divs take the href from one div and move it to the href of another div, and then repeat this for all the following divs.
I have it working so far as it does it for the first div but then it places that href link in all the others.
see https://jsfiddle.net/grmaw27y/5/
html:

Google

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus sit amet ipsum eget odio maximus posuere. Fusce dapibus id urna quis eleifend. Nam lacinia consequat lectus, at ultricies purus elementum non.

https://www.google.ie/

Yahoo

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

https://ie.yahoo.com/

js:
$('.entry').each(function() {
  var href = $('.entry p a').attr('href');
  $('.image a').attr('href', href);
});

A: Try this:
$('.entry').each(function(i,element) {
  var href = $(element).find('p a').attr('href');
  $(element).parent().prev().find('.image a').attr('href', href);
});

Working example:
https://jsfiddle.net/grmaw27y/6/
So what was wrong with your code?
Your expression to find the href var href = $('.entry p a').attr('href'); and assign href $('.image a').attr('href', href);, were working on class selectors. which return array of all matches. In every pass they were matching the same two elements.
To fix this we use the element object in loop, you specify exactly what you want to read and write.

A: You need to use traversal functions to select elements relative to each target:
$('.entry').each(function() {
  var href = $('p a', this).attr('href');
  $(this).closest('.row').find('.image a').attr('href', href);
});

https://jsfiddle.net/gbc22h0f/

A: You can loop over the container and find the relevant elements INSIDE each of the containers:

$('.container').each(function() {
  var href = $(this).find('div.entry a').attr('href');
  $(this).find('div.image a').attr('href', href);
});

Google

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus sit amet ipsum eget odio maximus posuere. Fusce dapibus id urna quis eleifend. Nam lacinia consequat lectus, at ultricies purus elementum non.

https://www.google.ie/

Yahoo

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

https://ie.yahoo.com/


text:
Q: HTTPS for configured site in ISPConfig returns No Data Received Currently I have ISPConfig installed. I see a problem whenever I try to access a domain with ssl(https://) it always return No data received even though I checked for SSL in the ISPConfig admin panel. I have already changed my ISPConfig to use the correct certificates and it works perfectly. I don't notice any logs being made in apache2 after the error and I'm using the same SSL for the domain and my ISPConfig. Any guidance would be well appreciated!

A: Turns out AT&T Uverse uses wireless STB's that carry an access point that connects to the router and to the outside world with port 443. So whenever it is connected it conflicts with anything else running on port 443.


text:
Q: Same dynamic route for mutltiple different pages - next.js I have an endpoint in the /api folder for fetching what we call assets. I wanted to implement search so I created a folder called assets with an index.js and a [query].js.
And this works fine but now I also need to implement a detailed page for a single assets with an endpoint assets/id. Since I already have the query handler if I creating [id].js will lead to conflicts.
What's the ideal way of dealing with this?


text:
Q: How to update Registry Values as "System" user? I have a Windows Forms application needs to update registry values. When I debug the application the values are being saved properly. But when I launch the application after the completion of installer (Visual Studio Setup Project - .vdproj), the application launches properly but it is not saving the registry values properly.
I am not getting any errors but can't seem to find the entries at location.
The values are being saved correctly if I double-click the .exe.
Is it because the installer launches the application as "System" user?
How do I solve this?

A: You should say which registry entries your code is trying to update, but if they are HKCU entries, for example, you are going to see differences running with the system account.
It is also unclear why you need a program to create registry entries when the setup will do this for you and it will just work. In Visual Studio setup projects that's in the Registry view. Many of the values you may want to store in the registry might be available as standard Windows Installer properties, and store them using the square bracket syntax, such as [TARGETDIR].


text:
Q: Error in executing while loop for fetching records from database I have an error in executing a while loop in php. actually in php code I tried to fetch records from database for that i establish connection at the beginning of code.In code my outer loop executed well but inner loop executed only one time and terminated.Then i tried to establish mysql connection once again within while loop then it executed.If i comment this it not work well.Tell me to run while loop there is need to establish connection once again or there is another way to solve problem.
Here is my code:
$con    = mysqli_connect("localhost", "root", "root", "scheduler");
$sql    = "select * from jobschedule";
$result = mysqli_query($con,$sql);
$sql2   = "SET GLOBAL event_scheduler = 1";

mysqli_query($con,$sql2);
while($row = mysqli_fetch_array($result))
{
    // $con = mysqli_connect("localhost", "root", "root", "scheduler");

    $dbname  = $row['DBName'];
    $jobname = $row['JobName'];

    $sql1    = "call $dbname.$jobname";
    $result1 = mysqli_query($con,$sql1);

    while($row1 = mysqli_fetch_array($result1))
    {
        echo '
';
           . '' . $row1['Name'] . '	';
           . '' . $row1['CountryCode'] . '	'
           . '' . $row1['District'] . '	'
           . '' . $row1['Population'] . '	'
           . '
';
        }
    }

A: Try this
//Connection
$con = mysqli_connect("localhost", "root", "root", "dbname") or die("Error " . mysqli_error($con));

//Query

$query = "SELECT * FROM tablename" ;

//execute the query.

$result = $con->query($query) or die("Error in the Query.." . mysqli_error($con));

//display information:

while($row = mysqli_fetch_array($result)) {
  echo $row["field_name"] . "
";
}

A: You are trying to acces normal array's values with keys
    $dbname = $row['DBName'];
    $jobname = $row['JobName'];

To do this you must have associative arrays. Try changing
$row = mysqli_fetch_array

to
$row = mysqli_fetch_assoc


text:
Q: VS30063: You are not authorized to access https://dev.azure.com I am trying to connect Azure DevOps using below code in asp.net core(2.1) mvc app
Uri orgUrl = new Uri("https://dev.azure.com/xxxxx/");
String personalAccessToken = "xxxxx";
VssConnection connection = new VssConnection(orgUrl, new VssBasicCredential(string.Empty, personalAccessToken));

But getting this error "VssUnauthorizedException: 'VS30063: You are not authorized to access https://dev.azure.com.'"
Same code is working in .net core console app, Please can anybody help me on this?
Here my code i am trying to get Work items, geting error on GetClient

A: There's no error on your code.

VS30063: You are not authorized to access https://dev.azure.com.

This is an unauthorized error code. It should caused by your PAT token is not available. By using your code, if I use a expired token, will receive the same error.

After generated a new PAT token, the error disappeared and the code work successfully.
So, just try with generate a new token from Azure Devops and use it.
Updated:
With the key code which from the screenshot of the updated question, I create a completed Application to writeLine the WIQL result. Still succeed shown as below:

Could you execute your code and share the error screenshot?(Note: Just for error line)

A: Did you set the PAT permissions on every scope you are using? After creating a new token, I forgot to set permissions on "Code" - "read" for the GitHttpClient.

A: I got this error while creating custom agent in azure devops after entering the PAT.
I gave full control while creating new PAT and used that PAT while configuring custom agent pool.


text:
Q: Why does a simple update cursor take so much time? This script is running for the past 10 minutes. It is operating on a table with only 10 records. What is wrong with the script?
declare
  cursor cus is
  select * from customers
  for update of salary;
begin
  for i in cus
  loop
    update customers
    set salary = salary * 0.15
    where current of cus;
  end loop;
end;

A: Kind of a simple cursor but I don't use the "where current of", rather I match on a key.
update customers
set salary = i.salary *.15
where cus_key = i.cus_key


text:
Q: Pandas escape carriage return in to_csv I have a string column that sometimes has carriage returns in the string:
import pandas as pd
from io import StringIO

datastring = StringIO("""\
country  metric           2011   2012
USA      GDP              7      4
USA      Pop.             2      3
GB       GDP              8      7
""")
df = pd.read_table(datastring, sep='\s\s+')
df.metric = df.metric + '\r'  # append carriage return

print(df)
  country  metric  2011  2012
0     USA   GDP\r     7     4
1     USA  Pop.\r     2     3
2      GB   GDP\r     8     7

When writing to and reading from csv, the dataframe gets corrupted:
df.to_csv('data.csv', index=None)

print(pd.read_csv('data.csv'))
  country metric  2011  2012
0     USA    GDP   NaN   NaN
1     NaN      7     4   NaN
2     USA   Pop.   NaN   NaN
3     NaN      2     3   NaN
4      GB    GDP   NaN   NaN
5     NaN      8     7   NaN

Question
What's the best way to fix this? The one obvious method is to just clean the data first:
df.metric = df.metric.str.replace('\r', '')

A: To anyone else who is dealing with such an issue:
@mike-müller's answer doesn't actually fix the issue, and the file is still corrupted when it is read by other CSV readers (e.g. Excel). You need to fix this once you write the file rather than while reading it.
The problem lies in not quoting strings having newline characters (\r, \n, or \r\n depending on the OS style). This will not keep the CSV reader (e.g. pandas, Excel, etc.) from parsing the newline characters and then it messes up the loaded CSV file into having multiple lines per unquoted records.
The generalized newline char in Python is \r\n as you strip string by these chars e.g. str.strip('\r\n'). This will make Python identify and cover all OS newline styles.
In pandas, reading CSV file by line_terminator='\r\n' wraps all strings having either \n or \r into double quotes to preserve quoting and keep readers from parsing newline chars later.
Just to provide the code:
pd.to_csv('data.csv', line_terminator='\r\n'))

A: I got three working solutions. All of these look equally robust to me.
This one (credit should go to @Shayan Amani) works good because now read_csv considers only \n as the line separator, and therefore '\r' is just a character. Note that the behavior of to_csv will change by the platform; On windows, lines are separated by '\r\n'. This won't change the result though, thanks to the skip_blank_lines=True option of read_csv.
df.to_csv("tmp/test.csv", index=False)
pd.read_csv("tmp/test.csv", lineterminator="\n")

This one solves the problem by forcing the quote for text columns.
import csv
df.to_csv("tmp/test.csv", index=False, quoting=csv.QUOTE_NONNUMERIC)
pd.read_csv("tmp/test.csv")

Another option is to explicitly specify the line separator when saving.
With this, text with '\r' is now quoted.
df.to_csv("tmp/test.csv", index=False, line_terminator="\r\n")
pd.read_csv("tmp/test.csv")

A: Specify the line_terminator:
print(pd.read_csv('data.csv', line_terminator='\n'))

  country  metric  2011  2012
0     USA   GDP\r     7     4
1     USA  Pop.\r     2     3
2      GB   GDP\r     8     7

UPDATE:
In more recent versions of pandas (the original answer is from 2015) the name of the argument changed to lineterminator.

A: In my case, applying quoting=csv.QUOTE_ALL solved the issue.
import csv
pd.to_csv('some_data.csv', quoting=csv.QUOTE_ALL)


text:
Q: How to pass states here? I have a component ModifyWordPartButton that has a state isHovered and a child IconButton. IconButton onclick that is a child of another component, SelectWordPartToModify, that has a method handleClickOpen(). IconButton is supposed to be able to have its onClick = SelectWordPartToModify's handleClickOpen().
When using this code:
ModifyWordPartButton:
.
.
.
render() {
  return (

      <IconButton className={this.state.isHovered ? 'hoveredClass' : null />

  );
}

SelectWordPartToModify:
.
.
.
render() {
    <ModifyWordPartButton />
}

results in IconButton inheritng ModifyWordPartButton's isHovered state but not inheriting SelectWordPartToModify's handleClickOpen().
And when I use this code:
ModifyWordPartButton:
.
.
.
render() {
  return (

      {this.children}

  );
}

SelectWordPartToModify:
.
.
.
render() {
  <ModifyWordPartButton onClick={this.handleClickOpen}>
    <IconButton onClick={this.handleClickOpen}
  </ModifyWordPartButton
}

IconButton doesn't inherit ModifyWordPartButton's isHovered state.
I tried in ModifyWordPartButton's render() to replace this.props.children with:
this.props.children.map(
  child => {
    React.cloneElement(child, this.state)
  }
)

but React gave me an error about not recognizing IconButton's isHovered property.
Here's the full code I use:
https://codesandbox.io/s/zwlz41mo93?codemirror=1&eslint=1&fontsize=14
How can I solve this?

A: Sorry, I don't fully understand your question, but.. Can't you pass more than one props to IconButton? Something like the following:
SelectWordPartToModify
render() {
    return <ModifyWordPart handleClick={this.handleClickOpen} />
}

ModifyWordPart
render() {
    return (
        <IconButton
            className={this.state.isHovered ? 'hoveredClass' : null}
            handleClick={this.props.handleClick} />
    );
}

This way, handleClickOpen must be defined in SelectWordPartToModify, and can be executed inside IconButton using this.props.handleClick(). Moreover, you also have the className of IconButton based on the isHovered property of ModifyTwoPart

EDIT: Regarding your sandbox:

*

*At line 78 of ModifyWordPartButton you should not write handleClickOpen={this.handleClickOpen} but instead onClick={this.handleClickOpen}: being a div a simple DOM element, you cannot pass to it property like a your own Component.

*At line 71 of the same file, again, you should use onClick instead of handleClickOpen: IconButton is indeed a Component, but it belongs with Material UI and it seems to expect an onClick props.

*Moreover, in both lines you should not write this.handleClickOpen, but instead this.props.handleClickOpen, because the function is passed to ModifyWordPartButton using the props!

*I guess the IconButton at line 60-68 of SelectSuffixToModify can be deleted without any ripercussion (if I guest right what you wanted to do, then it is not useful at all keeping it there).
I've forked your sandCodebox, here it goes → https://codesandbox.io/s/6wxj4nyn6z I think it does what you asked for.
Though, I think you need some clarification because, based on what you wrote, I think you have some confusion in your mind. When you write your own Component, you can make them expecting the props you want: in your example, ModifyWordPartButton is your own Component and you created him in a way that expect a prop named handleClickOpen; thus, when you call it from the SelectSuffixToModify render() method, you can pass it a function using handleClickOpen={...}.
Instead, IconButton is made from someone else, thus you should be aware of what are its props! Information which I guess you can find it on the official documentation of material UI :)


text:
Q: RadTreeView control for left pane navigation My page has a left pane which has a RAD Treeview telerik control. It is working fine with parent nodes and child nodes. Below is the image of what it looks like.

I am creating a custom userControl now, to replace this treeview control. I want this new control to be able to get all nodes, level wise and display it as a block, for example: When I land on the page for the first time, what I need to see is:

*

*Accessories

*Awards

*FIAT

*Technology

*Warranty

within a container(a div may be), and when I click on FIAT, I want it to display another div below this top level div which shows me:

*

*2014

*2015

then when I click on 2014 another div below which shows

*

*500

*500c

and so on.
Can someone direct me towards a solution for this.
Thanks.

A: Start by checking out the telerik ASP documentation on the tree control.
There are several examples.
Your tree structure would look something like this:
 <telerik:RadTreeView ID="RadTreeView1" runat="server" Height="250px" Width="100%"
        EnableDragAndDrop="true" OnNodeClick="RadTreeView1_NodeClick" OnNodeCollapse="RadTreeView1_NodeCollapse"
        OnNodeExpand="RadTreeView1_NodeExpand" OnNodeDrop="RadTreeView1_NodeDrop" Style="border: 1px solid #CBE7F5;">
        <Nodes>
            <telerik:RadTreeNode Text="Accessories" ExpandMode="ServerSide" Expanded="true">
                <Nodes>
                <!-- add Accessories nodes here -->
                </Nodes>
            </telerik:RadTreeNode>
            <telerik:RadTreeNode Text="Awards" ExpandMode="ServerSide">
                <Nodes>
                <!-- add Awards nodes here -->
                </Nodes>
            </telerik:RadTreeNode>
            <telerik:RadTreeNode Text="FIAT" ExpandMode="ServerSide">
                <Nodes>
                    <telerik:RadTreeNode Text="2014" ExpandMode="ServerSide">
                        <telerik:RadTreeNode Text="500" ExpandMode="ServerSide">
                        </telerik:RadTreeNode>
                        <telerik:RadTreeNode Text="500c" ExpandMode="ServerSide">
                        </telerik:RadTreeNode>
                    </telerik:RadTreeNode>
                    <telerik:RadTreeNode Text="2014" ExpandMode="ServerSide">
                    </telerik:RadTreeNode>
                </Nodes>
            </telerik:RadTreeNode>
            <telerik:RadTreeNode Text="Technology" ExpandMode="ServerSide">
                <Nodes>
                <!-- add Technology nodes here -->
                </Nodes>
            </telerik:RadTreeNode>
            <telerik:RadTreeNode Text="Warranty" ExpandMode="ServerSide">
                <Nodes>
                <!-- add Warranty nodes here -->
                </Nodes>
            </telerik:RadTreeNode>
</telerik:RadTreeView>


text:
Q: How can I get my Navbar to display at the top of the page?
This is my Navbar at the moment. I'm not sure why it's running long. I tried adjusting the css to keep it along the top of the page, but nothing seems to be working. I also tried to inspect element on the pink portion of the screen, but I am not able to read it properly. I am still fairly new to web development. Any help is greatly appreciated, thanks!
This is my app.js file:
import React, { Component } from 'react';
import Navbar from './Navbar'
import {BrowserRouter, Switch, Route} from "react-router-dom";
import './App.css';

import Home from '../pages/Home';
import Vault from '../pages/Vault';
import Footer from './Footer';

class App extends Component {

  render() {
    return (
    <BrowserRouter>
      <Navbar />
        <Switch>
          <Route exact path="/">
          <Home></Home>

          </Route>
          <Route exact path="/vault">
            <Vault></Vault>
          </Route>
          <Route path="/governance">
          </Route>
          <Route path="/whitepaper">
          </Route>
        </Switch>
    </BrowserRouter>
    );
  }
}

export default App;

And this is my Navbar.js file:
import React, { useState } from "react";
import { NavLink } from "react-router-dom";
import logo from '../components/logo.png'

const Navbar = () => {
  const [isOpen, setOpen] = useState(false);
  return (

          <a
            role="button"
            className={`navbar-burger burger ${isOpen && "is-active"}`}
            aria-label="menu"
            aria-expanded="false"
            onClick={() => setOpen(!isOpen)}
          >

          <div className={`navbar-menu ${isOpen && "is-active"}` }>

            <NavLink className="navbar-item" activeClassName="is-active" to="/">
              Home
            </NavLink>
            <NavLink className="navbar-item" activeClassName="is-active" to="/vault">
              Vault
            </NavLink>
            <NavLink className="navbar-item" activeClassName="is-active" to="/governance">
              Governance
            </NavLink>
            <NavLink className="navbar-item" activeClassName="is-active" to="/whitepaper">
              Whitepaper
            </NavLink>

  );
};

export default Navbar;

A: It's a bit tricky without having the original CSS file, but the following should work for you.
.navbar {
    position:fixed;
    top:0px;
    left:0px;
    width:100%;
    height:48px;
    background:red /* for testing purposes */
}


text:
Q: Unable to load new data fact table SSIS I am using visual studios 2017 and Microsoft SQL Studio 17.
While using SSIS I am trying to update the fact table with new data. I am getting an error trying this.

I have loaded some data (big amount) to the fact table this did not cover all the columns so there is null values. I have another table created with this data (8 rows) that I want to load in and populate it. I have the surrogate key with new table it searches using look up and then goes ahead and adds it. Everything is going fine except into the destination.
Getting this error. All data types match.

\Error Code DTS_E_PROCESSINPUTFAILED. The ProcessInput method on
  component "fact to receive" (2) failed with error code 0xC0209029
  while processing input "OLE DB Destination Input" (15). The identified
  component returned an error from the ProcessInput method. The error is
  specific to the component, but the error is fatal and will cause the
  Data Flow task to stop running. There may be error messages posted
  before this with more information about the failure.

If I can not trouble shoot this on SSIS would there be a command to run on T SQL you can advise.
Has gone through by assigning surrogate keys to the source table. This does not look like the data has entered successfully.


text:
Q: Running a cron every 1 day and 10 seconds? Is it possible to run a cron every 86410 seconds or simply every 1 day and 10 seconds?
I have a service which takes 24 hours to process the data from the moment it is called! Now, I need to make sure that I am giving the service enough time to process the data so instead of calling the service every 24 hours, I need to call the service every 24 hours and few seconds!
Is it possible using a cron?

A: I think it is interesting to note that if you do want to restart the processing every 86410 seconds, then your service start times would drift over days, later and later every time - so if you originally scheduled your process to start at 08:00, after about a year it would be starting at 09:00, and after about 23.6 years, it would go around the clock to start again at 8am.
Cron was definitely not designed for that kind of thing :-)
But if you are running on a recent Linux OS, you can use SystemD timer units to do exactly that. You may be familiar with SystemD service units - as this is how you write services for modern Linuxes, but SystemD can do a lot more, and one of those things is scheduling things that require interesting schedules.
Supposed you run your processing job as a SystemD service, it may look something like this:
/etc/systemd/system/data-processing.service
[Unit]
Description=Process some data
[Service]
Type=simple # its the default, but I thought I'd be explicit
ExecStart=/usr/bin/my-data-processor

You can then set up a timer unit to launch this service every 86410 seconds very simply - create a timer unit file in /etc/systemd/system/data-processing.timer with this content:
[Unit]
Description=start processing every day and 10 seconds
[Timer]
OnBootSec=0 # Start immediately after bootup
# Start the next processing 86410 seconds after the last start
OnUnitActive=86410
AccuracySec=1 # change from the default of 60, otherwise
# the service might start 86460 after the last start
[Install]
WantedBy=timers.target

Then just enable and start the timer unit - but not the service. If the service is enabled, you probably want to disable it as well - the timer will take care of running it as needed.
systemctl daemon-reload
systemctl enable data-processing.timer
systemctl start data-processing.timer

Looking at it a bit more, you mentioned that you want to start the next run of the service after the previous run has completed. What happens if it doesn't take exactly 86400 seconds to finish processing? If we change the requirement to be "restart the data processing service after it finished running, but give it 10 seconds to cool down first" then you don't need a timer at all - you just need to have SystemD restart the service after a 10 seconds cooldown, whenever it is done.
We can change the service unit above to do exactly that:
[Unit]
Description=Process some data
[Service]
Type=simple
ExecStart=/usr/bin/my-data-processor
Restart=always
RestartSec=10


text:
Q: Unexpected behavior from Popen once web app is deployed with apache I have some code that uses subprocess to look at the logs from a git directory.  My code seems to work fine when executed in a local django dev environment.  Once deployed however (with Apache / mode_wsgi) the output from stdout read() comes back empty.  My development and production machine are the same right now, and I also tried making sure every file was readable.
Does anybody have an idea why Popen is not returning any output once deployed here?  Thanks.
def getGitLogs(projectName, searchTerm=None, since):
    os.chdir(os.path.join(settings.SCM_GIT, projectName))
    cmd = "git log --since {0} -p".format(since)
    p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True)
    output = p.stdout.read()
    ### here output comes back as expected in dev environment, but empty in once deployed
    return filterCommits(parseCommits(output), searchTerm)

A: *

*Chain your chdir as part of your command (ie, cd /foo/bar/zoo)

*Pass the full path to git
So your command would end up cd /foo/bar/zoo && /usr/bin/git log --since


text:
Q: No type for 'Value' can satisfy both 'Value == Any' and 'Value == String' There is a type alias in a library we use that is defined as:
public typealias Parameters = [String: Any]

For convenience we ha
extension Parameters where Key: String, Value: StringProtocol {
    public var queryString: String {
        self.map { "\($0)=\($1)" }.joined(separator: "&")
    }
}

This used to work with Swift 5.6 but doesn't in Swift 5.7. The message is:
"No type for 'Value' can satisfy both 'Value == Any' and 'Value == String'"
How can this be refactored so that we can still have a nice extensions where Value is StringProtocol?


text:
Q: Jquery does update the sum inside the input element, but not inside the span (.val & .html) With this code I am trying to sum the value of my checkboxes. It works only when I use the result inside an input element.
<input type="text" id="total1" class="container-input noborder">

I want the results inside the span. Like this:

This code works inside the input, but not inside the span.
$('#total1').val(total2);

This code shows only the sum inside the span, but it did not update the results when I check the checkboxes.
("#total1").html(total2);

This my code:
    $(function(){
$(".tot_amount").click(function(event) {
var total = 0;
$(".tot_amount:checked").each(function() {
total += parseInt($(this).val());
});
//$("#tot_amount").val(sum.toFixed(3));

$('#total1').val(total);

});

});

$(document).ready(function () {
var total2=0;
    $(".tot_amount").each(function() {
total2 += parseInt($(this).val());

});

$('#total1').val(total2);

//$("#total1").html(total2);
});

A: did you mean to bind an event to your checkboxes ?
like so
$('#checkbox1').change(function() {
    if(this.checked) {
        //.. calculate something
    }
});

A:
Try this!

$('.tot_amount').click(function() {
    if($('.tot_amount').is(":checked")) {
        //do whatever
    } else {
       //do whatever
    }
});


text:
Q: Running MapReduce job periodically without Oozie? I have a mapreduce job as a 'jar' ,that should be run daily. Also, I need to run this jar from a remote java application. How can I schedule it: i.e, I just want to run job daily from my remote java application.
I read about Oozie, but I dont think it is apt here.

A: Take a look at Quartz. It enables you to run a standalone java programs or run inside  an web or application container (like JBoss or Apache Tomcat). There is a good integration with Spring and Spring batch in particular.
Quartz can be configured outside of the java code - in XML and the syntax is exactly like in crontab. So, I found it very handy.
äSome examples can be found here and here.

A: I am not clear about your requirement. You can use ssh command execution libraries in your program.
SSH library for Java
If you are running your program in linux environment itself, You can set some crontab for periodic execution.

A: If the trigger of your jar is your java program, then you should schedule your java program hourly rather than the jar. And if that is separate, then you can schedule your jar in Oozie workflow where you can have the java code execution in step one of oozie workflow and jar execution in the second step.
In oozie, you can pass the parameters from one level to another as well.Hope this helps.
-Dipika Harwani


text:
Q: Firefox: How to allow remembering of media query setting on non secure page? The image below says almost everything, but I'm adding this text so it is easier to search for.  "Remember this decision" does not work.
The response is "Your connection to this site is not secure…"

Is there a way I can disable this?  I'm trying to do some development on a personal server, and it's a huge hassle having to verify over and over again that I want to use my microphone.  Something in about:config?

A: You can't disable this protection without changing Firefox's code.
Code controlling this protection:
// Disable the permanent 'Allow' action if the connection isn't secure, or for
// screen/audio sharing (because we can't guess which window the user wants to
// share without prompting).
let reasonForNoPermanentAllow = "";
if (sharingScreen) {
  reasonForNoPermanentAllow = "getUserMedia.reasonForNoPermanentAllow.screen3";
} else if (sharingAudio) {
  reasonForNoPermanentAllow = "getUserMedia.reasonForNoPermanentAllow.audio";
} else if (!aRequest.secure) {
  reasonForNoPermanentAllow = "getUserMedia.reasonForNoPermanentAllow.insecure";
}

Link to source code


text:
Q: after remove hotmail from outlook, mails from hotmail in the pst file dispeared I have connected hotmail and transfered mails to my local pst file. after I remove hotmail account I don't see the mails from my local .pst file anymore

A: It sounds like you configured Outlook to access your Hotmail account originally with an IMAP connection. This could cause Outlook to remove the mail files from the PST when you detached the Hotmail account. I would recommend setting up Outlook with POP access to your Hotmail account. You can then set Hotmail to redownload all files from a certain date and on or all mail items. Configure Outlook to leave messages on the server. Once you remove the Hotmail account from Outlook, the emails will remain.


text:
Q: Perform page loads with jQuery on all normal anchor tags I have a website here with a dark Bootstrap theme.  I have tried various tricks for eliminating white flashes on page loads, but they only work about half the time.
Can I use jQuery to "intercept" links and load them asynchronously, so there is no flash?
I don't want to change the actual link format in the menu bar, etc., as that would require modifying my CMS.  I can change everything about the site template except the navigation, which is generated automatically.

A: You can bind all hyperlinks, or target the ones you want with the right CSS selector, and prevent the default behaviour then simply do an ajax query to get the page and do whatever you want from there.
$("a").on("click", function(event) {
    event.preventDefault();
    $.get(this.href, function(data) {
        // do stuff
    });
});


text:
Q: How to align v-cols horizontally in vuetify? I would like to align all seven of those buttons centered. As you can see the last one is a bit off compared to the first one.

How do I achieve this?
I've already tried justify="center" and justify="space-around"
Here is my code:
  <v-row no-gutters justify="space-around">
    <v-col v-for="(item, index) in buttons" :key="index">
      <toggle-button
        :weekday="item.weekday"
        :button="item.state"
      ></toggle-button>
    </v-col>
  </v-row>

Here is the toggle-button component:
<template>
  <v-btn
    outlined
    depressed
    :class="button ? 'primary white--text' : 'outlined'"
    @click="button ? (button = false) : (button = true)"
    v-model="button"
    icon
  >
    {{ $t("roomservice.weekdays." + weekday) }}
  </v-btn>
</template>

<script>
export default {
  data() {
    return {};
  },
  props: ["button", "weekday"]
};
</script>

A: v-col is not a flex and contents inside (toggle-button) are justified to start form left.
you can fix this by adding class="d-flex justify-center" on v-col
<v-row no-gutters justify="space-around">
    <v-col
        class="d-flex justify-center"
        v-for="(item, index) in buttons"
        :key="index">
        <toggle-button
            :weekday="item.weekday"
            :button="item.state"
        ></toggle-button>
    </v-col>
</v-row>


text:
Q: Insert Cyrillic text into SQL Server I need to insert Cyrillic text into a SQL Server database. I'm using MVC 4, and the controller code is:
    public ActionResult AddCategory(Ferro_Balkan.Models.category Cat)
    {
        Ferro_Balkan.Models.ferroEntities ent = new Ferro_Balkan.Models.ferroEntities();

        if (ModelState.IsValid)
        {
            ent.Categoriis.Add(Cat);
            ent.SaveChanges();
            return RedirectToAction("AdminCategory", "Admin");
        }

        return View(Cat);
    }

I don't know how to insert Cyrillic text... I need a solution that works within the code listed.

A: You need to verify that charset of the page submitting Cyrillic value(Cat) to you is set to UTF-8. If it is then you should not have any problem.


text:
Q: Access Java RMI from .NET I have a existing java based system which uses RMI.  I do not have access to change this system.
I want to be able to call the RMI api methods directly from .NET.  What is the best way to accomplish this?  Free or lowish cost preferred if its a third party component.
Thanks

A: Your best bet would be to build a Java facade for the existing system which will talk with it using RMI and on the other side provide something more standard - Web Services or maybe REST.
Additional advantage of this approach is the protection it gives you against the legacy app bugs and bad design decisions. For example, if there are some ugly workarounds that you need to do to call the existing application, those can be safely hidden in the facade layer without compromising the desing and integrity of the new app you are writing.

A: I'm not sure about .Net + RMI.  However it should be possible to build a Java component which talks to the RMI service and call that Java component from .Net using one of the supported mechanisms.
Article about calling Java from .Net

*

*http://it.toolbox.com/blogs/daniel-at-work/using-ikvm-to-call-java-from-net-21993

A: You should be able to access the EJB using CORBA
Look here: http://weblogic.sys-con.com/node/42640
Old but quite relevant.


text:
Q: Ошибка отправки AJAX запроса Пытаюсь отправить AJAX запрос, но что-то идёт не так. При нажатий запрос возвращает undefined. В чём проблема?
//HTML

//JQUERY
$(document).ready(function() {
    $("#start").bind("click", function(event) {
        $.ajax({
            url: "work.php",
            type: "POST",
            dataType: "html",
            async: false,
            success: function(data) {
                alert(data.text)
            }
        });
    });
});

//work.php
<?php echo "Hello World!";