text:
Q: Cart not adding correct item in React.js I'm learning React.js (and I'm a beginner at JavaScript) and having some difficulty getting my addToCart function working properly.  I've managed to get all my products to display but adding to cart on any of them only adds the first item, and once that item is out of stock then all the items go out of stock.
I'm sure I'm missing something obvious but would really appreciate some more experienced eyes on my code please.
Github repo for this app
Below are my FluxProduct.react.js product components:
var React = require('react');
var FluxCartActions = require('../actions/FluxCartActions');

var FluxProduct = React.createClass({

  addToCart: function(event){
    var id = this.props.selected.id;
    var update = {
      name: this.props.product.name,
      category: this.props.selected.category,
      price: this.props.selected.price
    }
    FluxCartActions.addToCart(id, update);
    FluxCartActions.updateCartVisible(true);
  },

  render: function() {
    var self = this;
    var products = this.props.product;
    var stockAvailable = (this.props.selected.id in this.props.cartitems) ? this.props.selected.stock - this.props.cartitems[this.props.selected.id].quantity : this.props.selected.stock;
    return (

      {Object.keys(products).map(function(product){
      return (

{products[product].name}

{products[product].category}

{products[product].description}

Price: ${products[product].price}

              <button type="button" onClick={self.addToCart} disabled={stockAvailable  > 0 ? '' : 'disabled'}>
                {stockAvailable > 0 ? 'Add To Cart' : 'Sold Out'}
              </button>

        )
        })}

    );
  },

});

module.exports = FluxProduct;

Relevant FluxCartApp.react.js components:
render: function(){
    return (

        <FluxCart products={this.state.cartItems} count={this.state.cartCount} total={this.state.cartTotal} visible={this.state.cartVisible} />
        <FluxProduct product={this.state.product} cartitems={this.state.cartItems} selected={this.state.selectedProduct} />

    );
  },

Relevant cart actions:
selectProduct: function(index){
    AppDispatcher.handleAction({
      actionType: FluxCartConstants.SELECT_PRODUCT,
      data: index
    })
  },

  addToCart: function(id, update){
    AppDispatcher.handleAction({
      actionType: FluxCartConstants.CART_ADD,
      id: id,
      update: update
    })
  },

Sorry but I'm not sure what further relevant code needs to be pasted, if anyone has any advice I'd be grateful.

A: You're accessing the products variable from inside your map function, when instead you should be using the product parameter that is passed to it. Additionally, why map on the keys of products, just us the products as an array:

{products.map(function(product){
return (

{product.name}

{product.category}

{product.description}

Price: ${product.price}

        <button type="button" onClick={self.addToCart.bind(null, product.id)} disabled={stockAvailable  > 0 ? '' : 'disabled'}>
          {stockAvailable > 0 ? 'Add To Cart' : 'Sold Out'}
        </button>

  )
  })}

Notice that I've used bind to pass the product ID through to addToCart as well, and this lets us use it like this, with the bound ID passed as the first argument:
addToCart: function(id, event){
    var update = {
      name: this.props.product.name,
      category: this.props.selected.category,
      price: this.props.selected.price
    }
    FluxCartActions.addToCart(id, update);
    FluxCartActions.updateCartVisible(true);
}

You may also be interested in the answer "JavaScript variable binding and loop" which may have been a contributing factor in your problem and often catches out JavaScript newcomers.


text:
Q: What's the difference between "Chain of responsibility" and "Strategy" patterns? I'm raising this question because of another question I asked here on SO some days ago.
I had to solve an specific problem, and after two replies I got, I realized two patterns can help to solve that problem (and any other similar).

*

*Chain of Responsibility

*Strategy
My question is:
What exactly is the difference between those patterns?

A: They're very different.
Strategy is about having a generic interface which you can use to provide different implementations of an algorithm, or several algorithms or pieces of logic which have some common dependencies.
For instance, your CollectionSorter could support a SortingStrategy (merge sort, quick sort, bubble sort). They all have the same interface and purpose, but can do different things.
In some cases you may decide to determine strategy inside. Maybe the sorter has some heuristics based on collection size etc. Most of the time it indeed is injected from outside. This is when the pattern really shines: It provides users the ability to override (or provide) behavior.
This pattern is base of the now-omnipresent Inversion of Control. Study that next once you're done with the classic patterns.
Chain of responsibility is about having a chain of objects which usually go from more detailed to more generic.  Each of the pieces in chain can provide the answer, but they have different levels of detail.
Popular GOF example is a context help system. When you click on a component in your desktop app, which help to display? First item in chain could look for help for the very component you clicked. Next in chain could try and display help for the whole containing dialog. Next for the application module... and so on.
Looks like you haven't, but should, read the GOF "Design Patterns" classic.

A: As the name suggests, the chain of responsibility pattern creates a chain of receiver objects for a request. This pattern decouples sender and receiver of a request based on type of request. This pattern comes under behavioral patterns. In this pattern, normally each receiver contains reference to another receiver.
A Chain of Responsibility Pattern says that just "avoid coupling the sender of a request to its receiver by giving multiple objects a chance to handle the request". For example, an ATM uses the Chain of Responsibility design pattern in money giving process.
Strategy is a behavioral design pattern that lets you define a family of algorithms, put each of them into a separate class, and make their objects interchangeable.
In Strategy pattern, we create objects which represent various strategies and a context object whose behavior varies as per its strategy object. The strategy object changes the executing algorithm of the context object.

A: Most patterns look very similar in code (or even uml) but patterns are centrally about context, responsibilities the particular problem they intend to solve rather than a particular source code. both decouples different things and for different reasons.
The chain pattern separates the responsibility of sending a request from the handling of the request. there could be a number of classes that can handle the same type of request (these classes generally implement the same interface) but the pattern allows the request to be passed along from one class (in the chain) to the other until a handler who is most fit to handle the request gets it and is responsible for handling the request (or until a null handler gets it and indicates the end of the chain). If you allow the wrong handler to handle the request, the result may "NEVER" be correct
The strategy is about method of processing or algorithm selection. take example of a case where you want to calculate the average of some samples. Any algorithm may "ALWAYS" be correct in the given context (e.g all classes having a strategy does same thing: calculates the average ), but the way the average is calculated, or the strategy for calculating the average differs from one class to the other, and the strategy pattern allows you to select which strategy to use in a decoupled manner.
now compare this to the chain pattern , where there can be a request for calculating average in which there is one handler that is responsible for computing average and there could be another request to calculate the standard deviation  in which there is another handler that is responsible for computing standard deviation. so the request to compute average will not in any situation be handled by any other handler other than the handler most fit. where as, any class in the strategy may calculate the average and if you don't like the way one class calculates average, you can "SWAP" one strategy for the other.
ways of implementing  these in source code may differ from programmer to programmer but should PTSUT (pass the same unit test")
Edit:
It could happen that certain members of the chain of responsibility may use strategy pattern to do their work

A: The most significant difference is a semantic behavior of the implementation.
A Chain of Responsibility can have 0...ALL of the responsibilities applied to an input and each Responsibility decides if acts on the input and then passes it on. This is a procedural pattern since all responsibilities may be applied.

Imagine applying a chain of filters to an input with each filter
  deciding if it should process the input or not before it passes it
  onto the next filter.

A Strategy has one and only one of the strategies apply to an input. This is a usually creational pattern since only a single strategy is applied.

Imagine deciding which database driver to use and how to create a connection out of a list of
  database drivers based on the input and once the correct one is found
  it is the only one that is used.

Both can be implemented as a List using a Visitor Pattern the difference would be you stop visiting when a Strategy returns true.
A Strategy Pattern can also be implemented as a Map where the Key is a Predicate that can decide to end the iteration of the keys and then you just get the Value and that is your result.

A: In Chain of Responsibility, it is each object's responsibility to send the call on to the next object in the chain, if the object cannot handle it.
In Strategy, all objects have the same interface, but some outside force has to supply which one is used.

A: You can consider chain of responsibility as a special case of the strategy pattern, which is more generic. As stated by Konrad the problem you address with the pattern-based solution is different.
BTW: You can find a kind of strategy in almost any GOF pattern.

A: Strategy pattern:

*

*It's a behavioural pattern

*It's based on delegation

*It changes guts of the object by modifying method behaviour

*It's used to switch between family of algorithms

*It changes the behaviour of the object at run time. One algorithm will be selected from a family of algorithm.

Have a look at this SE question for Strategy example :
Real World Example of the Strategy Pattern
Chain of Responsibility:

Chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain.

Key points:

*

*Multiple objects may handle the request and handler may not be a specific object

*In Chain of responsibility pattern, the request will be passed through a chain of objects until it has been handled. But in Strategy, one specific algorithm will be selected at run-time from a family of algorithms.

Real world example : In a company, a designated role have particular limits to process purchase request. If person with a designated role does not have enough power to approve purchase bill, he will forward the command/request to his successor, who have more power. This chain will continue until the command is processed.
Refer to below useful SE questions/links
Chain-of-responsibility_pattern
Chain-of-responsibility-pattern from oodesign
chain_of_responsibility from sourcemaking

A: Strategy pattern is a business level pattern, a standardized interface way of how to achieve given goals/data results.
Chain of responsibilities is more implementation pattern - describing how you process the data, but not focusing for what (goals of a strategy).
For example:
Let's say we have 100 young swimmers in a club and 4 times a year you must select 10 person team for a regular national competition.
The competitions have different profiles - some have more backstroke races, some more relay races, etc ... what means you must apply different team selection strategy.
So you have 4 dedicated strategies, one for each event.
In the code it could look like:
RankingsSet rankedClubSet = getSwimmersRankings(SwimmersSet allSwimmers)
SwimmersSet teamOf10 = selectTeamForCompetion(RankingsSet rankedClubSet, CompetionSelectionStrategy strategy)

But how to get the rankings?
You just ask for opinion the coaching staff:
swimmer(self-assessment) -> physiologist -> biological renewal trainer -> doctor -> swimming trainer -> teammates -> teachers -> parents ... ----> strategy/qualifying committee
This is a chain of responsibilities. The order is important ... a doctor cannot assess a swimmer without evaluation from physiologist, parent opinion does not matter if main trainer rejects a swimmer ...
The ranking information is merged while passing from one processor to the next processor, some data are hidden for some processor, other can be decorated with additional notes ...
What is interesting in this case that as a narrator from the club you can think of strategy on two levels:

*

*pure calculations on rankings numbers to determine the team  of 10 for a competition i.e. CompetionSelectionStrategy

*the entire process of selection - collecting rankings, tuning the dedicated strategies, questions how sport psychologist opinion matters etc.

but in "Design Patterns" terminology the strategy pattern is only 1.
Point 2. is too big to analyze in terms of single design pattern.
It is important to remember that in Design Pattern analysis you should focus on rather small pieces of functionality, where you can easily identify a single pattern and implement it.
When functionality chunk is too big automatically many patterns and relation between them are involved, the discussion becomes chaotic, some guys are so fixated on some patterns that they see them everywhere.  Identifying design patterns is based on slow analysis and careful problem decomposition.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Efficiently extracting rows from pandas dataframe in which I have to search for elements in a list My dataframe is like this:
id author
1  ['abc','def','alp']
2  ['akx','xyz','shdj','dhhs']
3  ['abc', 'alp','pqw']

For eg, I want to extract all the rows with authors ['abc','alp'].It should extract rows 1 and 3.
Is there any efficient way to do this using python pandas?

A: Use sets with list comprehension, for filtering boolean indexing:
L = ['abc','alp']
df = df[[set(x) >= set(L) for x in df.author]]
print (df)
   id           author
0   1  [abc, def, alp]
2   3  [abc, alp, pqw]

Detail:
print ([set(x) >= set(L) for x in df.author])
[True, False, True]


text:
Q: How to receive a real object in GraphQL dotnet client app? I run a GraphQL client and send the queries
        var response3 = await client2.SendQueryAsync<ADescriptorResponse2>(request2);
        var response2 = await client2.SendQueryAsync<dynamic>(request2);
        var response1 = await client2.SendQueryAsync<object>(request2);

There is
   public class ADescriptorResponse2
    {
        public ADescriptor aDescriptor { get; set; }
    }
    public class ADescriptor
    {
        public long  Action { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
    }

But in the 1st case
var response3 = await client2.SendQueryAsync(request2);
i receive the response3.Data ==null, type ADescriptorResponse2
In other both cases I receive Data correct but it isNewtonsoft.Json.Linq.JObject type.
Why I do not receive the Data of ADescriptorResponse2 filled with data?
What is incorrect?

A: This most probably means that the structure of the data is such that it cannot correctly deserialize to type of ADescriptorResponse2.
You can check the structure of the data which you get from response2 and response1 and see if it is in the shape of ADescriptorResponse2.
It could be some nested object issue where you need another object on top of ADescriptorResponse2 or something of that nature.


text:
Q: How to control settings of Windows Service from GUI? I have this Windows Service that communicates with TCP/IP.
What I want to know is a method for a Windows Form Application to able to modify the setting of this service, such as remote host address and port to connect, timeout length, and log settings.

I have researched about NamedPipe, WCF Service, and IPC, but I can't decide what matches my scenario the best.
Will be nice to able to change the service settings by doing something like this from the client side.

[Service].SetTimeout(3000);

Any suggestions?

A: If you want that kind of programmatic control, then WCF is your best bet.  With WCF, you get to define the API yourself, e.g., what methods to call, what messages to pass, etc.  The WCF framework takes care of exchanging the data for you.  And with the WCF config files, changing the back-end data exchange mechanism is trivial.  For example, you could replace a NetNamedPipeBinding used for same-machine communication with a NetTcpBinding for cross-machine communication simply by modifying the config file(s).  Full disclosure, though, if you haven't done WCF before, my experience was that the barrier to entry was pretty high.  Of course, I took my lumps with Visual Studio 2008.  It might be much easier in a more recent version.  Here's an answer I gave a while back with some tutorials that helped me.
For me personally, I've replaced the early WCF implementation with a TCP-based version over localhost in the project I work on.  The front-end application receives constant information from the Windows service when things are "running," and at the time of our decision, WCF streaming was not documented very well.  We also saw evidence of problems, although that might simply be because we did it wrong.  In any case, I'm very pleased with the solution we've come up with.
I can't speak to named pipes directly, but from what I've read, they're easy to use.
HTH.


text:
Q: Is it possible to change the version of System.Runtime in a Xamarin project? I've built a DLL of a NetStandard library which is used to access a database. The issue is that after referencing the DLL in my Xamarin Forms project, I cannot use any functions in my library because, the System.Runtime is outdated. Is there any way I can update the System.Runtime assembly in the project?

A: Go to the *.csproj file of the BucketList.Api and change the line:
<Reference Include="System.Runtime, Version=4.2.1.0, Culture=neutral, publicKeyToken=b04f5f711d50a3a">

to:
<Reference Include="System.Runtime, Version=4.1.2.0, Culture=neutral, publicKeyToken=b04f5f711d50a3a">

Recompile the BucketList.Api DLL and reference that.
Alternatively you may try this, which may or may not be legit:
<Reference Include="System.Runtime">


text:
Q: True or False method not working I am trying to set a method called hasPassed() for a test score but can't seem to do it.
The error I am getting is:

windowsformapplication1.student.HasPassed()' not all code paths return a value

This is my code:
public int YearMark
{
    get { return yearMark; }
    set { yearMark = value; }
}

private bool hasPassed;
public bool HasPassed()
{
    if (yearMark < 40)
    {
        hasPassed = false;
    }
    else
    {
        hasPassed = true;
    }
}

A: You forgot to return the bool value -
public bool HasPassed()
{
   return yearMark >= 40;
}

A: You need to return a value, try this:
public bool HasPassed()
{
    return ( yearMark >= 40 )
}

A: Apparently you are an old pascal user? You need to actually return the value after you assign it to hasPassed.
You should do it this way if you like your code:
public bool HasPassed()
    {
        if (yearMark < 40)
        {
            hasPassed = false;
        }
        else
        {
            hasPassed = true;
        }
        return hasPassed;

    }

Or this way if you want it simpler and keep understanding it at a first glance:
public bool HasPassed()
{
    if (yearMark < 40)
    {
        return false;
    }
    return true;
}

A: Your method has a bool return value, so you need to return true or false, not just set a field called hasPassed.  Change the method to return true or return false inside your if

A: The fix depends on how your intended design works. If the function HasPassed() is supposed to return the boolean value of hasPassed, then you need to explicitly return it in the code.
public bool HasPassed()
    {
        if (yearMark < 40)
        {
            hasPassed = false;
        }
        else
        {
            hasPassed = true;
        }
        return hasPassed;

    }

But, if you intend for HasPassed() to just change the value of the private variable hasPassed and not actually return anything, you need to change the return type of the function to void.
public void HasPassed()
    {
        if (yearMark < 40)
        {
            hasPassed = false;
        }
        else
        {
            hasPassed = true;
        }
    }

A: You don't necessarily need to return anything at all as long as you check what hasPassed is in your calling method.
private bool hasPassed;
public void HasPassed()
{
    if (yearMark < 40)
    {
        hasPassed = false;
    }
    else
    {
        hasPassed = true;
    }
}

public void Main()
{
    HasPassed();
    if (hasPassed)
    {
         //Do something
    }
}

Not how i'd go about it, but its another solution.


text:
Q: How to use mysql_real_escape_string function in PHP So in this program I'm writing, I actually grab a SQL query from the user using a form.  I then go on to run that query on my database.
I know not to "trust" user input, so I want to do sanitization on the input.  I'm trying to use mysql_real_escape_string but have been unsuccessful in getting it to work.
Here's what I'm trying, given the input:
select * from Actor;
//"query" is the input string:
$clean_string = mysql_real_escape_string($query, $db_connection);
$rs = mysql_query($clean_string, $db_connection);
if (!$rs)
{
    echo "Invalid input!";
}

This is ALWAYS giving me the

"Invalid input!"

error.
When I take out the clean_string part and just run mysql_query on query, the

"invalid
  input"

message is not output.  Rather, when I do this:
$rs = mysql_query($query, $db_connection);
if (!$rs)
{
   echo "Invalid input!";
}

It does NOT output

"invalid input".

However, I need to use the mysql_real_escape_string function.  What am I doing wrong?
Update:
Given
select * from Actor; as an input, I've found the following.
Using echo statements I've
found that before sanitizing, the string holds the value:
select * from Actor;
which is correct. However, after sanitizing it holds the incorrect
value of select *\r\nfrom Actor;, hence the error message.  Why is
mysql_real_escape_string doing this?

A: use it on the actual values in your query, not the whole query string itself.
example:
$username = mysql_real_escape_string($_POST['username']);
$query = "update table set username='$username' ...";
$rs = mysql_query($query);

A: Rather than using the outdated mysql extension, switch to PDO. Prepared statement parameters aren't vulnerable to injection because they keep values separate from statements. Prepared statements and PDO have other advantages, including performance, ease of use and additional features. If you need a tutorial, try "Writing MySQL Scripts with PHP and PDO".

A: mysql_real_escape_string() is the string escaping function. It does not make any input safe, just string values, not for use with LIKE clauses, and integers need to be handled differently still.
An easier and more universal example might be:
 $post = array_map("mysql_real_escape_string", $_POST);
 // cleans all input variables at once

 mysql_query("SELECT * FROM tbl WHERE id='$post[id]'
                OR name='$post[name]' OR mtime<'$post[mtime]' ");
 // uses escaped $post rather than the raw $_POST variables

Note how each variable must still be enclosed by ' single quotes for SQL strings. (Otherwise the escaping would be pointless.)

A: You should use mysql_real_escape_string to escape the parameters to the query, not the entire query itself.
For example, let's say you have two variables you received from a form. Then, your code would look like this:
$Query = sprintf(
    'INSERT INTO SomeTable VALUES("%s", "%s")',
    mysql_real_escape_string($_POST['a'], $DBConnection),
    mysql_real_escape_string($_POST['b'], $DBConnection)
);

$Result = mysql_query($Query, $DBConnection);

A: manual mysql_real_escape_string()

Escapes special characters in a string
  for use in an SQL statement

So you can't escape entire query, just data... because it will escape all unsafe characters like quotes (valid parts of query).
If you try something like that (to escape entire query)
echo mysql_real_escape_string("INSERT INTO some_table VALUES ('xyz', 'abc', '123');");

Output is

INSERT INTO some_table VALUES (\'xyz\',
  \'abc\', \'123\');

and that is not valid query any more.

A: This worked for me. dwolf (wtec.co)
<?php
// add data to db
require_once('../admin/connect.php');

$mysqli = new mysqli($servername, $username, $password, $dbname);

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$post = $mysqli->real_escape_string($_POST['name']);
$title = $mysqli->real_escape_string($_POST['message']);

/* this query with escaped $post,$title will work */
if ($mysqli->query("INSERT into press (title, post) VALUES ('$post', '$title')")) {
    printf("%d Row inserted.\n", $mysqli->affected_rows);
}

$mysqli->close();

//header("location:../admin");
?>


text:
Q: Change Excel Created Date Through VBS The created date I want to change through VBS is shown under the File tab (Excel 2010 or later) under Related Dates. My question is how to change Excel's interior created date and not the created date of the file (aka File Properties).
I can change Excel's interior created date with a macro:
ThisWorkbook.BuiltinDocumentProperties("Creation Date") = Date

How do you do this through VBS? Right now I have:
Dim objFSO, objFile
Set objFSO  = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile("C:\My\Path\Excel.xls")
objFile.BuiltinDocumentProperties("Creation Date") = Date

But this changes the created date of the file.

A: You'd do it the same way, by instantiating Excel and acting on the open workbook:
Dim e
Set e = CreateObject("Excel.Application")
e.Workbooks.Open "c:\my\path\excel.xls"
e.ActiveWorkbook.BuiltinDocumentProperties("Creation Date") = Date
e.ActiveWorkbook.Save
e.Quit


text:
Q: What is the difference between radiation, emission and reflection in terms of heat? I am reading heat transfer and I get confused between these terms. I know they are very basic terms but I can't relate them with heat. Any help is appreciated.

A: Heat IS radiation in the sence that it is infrared electromagnetic radiation.
Emission is how much energy (heat) one radiates outwards due to ones internal energy. Normally this behaviour is modelled as a blackbody radiator with an emissivity and absorbtivity (spelling please).
Reflection is the part of incoming radiation that is not absorbed by the blackbody (unless it is a perfect blackbody) and is thus reflected outwards.

A: Speaking as an architect and engineer I am familiar with three forms of heat emission or transfer:

*

*Conduction in which thermal motion of particles is transferred from a hot body to a cold one in contact with it.

*Convection in which heat is similarly transferred to a fluid medium, the locally heated volume of which then expands and rises, drawing in more cold fluid.

*Radiation in which electromagnetic energy, primarily in the infrared band, is emitted to carry away the excess energy of the agitated particles.

Thus, from my perspective one can give the more physics-related answer that in this context:

*

*"Heat" may refer either to the random kinetic energy of individual particles in a mass, or to electromagnetic radiation in the infrared band.

*Radiation is the emission of heat via black body radiation, which one may describe either as a classical wave or a stream of photons, according to which mathematical treatment is the more convenient at the time.

*Emission is the passing of heat energy in any form to somewhere else.

*Reflection is the blocking of incoming thermal radiation and returning it back to the medium in which it arrived.

A: Think about the duality of wave and particle proposed by Paul Dirac.
Emission is used in context that it is considered as particle, like blackbody emits photon energy (energy in packets).
Radiation is used in context that it is considered as wave, like frequency of electromagnetic waves.


text:
Q: Записать в указаную строку текстогого файла значение переменной на bash Есть в наличии файл скажем test.txt с таким содержанием:
text1
text2
3
44
text5

подскажите пожалуйста как на bash реализовать запись изменение скажем 3 строки, и по ходу выполнения скрипта изменять 5 строку и так далее,номер изменяемой строки также считывать из переменной, спасибо!

A: Если вам нужно брать номер строки из переменной, то просто подставьте
значение этой переменной в ваш скрипт.  Вот пример, который заменяет
третью строчку на text3 и пятую строчку на
text555 на GNU sed:
$ line=3
$ sed -e "${line}ctext3" -i -- ./txt.txt
$ line=5
$ sed -e "${line}ctext555" -i -- ./txt.txt
$
Вот те же действия с помощью более переносимого POSIX ed:
$ line=3
$ more <<-EOF | ed -s -- ./txt.txt
>    ${line}c
>    text3
>    .
>    wq
> EOF
$ line=5
$ more <<-EOF | ed -s -- ./txt.txt
>    ${line}c
>    text555
>    .
>    wq
> EOF
$


text:
Q: Programatically create credit memo I am working on script and want to know about how magento credit memo created. My requirement is same as magento after update quantities of product in order, hit update order button. Then enter custom shipping , custom Adjustment Refund , custom Adjustment Fee. How this work programatically.

A: Try this :
<?php
require_once('app/Mage.php');
Mage::app('default');

class creditmemo
{
    public function index()
    {
        $creditmemoData = array(
        'qtys' => array('order_item_id' => 3, 'qty' => '1'),
        'shipping_amount' => null,
        'adjustment_positive' => '0',
        'adjustment_negative' => null
    );

     $comment= 'comment for credit memo';

     $notifyCustomer =  true;
     $includeComment = false;
     $refundToStoreCreditAmount= '1';
        $order = Mage::getModel('sales/order')->load(101);
        //OR $order = Mage::getModel('sales/order')->loadByIncrementId('100001');

        // Case : 1 partial credit memo

            /*$orderItem = $order->getItemsCollection()->getItemByColumnValue('sku', 'test-1');
            $creditmemoData = array(
                'qtys' => array( $orderItem->getId() => 1)
            );*/

        // Case : 2 full credit memo
        // $creditmemoData = array();

        /** @var $service Mage_Sales_Model_Service_Order */
        $service = Mage::getModel('sales/service_order', $order);
        /** @var $creditmemo Mage_Sales_Model_Order_Creditmemo */
        $creditmemo = $service->prepareCreditmemo($creditmemoData);

        $creditmemo->setPaymentRefundDisallowed(true)->register();
        // add comment to creditmemo
        if (!empty($comment)) {
            $creditmemo->addComment($comment, $notifyCustomer);
        }
        try {
            Mage::getModel('core/resource_transaction')
                ->addObject($creditmemo)
                ->addObject($order)
                ->save();
            // send email notification
            $creditmemo->sendEmail($notifyCustomer, ($includeComment ? $comment : ''));
        } catch (Mage_Core_Exception $e) {
             $e->getMessage();
        }
        return $creditmemo->getIncrementId();
    }
}
$obj = new creditmemo();
$obj->index();
?>

A: If you do not need to play with online refund try this
$order = Mage::getModel('sales/order')->load($entity_id);
$orderCreditApi = Mage::getModel('sales/order_creditmemo_api');
$result = $orderCreditApi->create($order->getData('increment_id'));


text:
Q: Make More button in tabbed bar application slide out in iOS This is a simple question. So I have a tabbed bar application with a More... tab button. I was wondering if it's possible to make the More... button be a slide out menu button? I found tutorials on how to do it on a regular app design but things get a little more complicated when it comes to the tabbed bar application.

A: The thing is that you don't own the More button in the tab bar of a UITabBarController, so you can't control what happens. (You can access the navigation controller that appears when the More button is tapped, but it's still going to be just another view controller whose view is displayed above the tab bar.) If you want to write a new interface you'll have to write a whole new interface, i.e. don't use the built-in UITabBarController. That's no big deal; it isn't doing anything you can't manage to do yourself.


text:
Q: Is it possible to call one event of Kendo UI inside another event? Can someone answer how to call databound-event inside save event in Kendo UI?
The requirement is to access the KendoGrid data dynamically (as and when it changes). (I tried using the change function, but it is not firing.)
So I think, my requirement would be possible by calling the databound event inside the save  function, so that I get the latest value as well as and when it changes.
P.S:- I cant use this.refresh(); function inside the save function because, there's another requirement for me to add a new row when pressing enter key.


text:
Q: MS Access: Way to maintain persistent session across multiple Form Events? Hopefully this is a simple question, though the solution may not be. In MS Access, is it possible to instantiate a VBA class in the application or database scope?
What I want to do is persist a WinHttp instance with the same lifetime as the application or database so that as various Form Event handlers call a web service, they can do so using a persistent session object.
If not, it seems like I'll always need to grab and persist the session state, particularly the JSESSIONID, before the current instance goes out of scope and then quietly put it back on the next instantiation. This is coming up because I really can't afford the authentication overhead on the client or the server.
What would be the recommended way to maintain a physical or virtual persistent session across multiple Form Events?

A: Yes, this certainly is possible. Just dim it in a module outside of any sub or function (without the New keyword)
Public winHttpObj As Object

Public Sub CreateWinHttpObj
   Set winHttpObj = CreateObject("WinHttp.WinHttpRequest.5.1")
End Sub

You can refer to it from the same module, or from any other module by using the ModuleName.Variablename notation
If it's desirable is a whole different question.


text:
Q: How to create auto incrementing / SERIAL id columns using DBeaver with PostgreSQL? I am a new user for both PostgreSQL and DBeaver (Community edition ver. 5.1.6) and was looking for a way to create an auto incrementing ID column in a table through the DBeaver GUI.
From my research I can see that:

*

*You can set this up easily using SQL eg. id SERIAL NOT_NULL

*The underlying problem is that there is no such thing as a 'Serial data type', and that SERIAL equates to nextval('table_name_id_seq').

*When I create a table using the SERIAL command in SQL the resulting id column has a nextval('exampletable_id_seq'::regclass') value in the 'Default' attribute.
I have attempted to manually input the nextval() command within the 'Default' attribute for the column in DBeaver in a new table, for example. nextval('mytable_id_seq') with and without the '::regclass;. However this is not working.
I appreciate that doing this in SQL would be easier, and that there is a previously asked question at: Problems de Serial data type in DBeaver & PostgreSQL.
However, I could not find a satisfactory answer and the option of being able to do this through the GUI would be useful, especially if other setup is being done through the DBeaver GUI.
Specifically, my question is:

*

*Is there a functionality for DBeaver to add auto incrementing id's through the GUI?

*If so, what would be the steps to do this.

A: After reviewing the very helpful comments to my question above, I have realized that the question was asked due to my lack of experience with DBeaver.
For completeness I have set out the answer to my question below:

*

*Yes there is a way to auto-increment directly through the DBeaver GUI.

*This can be done by setting up an id variable when a table is created by setting a column with a type of serial and "not null" ticked, then setting the id as a primary key through constraints.
Screenshot attached below:

Due to the way PostgreSQL works, the 'Serial' type is a pseudotype that allows a sequence of numbers to be used (http://www.postgresqltutorial.com/postgresql-serial/).
So, in DBeaver, once you set up the tables this will be displayed as the following rather than with a 'serial' type:

I appreciate that this is a very obvious answer to anyone who is familiar with PostgreSQL and/ DBeaver, thank you for your understanding :)


text:
Q: Global inbox/supercollider on mobile should have a way to read more than four entries On a desktop computer the notifications pane in the supercollider has a scrollbar, so I can see all of my messages/notifications by scrolling.  On my (Android) phone, however, I can see the most-recent four entries but nothing past that -- no scrollbar, no "more" link, nothing.  Further, visiting the inbox clears all the notifications, so they won't show up as new next time I'm on a computer where I could see them -- I have to remember to back-read.  I've had to train myself to not click at all if the number in the red bubble is greater than 4, which is pretty annoying (especially as a moderator).
Could we please have some affordance for seeing all the notifications on the phone?  Failing that, could the mobile interface at least not mark as read notifications that were never displayed, so I'll catch them later?


text:
Q: Install4j: Launched app displays separate JavaApplicationStub in dock When we converted our application from Java 5/6 to Java 7, the icon installed on the Dock no longer behaves as expected.  Previously, the icon on the Dock would launch our application, and would then show as being the active application, as is normal for MacOS.
When we switched to Java 7, the installed Dock icon bounces when clicked, briefly changes to a generic window icon, then reverts and becomes inactive.  In its place a new icon appears on the Dock (as for an application which was not already kept in the Dock), with the correct appearance, but with the title JavaApplicationStub.  If the user then selects Options->Keep In Dock on this application, the icon reverts to what appears to be a generic console app icon on exit.
I know that JavaApplicationStub is the name of the actual executable launched by MacOS X, which then launches the JVM.  What I don't understand is why our application is no longer showing its actual title, nor why a new icon appears while it's running.
I have attempted to resolve this by adding CFBundleDisplayName to the generated Info.plist, along with the necessary InfoPlist.strings file (in Contents/Resources/en.lproj), but this didn't change anything.
Interestingly, I have also observed Install4j itself revert to this behavior, after the Dock gets updated by running a generated installer.
Am I doing something wrong here?  Is there an option in Install4j I should have changed when switching from Java 5/6 (using Apple JRE) to Java 7 (using bundled JRE 1.7.0_67)?
More Detail: We have the Install4j generated launcher invoke a stub jar file, which among other things performs a "silent update" self-patching operation.  Once updates, if any, have been applied, we launch our main application using a new instance of a URLClassLoader within the same JVM, as follows:
URLClassLoader cload = URLClassLoader.newInstance(new java.net.URL[]{new java.io.File(silentUpdate.getLocalInstallFolder() + FILENAME_JAR).toURI().toURL()});
Class<?> cl = cload.loadClass(MAIN_CLASS);
Method startMethod = cl.getMethod("main", new Class[]{String[].class});
startMethod.invoke(cl, new Object[]{args});


text:
Q: Wait for several backbone models to save using $.when.apply I'm trying to save several backbone models (not in a collection) and execute code after they all get saved.
This is my code simplified:
var requestsArray = modelsArray.map(function(model) {
    return model.save();
});

$.when.apply(undefined, requestsArray)
    .done(function() {
        console.log('DONE CALLBACK');
        console.log('ARGS', arguments);
     })
    .fail(function() {
        console.log('FAILED');
        console.log('ARGS', arguments);
    });

But when I run this - the done callback gets fired immediately and it doesn't wait for the ajax requests to finish.
Why is that?

A: It doesn't happen directly with requests :(
I had to do it this way:
var deferredsArray = modelsArray.map(function(model) {
    var dfd = new $.Deferred();
    model.save().then(function() {
          dfd.resolve();
        }, function() {
          dfd.reject();
        });
    return dfd;
});

$.when.apply(undefined, deferredsArray)
    .done(function() {
        console.log('ALL SUCCESSFUL');
    })
    .fail(function() {
        console.log('AT LEAST ONE FAILED');
    });

And when when all are successful - then the done method of $.when gets called.


text:
Q: Volley timeout error when trying to send data into php database First thing is, I am new to android programming.
I was trying to send data to a PHP server using volley library by watching a video through youtube. But whenever I am clicking the register button, getting an error "com.android.volley.timeouterror". Please help me.
This is my code...
    StringRequest stringRequest= new StringRequest(Request.Method.POST, ip, new Response.Listener<String>() {
                                    @Override
                                    public void onResponse(String response) {
                                        try {
                                            JSONArray jsonArray=new JSONArray(response);
                                            JSONObject jsonObject=jsonArray.getJSONObject(0);
                                            String code=jsonObject.getString("code");// used in php file
                                            String message=jsonObject.getString("message");
                                            builder.setTitle("Server Response");
                                            builder.setMessage(message);   //message from server
                                            displayAlert(code);
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }}
                                }, new Response.ErrorListener() {
                                    @Override
                                    public void onErrorResponse(VolleyError error) {
                                        Toast.makeText(first.this, "Call admin error in query"+error, Toast.LENGTH_SHORT).show();
                                    }
                                })//passing data to string request getparams method
                                 {
                                      @Override
                                     protected Map<String, String> getParams() throws AuthFailureError {
                                         HashMap<String, String> params= new HashMap<>();
                                         params.put("name",name);
                                         params.put("email",email);
                                         params.put("password",password);
                                         return params;
                                     }};
                                //string request to requestqueue
                                MySingleton.getInstance(first.this).addToRequestqueue(stringRequest);

                            } else {
                                builder.setTitle("Something went wrong!");
                                builder.setMessage("password doesn't match");
                                displayAlert("input_error");
                            }
                        }
            }

    });

}
public void displayAlert(final String code){
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            if (code.equals("input_error")){
                jet3.setText("");
                jet4.setText("");
            }
            else {
                if(code.equals("Reg_Success")){
                    finish();
                }
                else if(code.equals("Process_Failed")){
                    jet1.setText("");
                    jet2.setText("");
                    jet3.setText("");
                    jet4.setText("");
                }
            }
        }
    });
    AlertDialog alertDialog= builder.create();
    alertDialog.show();
}

And file mysingleton.java
public class MySingleton {
private static MySingleton mInstance;
 private RequestQueue requestQueue;
 private static Context mCtx;
 //create a constructor
 private MySingleton(Context context){
     mCtx=context; //initialize context
     requestQueue=getRequestQueue(); //initialize request queue
 }
 public RequestQueue getRequestQueue(){
     if(requestQueue==null){
         requestQueue= Volley.newRequestQueue(mCtx.getApplicationContext());
     }
     return requestQueue;
}
//return instance of class
public static synchronized MySingleton getInstance(Context context){
     //initialize mInstance if it is null
     if (mInstance==null){
         mInstance=new MySingleton(context);
     }
     return mInstance;
}
//adding request to requestqueue
public <T>void addToRequestqueue(Request<T> request){
    requestQueue.add(request);
}

}

A: use the following code
`
// your time out time extend it
 private static final int MY_SOCKET_TIMEOUT_MS = 10000;

 MySingleton.getRequestQueue().setRetryPolicy(new DefaultRetryPolicy(
    MY_SOCKET_TIMEOUT_MS,
    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));


text:
Q: How to create a funtion object for a class member function which defined in macro I have something in my CPP like
#define DECLARE_some(name, argType, returnType) \
        class myclass##name : public Service::ServiceRpcHandler<a, r> { \
        public: \
            myclass##name(Service *); \
            CONST_STRING getName() const override;\
            void operator()(Service::ServiceRpcHandler<a, r>::type *); \
        };#decleration

 #define IMPLEMENT_Some(name, argType, returnType) \
            class myclass##name::myclass##name(Service * owner) : Service::ServiceRpcHandler<a, r>(o) { } \
            CONST_STRING myclass##name::getName() const { return #name; }\
            void myclass##name::operator()(Service::ServiceRpcHandler<a, r>::type * twk)#implementation of a declared macro

All i just want is to create a function object for void myclass##name::operator()(Service::ServiceRpcHandler<a, r>::type * twk). i have understood that myclass##name::operator() is itself an functor but anyhow i want to make an another one something like `std::function<(?)(?)>
I have edited as one of the comment suggests

A: There's nothing particularly mysterious about creating a function object. In order to create a function object that invokes the constructed class's () operator, well, the first thing you need to do is, well, an instance of the class. You can't invoke operator() out of thin air. You need an object whose () operator your function object will forward to.
myclass##name(Service *);

The macro creates a class whose constructor takes a Service * parameter. So, presuming that the macro is used to construct a class myclassdisplay, one way to do this would be:
auto f=[](Service *p, Service::ServiceRpcHandler<a, r>::type *arg)
{
    myclassdisplay c(p);

    c(arg);
};

The function constructs a new instance of the myclassdisplay, and invokes its () operator.
You could make this into a macro of its own:
#define FUNCTOR(name) [](Service *p, Service::ServiceRpcHandler<a, r>::type *arg)\
{\
    myclass##name c(p);\
\
    c(arg);\
};

And then use this in the same fashion:
auto f=FUNCTOR(display);

Your question isn't clear exactly where the instances of the class come from. This would be the way to have the class instances constructor in the functor wrapper itself. If the class instances are already declared, the sample functor should be modified accordingly.


text:
Q: Prove that a certain function is upper semicontinuous The following definition can be found here.

Definition. Let $X$ be a topological space. A function $f: X \to [-\infty,\infty)$ is said to be upper semicontinuous if for every $x_0 \in X$ and $M > f(x_0)$ a neighbourhood $U$ of $x_0$ exists such that $M > f(x)$ holds for every $x \in U$.

Consider $X = \Omega$, where $\Omega \subseteq \mathbb{C}$. Assume $F: \Omega \to \mathbb{C}$ is continuous on $\Omega$. Then $\log |F|$ is upper semicontinuous on $\Omega$. How do I prove this? I think we can distinguish two cases: either $F(x_0) = 0$ or $F(x_0) \neq 0$. In both cases we can find such neighbourhoods by the continuity of $F$.

A: Let $x_0 \in \Omega$ such that $F(x_0) \neq 0$ and $M > \log|F(x_0)|$. Then $M - \log|F(x_0)| > 0$ and by the continuity of $\log|F|$ (as a composition of continuous functions) we find a neighbourhood $U$ around $x_0$ such that $$|\log|F(x)| - \log|F(x_0)|| < M - \log|F(x_0)|$$ or equivalently $$\log|F(x)|< M$$
Let $x_0 \in \Omega$ such that $F(x_0) = 0$. Then $\log|F(x_0)| = -\infty$. Further $M > \log|F(x)|$ implies $|F(x)| < e^M$ or equivalently $$|F(x) - F(x_0)| < e^M$$ But $F$ is continuous at $x_0$, so we can find a neighbourhood $V$ around $x_0$ such that above inequality is fulfilled.
Many thanks goes to Daniel Fischer!


text:
Q: Get True or False comparing images with Pillow I made a code, who takes screenshots, and compares with a target image, when then are equal, it clicks on a specific place on the screen, but, the both images is equal but the program gets false always
The code:
import time
import pyautogui
from PIL import Image
from PIL import ImageChops

def wait(secs):
    time.sleep(secs)

def Screenshot_Taker(path, l, t, r, b):

    wait(2)

    image = pyautogui.screenshot()

    box = (l, t, r, b)

    image = image.crop(box)

    image.save(path, format = "png")

def Image_Compare_Click(Image1, Image2, l, t, r, b, x, y):

    image1 = Image.open(Image1).convert("RGB")
    image2 = Image.open(Image2).convert("RGB")

    while True:

        diff = ImageChops.difference(image1, image2)

        if diff.getbbox():
            print("Images are not the same")
            Screenshot_Taker(Image1, l, t, r, b)
            pyautogui.moveTo(x = 1365, y = 767)
            continue

        else:
            print("Images are the same")
            wait(1)
            pyautogui.click(x = x, y = y)
            wait(1)
            pyautogui.moveTo(x = 1365, y = 767)
            break

When I run:
Screenshot_Taker(path = "Image1.png",
l = 320, t = 550, r = 370, b = 610)

Image_Compare_Click(Image1 = "Image1.png", "Image2.png",
l = 320, t = 550, r = 370, b = 610, x = 345, y = 580)

The output is:
Images are not the same
Images are not the same
Images are not the same
Images are not the same
Images are not the same

A: That's because you are comparing the same old two images. In your Image_Compare_Click, you need to do the following:
def Image_Compare_Click(Image1, Image2, l, t, r, b, x, y):

    # image1 = Image.open(Image1).convert("RGB") # <-- commented this
    image2 = Image.open(Image2).convert("RGB")

    while True:
        image1 = Image.open(Image1).convert("RGB") #<-- added this
        diff = ImageChops.difference(image1, image2)
        ...


text:
Q: Survival Probability for Random Walks The Survival Probability for a walker starting at the origin is defined as the probability that the walker stays positive through n steps. Thanks to the Sparre-Andersen Theorem I know this PDF is given by
Plot[Binomial[2 n, n]*2^(-2 n), {n, 0, 100}]

However, I want to validate this empirically.
My attempt to validate this for n=100:
FoldList[
  If[#2 < 0, 0, #1 + #2] &,
  Prepend[Accumulate[RandomVariate[NormalDistribution[0, 1], 100]], 0]]

I wantFoldList to stop if #2 < 0 evaluates to True, not just substitute in 0.

A: We can do this using an implementation of FoldWhileList.
First, implement FoldWhileList using this great answer.
FoldWhileList[f_, test_, start_, secargs_List] :=
 Module[{tag},
  If[# === {}, {start}, Prepend[First@#, start]] &@
   Reap[Fold[If[test[##], Sow[f[##], tag], Return[Null, Fold]] &,
      start, secargs], _, #2 &][[2]]]

Now we simply run this using the test #2 >= 0 (note that the implementation of NestWhile breaks when test stops evaluating True - our implementation of FoldWhileList also does this, therefore we invert the test you originally used.
FoldWhileList[Plus, #2 >= 0 &, 0,
 Prepend[Accumulate[RandomVariate[NormalDistribution[0, 1], 100]], 0]]

We can now estimate your PDF:

and overlay it over the original plot also:

which doesn't seem like a great match - perhaps there's an issue with your original code, as this answer surmises.

A: It seems to me that this is a problem to which Catch and Throw can be usefully applied.
SeedRandom[1];
Module[{result = {0}, s},
  Catch[
    Fold[
      If[#2 < 0, Throw[Null], result = {result, s = #1 + #2}; s] &,
      0,
      Accumulate[RandomVariate[NormalDistribution[0, 1], 100]]]];
  result // Flatten]

A: How about the following brute force approach:
n = 100;
SeedRandom[12345];
nsim = 1000000;
Total[Table[If[Min[Accumulate[RandomVariate[NormalDistribution[0, 1], n]]] <= 0, 0, 1],
    {i, nsim}]]/nsim // N
(* 0.056092 *)
Binomial[2 n, n] 2^(-2 n) // N
(* 0.0563485 *)

To get all of the values from 1 to 100 "simultaneously"...
SeedRandom[12345];
nsim = 100000;
n = 100;
z = ConstantArray[0, n];
Do[
 x = Accumulate[RandomVariate[NormalDistribution[0, 1], n]];
 i = Flatten[Position[x, _?NonPositive]];
 If[Length[i] > 0, If[i[[1]] > 1, z[[1 ;; i[[1]] - 1]] = z[[1 ;; i[[1]] - 1]] + 1], z = z + 1],
 {j, nsim}]
z = z/nsim;
ListPlot[{z, Table[Binomial[2 j, j] 2^(-2 j), {j, n}]}, PlotRange -> All, ImageSize -> Large]

A: Count number of steps before random walk value either goes negative or over $m$ steps are already taken, for $n$ walks. Then count amount of last successful steps on each integer bin, reverse it, accumulate these values (essentially extend last nonnegative value backwards to every value before it), reverse it again to get the original order, drop the extra value that counted paths that continued over $m$ steps and calculate probabilities:
With[{n = 5000, m = 100},
 Table[First@
         NestWhile[# + {1, RandomVariate@NormalDistribution[]} &,
                   {-1, 0}, Last@# >= 0 && First@# <= m &], n] //
       BinCounts[#, {1, Max@# + 1, 1}] & // Reverse // Accumulate //
    Reverse // Most@#/n & //
  ListPlot[{#, Table[Binomial[2 j, j] 2^(-2 j), {j, m}]},
    PlotRange -> All] &]

A: Something seems odd to me about your code.  You are summing twice, once with Accumulate and once with FoldList.  If this is really what you want then you could use:
SeedRandom[26]
sum = Prepend[Accumulate[RandomVariate[NormalDistribution[0, 1], 100]], 0];

TakeWhile[sum, NonNegative] // Accumulate

8

{0, 1.10708, 1.23211, 2.28173, 3.30295, 4.05759, 5.26123, 6.62964}

This is equivalent to your FoldList construct up to the appropriate point:
FoldList[If[#2 < 0, 0, #1 + #2] &, sum]

{0, 1.10708, 1.23211, 2.28173, 3.30295, 4.05759, 5.26123, 6.62964, 0, ...

Perhaps you meant to only sum once.  In that case TakeWhile[sum, NonNegative] is a direct solution but also sub-optimal as it does not provide early exit behavior, which I suspect is what you're actually after here.  It is not clear to me if you need the cumulative sum (walk) itself or only its length; if the latter consider this:
SeedRandom[26]
dist = RandomVariate[NormalDistribution[0, 1], 100];

Module[{i = 0},
  Fold[If[# < 0, Return[i, Fold], i++; # + #2] &, 0, dist]
]

8


text:
Q: Using a mocked object form multiple threads I've inherited a piece of legacy code and I'm now struggling with a test which fails sometimes.
The test setup goes like this:
ADao aDao = EasyMock.createNiceMock(ADao.class);
aDao.aCall(EasyMock.eq(anObject), EasyMock.eq(true));
EasyMock.expectLastCall().andReturn(TestHelper.getAList(anObject));

Then the aDao is passed to a controller for some worker threads, the controller starts N threads and the test communicates with one of the threads using event queues.
The problem I'm having is that when the worker threads try to use the mocked Dao, they don't get back the list passed to andReturn but its copy, and the copy sometimes is incomplete. TestHelper.getAList returns an ArrayList of 139 items, but the mock sometimes returns a perfect copy, sometimes a copy with 14 or 16 items. I believe the copying is still performed in another thread because iterating over the returned list throws ConcurrentModificationException.
Is there a way to make EasyMock either a/ use the object it was set up with instead of a copy or b/ finish copying before the object is passed to a caller?
(Marking EasyMock with makeThreadSafe(..., false) does not solve the problem.)

A: OK, I solved the problem with
EasyMock.expectLastCall().andAnswer(new IAnswer<List>() { ... });


text:
Q: Are C for loops different from PHP for loops? It seems like the following from the PHP manual regarding for loops is incorrect.

They behave like their C counterparts.

This is my understanding of for loops.
In C
for (i = foo; i < 10; i++) {   /* body */ }
is equivalent to
if ( i = foo )
{   while (i < 10)
    {    /* body */
         i++;
    }
}

In PHP the comparable loop
for ($i = $foo; $i < 10; $i++) { /* body */ }
becomes
$i = $foo;
while ($i < 10)
{   /* body */
    $i++;
}

The difference is that in PHP $i = $foo is not a condition but rather a convenient place for a statement.  Suppose we change the single = to ==.  The distinction becomes significant.  Is this correct?  If so, then PHP and C loops behave differently and the manual is incorrect, right?

A: This is not true:
if ( i = foo )  //what??
{   while (i < 10)
    {    /* body */
         i++;
    }
}

The C for loop is basically:
int i = foo;
while (i < 10)
 {    /* body */
      i++;
 }

A: They are exactly the same, but your understanding of C's for loops is wrong. They are the same as in PHP.
 for (x; y; z) { /* body */ }

is almost like
 x;

 while (y) {
     /* body */
     z;
 }

Though the for and while examples in C are not exactly the same because of scopes and things.

A: It's been a while since I learned or spend time with C, but I'm pretty sure the first statement in a C for-loop is an expression setting a variable to a value, just like it is in C.

A: In C i=foo is indeed a condition, it's equivalent to (i=foo)!=0 since 0 is false in C and not-0 is true.
The issue is that C for loops don't work the way you think they do, as evidenced by the fact that you can initialize a for loop with i=0.


text:
Q: How do you combine two columns into a new column in a dataframe made of two or more different csv files? I have several csv files all named with dates and for all of them I want to create a new column in each file that contains data from two other columns placed together. Then, I want to  combine them into one big dataframe and choose only two of those columns to keep. Here's an example:
Say I have two dataframes:
  a b c        a b c
x 1 2 3      x 3 2 1
y 2 3 1      y 2 1 3

Then I want to create a new column d in each of them:
  a b c  d        a b c  d
x 1 2 3 13      x 3 2 1 31
y 2 3 1 21      y 2 1 3 23

Then I want to combine them like this:
  a b c  d
x 1 2 3 13
y 2 3 1 21
x 3 2 1 31
y 2 1 3 23

Then keep two of the columns a and d and delete the other two columns b and c:
  a  d
x 1 13
y 2 21
x 3 31
y 2 23

Here is my current code (It doesn't work when I try to combine two of the columns or when I try to only keep two of the columns):
    f <- list.files(pattern="201\\d{5}\\.csv")        # reading in all the files
    mydata <- sapply(f, read.csv, simplify=FALSE)     # assigning them to a dataframe
    do.call(rbind,mydata)                             # combining all of those dataframes into one
    mydata$Data <- paste(mydata$LAST_UPDATE_DT,mydata$px_last)   # combining two of the columns into a new column named "Data"
    c('X','Data') %in% names(mydata)               # keeping two of the columns while deleting the rest

A: The object mydata is a list of data frames. You can change the data frames in the list with lapply:
lapply(mydata, function(x) "[<-"(x, "c", value = paste0(x$a, x$b)))

file1 <- "a b
x 2 3"
file2 <- "a b
x 3 1"
mydata <- lapply(c(file1, file2), function(x) read.table(text = x, header =TRUE))
lapply(mydata, function(x) "[<-"(x, "c", value = paste0(x$a, x$b)))

# [[1]]
#   a b  c
# x 2 3 23
#
# [[2]]
#   a b  c
# x 3 1 31

A: You can use rbind (data1,data2)[,c(1,3)] for that. I assume that you can create col d in each dataframe which is a basic thing.
 data1<-structure(list(a = 1:2, b = 2:3, c = c(3L, 1L), d = c(13L, 21L
    )), .Names = c("a", "b", "c", "d"), row.names = c("x", "y"), class = "data.frame")

 > data1
      a b c  d
    x 1 2 3 13
    y 2 3 1 21

data2<-structure(list(a = c(3L, 2L), b = c(2L, 1L), c = c(1L, 3L), d = c(31L,
23L)), .Names = c("a", "b", "c", "d"), row.names = c("x", "y"
), class = "data.frame")

> data2
  a b c  d
x 3 2 1 31
y 2 1 3 23

data3<-rbind(data1,data2)

    > data3
   a b c  d
x  1 2 3 13
y  2 3 1 21
x1 3 2 1 31
y1 2 1 3 23

finaldata<-data3[,c("a","d")]
    > finaldata
   a  d
x  1 13
y  2 21
x1 3 31
y1 2 23


text:
Q: Android Studio project build with deployGate gradle plugin I just started using DeployGate with my Android application in Android Studio and I want to use the gradle plugin, to upload my new versions (I think it is for that, or had I misunderstood it?).
I finally achieved that my project build successful with my modified build.gradle (Module:app):
apply plugin: 'deploygate'
apply plugin: 'com.android.application'

deploygate {
    userName = "[myUsername]" //yes, I replaced it with my own
    token = "[myAPIKey]"      // also
    apks {
        release {
            sourceFile = file("C:\\AndroidStudioProjects\\MyApp\\app\\app-release.apk")
        }

        debug {
            sourceFile = file("C:\\AndroidStudioProjects\\MyApp\\app\\build\\outputs\\apk\\app-debug.apk")

            //Below is optional
            //message = "test upload2 sample"
            //visibility = "public"
            //distributionKey = "[distribution_key]"
            //releaseNote = "release note sample"
        }
    }
}

android {
    compileSdkVersion 23
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "bendaf.myapp"
        minSdkVersion 18
        targetSdkVersion 23
        versionCode 13
        versionName "1.2.1"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile 'com.android.support:appcompat-v7:23.0.0'
    compile 'com.deploygate:sdk:3.1'
}

but when I try to execute the command gradle uploadDeployGate in terminal it sais BUILD FAILED. (I am not too experienced with gradle, so am I doing it right?)
my stacktrace is:
    * Exception is:
    org.gradle.api.GradleScriptException: A problem occurred evaluating project ':app'.
        at     org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:54)
        at org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl.apply(DefaultScriptPluginFactory.java:190)
        at org.gradle.configuration.project.BuildScriptProcessor.execute(BuildScriptProcessor.java:39)
        at org.gradle.configuration.project.BuildScriptProcessor.execute(BuildScriptProcessor.java:26)
        at org.gradle.configuration.project.ConfigureActionsProjectEvaluator.evaluate(ConfigureActionsProjectEvaluator.java:34)
        at org.gradle.configuration.project.LifecycleProjectEvaluator.evaluate(LifecycleProjectEvaluator.java:55)
        at org.gradle.api.internal.project.AbstractProject.evaluate(AbstractProject.java:521)
        at org.gradle.api.internal.project.AbstractProject.evaluate(AbstractProject.java:82)
        at org.gradle.configuration.DefaultBuildConfigurer.configure(DefaultBuildConfigurer.java:31)
        at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:129)
        at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:106)
        at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:86)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:80)
        at org.gradle.launcher.cli.ExecuteBuildAction.run(ExecuteBuildAction.java:33)
        at org.gradle.launcher.cli.ExecuteBuildAction.run(ExecuteBuildAction.java:24)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:36)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
        at org.gradle.launcher.cli.RunBuildAction.run(RunBuildAction.java:51)
        at org.gradle.internal.Actions$RunnableActionAdapter.execute(Actions.java:171)
        at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:237)
        at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:210)
        at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:35)
        at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:24)
        at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:206)
        at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:169)
        at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:33)
        at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:22)
        at org.gradle.launcher.Main.doAction(Main.java:33)
        at org.gradle.launcher.bootstrap.EntryPoint.run(EntryPoint.java:45)
        at org.gradle.launcher.bootstrap.ProcessBootstrap.runNoExit(ProcessBootstrap.java:54)
        at org.gradle.launcher.bootstrap.ProcessBootstrap.run(ProcessBootstrap.java:35)
        at org.gradle.launcher.GradleMain.main(GradleMain.java:23)
Caused by: org.gradle.api.internal.plugins.PluginApplicationException: Failed to apply plugin [id 'com.android.application']
        at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.applyPlugin(DefaultObjectConfigurationAction.java:117)
        at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.access$200(DefaultObjectConfigurationAction.java:36)
        at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction$3.run(DefaultObjectConfigurationAction.java:80)
        at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.execute(DefaultObjectConfigurationAction.java:131)
        at org.gradle.api.internal.project.AbstractPluginAware.apply(AbstractPluginAware.java:37)
        at org.gradle.api.Project$apply$0.call(Unknown Source)
        at org.gradle.api.internal.project.ProjectScript.apply(ProjectScript.groovy:34)
        at org.gradle.api.Script$apply$0.callCurrent(Unknown Source)
        at build_78pi66j0mnhjns6vp3krggobhd.run(C:\AndroidStudioProjects\VivagoDatatransmission\app\build.gradle:25)
        at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:52)
        ... 31 more
Caused by: org.gradle.tooling.BuildException: Gradle version 2.2 is required. Current version is 2.1. If using the gradle wrapper, try editing the distributionUrl in C:\An
droidStudioProjects\VivagoDatatransmission\gradle\wrapper\gradle-wrapper.properties to gradle-2.2-all.zip
        at com.android.build.gradle.BasePlugin.checkGradleVersion(BasePlugin.groovy:436)
        at com.android.build.gradle.BasePlugin.configureProject(BasePlugin.groovy:265)
        at com.android.build.gradle.BasePlugin$_apply_closure1.doCall(BasePlugin.groovy:252)
        at com.android.build.gradle.BasePlugin$_apply_closure1.doCall(BasePlugin.groovy)
        at com.android.build.gradle.internal.profile.SpanRecorders$2.call(SpanRecorders.groovy:52)
        at com.android.builder.profile.ThreadRecorder$1.record(ThreadRecorder.java:48)
        at com.android.build.gradle.internal.profile.SpanRecorders.record(SpanRecorders.groovy:54)
        at com.android.build.gradle.BasePlugin.apply(BasePlugin.groovy:251)
        at com.android.build.gradle.AppPlugin.super$2$apply(AppPlugin.groovy)
        at com.android.build.gradle.AppPlugin.apply(AppPlugin.groovy:66)
        at com.android.build.gradle.AppPlugin.apply(AppPlugin.groovy)
        at org.gradle.api.internal.plugins.DefaultPluginContainer.providePlugin(DefaultPluginContainer.java:188)
        at org.gradle.api.internal.plugins.DefaultPluginContainer.addPluginInternal(DefaultPluginContainer.java:137)
        at org.gradle.api.internal.plugins.DefaultPluginContainer.apply(DefaultPluginContainer.java:103)
        at org.gradle.api.internal.plugins.DefaultObjectConfigurationAction.applyPlugin(DefaultObjectConfigurationAction.java:115)
        ... 40 more

According to the error message the problem is in my gradle-wrapper.properties, but it have the right gradle version, I think:
distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip

so what is the problem here? Or am I doing something wrong? How should I upload the app automatically to DeployGate?
Thanks, for the answer.

A: You are running globally-installed gradle command which doesn't respect gradle-wrapper.properties you edited. Instead, you need to run gradlew command.
Gradle wrapper is the preferred way of starting a Gradle build that allows you to run a specific version of Gradle for each project. With the wrapper, all you have to do to build your project is:

*

*Checkout the repository

*Run gradlew
That's all. You don't even need to install Gradle beforehand, the wrapper takes care of everything, so you can build your application anywhere and easily migrate into continuous integration.


text:
Q: How send 2 params in action by link_to, if 1 params exist on page and I can get this value by JS I'm beginner in ror. I have page with datatable. When I choose tr in datatable and push button I want send in action 1 values(I can get this by JS) from tr, and 1 values from code( send by link_to). I don't know why do this. How combine result JS and link_to, and catch this in action. I'm confused...
$.get('mycontroller/create', {user_id: "current_user.id", h_id: $(this).data("h-id")});

Don't find current_user.id
<%= link_to "Add to h-list", my_controller_create_path(current_user.id), method: :post , :class => "btn btn-default">

don't sending h_id
def create
    @h = h.new(????)
    @h.save
    end

I want get value in action and write it in database. Please help me

A: If I understood correctly, do you want 1 of your link_to parameters to be retrieved via your js? Why not play with the "href" attribute of the link generated by your link_to?
I would have done so:
Ruby (ERB)
<%= link_to 'mylink', your_path, class: 'someClass', id: 'someId'  %>

JS (jQuery)
   $("#someId").attr('href', function(_, href){
        return href+'?param=value'
    });

I hope it will help you

A: your_controller.rb
  def create
    @h = h.new(your_params)
    @h.h_id_attribute = params[:h-id]
    @h.save
 end

Javascript
$("#someId").attr('href', function(_, href){
    return href+'?h-id=your_value'
});

in your view
<%= link_to 'mylink', my_controller_create_path(current_user.id), class: 'someClass', id: 'someId'  %>

Can you try that?


text:
Q: TikZ - How can I draw a line through a point on a line, with the new line perpendicular to the old line? I have a line A-B between the two points A and B and a point X on A-B.
Now I'd like to draw a line through X which then is perpendicular to the line A-B. How can I do this?
Also:
No other (directly related) points around the line are given, I only have X which is the product of the usage of \path and creating two intersecting paths. Hence I say I can't use code in replies to other related questions (shown on the right), at least I do not see how.
Picture

MWE
\documentclass{standalone}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{lmodern}

\usepackage{
tikz,
xspace
}

\usetikzlibrary{
intersections,
calc
}

\begin{document}
\begin{tikzpicture}[font=\small]
\draw
(0,0) coordinate (A)
(1,1.435) coordinate (B)
(3,3) coordinate (C)
;
\draw[thick] (A) rectangle (C);
\draw[thick] (A)--(B) node[pos=0.6] (x) {x};
\end{tikzpicture}
\end{document}

A: These basic geometry constructions are easy in Metapost once you have got the hang of the declarative equations.  Here's my attempt at the canonical plain Metapost approach, explained at the end of Chapter 9 of The Metafont Book.

prologues := 3;
outputtemplate := "%j%c.eps";

beginfig(1);

% some arbitrary points
z1 = (20,80);
z2 = (90,30);
z3 = (60,80);

% a point somewhere on the line through z1 and z2;
z4 = whatever[z1,z2];

% the direction of z3 from z4 is at right angles to that of z2 from z1
z3-z4 = whatever*(z2-z1) rotated 90;

% mark the right angle neatly
draw unitsquare scaled 5 rotated angle (z2-z1) shifted z4 withcolor .7 white;

draw z1--z2;
draw z3--z4 withcolor .67 red;

dotlabel.top("A",z1);
dotlabel.bot("B",z2);
dotlabel.rt("X",z3);
endfig;
end.

The whatever feature provides an arbitrary anonymous numeric variable.  These variables can take any real value, and either sign, so in this case the order of the subtractions does not matter, and point X can be on either side of the line AB.
There is a rich source of geometry material for Metapost (in French) on the Syracuse site.

A: A faster solution with PSTricks just for fun.
\documentclass[pstricks,border=12pt,12pt]{standalone}
\usepackage{pst-eucl}

\begin{document}
\begin{pspicture}(8,8)
    \pstGeonode[CurveType=polyline](0,6){A}(6,0){B}([nodesep=4]{B}A){X}
    \pcline[linecolor=blue]([offset=1]{A}X)([offset=4]{B}X)
\end{pspicture}
\end{document}

A: This solution slopes the middle node and uses it's north and south anchors as points forming the perpendicular line. Negative shorten <|> make line (red line in figure) as longer as needed. This trick also works with empty and not drawn nodes (green line in figure). It doesn't work with coordinate nodes.
\documentclass[border=2mm,tikz]{standalone}

\begin{document}
\begin{tikzpicture}

\draw (0,0) -- (3,2) node[pos=0.3, sloped, draw] (x) {X} node[pos=0.7,sloped] (y){};
\draw[ shorten >=-1cm, shorten <=-0.5cm, red] (x.south)--(x.north);
\draw[ shorten >=-0.5cm, shorten <=-1cm, green] (y.south)--(y.north);
\end{tikzpicture}
\end{document}

A: With dirty tikz and a transformation:
\documentclass{standalone}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{lmodern}

\usepackage{
  tikz,
  xspace
}

\usetikzlibrary{
  intersections,
  calc
}

\begin{document}
\begin{tikzpicture}[font=\small]
  \draw
  (0,0) coordinate (A)
  (1,1.435) coordinate (B)
  (3,3) coordinate (C)
  ;
  \draw[thick] (A) rectangle (C);
  \draw[thick] (A)--(B) node[pos=0.6] (x) {x};

  \draw[red,thick,transform canvas={rotate around={90:(x)}}] (A) -- (B) ;
\end{tikzpicture}
\end{document}

You prepare a line from A to B, and then (before drawing it) you rotate it 90° around X. Of course, if you want a different length, you can place coordinates accordingly on your path from A to B.
Apparently, using transform canvas is necessary if the coordinates are given with node names, it is not, however, if the coordinates are given directly. The manual says that transform canvas is evil, but hardcoding coordinates is also evil, so...

A: Jake's link indeed had the solution.
If one has content shown at X, playing around with inner and outer sep-values is needed. Or use .center (thanks to Jake).
\documentclass{standalone}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{lmodern}

\usepackage{
tikz,
}

\usetikzlibrary{
intersections,
calc
}

\begin{document}
\begin{tikzpicture}[font=\small]
\draw
(0,0) coordinate (A)
(1,1.435) coordinate (B)
(3,3) coordinate (C)
;
\draw[thick] (A) rectangle (C);
\draw[thick] (A)--(B) node[pos=0.6, inner sep=0pt, outer sep=0pt](x){x};
\draw[thick] ($(x)!0.5cm!90:(A)$) -- ($(x)!0.5cm!-90:(A)$);
\end{tikzpicture}
\end{document}


text:
Q: Converting string array into binary string I have a string array with numeric elements:
string[] numbers = {"2","3","10","9","4"};

I would like to convert each string to a 16-bit binary equivalent and concatenate, such that resulting string must look like this:
00000000000000100000000000000011000000000000101000000000000010010000000000000100

Do I have to convert string array to int array and apply a /2 function or is there any other efficient way to achieve that? Also, how do I get 16bit results?

A: string result = string.Join("", numbers.Select(n => Convert.ToString(Int16.Parse(n), 2).PadLeft(16, '0')));

A: using System;
using System.Text;

namespace Proggram
{
    internal class Program
    {

        internal static int Main(string[] args)
        {
            var sb = new StringBuilder();
            string[] numbers = { "2", "3", "10", "9", "4" };
            foreach (var number in numbers)
            {
                sb.Append(NumbertoStrToBinaryStr(number));
            }

            Console.WriteLine(sb.ToString());
            return 0;
        }

        private static string NumbertoStrToBinaryStr(string numberstr)
        {
            var result = new StringBuilder();
            if (!uint.TryParse(numberstr, out var n)) return result.ToString();

            const int start =  32 - 1;
            for (var mask = 1u << start; mask != 0; mask >>= 1)
            {
                var set = (mask & n) == mask;
                result.Append( set ? '1' : '0');
            }

            return result.ToString();
        }
    }
}

A: you can use for loop to access each element like this code...
string binary_number ="";
string[] numbers = { "2", "3", "10", "9", "4" };
for (int i = 0;i < numbers.Length;i++) {
  binary_number += Convert.ToString(Int16.Parse(numbers[i]), 2).PadLeft(16, '0')));
}


text:
Q: Azure DevOps Release Pipeline - Pass environment variable to docker container I have a release pipeline in Azure DevOps. This is pulling a docker image from an ACR and publishing to a Web App (linux container). All works fine (container is published & runs as expected), however I can't seem to pass in any custom environment variables at runtime to the container.
Release pipeline
In the pipeline 'Deploy Azure App Service' under the variable tab, I have added, MY_ENV test01 and then under 'App settings' I have added
-e MY_ENV
The release is published and the image is updated ok.
Container Logs
The docker run command in the logs does not have the environment variable
I was expected -e MY_ENV in the command, but it missing.
Anyone know how to pass an ENV variable to a docker container at runtime via an Azure DevOps release pipeline?
Thanks

A: Looks like the way you are passing the App settings is wrong in your deploy app service pipeline task -e MY_ENV. Instead just directly add -MY_ENV test01 as part of your app settings. and it should be available as part of your environment. see : https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/deploy/azure-rm-web-app-deployment?view=azure-devops

If this still fails, you can pass/set your environment variables as follows : https://learn.microsoft.com/en-us/azure/app-service/configure-custom-container?pivots=container-linux#configure-environment-variables
You can run this Azure CLI command as part of your devops pipeline (https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/deploy/azure-cli?view=azure-devops)


text:
Q: Telerik Kendo grid virtual scrolling and Excel export When I use virtual scrolling for performances issues, exporting to excel does not retrieve  all data but only rendered data.
I can't find anything on teleric or SO forums, any idea how to fix that ?
.Scrollable(scrollable => scrollable.Virtual(true))
.PageSize(20)

Also, because of custom toolbar, i have to use this syntax for excel export :

      Excel

Thank you.

A: I found out how to get all data, even with virtual scrolling and custom toolbar syntax.
Just add the following at kendo grid initialization :
.Excel(excel =>
{
    excel.AllPages(true);
})

Good luck.


text:
Q: How to programmatically start Netlogo on a multi-monitor setup, with mixed high-dpi and low-dpi displays? Netlogo starts on my monitors with a really tiny font. The GUI is unusable. I cannot enlarge the GUI widgets.
Does anyone know how to do this programmatically, via bash Command Line Options, or environment variables or any other way?
I have a standalone Linux PC with 2 Monitors and an NVidia 1050 graphics card. The primary display is an older 1920x1280 pixel monitor (25-inch), the other is a 3840x2560 pixel Monitor (27 Inch).  I had to tweak my  Gnome desktop, to get the graphical desktop and most apps to render properly at all: After switch on a certain setting, "Fractional Scaling", located in Settings / Display.
But not NetLogo.
I found a solution for the java-based Data-Mining Tool "Weka", based on Environment variables. To display the Weka GUI properly, Weka must not be started with the standard
java  -cp weka.jar weka.gui.GUIChooser     # Tiny GUI
but with
export GDK_SCALE=3; java  -cp weka.jar weka.gui.GUIChooser    # GUI is readable
But for NetLogo, which also a jar-based Java App, just like Weka,  this does not have any effect:
~/bin/NetLogo 6.2.2/NetLogo         # Tiny GUI
export GDK_SCALE=3 && "~/bin/NetLogo 6.2.2/NetLogo"            # Tiny GUI
Environment variables do not seem to have any effect. Is there a magic command-line option, perhaps, that I can pass to netlogo? Any setting in the NetLogo GUI itself? A Netlogo Command?

I am posting this here because I know the Netlogo developers keep an eye on this site (but AFAIK not on one of the smaller StackExchange sites)
There are quite a few answers here when you search for [highdpi] but most Q+As refer to different technologies, not Java.


text:
Q: Top down movement/isometric movement in Pygame I'm sorry if this question has already been asked before but I've checked everywhere and I can't find the answer.
How do you do top down movement in pygame?
This would be easy if I was just using rectangles but I'm going to be using individual character sprites (Ex. If I press d to make player go right, it shows me the character sprite of him going right and moves the character right).
Example image of what I mean:

A: You draw a different sprite depending on which direction the character is going.
Assuming dx / dy are the character's velocity and x/y its location on screen,
up_sprite = pygame.image.load('up.png')
down_sprite = pygame.image.load('down.png')
left_sprite = pygame.image.load('left.png')
right_sprite = pygame.image.load('right.png')

sprite = down_sprite  # to initialize things off with

def your_game_loop():

    if dx > 0:
       sprite = right_sprite
    elif dx < 0:
       sprite = left_sprite
    elif dy > 0:
       sprite = down_sprite
    elif dy < 0:
       sprite = up_sprite

    sprite.blit(screen, (x, y))


text:
Q: How can one use Azure Service Connection in Azure DevOps Server 2019 (on-prem) to run terraform from a script running in a release stage? So I am aware of a couple Azure DevOps terraform tasks. But we wrap our terraform calls with powershell scripts, so these tasks are of no use to us.
So, given that we call terraform from scripts the only way we could find to make terraform authenticate is by following this procedure:

*

*Create Service Connection using the Service Principal dedicated to the pod

*Create a variable group and link it to the Key Vault containing the SP credentials.

*Every task running the powershell code wrapping terraform would have environment variables ARM_CLIENT_ID and ARM_CLIENT_SECRET mapped to the variables in the variable group from (2). ARM_TENANT_ID and ARM_SUBSCRIPTION_ID are set accordingly.

But this is incredibly cumbersome. Is it possible to do it with just the Service Connection?

A:
Is it possible to do it with just the Service Connection?

I am afraid it is impossible to do it with just the Service Connection for the powershell scripts.
According to the Microsoft replied:

This is as per service connection design and security considerations. Scripts in the build or release are not allowed to
  access secrets stored in service connections.

You can check the ticket here.
Hope this helps.


text:
Q: SQL Server Data Tools 2015 installation error I'm trying to install SQL Server Data Tools - Visual Studio 2015, but I keep getting an "Unspecified error".
The log file is at https://drive.google.com/open?id=0B3CEKzS2Sw8OODNJOXZJVGRWQlU.
I already have Visual Studio Professional 2015 installed.
I want to install SSDT 2015 because my databases were recently migrated from SQL Server 2008 R2 to 2014, and I need to use SSIS.  Previously, I used SQL Server Business Intelligence Development Studio to create my DTS packages, which I still have installed to access old packages.
I've tried to find a resolution to my problem but everything seems to be about VS 2013 installation issues.
Please let me know if I need to provide more information.
Here's the relevant section from the linked log file.
[2308:24BC][2016-10-12T09:32:14]: Plan complete, result: 0x0
[2308:24BC][2016-10-12T09:32:14]: Apply begin
[287C:2C64][2016-10-12T09:32:14]: Creating a system restore point.
[287C:2C64][2016-10-12T09:32:21]: Created a system restore point.
[287C:2C64][2016-10-12T09:32:21]: Caching bundle from: 'C:\Users\JENMCC~1\AppData\Local\Temp\{2e9e05c8-ae49-4af6-9121-fa821d1b5334}\.be\SSDTSetup.exe' to: 'C:\ProgramData\Package Cache\{2e9e05c8-ae49-4af6-9121-fa821d1b5334}\SSDTSetup.exe'
[287C:2C64][2016-10-12T09:32:21]: Registering bundle dependency provider: {2e9e05c8-ae49-4af6-9121-fa821d1b5334}, version: 14.0.60923.0
[2308:28AC][2016-10-12T09:32:21]: Prompt for source of package: DotNet46, payload: DotNet46, path: U:\Downloads\Microsoft\SSDT\SSDT 2015\payload\neutral\NDP461-KB3102436-x86-x64-AllOS.exe
[2308:28AC][2016-10-12T09:32:21]: Acquiring package: DotNet46, payload: DotNet46, download from: https://go.microsoft.com/fwlink/?LinkId=715689
[2308:28AC][2016-10-12T09:32:21]: Error 0x80072ee7: Failed to send request to URL: https://go.microsoft.com/fwlink/?LinkId=715689
[2308:28AC][2016-10-12T09:32:21]: Error 0x80072ee7: Failed to send request to URL: https://go.microsoft.com/fwlink/?LinkId=715689
[2308:28AC][2016-10-12T09:32:21]: Error 0x80072ee7: Failed to connect to URL: https://go.microsoft.com/fwlink/?LinkId=715689
[2308:28AC][2016-10-12T09:32:21]: Error 0x80072ee7: Failed to get size and time for URL: https://go.microsoft.com/fwlink/?LinkId=715689
[2308:28AC][2016-10-12T09:32:21]: Error 0x80072ee7: Failed attempt to download URL: 'https://go.microsoft.com/fwlink/?LinkId=715689' to: 'C:\Users\JENMCC~1\AppData\Local\Temp\{2e9e05c8-ae49-4af6-9121-fa821d1b5334}\DotNet46'
[2308:28AC][2016-10-12T09:32:21]: Error 0x80072ee7: Failed to acquire payload from: 'https://go.microsoft.com/fwlink/?LinkId=715689' to working path: 'C:\Users\JENMCC~1\AppData\Local\Temp\{2e9e05c8-ae49-4af6-9121-fa821d1b5334}\DotNet46'
[2308:28AC][2016-10-12T09:32:21]: Failed to acquire payload: DotNet46 to working path: C:\Users\JENMCC~1\AppData\Local\Temp\{2e9e05c8-ae49-4af6-9121-fa821d1b5334}\DotNet46, error: 0x80072ee7.
[2308:28AC][2016-10-12T09:32:21]: Applied non-vital package: DotNet46, encountered error: 0x80072ee7. Continuing...
[2308:28AC][2016-10-12T09:32:21]: Prompt for source of package: adalsql13X64, payload: adalsql13X64, path: U:\Downloads\Microsoft\SSDT\SSDT 2015\payload\x64\adalsql.msi
[2308:28AC][2016-10-12T09:32:21]: Acquiring package: adalsql13X64, payload: adalsql13X64, download from: https://go.microsoft.com/fwlink/?LinkId=817285&clcid=0x409
[2308:28AC][2016-10-12T09:32:21]: Error 0x80072ee7: Failed to send request to URL: https://go.microsoft.com/fwlink/?LinkId=817285&clcid=0x409
[2308:28AC][2016-10-12T09:32:21]: Error 0x80072ee7: Failed to send request to URL: https://go.microsoft.com/fwlink/?LinkId=817285&clcid=0x409
[2308:28AC][2016-10-12T09:32:21]: Error 0x80072ee7: Failed to connect to URL: https://go.microsoft.com/fwlink/?LinkId=817285&clcid=0x409
[2308:28AC][2016-10-12T09:32:21]: Error 0x80072ee7: Failed to get size and time for URL: https://go.microsoft.com/fwlink/?LinkId=817285&clcid=0x409
[2308:28AC][2016-10-12T09:32:21]: Error 0x80072ee7: Failed attempt to download URL: 'https://go.microsoft.com/fwlink/?LinkId=817285&clcid=0x409' to: 'C:\Users\JENMCC~1\AppData\Local\Temp\{2e9e05c8-ae49-4af6-9121-fa821d1b5334}\adalsql13X64'
[2308:28AC][2016-10-12T09:32:21]: Error 0x80072ee7: Failed to acquire payload from: 'https://go.microsoft.com/fwlink/?LinkId=817285&clcid=0x409' to working path: 'C:\Users\JENMCC~1\AppData\Local\Temp\{2e9e05c8-ae49-4af6-9121-fa821d1b5334}\adalsql13X64'
[2308:28AC][2016-10-12T09:32:21]: Failed to acquire payload: adalsql13X64 to working path: C:\Users\JENMCC~1\AppData\Local\Temp\{2e9e05c8-ae49-4af6-9121-fa821d1b5334}\adalsql13X64, error: 0x80072ee7.
[287C:2500][2016-10-12T09:32:21]: Removing cached package: DotNet46, from path: C:\ProgramData\Package Cache\83D048D171FF44A3CAD9B422137656F585295866\
[287C:2500][2016-10-12T09:32:21]: Unable to remove cached package: DotNet46, from path: C:\ProgramData\Package Cache\83D048D171FF44A3CAD9B422137656F585295866\, reason: 0x80070003. Continuing...
[2308:24BC][2016-10-12T09:32:21]: Error 0x80072ee7: Failed while caching, aborting execution.
[287C:2C64][2016-10-12T09:32:21]: Removed bundle dependency provider: {2e9e05c8-ae49-4af6-9121-fa821d1b5334}
[287C:2C64][2016-10-12T09:32:21]: Removing cached bundle: {2e9e05c8-ae49-4af6-9121-fa821d1b5334}, from path: C:\ProgramData\Package Cache\{2e9e05c8-ae49-4af6-9121-fa821d1b5334}\
[2308:24BC][2016-10-12T09:32:22]: Apply complete, result: 0x80072ee7, restart: None, ba requested restart:  No

A: Had the same problem on a 2016 server. I moved the install to the root directory and ran as administrator Also had to disabled IE enhanced security configuration. After that the install worked Fine.

A: The error is unable to send request, so you can try install with offline. Here is the detail:
"An ISO image of SSDT can be used as an alternative way to install SSDT or to set up an Administrative Installation point."
https://msdn.microsoft.com/en-us/mt186501

A: just try -- Run as administrator instead of clicking straight away

A: neera's answer did not worked form me. Another possible solution to the connection problem ('Failed to send request to URL') is to install SSDT from a .iso, but this is not trivial when working in a virtual machine.
Diagnosis: During the installation process of SSDT, a few components are supposed to be downloaded (i.e. the link in your log file represents one of those). Your virtual machine attempts to download such files through Internet Explorer (IE). However, by default the IE Enhanced Security Option is enabled. As a result, this stops you from downloading the required tools.
Solution: Log in your virtual machine, launch "Server Manager", select "Local Server" on the left, turn off "IE Enhanced Security Configuration".

A: Through a very tedious process, I successfully installed SSDT 2015.
Even though the log showed:
 Failed to send request to URL...

I was able to manually go to the specified URL in the web browser, so I downloaded the missing items and ran the install again. This time, install gave me a new URL that it couldn't request. So I download that item and tried again. The third time, it came up with another failed request. Again, I downloaded the missing item...
Overall, I ended up downloading 25+ items before the SSDT 2015 installation completed successfully. Using the URLs referenced in the log, I manually download the following files and put them in the directories shown in the log file.
 adalsql.msi
 CommonAzureTools.cab
 CommonAzureTools.msi
 NDP461-KB3102436-x86-x64-AllOS.exe
 SharedManagementObjects.msi
 SQL_AS_ADOMD.msi
 SQL_AS_AMO.msi
 SQL_AS_AMO2012.msi
 SQL_AS_AMO2014.msi
 SQL_AS_OLEDB.msi
 SqlDom.msi
 SqlLocalDB.msi
 sqlncli.msi
 SQLSysClrTypes.msi
 SSDT.msi
 SSDTAS.msi
 SSDTDBSvcExternals.msi
 SSDTIS.msi
 SSDTPostInstall.msi
 SSDTRS.msi
 SSISOneDesigner2012.msi
 SSISOneDesigner2014.msi
 TSqlLanguageService.msi
 vsta_ls.exe
 vsta_setup.exe

After each download and restart of the SSDT install, the progress would get a little bit more advanced before erroring out with another file it couldn't download.
FYI, I downloaded the installation file from msdn.microsoft.com/en-us/mt186501, so it should have worked.

A: This is what worked for me based on what John Altamura wrote in: https://developercommunity.visualstudio.com/content/problem/246732/ssdt-1560-installer-the-configuration-registry-key.html
I uninstalled my SSDT using Visual Studio installer
I uninstalled Visual Studio using the Visual Studio installer
I then went to Add or Remove Programs and uninstalled everything that looked like it was related to Visual Studio
Then I had to actually re-download the VS installer from https://visualstudio.microsoft.com/downloads/, as I needed the InstallCleanup.exe program in "C:\Program Files (x86)\Microsoft Visual Studio\Installer\resources\app\layout\". This step is only needed if you uninstall VS Installer before running Installcleanup.exe.
Run InstallCleanup.exe from C:\Program Files (x86)\Microsoft Visual Studio\Installer\resources\app\layout\"
Uninstall VS Installer from Add or Remove Programs.
Then to be safe I deleted this directory: C:\Program Files (x86)\Microsoft Visual Studio
Then I restarted my PC.
Download Visual Studio 2017 from https://visualstudio.microsoft.com/downloads/ Just in case I performed a minimal install from VS Installer, of only installing a single language pack
Then download SSDT from here: https://learn.microsoft.com/en-us/sql/ssdt/download-sql-server-data-tools-ssdt?view=sql-server-2017 and install Then, it all worked perfectly.

A: ISO image for SSDT is 1GB (https://msdn.microsoft.com/en-us/mt186501.aspx) and it can be unaffordable for some VMs, but it really works, you can install it without internet access.
But, the error mentioned in the question was simply a connection issue and I used to solve it from MLguy solution. I'm using Windows Server 2012 Datacenter Build Server and IE Enhanced Security Configuration was blocking the downloads required for SSDT installation. I turned off IE Enhanced Security Configuration and installation was successful.
I wouldn't recommend disabling any other security feature. And yes, it would be better to turn IE Enhanced Security Configuration on after installation is completed.

A: You should be able to see the log file in the following location:
C:\xxx\xxx\AppData\Roaming\Microsoft\VisualStudio\14.0\ActivityLog.xml

A: Disable Security programs. I had to allow all network traffic from F-secure Client security to make this setup to work.


text:
Q: PageSpeed Insights: poor both mobile and desktop I am not a programmer nor developer and although I followed the links on Google to remove the problems it showed, I do not understand a thing. Therefore I would like to ask you to tell me in some comprehensible words what I should do to rectify the optimisations so that the speed of my pages is as it should be.

A: UPDATE

Reduce server response time

Your web server is TOO SLOW!
Getting a better ISP/Host is the easiest way to significantly speed up your page.  This will speed things up about 10X.  All those 600-900ms response times in the waterfall should be one tenth the time.
For example your style.css takes only 7 ms to download the file, but the server waited 632 ms to send the first byte. This is almost a 100X unnecessary delay.
URL: https://moreyouthfulskin.com/wp-content/themes/wellness-pro/style.css?ver=1.0.0
Loaded By: https://moreyouthfulskin.com/en/home/:59
Host: moreyouthfulskin.com
Request Start: 5.951 s
Time to First Byte: 632 ms
Content Download: 7 ms
Bytes In (downloaded): 7.9 KB
Uncompressed Size: 36.9 KB
Bytes Out (uploaded): 0.2 KB

This above data is from this link: Web Page Performance Test for https://moreyouthfulskin.com/en/home/

Leverage browser caching

The 1 day cache is not a big deal, it is a small issue. It is more of a warning.  It is a web server setting. It is not worth much effort when you have so many other serious issues.

Eliminate render-blocking JavaScript and CSS in above-the-fold content

The CSS after the JS is big. This is usually caused by WP plug-ins.  Only use plug-ins that do not degrade performance.  Check your page speed be and after installing any plug-in. Then think about whether it is worth it.

Remove or at least speed up the redirects.

Your redirects are costing you because your web server is too slow. Get a new ISP.  The two redirects took over 5 seconds.  This means there is an unnecessary 5 second delay before the page even begins to load the first byte of the home page.

Optimize images, Minify JavaScript, and Minify CSS

At the bottom of Google Pagespeed results there is a link to Optimized images, Minified JavaScript, and Minified CSS.  Download them, then upload them to the proper directory/folder on your server. This one is easy.  If you cannot do this then you are in this way over your head.
END OF UPDATE

Your biggest issue is you have CSS and fonts being loaded after the JavaScript.  This is costing you about 5 seconds load time.
Also your page load had two redirects using 2 seconds.
Your server needs to be configured to use a longer max-age cache .
Curently your cache is 14400 seconds.  cache-control: public, max-age=14400