text:
Q: flash builder mobile, using PersistenceManager properly? I'm new to mobile app dev, but I'm trying to build a mobile RPG game character sheet app. Instead of using SQLite, Im trying to use PersistenceManager to persist the character data when the app is interrupted or shutdown, but Im not sure if Im using it properly. Heres what I have so far.
Main.mxml:
<?xml version="1.0" encoding="utf-8"?>
<s:ViewNavigatorApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
                        xmlns:s="library://ns.adobe.com/flex/spark" firstView="views.CharactersView"
                        applicationDPI="160" persistNavigatorState="true">

</s:ViewNavigatorApplication>

CharactersView.mxml:
<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark" creationComplete="creationCompleteHandler(event)">

<fx:Script>
    <![CDATA[
        import mx.collections.ArrayCollection;
        import mx.events.FlexEvent;

        protected function creationCompleteHandler(event:FlexEvent):void
        {
            var o:Object = new Object();
            o.name = "Aragorn";
            o.type = "Ranger";
            o.strength = 97;
            o.speed = 7;
            Database.insertCharacter(o);
            trace(Database.characters.length);
        }

    ]]>
</fx:Script>

<s:List id="list" width="100%" height="100%"/>

Database.as:
import spark.managers.PersistenceManager;

public class Database
{
    private static var data:Array = [];
    private static var pm:PersistenceManager = new PersistenceManager();

    public static function get characters():Array
    {
        if (!pm.load() || pm.getProperty("characters") == null)
        {
            Database.data = [];
        }
        else
        {
            Database.data = pm.getProperty("characters") as Array;
        }
        return data;
    }

    public static function insertCharacter(o:Object):void
    {
        Database.data.push(o);
        pm.setProperty("characters", Database.data);
        pm.save();
    }

}

In the creationComplete handler of CharactersView.mxml, I'm creating a one-off character with some arbitrary info just to test if inserting characters works. Every time I run this, completely as-is, the trace statement (length of my array) returns 1. Shouldn't it go up by one every time I run it? This is telling me something isn't right, but is it the persistencemanager not saving the data properly? Do I need to check if pm.save() returns true, and if it does, should I dispatch an event and only THEN run the trace statement to get the proper length? That seems overly complicated just to save some data, so I'm not entirely sure whats going on or how to fix it.
In any case, what I'm asking is if my current setup is correct, and if its not, does anyone have a simple example, or could create a simple example based on my code for how to properly use persistencemanager?
Once I get this technique down I can create several other apps as well, so Im really hoping to get this nailed down. Thanks in advance!
EDIT: It seems I'm using everything correctly regarding the PM and the answer I received did help me get my app working. However, when moving forward my app started acting funny. For instance, my list seems to react really slowly to interaction, as do most of the other components. New code below.
Main.mxml:
<?xml version="1.0" encoding="utf-8"?>
<s:ViewNavigatorApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
                        xmlns:s="library://ns.adobe.com/flex/spark" firstView="views.CharactersView"
                        applicationDPI="160" persistNavigatorState="true">

</s:ViewNavigatorApplication>

CharactersView.mxml:
<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark" creationComplete="creationCompleteHandler(event)">

<fx:Script>
    <![CDATA[
        import mx.collections.ArrayCollection;
        import mx.events.FlexEvent;

        protected function creationCompleteHandler(event:FlexEvent):void
        {
            update();
        }

        private function update():void
        {
            title = "D&D Characters (" + Database.characters.length + ")";
            list.dataProvider = new ArrayCollection(Database.characters);
        }

        protected function button1_clickHandler(event:MouseEvent):void
        {
            var vo:CharacterVO = new CharacterVO();
            vo.name = "Aragorn";
            vo.className = "Ranger";
            vo.race = "Human";
            vo.level = 6;
            vo.gender = "Male";
            vo.alignment = "Unaligned";
            vo.hp = 25;
            vo.xp = 100;
            Database.insertCharacter(vo);
            update();
        }

    ]]>
</fx:Script>

<s:actionContent>
    <s:Button label="+" click="button1_clickHandler(event)"/>
</s:actionContent>

<s:List id="list" width="100%" height="100%"/>

</s:View>

Database.as:
import spark.managers.PersistenceManager;

public class Database
{
    private static var data:Array = [];
    private static var pm:PersistenceManager = new PersistenceManager();

    public static function get characters():Array
    {
        return data;
    }

    public static function insertCharacter(o:CharacterVO):void
    {
        Database.data.push(o);
        pm.setProperty("characters", Database.data);
        pm.save();

        if (!pm.load() || pm.getProperty("characters") == null)
        {
            Database.data = [];
        }
        else
        {
            Database.data = pm.getProperty("characters") as Array;
        }
    }

}

CharacterVO.as:
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
import flash.utils.IExternalizable;

public class CharacterVO implements IExternalizable
{
    public var name:String;
    public var className:String;
    public var race:String;
    public var gender:String;
    public var alignment:String;
    public var level:Number;
    public var hp:Number;
    public var xp:Number;

    public function writeExternal(output:IDataOutput):void {
        output.writeUTF(name);
        output.writeUTF(className);
        output.writeUTF(race);
        output.writeUTF(gender);
        output.writeUTF(alignment);
        output.writeFloat(level);
        output.writeFloat(hp);
        output.writeFloat(xp);
    }

    public function readExternal(input:IDataInput):void {
        name = input.readUTF();
        className = input.readUTF();
        race = input.readUTF();
        gender = input.readUTF();
        alignment = input.readUTF();
        level = input.readFloat();
        hp = input.readFloat();
        xp = input.readFloat();
    }
}

As you can see most of the code is the same as what I first posted. I added the CharacterVO class, I moved a few things around in CharactersView.mxml, and I moved the PersistenceManager loading code to the insertCharacter function (this way, I'm only loading the PM whenever a new item is added, not everytime I call Database.characters).
Again, my app seems to react real slow to interaction, sometimes it doesnt react at all. Something just isnt right, Ive never had this issue with a mobile app before. Could it be that storing the array in the PM and then attempting to set it as the List's dataProvider is causing an issue?

A: I'm not too familiar with using this however from the docs it looks like you probably can't use a generic Object since I don't believe it implements IExternalizable, according to the docs this doesn't cause an error for some reason but it can't actually read/write those objects.
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/spark/managers/PersistenceManager.html

When storing values using the manager, it is important that all values
  can be properly be written to a shared object. Complex objects that
  store classes or non-standard flash primitives must implement
  flash.net.IExternalizable interface to work properly. Saving
  incompatible objects does not cause an RTE, but creates undefined
  behavior when the data is read back.

When using this myself, one time helping another SO poster on a project I don't recall really having any issues except if we changed properties of the model object we were storing/retrieving then we had to manually blow away the local shared object it was creating otherwise it couldn't de-serialize it (makes sense but just something to be aware of).  I don't actually recall implementing IExternalizable but it's possible the other guy did it.
Try this:
[CharacterVO.as]
public class CharacterVO implements IExternalizable
{
    public var name:String;
    public var type:String;
    public var strength:Number;
    public var speed:Number;

    public function writeExternal(output:IDataOutput) {
        output.writeUTF(name);
        output.writeUTF(type);
        output.writeFloat(strength);
        output.writeFloat(speed);
    }

    public function readExternal(input:IDataInput) {
        name = input.readUTF();
        type = input.readUTF();
        strength = input.readFloat();
        speed = input.readFloat();
    }
}

Then instead of creating a Generic object create instances of that VO.  I believe Array will serialize automatically by serializing all it's elements in order.


text:
Q: SOQL statement inside a getter/setter - what benefits? I've seen some SOQL done in a getter as such:
    public static Map<String, sObjectHere> methodName {
        get {
                someMapHere = new Map<String, sObjectHere>();
                List<sObjectHere> sobjectList = [SELECT <Fields here> FROM sObjectHere];

                for (sObjectHere i : sobjectList) {
                    someMapHere.put(key, value);
                }

            return someMapHere;
        }

        private set;
    }

What benefits des this serve over a regular method that returns a soql statement and then iterating it and putting it in a map. What does get do in this context?

A: In this example there is no difference than having a getMap() method that always executes the same code as in the getter. Not to be too nitpicky with terms, but what you have is a property and not a method.
Normally, you use a syntax like this to lazy load (see also, lazy instantiation) properties of a class. This has two benefits:

*

*you only consume the time needed to get the property if it's actually needed instead of automatically initializing it when the class is first referenced and

*repeated accesses of the property don't go all the way back to the database to fetch the values, which improves performance and conserves query limits.

These are particularly helpful in an environment like Salesforce where governor limits dictate how much you can get away with in any given transaction.
Lazy loading example:
public static Map<Id, Contact> contactMap {
  get {
    // if contactMap hasn't been initialized yet, initialize it
    if(contactMap == null) {
        contactMap = new Map<Id, Contact>([SELECT Id, Name FROM Contact LIMIT 100]);
    }
    // subsequent calls don't need to execute the query
    return contactMap;
  }
  private set;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Callout Touch Event I have a custom MKAnnotationView which I have customised according to the documentation of Apple Docs.
Here's my code for AnnotationView with Custom Callout view.
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
    UIView *hitView = [super hitTest:point withEvent:event];
    if (hitView == nil && self.selected) {
        CGPoint pointInAnnotationView = [self.superview convertPoint:point toView:self];
        hitView = [self.calloutView hitTest:pointInAnnotationView withEvent:event];
    }
    return hitView;
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent*)event
{
    CGRect rect = self.bounds;
    BOOL isInside = CGRectContainsPoint(rect, point);
    if(!isInside)
    {
        for (UIView *view in self.subviews)
        {
            isInside = CGRectContainsPoint(view.frame, point);
            if(isInside)
                break;
        }
    }
    return isInside;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated{
    [super setSelected:selected animated:animated];

    if (selected) {
        CGRect annotationViewBounds = self.bounds;
        CGRect calloutViewFrame = self.calloutView.frame;
        self.backgroundColor = [UIColor clearColor];

        // Center the callout view above and to the right of the annotation view.
        calloutViewFrame.origin.x = -(calloutViewFrame.size.width - annotationViewBounds.size.width) * 0.5;
        calloutViewFrame.origin.y = -calloutViewFrame.size.height + 1.0;
        self.calloutView.frame = calloutViewFrame;
        self.calloutView.layer.cornerRadius = 10;
        self.calloutView.layer.masksToBounds = YES;

        [self.calloutView setupCalloutView:self.info];

        [self addSubview:self.calloutView];
    } else {
        [self.calloutView removeFromSuperview];
    }
}

I have a button in custom callout view where I am not getting touch action. But I am getting hitTest event of Custom Callout View.
- (UIView*)hitTest:(CGPoint)point withEvent:(UIEvent*)event
{
    UIView* hitView = [super hitTest:point withEvent:event];
    if (hitView != nil)
    {
        [self.superview bringSubviewToFront:self];
    }
    return hitView;
}

So what is the correct way of getting touch event in custom callout view to open detail view controller.


text:
Q: Multiple inequality (a < b < c...) with potentially missing value I would like to test multiple inequalities at once, i.e.
if (a < b < c < ...)

which is fine when all the values are present. However sometimes the numeric value of one or more of the variables to be compared may be missing/unknown; the correct behaviour in my context is to assume the associated inequality is satisfied. Let's say I assign the special value None when the value is unknown: the behaviour I want from the < operator (or an alternative) is:
>>> a = 1; b = 2; c = 3
>>> a < b < c # this works fine, obviously
True
>>> b = None
>>> a < b < c # would like this to return True
False

So I want to get True if one variable is truly smaller than the other, or if one variable is missing (takes any particular pre-decided non-numerical value), or if both variables are missing, and I want to be able to string the comparisons together one go i.e. a < b < c < ...
I would also like to do this with <= as well as <.
Thanks

A: You want to test if your sequence – bar the undefined values – is in ascending order:
import operator

def isAscending(strictly, *seq):
    cmp_op = operator.lt if strictly else operator.le
    seq = [e for e in seq if e is not None]
    return all(cmp_op(a, b) for a, b in zip(seq, seq[1:]))

a, b, c = 1, None, 2
print isAscending(True, a, b, c) # strictly ascending ?

Edited for spelling, and to use comparison operators as suggested.

A: This looks like you are actually trying to test if your values are unique and in sorted order which could be replaced by something like:
>>> def my_test(l):
>>>     filt_l = [v for v in l if not v is None]
>>>     return (sorted(filt_l) == filt_l) and (len(filt_l) == len(set(filt_l)))

>>> my_test([1,2,3])
True
>>> my_test([1,None,3])
True
>>> my_test([1,4,3])
False
>>> my_test([1,1,3])
False

Edit: including timings it seems that the function suggested by sebdelsol is even faster
>>> %timeit isAscending([int(1000*random.random()) for i in xrange(10000)])
100 loops, best of 3: 3.44 ms per loop

>>> %timeit my_test([int(1000*random.random()) for i in xrange(10000)])
100 loops, best of 3: 5.67 ms per loop

A: You could create your own type overloading comparison methods (as in this question: python overloading operators)
E.g.
class N(object):
    def __init__(self, value):
        self.value = value

    def __lt__(self, other):
        return (self.value is None or self.value < other.value)
    ...

a = N(1); b = N(None); c = N(3)
print a < b < c

A: If you have your values in a list ([a, b, c]), then you can filter the None values from it, pair them up using zip(), apply the operator to all the pairs and see if all them hold.
In code:
import operator  # For operator.lt, which is < ("less than")

def mass_comparify(op, *args):
    return all(op(a, b) for a, b in zip(args, args[1:])
               if a is not None and b is not None)

print(mass_comparify(operator.lt, 1, None, 3))  # Prints True because 1 < 3

A: I don't think you have a better option than to define a comparison function which does the comparison as you want, and then write the inequalities as
comp(a,b) and comp(b,c) and ...

A: I don't know if it fits perfectly, but you can use reduce:
>>> import operator
>>> reduce(operator.__lt__, [1, None, 3])
True
>>> reduce(operator.__lt__, [1, None, 0])
False

or, much more solid, as it explicitly ignores None values:
>>> import operator
>>> reduce(operator.__lt__, filter(None, [1, None, 3]))
True
>>> reduce(operator.__lt__, filter(None, [1, None, 0]))
False


text:
Q: StringBuilder Java Как я могу передать параметр в builder.append?
Дело в том, что мне необходимо вывести мою строку, но перед этим сделать её длиной в 100.000 символов.
Мне подсказали, что можно сделать это с помощью StringBuilder.
Я попытался передать строку в builder.append, но компилятор выдаёт ошибку.
StringBuilder builder = new StringBuilder();
String text = (Poem.text);
for (int i = 0; i < 100000; i++) {
    builder.append(text);
}
String result = builder.toString();
System.out.println(result);

Я ещё совсем новичок в программировании, буду рад любому совету!

A:        public class Solution {

        static class Poem {
            static String text = "ввести любой текст ";
        }

        static void pr() {
            StringBuilder builder = new StringBuilder();
            String text = (Poem.text);

    //пока строка меньше 100_000 символов
            while (builder.length() < 100_000) {
                builder.append(text);

            }
            System.out.println(builder.toString());
            System.out.println(builder.length());
        }

        public static void main(String[] args) {
            Solution.pr();

        }
    }


text:
Q: Spark creates new row when reading in CSV with line break in text So, this issue has been talked about quite a bit, but it was supposed to be fixed in Spark 2.2.0 which was just released. From what I can tell, the wholeLine option is supposed to fix this issue, however I am having no luck. The issue is that when there is a line break in a value, say like, a notes column that has a bunch of text in it, and there's a line break in those notes, Spark treats it as a new row.
Here is the snippet I'm using to read the data from the CSV.
sparkSession.read
  .option("header", "true")
  .option("delimiter", ",")
  .option("multiLine", "true")
  .option("inferSchema", true)
  .option("wholeFile", "true")
  .option("quoteMode", "ALL")
  .option("parserLib", "univocity")
  .csv(csvFilePath)

As you can tell, I'm using every option under the sun, but I'm still getting the wrong output. The output I get is below, those are all supposed to be unique integers, but they're being polluted with data from other columns, from another row. I've changed the data a little but you can see there is string data in the column with the IDs.
+--------------------+
|                  ID|
+--------------------+
|             3876849|
|             3876872|
|          consistent|
|                4/30|
|,blah blah blah  ...|
|             3876876|
|             3876878|
|       5-6 days ago"|
|             3876879|
|             3876880|
|blah blah blah bl...|
|             3876893|
|*blah blah blah  ...|
|             3876900|
|             3876904|
+--------------------+

This has me really stumped, for good measure I'm including my build.sbt as well.
name := "MyApp"
organization := "com.test"
version := "1.0-SNAPSHOT"
scalaVersion := "2.11.8"

libraryDependencies ++= Seq(
  "org.apache.spark" % "spark-core_2.11" % "2.2.0" % "provided",
  "org.apache.spark" % "spark-sql_2.11" % "2.2.0" % "provided",
  "org.apache.spark" % "spark-hive_2.11" % "2.2.0" % "provided",
  "org.elasticsearch" % "elasticsearch-spark-20_2.11" % "5.5.0",
  "org.apache.logging.log4j" % "log4j-core" %"2.8.2"
)
assemblyMergeStrategy in assembly := {
  case PathList("META-INF", xs @ _*) => MergeStrategy.discard
  case x => MergeStrategy.first
}

assemblyOption in assembly := (assemblyOption in assembly).value.copy(includeScala = false)


text:
Q: Having the current bank account information of an employee I have the following query to get for EmployeeId = 5625, the list of their related bank information :
    SELECT
   [E].[EmployeeId],
   ISNULL([AFB].BankInformationId, 0) AS BankInformationId,
   [BIS].[Label] AS [System],
   [BIT].[Label] AS [Type],
   [BI].[Label] AS [Bank Name],
   [BI].[AccountNumber],
   [BI].[HolderFirstName] + ' ' + [BI].[HolderLastName] AS [Holder Full Name],
   [BI].UpdatedDate,
   [BI].CreatedDate
FROM
   [Employee] AS [E]
   LEFT JOIN
      [AF_AdminFile] AS [AAF]
      ON [AAF].[AdminFileId] = [E].[AdminFileId]
   LEFT JOIN
      [AF_BankInformation] AS [AFB]
      ON [AFB].[AdminFileId] = [AAF].[AdminFileId]
   LEFT JOIN
      [BankInformation] AS [BI]
      ON [BI].[BankInformationId] = [AFB].[BankInformationId]
   LEFT JOIN
      [BankInformationType] AS [BIT]
      ON [BIT].[BankInformationTypeId] = [AFB].[BankInformationTypeId]
   LEFT JOIN
      [BankInformationSystem] AS [BIS]
      ON [BIS].[BankInformationSystemId] = [BI].[BankInformationSystemId]
   LEFT JOIN
      [Currency] AS [Cur]
      ON [Cur].[ID] = [BI].[CurrencyId]
WHERE
   e.EmployeeId = 5625

The output of the query mentioned above :
EmployeeId  BankInformationId   System      Type     Bank Name      AccountNumber     Holder Full Name  UpdatedDate                     CreatedDate
5625        25223               European    Salary   lorem ipsum    lorem ipsum       XXXXXXXXX         2019-06-21  12:52:10.5583656    2019-04-09 17:30:26.5767272
5625        9913                European    Salary   lorem ipsum    lorem ipsum       XXXXXXXXX         2018-10-15  07:12:41.7955086    2017-05-30 09:47:35.2461420
5625        18933               European    Salary   lorem ipsum    lorem ipsum       XXXXXXXX          2018-10-01 05:52:37.7380577     2018-10-01 05:52:37.7380577
5625        10920               Asian       Expenses lorem ipsum    lorem ipsum       XXXXXXXXX         2017-07-25 07:09:33.6450526     2017-07-25 07:09:33.6450526
5625        10920               Asian       Unused   lorem ipsum    lorem ipsum       XXXXXXXXX         2017-07-25 07:09:33.6450526     2017-07-25 07:09:33.6450526
5625        25223               European    Unused   lorem ipsum    lorem ipsum       XXXXXXXXX         2019-06-21 12:52:10.5583656     2019-04-09 17:30:26.5767272
5625        19574               Asian       Unused   lorem ipsum    lorem ipsum       XXXXXXXXX         2019-04-09 17:30:41.0204536     2018-10-15 07:08:26.6160286
5625        9913                European    Unused   lorem ipsum    lorem ipsum       XXXXXXXXX         2018-10-15 07:12:41.7955086     2017-05-30 09:47:35.2461420
5625        1594                European    Unused   lorem ipsum    lorem ipsum       XXXXXXXXX         2017-08-07 04:13:19.4727086     2015-04-20 15:52:05.7233965

I want to have the latest (as current) bank information for the BankInformationId=10920 the record having Unused type means that the account is no more used (and it is not a current)
EmployeeId  BankInformationId   System      Type     Bank Name      AccountNumber     Holder Full Name  UpdatedDate                     CreatedDate
5625        10920               Asian       Expenses lorem ipsum    lorem ipsum       XXXXXXXXX         2017-07-25 07:09:33.6450526     2017-07-25 07:09:33.6450526
5625        10920               Asian       Unused   lorem ipsum    lorem ipsum       XXXXXXXXX         2017-07-25 07:09:33.6450526     2017-07-25 07:09:33.6450526

How to get the current/last account information knowing that :

*

*The account types are Salary, Expenses and Unused

*I want to get the current Salary and Expenses bank information that
are still used (which don't have the Unused type yet).

A: Use a CTE and add a row_number() based on the last updated date. Something like this;
;with T as(
   SELECT
    ROW_NUMBER() OVER (PARTITION BY [E].[EmployeeId] order by [BI].UpdatedDate desc) rn,
   [E].[EmployeeId],
   ISNULL([AFB].BankInformationId, 0) AS BankInformationId,
   [BIS].[Label] AS [System],
   [BIT].[Label] AS [Type],
   [BI].[Label] AS [Bank Name],
   [BI].[AccountNumber],
   [BI].[HolderFirstName] + ' ' + [BI].[HolderLastName] AS [Holder Full Name],
   [BI].UpdatedDate,
   [BI].CreatedDate
FROM
   [Employee] AS [E]
   LEFT JOIN
      [AF_AdminFile] AS [AAF]
      ON [AAF].[AdminFileId] = [E].[AdminFileId]
   LEFT JOIN
      [AF_BankInformation] AS [AFB]
      ON [AFB].[AdminFileId] = [AAF].[AdminFileId]
   LEFT JOIN
      [BankInformation] AS [BI]
      ON [BI].[BankInformationId] = [AFB].[BankInformationId]
   LEFT JOIN
      [BankInformationType] AS [BIT]
      ON [BIT].[BankInformationTypeId] = [AFB].[BankInformationTypeId]
   LEFT JOIN
      [BankInformationSystem] AS [BIS]
      ON [BIS].[BankInformationSystemId] = [BI].[BankInformationSystemId]
   LEFT JOIN
      [Currency] AS [Cur]
      ON [Cur].[ID] = [BI].[CurrencyId]
WHERE
   e.EmployeeId = 5625
)
select [EmployeeId],BankInformationId,[System],[Type],[Bank Name],[AccountNumber],[Holder Full Name],UpdatedDate,CreatedDate
FROM T
WHERE rn=1
AND [TYPE]<> 'Unused'
and BankInformationId not in (select distinct BankInformationId from T where [TYPE]= 'Unused')


text:
Q: C++: static variables not changing with static set() function After reading StackOverflow's discussions and implementing some advices, I have these pieces of code intended just to test the behavior of static members of a class.
Here is the header, which has the class declaration:
class OurClass
    {
    private:
        static int x, y;

    public:
        static void setVals(int valx, int valy);
        static int getValx();
        static int getValy();
        static void initialize();
    };

And here is the cpp file, which has the definition of these members as well as the main() function:
#include <iostream>
#include "OurClass.hpp"

using namespace std;

void OurClass::initialize()
    {
    static int x = 0;
    static int y = 0;
    }

void OurClass::setVals(int valx, int valy)
    {
    static int x = valx;
    static int y = valy;
    }

int OurClass::getValx()
    {
    static int x;
    return x;
    }

int OurClass::getValy()
    {
    static int y;
    return y;
    }

int main(void)
{
OurClass::inicializa();

cout << "Provide x and y..." << endl;

OurClass::setVals(cin.get(), cin.get());

cout << "Value of x: " << OurClass::getValx() << endl;
cout << "Value of y: " << OurClass::getValy() << endl;
return 0;
}

So, assuming that a static variable exists for the class, and that static functions only access static variables, I was expecting that x and y would have the values that we read from the keyboard with the setVals() call in main(). But when printing their values in the couts, they still have the value we assigned in the initialize() function (which BTW was another suggestion I got here, that is, initialize a static variable in a method).
I am also unable to refer directly to the variables by OurClass::x or y even if I make them public.
Do you guys know why?

A: Instead of setting values of existing variables this code creates new local static variables. Fix:
void OurClass::initialize()
{
    x = 0;
    y = 0;
}

void OurClass::setVals(int valx, int valy)
{
    x = valx;
    y = valy;
}

int OurClass::getValx()
{
    return x;
}

int OurClass::getValy()
{
    return y;
}

And add the definitions of those static variables in a .cc file (not header):
int OurClass::x;
int OurClass::y;

A: First you need to access your local class's static variable instead declaring new method local variables in each method. Check below.
class Out {
private:
    static int x, y;

public:
    void set(int x, int y);
    int getSum();
};

int Out::x = 0;
int Out::y = 0;

void Out::set(int x, int y) {
    Out::x = x;
    Out::y = y;
}

int Out::getSum() {
    return Out::x + Out::y;
}


text:
Q: What is the minimum space complexity in problem of find longest common substring? const char *_longest_common_substr(const char *s1, const char *s2, int n, int m) {
   // assert n >= m
   int max = 0; // keep track of max length found
   int tmp = 0; // value is incremented till letters match
   int begin = 0;
   int try_begin = 0; // possible new begin index
   int end = 0; // rv = s2[begin : end - 1]

   for (int i = 0; i < n; i++) {
       tmp = 0;
       try_begin = 0;
       // s1 is scanned circularly
       for (int j = 0; j < m; j++) {
           int index = (j + i) % n; // current s1 index
           if (index < n && s1[index] == s2[j]) {
               if (tmp == 0)
                   try_begin = j;
               tmp++;
           } else {
               tmp = 0;
           }
           if (tmp > max) {
               max = tmp;
               begin = try_begin;
               end = j + 1;
           }
       }
   }

   int size = begin >= end ? 0 : end - begin;
   char *rv = malloc((size + 1) * sizeof(*rv));
   int i;
   for (i = 0; i < size; i++)
       rv[i] = s2[begin + i];
   rv[i] = '\0';
   return rv;
}

const char *longest_common_substr(const char *s1, const char *s2, int n, int m) {
   if (n < m)
       return _longest_common_substr(s2, s1, m, n);
   return _longest_common_substr(s1, s2, n, m);
}

Is this code correct to find longest common substring? I don't understand why in many places, for example wikipedia, they use a matrix to solve the problem, while in this apparently simple solution there is no need for it and time complexity is still O(n*m) while space complexity is O(1).
A possible test is
int main() {
    const char *str1 = "identification";
    const char *str2 = "administration";

    printf("%s\n", longest_common_substr(str1, str2, strlen(str1), strlen(str2)));

}

and the output is
ation

substring is intended in a circular way, so with input
action
tionac

the output will be
tionac

anyway i could add two different invalid character at the end of the strings to remove this property

A: Your algorithm is a weird one. You count circular substrings on the longest string only. And if the strings are of equal length you count circular substrings on the first one only.
For instance:

*

*for "bxa" and "ab" you find the solution "ab" because you count circular substrings on bxa

*but for "bxa" and "zaby" you don't consider circular substrings in "bxa" and you don't find "ab" as a solution

*("abx", "bya") and ("bya", "abx") have different solutions even though only the position of the arguments changes. (you count circular substrings only on the first argument if both arguments are of equal length).
You must either:

*

*not count circular substrings at all (the classic algorithm as described in the wiki link) or:

*count circular substrings for both strings (this is a different algorithm then longest common substring)
So the complexity of your algorithm is not comparable with the wiki algorithm because it is a different algorithm solving a different problem.

A: Your algorithm performs circular matching, which is different from the classic LCS algorithm. Yet it can be simplified to remove this extra matching and also remove the need to make s1 the longer string:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *longest_common_substr(const char *s1, const char *s2, int n1, int n2) {
    int begin = 0;  // offset of lcs in s2
    int max = 0;    // length of lcs

    for (int i = 0; i < n1; i++) {
        int tmp = 0;        // count of matched letters
        int index = i;      // current s1 index
        for (int j = 0; j < n2; j++, index++) {
            if (index == n1) {
                index = 0;
                tmp = 0;    // do not match circularly
            }
            if (s1[index] == s2[j]) {
                tmp++;
                if (tmp > max) {
                    max = tmp;
                    begin = j - (tmp - 1);
                }
            } else {
                tmp = 0;
            }
        }
    }

    char *rv = malloc(sizeof(*rv) * (max + 1));
    memcpy(rv, s2 + begin, max);
    rv[max] = '\0';
    return rv;
}

int main(int argc, char *argv[]) {
    if (argc == 3) {
        const char *s1 = argv[1];
        const char *s2 = argv[2];
        char *p = longest_common_substr(s1, s2, strlen(s1), strlen(s2));
        if (p) {
            printf("lcs('%s','%s') -> '%s'\n", s1, s2, p);
        }
    }
    return 0;
}

The above does have a time complexity of O(n1*n2) and a space complexity of O(1). Achieving better time complexity is usually a desired goal, which may explain why the Wikipedia article has a suboptimal example for the more complex case.


text:
Q: Google Endpoints - Invalid Token, allowed_client_id using token from OAuth2.0 Playground So in my google cloud project I generated a Web Client ID, and follow the steps in
https://developers.google.com/adwords/api/docs/guides/oauth_playground
to get the authentication token.
In my @endpoints.api(allowed_client_ids=) I've put the client id inside it. Then in OAuth2 playground I sent a http request using the authentication token which I have acquired (e.g: Bearer ya29.bwL-f-hz-wcxFq_i-IlEQaJDiinwIP7ad7CaZoRkJRdGrsxxs4Wc9ZeNOgVlhD69zOQk) to the API.
But the problem is, it did not recognize the token, and said it is an invalid token. To compare with, I put endpoints.API_EXPLORER_CLIENT_ID together inside the allowed_clients_ids=, and when I tested it using API Explorer it just works. So am I doing something wrong?

A: You have specify your own client id and client secret. see this
screenshot


text:
Q: Add a checkbox to product image gallery (like "Disable/Exclude") I'm trying to code a new checkbox to be appended to the columns in the image gallery, beside "Disable". Its behavior would be the same as "Disable/Exclude" = Yes/No with entry in the database.
The idea is to add a "Use as page" checkbox for each image in the image gallery. The goal being to make a JS carousel with all pictures checked as "Use as page".
I have a few things done but I cannot :

*

*update data in the database => set 0 or 1 to the "page" field (see below)

*retrieve data from the database and then check/uncheck the checkbox depending on the "page" field.

--> So my question is : how to update data in the database and retrieve it in the checkbox (0 or 1 depending on the field value) ?
Thanks all for your very precious help.

Here is what I've done (1.4.1.0) :
1- Update table catalog_product_entity_media_gallery_value
Added a new field (which name is "page") :

*

*page   tinyint(4)     UNSIGNED   No   0

2- Made the following changes to class Mage_Catalog_Model_Product_Attribute_Backend_Media
Line 49 :
from
$localAttributes = array('label', 'position', 'disabled');

to
$localAttributes = array('label', 'position', 'disabled', 'page');

Line 223 :
from
$data['disabled'] = (int) $image['disabled'];

to
$data['disabled'] = (int) $image['disabled'];
$data['page'] = (int) $image['page'];

Line 301
from
$mediaGalleryData['images'][] = array(
    'file'     => $fileName,
    'position' => $position,
    'label'    => '',
    'disabled' => (int) $exclude
);

to
$mediaGalleryData['images'][] = array(
    'file'     => $fileName,
    'position' => $position,
    'label'    => '',
    'disabled' => (int) $exclude,
    'page' => (int) $exclude,
);

Line 328
from
$fieldsMap = array(
    'label'    => 'label',
    'position' => 'position',
    'disabled' => 'disabled',
    'exclude'  => 'disabled',
);

to
$fieldsMap = array(
    'label'    => 'label',
    'position' => 'position',
    'disabled' => 'disabled',
    'exclude'  => 'disabled',
    'page'  => 'disabled',
);

3- Made the following changes to template adminhtml/default/default/template/catalog/product/helper/gallery.phtml
Line 64
from
    <?php echo Mage::helper('catalog')->__('Exclude') ?>

to
    <?php echo Mage::helper('catalog')->__('Exclude') ?>
    <?php echo Mage::helper('catalog')->__('Is Page') ?>

Line 77
from
<input type="checkbox" <?php if($_block->getElement()->getReadonly()):?> disabled="disabled"<?php endif;?> onclick="<?php echo $_block->getJsObjectName(); ?>.updateImage('__file__')" />

to
<input type="checkbox" <?php if($_block->getElement()->getReadonly()):?> disabled="disabled"<?php endif;?> onclick="<?php echo $_block->getJsObjectName(); ?>.updateImage('__file__')" />
<input type="checkbox" <?php if($_block->getElement()->getReadonly()):?> disabled="disabled"<?php endif;?> onclick="<?php echo $_block->getJsObjectName(); ?>.updateImage('__file__')" />

Line 105
from

to
            <input type="hidden" />
            <input type="hidden" />

A: This is how I solved the problem and is working perfectly. Beside your changes make these too.
1. In Mage_Catalog_Model_Product_Attribute_Backend_Media
change
public function addImage(Mage_Catalog_Model_Product $product, $file,
    $mediaAttribute = null, $move = false, $exclude = true)

to
public function addImage(Mage_Catalog_Model_Product $product, $file,
    $mediaAttribute = null, $move = false, $exclude = true, $page = false)

change
public function addImagesWithDifferentMediaAttributes(Mage_Catalog_Model_Product $product,
    $fileAndAttributesArray, $filePath = '', $move = false, $exclude = true)

to
public function addImagesWithDifferentMediaAttributes(Mage_Catalog_Model_Product $product,
    $fileAndAttributesArray, $filePath = '', $move = false, $exclude = true, $page = true)

change
$savedFileName = $this->addImage($product, $filePath . $value['file'], null, $move, $exclude);

to
$savedFileName = $this->addImage($product, $filePath . $value['file'], null, $move, $exclude, $page );

2. Go to Mage_Catalog_Model_Resource_Product_Attribute_Backend_Media
change
array('label','position','disabled')

to
array('label','position','disabled','page')

change
            array(
                'label_default' => 'label',
                'position_default' => 'position',
                'disabled_default' => 'disabled',
            )

to
            array(
                'label_default' => 'label',
                'position_default' => 'position',
                'disabled_default' => 'disabled',
                'page_default' => 'page'
            )

3. In js/mage/adminhtml/product.js
change
    this.getFileElement(file, 'cell-label input').value = image.label;
    this.getFileElement(file, 'cell-position input').value = image.position;
    this.getFileElement(file, 'cell-remove input').checked = (image.removed == 1);
    this.getFileElement(file, 'cell-disable input').checked = (image.disabled == 1);

to
    this.getFileElement(file, 'cell-label input').value = image.label;
    this.getFileElement(file, 'cell-position input').value = image.position;
    this.getFileElement(file, 'cell-remove input').checked = (image.removed == 1);
    this.getFileElement(file, 'cell-disable input').checked = (image.disabled == 1);
    this.getFileElement(file, 'cell-page input').checked = (image.page == 1);

change
    this.images[index].label = this
            .getFileElement(file, 'cell-label input').value;
    this.images[index].position = this.getFileElement(file,
            'cell-position input').value;
    this.images[index].removed = (this.getFileElement(file,
            'cell-remove input').checked ? 1 : 0);
    this.images[index].disabled = (this.getFileElement(file,
            'cell-disable input').checked ? 1 : 0);

to
    this.images[index].label = this
            .getFileElement(file, 'cell-label input').value;
    this.images[index].position = this.getFileElement(file,
            'cell-position input').value;
    this.images[index].removed = (this.getFileElement(file,
            'cell-remove input').checked ? 1 : 0);
    this.images[index].page = (this.getFileElement(file,
            'cell-page input').checked ? 1 : 0);
    this.images[index].disabled = (this.getFileElement(file,
            'cell-disable input').checked ? 1 : 0);

Simply use search text to find where to change the code. Hope this helped.

A: After much toil I discovered that in addition to the original post and the 2nd poster's recommendations, you also need to open up /app/code/core/Mage/Catalog/sql/catalog_setup/mysql4-upgrade-1.5.9.9-1.6.0.0.php, go to around line 2023 where it starts with this:
$installer->getTable('catalog/product_attribute_media_gallery_value') => array(

Change this:
'disabled' => array(
    'type'      => Varien_Db_Ddl_Table::TYPE_SMALLINT,
    'unsigned'  => true,
    'nullable'  => false,
    'default'   => '0',
    'comment'   => 'Is Disabled'
 )

To this:
'disabled' => array(
    'type'      => Varien_Db_Ddl_Table::TYPE_SMALLINT,
    'unsigned'  => true,
    'nullable'  => false,
    'default'   => '0',
    'comment'   => 'Is Disabled'
 ),
'page' => array(
    'type'      => Varien_Db_Ddl_Table::TYPE_SMALLINT,
    'unsigned'  => true,
    'nullable'  => false,
    'default'   => '0',
    'comment'   => 'Page'
 )

When Magento saves it checks this file to make sure the fields getting passed match the values in these arrays.

A: I got the error

Notice: Undefined index 'page'

in the class
Mage_Catalog_Model_Product_Attribute_Backend_Media
in the line 224.
I had to change
js/mage/adminhtml/product.js
newImage.position = this.getNextPosition();

to
newImage.position = this.getNextPosition();
newImage.page = 0;

It works great now.
Thanks.

A: I was working on something similar recently, and found that this piece of code was part of the solution:
$fieldset->addField('entire_range', 'checkbox', array(
      'checked'    => $this->getEntireRange()==1 ? 'true' : 'false',
      'onclick'    => 'this.value = this.checked ? 1 : 0;'

));
I couldn't get it to save the value to the database either.  It's something to with the Varien_Data_Form_Element_Checkbox class.
Hope this helps, please post your solution if you find it!
Cheers,
JD


text:
Q: How to get current band set from android device/adb when its in not attched to BTS(airplane mode) We have set our band to LTE B3 using service mode in Samsung galaxy S5 (*#0011#).
We are able to navigate to NAS and it protocols and then set band as LTE B3. But we couldn't validate whether it came to effect or not. It's showing as no service in airplane mode. How to get the band set on UE before its getting attached to network
We have checked in service mode and build.prop of UE as well.

A: Since you can see NAS messages, look at the UE Capability Info message and see if your particular S5 supports Band 3. Not all variants support this band.


text:
Q: Error occurs while passing parameter in function Angular 2 I am trying to call a function from html and it has one int parameter to pass but when I do this it shows error . I have no clue wher I am doing Wrong. following are the typescript and html code and also the error in the image
Component
@Component({
    selector: 'approval',
    templateUrl: '../app/layouts/approval.html'
})
export class ApprovalComponent {
    private _data: Observable<any[]>;

    constructor(public http: Http) {
        this.getAllUser();

    }

    approvalPendingRequest(id) {

        var result = this.http.get('https://localhost:44300/api/apis/GetSubscriptionById/'+ id)
            .subscribe(
            data => this._data = data.json(),
            err => this.logError(err),
            () => console.log('getsubscription api call')
            );

        alert(result);

    }
}

Html

Pending Approvals

<link href="../../Content/bootstrap.css" rel="stylesheet" />
<link href="../../Content/bootstrap-theme.min.css" rel="stylesheet" />

            <button type="button" class="btn-u  pull-center" data-toggle="modal" data-target="#myModal">Invite User</button>

                            Account Manager
                            Subscription
                            Created By
                            Pending

                            {{user.AccountManagerId}}
                            {{user.SubscriptionId}}
                            {{user.CreatedBy}}

                                <button type="button" class="btn btn-xs btn-danger" (click)="approvalPendingRequest({{user.SubscriptionId}})">

                                </button>

                <button type="button" class="close" data-dismiss="modal">×</button>

Add New User

                <form (submit)='inviteUser()'>

                        Name
                        <input type="text" class="form-control" required
                                name="name">

                        Email
                        <input type="email" class="form-control" required
                                name="alterEgo">

                        Partner
                        <select class="form-control"
                                 name="power">
                            <option *ngFor="let p of powers" [value]="p">{{p}}</option>
                        </select>

                    <button type="submit" class="btn btn-default" data-dismiss="myModal">Invite</button>
                </form>

image

A: Use this rather:
(click)="approvalPendingRequest(user.SubscriptionId)">

You don't need {{...}} here since you are still in an expression executed when the click event occurs.


text:
Q: How to modify the value of an input in spree commerce cart I have the following cart view that i addapted with bootstrap.

      <% if variant.images.length == 0 %>
        <%= link_to small_image(variant.product), variant.product %>
      <% else %>
        <%= link_to image_tag(variant.images.first.attachment.url(:product)), variant.product %>
      <% end %>

<%= link_to line_item.name, product_path(variant.product) %>

      <%= variant.options_text %>
      <% if line_item.insufficient_stock? %>

          <%= Spree.t(:out_of_stock) %>

      <% end %>

        <%= line_item_description_text(line_item.description) %>

      <%= line_item.single_money.to_html %>

      <%= item_form.number_field :quantity, min: 0, class: "form-control line_item_quantity", size: 5 %>

        <%= line_item.display_amount.to_html unless line_item.quantity.nil? %>

        <%= link_to content_tag(:span, '', class: 'glyphicon glyphicon-minus-sign'), '#', class: 'delete', id: "delete_#{dom_id(line_item)}" %>

and the following coffeescript that goes along with it
    Spree.ready ($) ->
  if ($ 'form#update-cart').is('*')
    ($ 'form#update-cart a.delete').show().one 'click', ->
      ($ this).parents('.line-item').first().find('input.line_item_quantity').val 0
      ($ this).parents('form').first().submit()
      false

  ($ 'form#update-cart').submit ->
     ($ 'form#update-cart #update-button').attr('disabled', true)

Now the delete button does not work with this cart html ( while it is working with the original view a following)

      <% if variant.images.length == 0 %>
        <%= link_to small_image(variant.product), variant.product %>
      <% else %>
        <%= link_to image_tag(variant.images.first.attachment.url(:small)), variant.product %>
      <% end %>

<%= link_to line_item.name, product_path(variant.product) %>

      <%= variant.options_text %>
      <% if line_item.insufficient_stock? %>

          <%= Spree.t(:out_of_stock) %>

      <% end %>

        <%= line_item_description_text(line_item.description) %>

      <%= line_item.single_money.to_html %>

      <%= item_form.number_field :quantity, min: 0, class: "form-control line_item_quantity", size: 5 %>

      <%= line_item.display_amount.to_html unless line_item.quantity.nil? %>

      <%= link_to content_tag(:span, '', class: 'glyphicon glyphicon-minus-sign'), '#', class: 'delete', id: "delete_#{dom_id(line_item)}" %>

It seems to me that the coffeescript should work in both cases!
What am i missing after i modify the view ? It seems to me that the coffeescript should perform the search in both cases...

A: It doesn't look like you've done anything wrong when it comes to keeping the markup for the javascript the same.  My guess would be that Spree.ready ($) -> isn't actually firing.  That could be caused by you removing javascript files during your view customization by accident.   You should try checking your web developer console to see if there are any javascript errors like Spree not being defined or something like that.


text:
Q: Slowed app in C# form I start app and set is as child in form app. But app is slow and when I open new tab when loading another page app falldown.
Process p = Process.Start("C:/Users/---/Desktop/Tor Browser/Browser/firefox.exe");
p.WaitForInputIdle();
System.Threading.Thread.Sleep(7000);
appWin = p.MainWindowHandle;
SetParent(appWin, this.Handle);

I use thread because I need to wait to connect browser and open it, than set it.
Is there any option how to make it faster give to process more resources?

A: Not sure what's the intention behind sleeping the UI thread by 7 seconds as can be seen in your code. You shouldn't do that and moreover, consider running that external exe in a separate thread than UI thread.
System.Threading.Thread.Sleep(7000);


text:
Q: Is it possible to make a python message dialog using Model-View-Controller architecture? I'm trying to do a class that holds all my message dialogs such I don't need to have them mixed with my logic. The aim is to keep the GUI code away of the Non-GUI stuff, I'd like achieve a nice Model-View-Controller architecture
class errorMessageDialog(wx.MessageDialog):

    def __init__(self, message, caption= 'Error'):
        wx.MessageDialog.__init__(self, None, message, caption, wx.OK | wx.ICON_ERROR)
        self.ShowModal()
        self.Destroy()

I've manage to do it for simple error messages (see exemple above), however I'd like to do a message dialog where the user can select either OK or Cancel. In that case the method should return a boolean. I tried the following:
class safetyCheck(wx.MessageDialog):
    def __init__(self, message="Make sure the following commands are correct", caption= 'Safety Warning'):
    wx.MessageDialog.__init__(self, None, message, caption, wx.OK | wx.CANCEL | wx.CENTRE | wx.ICON_EXCLAMATION)

        if self.ShowModal() == wx.ID_OK:
            safetyCheckPassed = True
        else:
            safetyCheckPassed = False
        return safetyCheckPassed
        self.Destroy()

I might be mistaken but I think what I'm trying to achieve is not possible cause the self.Destroy method must be called before the return, therefore the return line is never run.
Obviously I could create my dialog inside my model code but this would be messy.
EDIT:
I considered the suggestions below but I didn't manage to make any of those work I ended up with this solution.
class SafetyCheckAFT(wx.MessageDialog):

    def __init__(self):
        pass

    def dialog(self):
        message="Make sure the following commands are correct"
        caption= 'Safety Warning'
        dlg= wx.MessageDialog(None, message, caption, wx.OK | wx.CANCEL | wx.CENTRE | wx.ICON_EXCLAMATION)

        if dlg.ShowModal() == wx.ID_OK:
            self.safetyCheckPassed = True
        else:
            self.safetyCheckPassed = False
        dlg.Destroy()

    def isSaftyCheckPassed(self):
         return self.safetyCheckPassed

sc=SafetyCheckAFT()
sc.dialog()
if sc.isSaftyCheckPassed():
    print("cool beans")

A: Take a look at: How do I correctly clean up a Python object?
Using the python with statement in conjunction with an __exit__ statement you should be able to have your resource cleaned up.
You may also want to try use try: and finally: putting the return statement at the end of the try and the cleanup in finally:
I haven't tested this though, I haven't used python in a while.

A: Let me suggest another solution. You could also have a helper class that makes the dialog for you:
Model -> Helper -> safetyCheck
The helper class has a static method which creates the dialog, saves the result, destroys the dialog, and then returns the result.
class safetyCheck(wx.MessageDialog):
    def __init__(self, message="Make sure the following commands are correct", caption= 'Safety Warning'):
        wx.MessageDialog.__init__(self, None, message, caption, wx.OK | wx.CANCEL | wx.CENTRE | wx.ICON_EXCLAMATION)

    def ShowModal(self):
        return wx.MessageDialog.ShowModal() == wx.ID_OK

class Helper:
    @staticmethod
    def safety_check_popup(*args, **kwargs):
        dialog = safetyCheck(*args, **kwargs)
        result = dialog.ShowModal()
        dialog.Destroy()
        return result


text:
Q: Align two panels side by side to cover the whole screen (ExtJS 6.2.0) I have this Panel
Ext.define('Mine.view.newDashboardPanel', {
    extend: 'Ext.Container',

    xtype: 'basic-panels',

    controller: 'newDashboard',

    layout: 'fit',...

and have created this Container :
Ext.define('Mine.view.newDashboard', {
    extend: 'Ext.Container',
    alias: 'widget.newDashboard',

    controller: 'newDashboard',
    reference: 'dashboard',

    layout: {
        type: 'border',
        align: 'stretch '
    },
    height: 620,

    style: {
        'backgroundColor': '#909090 !important'
    },

    items: [{

            region: 'west',
            xtype: 'panel',
            //margin: '5 0 0 5',

            width: 200,
            collapsible: true, // make collapsible
            id: 'west-region-container',
            layout: 'fit',
            items: [{
                xtype: 'settingsMenu2'

            }]
        },
        {
            xtype: 'basic-panels',
           layout: 'fit'
        }
    ]

});

The latter code is to create the main view which is a sidebar and the Mine.view.newDashboardPanel panel My problem is that the panel (xtype basic-panels) doesn't cover its whole allocated space and therefore Mine.view.newDashboard doesn't cover the screen.
How to achieve this ?
Thanks !

A: To accomplish that specify region:'center'
{
    xtype: 'basic-panels',
    region: 'center'
}

Ext.define('Mine.view.newDashboard', {
    extend: 'Ext.Container',
    alias: 'widget.newDashboard',

    controller: 'newDashboard',
    reference: 'dashboard',

    layout: 'border',
    height: 620,

    style: {
        'backgroundColor': '#909090 !important'
    },

    items: [{

        region: 'west',
        xtype: 'panel',
        //margin: '5 0 0 5',

        width: 200,
        collapsible: true, // make collapsible
        id: 'west-region-container',
        items: [{
            xtype: 'settingsMenu2'

        }]
    }, {
        xtype: 'basic-panels',
        region: 'center'
    }]

});


text:
Q: ASP.NET MVC - passing modified viewmodel from AJAX to view I'm creating a ASP.NET MVC 5 SQL Server (Entity Framework, database-first) application where there is an order record and a set of line item records attached to it. The user should be able to add new line item records to the viewmodel through an "Add" button, but the line items should not be committed to the database until the user clicks the "Save" button. Clicking the "Add" button should not refresh the page -- the page should stay exactly where it is, just with the extra rows added.
Right now, I have new rows being added in this way:
View:
@model Models.OrderViewModel

        Header 1

        Header 2

        Header 3

    @if (Model.LineItemRows.Count > 0)
    {
    for (int i = 0; i < Model.LineItemRows.Count; i++)
    {
        @Html.Partial("ViewRow", Model.LineItemRows[i])
    }
    }

<input type="button" id="mybutton" value="Add New Line Item" class="btn btn-default" />

Controller:
[HttpPost]
public ActionResult AddNewLineItem(OrderViewModel viewModel)
{
    OrderLineItemRowViewModel lineItemRow = new OrderLineItemRowViewModel();
    // Set some defaults
    lineItemRow.active = true;
    lineItemRow.location = "I";

    if (viewModel.LineItemRows != null) // This shouldn't ever be null
    {
    viewModel.LineItemRows.Add(lineItemRow);
    }

    return PartialView("ViewRow", lineItemRow);
}

When the user clicks on the "Add" button, a jQuery function serializes the current viewmodel and sends it back to the controller. The controller makes a new row with some default options, adds it to the viewmodel rowset that's passed in, then returns a partial view that represents the new row (and sends the data for the new row into the partial view so we know how to populate it).
The thing that's missing from this is...how do I send back the modified viewmodel to the original view? Basically, I've got what should be the current viewmodel in AddNewLineItem() but I have no idea where it needs to be sent.
I'm fairly new to ASP.NET MVC, so my apologies if I'm missing something obvious here.

A: You'd need to create a new partial view that would take your OrderViewModel and generate all of the rows in your table.  Move the ajax call to this new partial view. AddNewLineItem would return the new partial view and redraw the entire table and not just one row.  This would allow 'viewModel': @Html.Raw(Json.Encode(Model)), to always be current, since it's in the new partial view that gets regenerated each time a row is added

A: All you're doing is sending back JSON for your AJAX method right?
Here's what I do when sending data back.
If you're serializing the whole form to a controller, then this should work.
Have your new controller take all of that serialized data and modify model to be what you want- then return the results back as JSON.
//Controller Code
var model // <-- this is your modified viewModel with the new row in it
var jsonModel = Json(new
            {
                data = model
            }, JsonRequestBehavior.AllowGet);
return jsonModel;

Then it's simply a matter of making your JavaScript/JQuery function consume the json that gets returned.


text:
Q: How can I mock an instance of a class? I have the below code, and I am trying to mock out exg.metadata
class data:
    def __init__(self):
        pass

    def trade_status(self, exg, fields, values, msgtype, sequence):
        ...
        if security_id in exg.metadata:
            market_seg = exg.metadata[security_id]['market_segment']
            exg.write_meta(security_id, exg.metadata.pop(security_id))
            self._send_tick_size_rules(exg, security_id, market_seg)

It may help to state that when I print(type(exg)) I get a class (<class 'exchanges.impl.bate.parser.Exchange'>). I'm not exactly sure what exg is, any idea how I can find out? When I print it, all it says is BATES, which looks like a string but it's clearly not.
Also, it may help to see what the exchange looks like:
class BATSExchange(exchanges.L3Exchange):
    protocol = None
    data_file_type = quote.BatseurBook
    package_buffer = None
    buffer_capacity = 1000000
    multiple_files = True

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # store meta and tick size content
        self.metadata = {}

Do I mock the exchange?


text:
Q: Show that Turing recognizable languages are closed under intersection. The question ans its answer is given in the following picture:

But it is not clear for me what if one of the machine loops and the other rejects, will the TM describing the intersection reject also? I feel that the answer is not clear in that case.
Also what if the 2 machines loop, will the given machine loop?

A: "If either of these two halts and rejects, $M'$ rejects." This answers your first question. If one of the machines loops and the other rejects, then you only simulate the looping one until the other one provides you with the rejection; after that the decision is clear (rejection) and there is no point in continuing the simulation, no matter what the other machine does (loop, accept, reject).
And yes, if both do not stop, then the new machine will not stop either but continue to simulate one step of the first, one of the second, one of the first etc. This is what alternating means. It is the most simple case of a technique called dovetailing, which is used to simulate several processes in the case where some possibly do not stop, and thus sequential simulation could possibly get stuck on the first process without ver touching the other ones.
By the way: the term "to loop" is a bit misleading here. It suggests that the machine keeps doing the same over and over. However, it can compute forever without repeating configurations and even without repetiton on a more abstract level.


text:
Q: Node.js: fs.readdir does not return a file written by fs.writeFile My app
A simple Node.js http server which creates files in a given directory by calling POST /deploy. After the file is written, I want to list all the files in that directory using console.log.
For creating files (POST /deploy), I call:
fs.writeFile(filename, content, 'utf8', callback(null, {'newFile': filename}));

The callback writes the HTTP response and lists the files using:
fs.readdir(some_directory, (err, files) => {
    files.forEach(file => {
        console.log(file);
        // Do something with the file
    }
}

My problem
The new file is not listed in the callback. Only after I call deploy again, the previous file is listed. For example, if I create files a and b using /deploy consecutively, a is listed only when b is created and b is not listed until I make another call.
I assume the file is not closed when the callback is called, so that only later calls to fs.readdir see the file, after it has been closed.
How can I call the callback function only after the file is properly closed and can be listed using fs.readdir?
What have I tried

*

*Reading the fs.close() manual. It works, but requires an fd, not a filename, so I have to open the files just for closing it, which seems cumbersome:
fs.open(filename, 'w', function(error, fd) {
    fs.write(fd, content, function(err, written, buffer) {
        fs.close(fd, callback(null, {'newFile': filename}));
    });
});

*Searching for similar problems in SO

A: I think this is your problem:
fs.writeFile(filename, content, 'utf8', callback(null, {'newFile': filename}));

In the code above you run the callback immediately, without waiting for the operation to finish. It would work only if your call to callback(null, {'newFile': filename}) actually returned a function to call as a callback, which I doubt it does.
This may help:
fs.writeFile(filename, content, 'utf8', () => callback(null, {'newFile': filename}));

because here the callback() will be called after the write operation finishes. But this is still not enough because you need to handle errors:
fs.writeFile(filename, content, 'utf8', (err) => {
  if (err) {
    // handle possible errors
  } else {
    callback(null, {'newFile': filename});
  }
});

e.g. if your callback can take error as the first argument you could do:
fs.writeFile(filename, content, 'utf8', (err) => {
  if (err) {
    callback(err);
  } else {
    callback(null, {'newFile': filename});
  }
});

or returning early you can avoid else:
fs.writeFile(filename, content, 'utf8', (err) => {
  if (err) {
    return callback(err);
  }
  callback(null, {'newFile': filename});
});


text:
Q: My login function not working I am developing a C# application which need a login form , user and password are saved in a SQL Server database .
I use my CodePass Function to code password , I have added a user and it's coded password to my database before (user , password and login role are saved in database)
Now when i Call my doLogin function like this
doLogin("Arashdn","123");

It returns 0 ( a wrong user or password)
After debugging application I find that hash(a variable to keep encrypted password read from database) is holding 123 not encrypted password.
What Can the problem be?
Here is my Code:
public class DB
{
    public static string constr = "Server=localhost;Database=University;
    Integrated Security=true;MultipleActiveResultSets=True;";
    public static string userTable = "Users", userPassword = "Passwd",
    userName = "UserID", loginRole = "Role";
}

public class login
{
    public int doLogin(string user, string pass)
    {
        string role="0";
        SqlConnection conn = new SqlConnection(DB.constr);
        try
        {
            conn.Open();
            SqlCommand my_cm = conn.CreateCommand();
            SqlDataReader dbread1;
            my_cm.CommandText = "Select " + DB.userPassword + " from " +
                DB.userTable + " WHERE " + DB.userName + "=" + user;
            dbread1 = my_cm.ExecuteReader();
            string hash="";

            while (dbread1.Read())
            {
               hash = dbread1[0].ToString();
            }

            if (CodePass(user, pass) == hash)
            {
                SqlCommand my_cm2 = conn.CreateCommand();
                SqlDataReader dbread2;
                my_cm2.CommandText = "Select " + DB.loginRole + " from " +
                DB.userTable + " WHERE " + DB.userName + "=" + user;
                dbread2 = my_cm2.ExecuteReader();

                while (dbread2.Read())
                {
                   role = dbread2[0].ToString();
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            if (conn.State == System.Data.ConnectionState.Open)
                    conn.Close();
        }

        return int.Parse(role);
    }

    public string CodePass(string user, string pass)
    {
        System.Security.Cryptography.SHA1CryptoServiceProvider sha =
              new SHA1CryptoServiceProvider();
        return System.Text.Encoding.ASCII.GetString(
          sha.ComputeHash(System.Text.Encoding.ASCII.GetBytes(user + pass)));
    }
}

Thanks

A: The likelyhood is that you have at least 2 records in the database that match the username, one with the password of "123".
From SqlManager see what the result of the following is, remember to substitute for the username:
select userID,passwd from Users where userId= '<put the username here>';

Your existing code could be rewritten to make use of SqlParameters to avoid some Sql injection attacks and also dispose of your objects properly.  Additionally most of the logic could be moved to a single database query as below.
This modification will return 0 if the user and password is incorrect.  You could throw an exception or return another value instead.
public class DB
{
    public static string constr = "Server=localhost;Database=University; Integrated Security=true;MultipleActiveResultSets=True;";
    public static string userTable = "Users", userPassword = "Passwd",
    userName = "UserID", loginRole = "Role";
}

public class login
{
   public int doLogin(string user, string pass)
   {
      string role="0";
      using (var conn = new SqlConnection(DB.constr) {
        using (var my_cm = conn.CreateCommand() {
         my_cm.CommandText = string.Format(
             "select {0} from {1} where {2} = @username and {3} = @password",
             DB.loginRole,
             DB.userTable,
             DB.userName,
             DB.userPassword);
         my_cm.Parameters.AddWithValue("@username", user);
         mt_cm.Parameters.AddWithValue("@password", CodePass(user,pass));
         using (var dbread = my_cm.ExecuteReader()) {
           if (!dbread.Read()) {
             return 0; // or something else if user not found
           }
           return int.Parse(dbRead[0].ToString());
         }
      }
    }
  }

  public string CodePass(string user, string pass)
  {
    System.Security.Cryptography.SHA1CryptoServiceProvider sha =
          new SHA1CryptoServiceProvider();
    return System.Text.Encoding.ASCII.GetString(
      sha.ComputeHash(System.Text.Encoding.ASCII.GetBytes(user + pass)));
  }
}

A: Based on :
After debuging application I find that hash(a variable to keep encrypted password red from database) is holding 123 not encrypted password.
i would recommend to go look in your DB and change your PW in your PW field from 123 to  #<=??D?mB?MyE??C? because your DB only hold's the data it get's nothing more and it looks like you saved 123 instead of #<=??D?mB?MyE??C?
and your commend:
CodePass returns encrypted password , and password is saved encryptedly in DB but hash is keeping unecrypted password
doesn't make sense because your DB will not be able to decrypt with this query
EDIT
if
the passwd feild in database is #<=??D?mB?MyE??C? not 123 but dbread1 is reading 123 and this is the problem
is true please check the following things:

*

*is it the right DataBase?

*is it the right Table?

*last but not least do you reading in the right column?

A: I find the problem
I have both sql server express and developer edition on my computer and I have another database in SQLServer Developer in which passwd was 123 and my main DB was is SQLServer Express ...
Silly me


text:
Q: How to repair .zip files? To begin with, I don't know a single thing about coding, computers, etc. It'd be nice of computer masters if my question could be answered in detail (ex: type this in, screenshot, if possible).
First of all, I received several .zip files on my MacBook Air. I don't even know what kind, but the whole thing is around 31.5 cm wide and 23 cm long.
I think the .zip files contain .img files, probably more than 4000. The reason behind this huge file is because we're making an album of a bunch of pictures. However, I'm not sure if these images are screenshots or .gifs.
For some reason, the files that I receive look like images to me, but the extension sometimes says .gif instead of .img.
Now, when I try to open the .zip files, a notice that reads:

Cannot read archive data.

to which I usually press 'Ignore All' or 'Stop'.
Since 'Stop' is highlighted in blue, it looks promising. I press on it, and it says:

Cannot read archive data.

The same thing happens when I press on 'Ignore All'.
I tried to look for a solution already, to which this one website told me to use something called Terminal. (The .zip file's name is memories.)
I assumed that the .zip files were corrupted, so (as the website told me) I entered:
zip
(enter)
-F memories.zip --out please.zip

This didn't work. This showed up:
Fix archive (-F) - assume mostly intact archive
    zip warning: No .zip file found
        (If all you have are splits (.z01, .z02, ...) and no .zip, try -FF)
zip I/O error: No such file or directory
zip error: File not found or no read permission (memories.zip)

I tried the following:
-FF memories.zip --out please.zip

Still didn't work. This showed up:
Fix archive (-FF) - salvage what can
    zip warning: could not open input archive: memories.zip
Scanning for entries...

Could not find:
  memories.z01

Hit c      (change path to where this split file is)
    s      (skip this split)
    q      (abort archive - quit)
    e      (end this archive - no more splits)
    z      (look for .zip split - the last split)
 or ENTER  (try reading this split again):

I stopped here, as I didn't have a clue what to do next. Can someone please help me...?

A: I guess that the person who zipped the files up decided to split them into
parts in order to have reasonable-sized files, and you have not downloaded
the .zip file or not all the other parts/splits.
The Winzip article
Splitting Zip files
says:

Each of the segments of the split Zip file will have a different extension. WinZip creates files with names like Data.z01 or Data.zx01, Data.z02 or Data.zx02, and so on, except for the very last segment of the new Zip file. The last segment will always have either the .zip or .zipx extension, respectively, based on the compression method used when creating the Zip file (e.g., Data.zip, Documents.zipx).
To open the split Zip file, open the file with the .zip or .zipx extension. Don't try to open any of the files with the numbered extensions; WinZip won't recognize them as Zip files.
Once the split Zip file has been opened, you can work with it much as you would work with a regular Zip file, except you can't add any new files or remove existing files. Some operations such as creating self-extracting Zip files and editing comments are also disabled for split Zip files.

From the errors you are getting, it seems that you have downloaded some splits,
but not the main .zip file.
You should get that file, and check also that you have all the splits.


text:
Q: Password recovery and password derived key encryption Hi (sorry about the wordy post)
I'm working on a web app that will store some of the users personal data.
I have looked into various ways of encrypting the data to protect it from intruders if the database or web server was compromised and think that creating and storing a unique "master key" encrypted with a password derived key for each user is the best way to go for my set-up.
The only issue I can see is with forgotten passwords. Currently, the users can reset a forgotten password by receiving an email containing a link with a unique token that takes then to the password reset form.
My idea is to add security questions to the registration page that will be used to create a 2nd derived key and use it to encrypt the users master key. The answers will not be stored in the database, just the key derived from them. The questions would be more opinion based than personal or factual.
This will mean there are two encrypted versions of the "master key".
These questions would be added to the existing password reset form and the answers used to recreate the derived key and decrypt the master key. This would mean that the original master key can then be encrypted using the new password.
I have read many posts on how security questions should not be used to reset passwords but in this case it seems like an additional layer of security.
Does anyone see any potential problems with this approach or have any other suggestions?
Thanks

A: It is not clear who you are trying to protect the data from (your organisation or potential intruders), but I would presume that intruders is your main concern, since your organisation has access to the code of the application and therefore can view the passwords that the user is inputting (unless encryption/decryption takes place on the client side).
I would not encrypt the data using the passwords of the users. Instead, I would generate random key(s) for each user, store them on a separate server, and retrieve them once the user authenticates successfully. That separate server would have to be inaccessible from the outside world.
Note that user authentication should also take place on the second server as well. Do not return the keys without prior user authentication, in case the first server gets compromised. You can additionally encrypt these keys using the user passwords and on a different column, using a master key that you are holding in case someone forgets their passwords.
This way you will get stronger passwords as well, than what the average user is going to use.


text:
Q: Как сделать вот такую классную фишку как на Facebook Здравствуйте! Зашел на Facebook в консоль и увидел такое:

Как мне сделать такое же?

A: Всё просто: сообщения в консоль можно форматировать и применять к ним CSS

console.log('%c Остановитесь! ', 'background: blue; color: red; text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black; font-size: 50px;');

Замечание: следует открыть консоль браузера, ибо песочница не покажет как надо
%c — оформляет вывод с соответствии с CSS, переданным дополнительным параметром.

Дополнение:
помимо вывода на основе CSS можно по другому форматировать вывод в консоль. О других параметрах можно посмотреть в соседнем ответе от @Elena

Нашел на enSO весёлую штуку, которую можно сотворить:

var css = "text-shadow: -1px -1px hsl(0,100%,50%), 1px 1px hsl(5.4, 100%, 50%), 3px 2px hsl(10.8, 100%, 50%), 5px 3px hsl(16.2, 100%, 50%), 7px 4px hsl(21.6, 100%, 50%), 9px 5px hsl(27, 100%, 50%), 11px 6px hsl(32.4, 100%, 50%), 13px 7px hsl(37.8, 100%, 50%), 14px 8px hsl(43.2, 100%, 50%), 16px 9px hsl(48.6, 100%, 50%), 18px 10px hsl(54, 100%, 50%), 20px 11px hsl(59.4, 100%, 50%), 22px 12px hsl(64.8, 100%, 50%), 23px 13px hsl(70.2, 100%, 50%), 25px 14px hsl(75.6, 100%, 50%), 27px 15px hsl(81, 100%, 50%), 28px 16px hsl(86.4, 100%, 50%), 30px 17px hsl(91.8, 100%, 50%), 32px 18px hsl(97.2, 100%, 50%), 33px 19px hsl(102.6, 100%, 50%), 35px 20px hsl(108, 100%, 50%), 36px 21px hsl(113.4, 100%, 50%), 38px 22px hsl(118.8, 100%, 50%), 39px 23px hsl(124.2, 100%, 50%), 41px 24px hsl(129.6, 100%, 50%), 42px 25px hsl(135, 100%, 50%), 43px 26px hsl(140.4, 100%, 50%), 45px 27px hsl(145.8, 100%, 50%), 46px 28px hsl(151.2, 100%, 50%), 47px 29px hsl(156.6, 100%, 50%), 48px 30px hsl(162, 100%, 50%), 49px 31px hsl(167.4, 100%, 50%), 50px 32px hsl(172.8, 100%, 50%), 51px 33px hsl(178.2, 100%, 50%), 52px 34px hsl(183.6, 100%, 50%), 53px 35px hsl(189, 100%, 50%), 54px 36px hsl(194.4, 100%, 50%), 55px 37px hsl(199.8, 100%, 50%), 55px 38px hsl(205.2, 100%, 50%), 56px 39px hsl(210.6, 100%, 50%), 57px 40px hsl(216, 100%, 50%), 57px 41px hsl(221.4, 100%, 50%), 58px 42px hsl(226.8, 100%, 50%), 58px 43px hsl(232.2, 100%, 50%), 58px 44px hsl(237.6, 100%, 50%), 59px 45px hsl(243, 100%, 50%), 59px 46px hsl(248.4, 100%, 50%), 59px 47px hsl(253.8, 100%, 50%), 59px 48px hsl(259.2, 100%, 50%), 59px 49px hsl(264.6, 100%, 50%), 60px 50px hsl(270, 100%, 50%), 59px 51px hsl(275.4, 100%, 50%), 59px 52px hsl(280.8, 100%, 50%), 59px 53px hsl(286.2, 100%, 50%), 59px 54px hsl(291.6, 100%, 50%), 59px 55px hsl(297, 100%, 50%), 58px 56px hsl(302.4, 100%, 50%), 58px 57px hsl(307.8, 100%, 50%), 58px 58px hsl(313.2, 100%, 50%), 57px 59px hsl(318.6, 100%, 50%), 57px 60px hsl(324, 100%, 50%), 56px 61px hsl(329.4, 100%, 50%), 55px 62px hsl(334.8, 100%, 50%), 55px 63px hsl(340.2, 100%, 50%), 54px 64px hsl(345.6, 100%, 50%), 53px 65px hsl(351, 100%, 50%), 52px 66px hsl(356.4, 100%, 50%), 51px 67px hsl(361.8, 100%, 50%), 50px 68px hsl(367.2, 100%, 50%), 49px 69px hsl(372.6, 100%, 50%), 48px 70px hsl(378, 100%, 50%), 47px 71px hsl(383.4, 100%, 50%), 46px 72px hsl(388.8, 100%, 50%), 45px 73px hsl(394.2, 100%, 50%), 43px 74px hsl(399.6, 100%, 50%), 42px 75px hsl(405, 100%, 50%), 41px 76px hsl(410.4, 100%, 50%), 39px 77px hsl(415.8, 100%, 50%), 38px 78px hsl(421.2, 100%, 50%), 36px 79px hsl(426.6, 100%, 50%), 35px 80px hsl(432, 100%, 50%), 33px 81px hsl(437.4, 100%, 50%), 32px 82px hsl(442.8, 100%, 50%), 30px 83px hsl(448.2, 100%, 50%), 28px 84px hsl(453.6, 100%, 50%), 27px 85px hsl(459, 100%, 50%), 25px 86px hsl(464.4, 100%, 50%), 23px 87px hsl(469.8, 100%, 50%), 22px 88px hsl(475.2, 100%, 50%), 20px 89px hsl(480.6, 100%, 50%), 18px 90px hsl(486, 100%, 50%), 16px 91px hsl(491.4, 100%, 50%), 14px 92px hsl(496.8, 100%, 50%), 13px 93px hsl(502.2, 100%, 50%), 11px 94px hsl(507.6, 100%, 50%), 9px 95px hsl(513, 100%, 50%), 7px 96px hsl(518.4, 100%, 50%), 5px 97px hsl(523.8, 100%, 50%), 3px 98px hsl(529.2, 100%, 50%), 1px 99px hsl(534.6, 100%, 50%), 7px 100px hsl(540, 100%, 50%), -1px 101px hsl(545.4, 100%, 50%), -3px 102px hsl(550.8, 100%, 50%), -5px 103px hsl(556.2, 100%, 50%), -7px 104px hsl(561.6, 100%, 50%), -9px 105px hsl(567, 100%, 50%), -11px 106px hsl(572.4, 100%, 50%), -13px 107px hsl(577.8, 100%, 50%), -14px 108px hsl(583.2, 100%, 50%), -16px 109px hsl(588.6, 100%, 50%), -18px 110px hsl(594, 100%, 50%), -20px 111px hsl(599.4, 100%, 50%), -22px 112px hsl(604.8, 100%, 50%), -23px 113px hsl(610.2, 100%, 50%), -25px 114px hsl(615.6, 100%, 50%), -27px 115px hsl(621, 100%, 50%), -28px 116px hsl(626.4, 100%, 50%), -30px 117px hsl(631.8, 100%, 50%), -32px 118px hsl(637.2, 100%, 50%), -33px 119px hsl(642.6, 100%, 50%), -35px 120px hsl(648, 100%, 50%), -36px 121px hsl(653.4, 100%, 50%), -38px 122px hsl(658.8, 100%, 50%), -39px 123px hsl(664.2, 100%, 50%), -41px 124px hsl(669.6, 100%, 50%), -42px 125px hsl(675, 100%, 50%), -43px 126px hsl(680.4, 100%, 50%), -45px 127px hsl(685.8, 100%, 50%), -46px 128px hsl(691.2, 100%, 50%), -47px 129px hsl(696.6, 100%, 50%), -48px 130px hsl(702, 100%, 50%), -49px 131px hsl(707.4, 100%, 50%), -50px 132px hsl(712.8, 100%, 50%), -51px 133px hsl(718.2, 100%, 50%), -52px 134px hsl(723.6, 100%, 50%), -53px 135px hsl(729, 100%, 50%), -54px 136px hsl(734.4, 100%, 50%), -55px 137px hsl(739.8, 100%, 50%), -55px 138px hsl(745.2, 100%, 50%), -56px 139px hsl(750.6, 100%, 50%), -57px 140px hsl(756, 100%, 50%), -57px 141px hsl(761.4, 100%, 50%), -58px 142px hsl(766.8, 100%, 50%), -58px 143px hsl(772.2, 100%, 50%), -58px 144px hsl(777.6, 100%, 50%), -59px 145px hsl(783, 100%, 50%), -59px 146px hsl(788.4, 100%, 50%), -59px 147px hsl(793.8, 100%, 50%), -59px 148px hsl(799.2, 100%, 50%), -59px 149px hsl(804.6, 100%, 50%), -60px 150px hsl(810, 100%, 50%), -59px 151px hsl(815.4, 100%, 50%), -59px 152px hsl(820.8, 100%, 50%), -59px 153px hsl(826.2, 100%, 50%), -59px 154px hsl(831.6, 100%, 50%), -59px 155px hsl(837, 100%, 50%), -58px 156px hsl(842.4, 100%, 50%), -58px 157px hsl(847.8, 100%, 50%), -58px 158px hsl(853.2, 100%, 50%), -57px 159px hsl(858.6, 100%, 50%), -57px 160px hsl(864, 100%, 50%), -56px 161px hsl(869.4, 100%, 50%), -55px 162px hsl(874.8, 100%, 50%), -55px 163px hsl(880.2, 100%, 50%), -54px 164px hsl(885.6, 100%, 50%), -53px 165px hsl(891, 100%, 50%), -52px 166px hsl(896.4, 100%, 50%), -51px 167px hsl(901.8, 100%, 50%), -50px 168px hsl(907.2, 100%, 50%), -49px 169px hsl(912.6, 100%, 50%), -48px 170px hsl(918, 100%, 50%), -47px 171px hsl(923.4, 100%, 50%), -46px 172px hsl(928.8, 100%, 50%), -45px 173px hsl(934.2, 100%, 50%), -43px 174px hsl(939.6, 100%, 50%), -42px 175px hsl(945, 100%, 50%), -41px 176px hsl(950.4, 100%, 50%), -39px 177px hsl(955.8, 100%, 50%), -38px 178px hsl(961.2, 100%, 50%), -36px 179px hsl(966.6, 100%, 50%), -35px 180px hsl(972, 100%, 50%), -33px 181px hsl(977.4, 100%, 50%), -32px 182px hsl(982.8, 100%, 50%), -30px 183px hsl(988.2, 100%, 50%), -28px 184px hsl(993.6, 100%, 50%), -27px 185px hsl(999, 100%, 50%), -25px 186px hsl(1004.4, 100%, 50%), -23px 187px hsl(1009.8, 100%, 50%), -22px 188px hsl(1015.2, 100%, 50%), -20px 189px hsl(1020.6, 100%, 50%), -18px 190px hsl(1026, 100%, 50%), -16px 191px hsl(1031.4, 100%, 50%), -14px 192px hsl(1036.8, 100%, 50%), -13px 193px hsl(1042.2, 100%, 50%), -11px 194px hsl(1047.6, 100%, 50%), -9px 195px hsl(1053, 100%, 50%), -7px 196px hsl(1058.4, 100%, 50%), -5px 197px hsl(1063.8, 100%, 50%), -3px 198px hsl(1069.2, 100%, 50%), -1px 199px hsl(1074.6, 100%, 50%), -1px 200px hsl(1080, 100%, 50%), 1px 201px hsl(1085.4, 100%, 50%), 3px 202px hsl(1090.8, 100%, 50%), 5px 203px hsl(1096.2, 100%, 50%), 7px 204px hsl(1101.6, 100%, 50%), 9px 205px hsl(1107, 100%, 50%), 11px 206px hsl(1112.4, 100%, 50%), 13px 207px hsl(1117.8, 100%, 50%), 14px 208px hsl(1123.2, 100%, 50%), 16px 209px hsl(1128.6, 100%, 50%), 18px 210px hsl(1134, 100%, 50%), 20px 211px hsl(1139.4, 100%, 50%), 22px 212px hsl(1144.8, 100%, 50%), 23px 213px hsl(1150.2, 100%, 50%), 25px 214px hsl(1155.6, 100%, 50%), 27px 215px hsl(1161, 100%, 50%), 28px 216px hsl(1166.4, 100%, 50%), 30px 217px hsl(1171.8, 100%, 50%), 32px 218px hsl(1177.2, 100%, 50%), 33px 219px hsl(1182.6, 100%, 50%), 35px 220px hsl(1188, 100%, 50%), 36px 221px hsl(1193.4, 100%, 50%), 38px 222px hsl(1198.8, 100%, 50%), 39px 223px hsl(1204.2, 100%, 50%), 41px 224px hsl(1209.6, 100%, 50%), 42px 225px hsl(1215, 100%, 50%), 43px 226px hsl(1220.4, 100%, 50%), 45px 227px hsl(1225.8, 100%, 50%), 46px 228px hsl(1231.2, 100%, 50%), 47px 229px hsl(1236.6, 100%, 50%), 48px 230px hsl(1242, 100%, 50%), 49px 231px hsl(1247.4, 100%, 50%), 50px 232px hsl(1252.8, 100%, 50%), 51px 233px hsl(1258.2, 100%, 50%), 52px 234px hsl(1263.6, 100%, 50%), 53px 235px hsl(1269, 100%, 50%), 54px 236px hsl(1274.4, 100%, 50%), 55px 237px hsl(1279.8, 100%, 50%), 55px 238px hsl(1285.2, 100%, 50%), 56px 239px hsl(1290.6, 100%, 50%), 57px 240px hsl(1296, 100%, 50%), 57px 241px hsl(1301.4, 100%, 50%), 58px 242px hsl(1306.8, 100%, 50%), 58px 243px hsl(1312.2, 100%, 50%), 58px 244px hsl(1317.6, 100%, 50%), 59px 245px hsl(1323, 100%, 50%), 59px 246px hsl(1328.4, 100%, 50%), 59px 247px hsl(1333.8, 100%, 50%), 59px 248px hsl(1339.2, 100%, 50%), 59px 249px hsl(1344.6, 100%, 50%), 60px 250px hsl(1350, 100%, 50%), 59px 251px hsl(1355.4, 100%, 50%), 59px 252px hsl(1360.8, 100%, 50%), 59px 253px hsl(1366.2, 100%, 50%), 59px 254px hsl(1371.6, 100%, 50%), 59px 255px hsl(1377, 100%, 50%), 58px 256px hsl(1382.4, 100%, 50%), 58px 257px hsl(1387.8, 100%, 50%), 58px 258px hsl(1393.2, 100%, 50%), 57px 259px hsl(1398.6, 100%, 50%), 57px 260px hsl(1404, 100%, 50%), 56px 261px hsl(1409.4, 100%, 50%), 55px 262px hsl(1414.8, 100%, 50%), 55px 263px hsl(1420.2, 100%, 50%), 54px 264px hsl(1425.6, 100%, 50%), 53px 265px hsl(1431, 100%, 50%), 52px 266px hsl(1436.4, 100%, 50%), 51px 267px hsl(1441.8, 100%, 50%), 50px 268px hsl(1447.2, 100%, 50%), 49px 269px hsl(1452.6, 100%, 50%), 48px 270px hsl(1458, 100%, 50%), 47px 271px hsl(1463.4, 100%, 50%), 46px 272px hsl(1468.8, 100%, 50%), 45px 273px hsl(1474.2, 100%, 50%), 43px 274px hsl(1479.6, 100%, 50%), 42px 275px hsl(1485, 100%, 50%), 41px 276px hsl(1490.4, 100%, 50%), 39px 277px hsl(1495.8, 100%, 50%), 38px 278px hsl(1501.2, 100%, 50%), 36px 279px hsl(1506.6, 100%, 50%), 35px 280px hsl(1512, 100%, 50%), 33px 281px hsl(1517.4, 100%, 50%), 32px 282px hsl(1522.8, 100%, 50%), 30px 283px hsl(1528.2, 100%, 50%), 28px 284px hsl(1533.6, 100%, 50%), 27px 285px hsl(1539, 100%, 50%), 25px 286px hsl(1544.4, 100%, 50%), 23px 287px hsl(1549.8, 100%, 50%), 22px 288px hsl(1555.2, 100%, 50%), 20px 289px hsl(1560.6, 100%, 50%), 18px 290px hsl(1566, 100%, 50%), 16px 291px hsl(1571.4, 100%, 50%), 14px 292px hsl(1576.8, 100%, 50%), 13px 293px hsl(1582.2, 100%, 50%), 11px 294px hsl(1587.6, 100%, 50%), 9px 295px hsl(1593, 100%, 50%), 7px 296px hsl(1598.4, 100%, 50%), 5px 297px hsl(1603.8, 100%, 50%), 3px 298px hsl(1609.2, 100%, 50%), 1px 299px hsl(1614.6, 100%, 50%), 2px 300px hsl(1620, 100%, 50%), -1px 301px hsl(1625.4, 100%, 50%), -3px 302px hsl(1630.8, 100%, 50%), -5px 303px hsl(1636.2, 100%, 50%), -7px 304px hsl(1641.6, 100%, 50%), -9px 305px hsl(1647, 100%, 50%), -11px 306px hsl(1652.4, 100%, 50%), -13px 307px hsl(1657.8, 100%, 50%), -14px 308px hsl(1663.2, 100%, 50%), -16px 309px hsl(1668.6, 100%, 50%), -18px 310px hsl(1674, 100%, 50%), -20px 311px hsl(1679.4, 100%, 50%), -22px 312px hsl(1684.8, 100%, 50%), -23px 313px hsl(1690.2, 100%, 50%), -25px 314px hsl(1695.6, 100%, 50%), -27px 315px hsl(1701, 100%, 50%), -28px 316px hsl(1706.4, 100%, 50%), -30px 317px hsl(1711.8, 100%, 50%), -32px 318px hsl(1717.2, 100%, 50%), -33px 319px hsl(1722.6, 100%, 50%), -35px 320px hsl(1728, 100%, 50%), -36px 321px hsl(1733.4, 100%, 50%), -38px 322px hsl(1738.8, 100%, 50%), -39px 323px hsl(1744.2, 100%, 50%), -41px 324px hsl(1749.6, 100%, 50%), -42px 325px hsl(1755, 100%, 50%), -43px 326px hsl(1760.4, 100%, 50%), -45px 327px hsl(1765.8, 100%, 50%), -46px 328px hsl(1771.2, 100%, 50%), -47px 329px hsl(1776.6, 100%, 50%), -48px 330px hsl(1782, 100%, 50%), -49px 331px hsl(1787.4, 100%, 50%), -50px 332px hsl(1792.8, 100%, 50%), -51px 333px hsl(1798.2, 100%, 50%), -52px 334px hsl(1803.6, 100%, 50%), -53px 335px hsl(1809, 100%, 50%), -54px 336px hsl(1814.4, 100%, 50%), -55px 337px hsl(1819.8, 100%, 50%), -55px 338px hsl(1825.2, 100%, 50%), -56px 339px hsl(1830.6, 100%, 50%), -57px 340px hsl(1836, 100%, 50%), -57px 341px hsl(1841.4, 100%, 50%), -58px 342px hsl(1846.8, 100%, 50%), -58px 343px hsl(1852.2, 100%, 50%), -58px 344px hsl(1857.6, 100%, 50%), -59px 345px hsl(1863, 100%, 50%), -59px 346px hsl(1868.4, 100%, 50%), -59px 347px hsl(1873.8, 100%, 50%), -59px 348px hsl(1879.2, 100%, 50%), -59px 349px hsl(1884.6, 100%, 50%), -60px 350px hsl(1890, 100%, 50%), -59px 351px hsl(1895.4, 100%, 50%), -59px 352px hsl(1900.8, 100%, 50%), -59px 353px hsl(1906.2, 100%, 50%), -59px 354px hsl(1911.6, 100%, 50%), -59px 355px hsl(1917, 100%, 50%), -58px 356px hsl(1922.4, 100%, 50%), -58px 357px hsl(1927.8, 100%, 50%), -58px 358px hsl(1933.2, 100%, 50%), -57px 359px hsl(1938.6, 100%, 50%), -57px 360px hsl(1944, 100%, 50%), -56px 361px hsl(1949.4, 100%, 50%), -55px 362px hsl(1954.8, 100%, 50%), -55px 363px hsl(1960.2, 100%, 50%), -54px 364px hsl(1965.6, 100%, 50%), -53px 365px hsl(1971, 100%, 50%), -52px 366px hsl(1976.4, 100%, 50%), -51px 367px hsl(1981.8, 100%, 50%), -50px 368px hsl(1987.2, 100%, 50%), -49px 369px hsl(1992.6, 100%, 50%), -48px 370px hsl(1998, 100%, 50%), -47px 371px hsl(2003.4, 100%, 50%), -46px 372px hsl(2008.8, 100%, 50%), -45px 373px hsl(2014.2, 100%, 50%), -43px 374px hsl(2019.6, 100%, 50%), -42px 375px hsl(2025, 100%, 50%), -41px 376px hsl(2030.4, 100%, 50%), -39px 377px hsl(2035.8, 100%, 50%), -38px 378px hsl(2041.2, 100%, 50%), -36px 379px hsl(2046.6, 100%, 50%), -35px 380px hsl(2052, 100%, 50%), -33px 381px hsl(2057.4, 100%, 50%), -32px 382px hsl(2062.8, 100%, 50%), -30px 383px hsl(2068.2, 100%, 50%), -28px 384px hsl(2073.6, 100%, 50%), -27px 385px hsl(2079, 100%, 50%), -25px 386px hsl(2084.4, 100%, 50%), -23px 387px hsl(2089.8, 100%, 50%), -22px 388px hsl(2095.2, 100%, 50%), -20px 389px hsl(2100.6, 100%, 50%), -18px 390px hsl(2106, 100%, 50%), -16px 391px hsl(2111.4, 100%, 50%), -14px 392px hsl(2116.8, 100%, 50%), -13px 393px hsl(2122.2, 100%, 50%), -11px 394px hsl(2127.6, 100%, 50%), -9px 395px hsl(2133, 100%, 50%), -7px 396px hsl(2138.4, 100%, 50%), -5px 397px hsl(2143.8, 100%, 50%), -3px 398px hsl(2149.2, 100%, 50%), -1px 399px hsl(2154.6, 100%, 50%); font-size: 40px;";

console.log("%cExample %s", css, 'all code runs happy');

выведет в консоль:

И еще вопрос: можно ли в консоль вывести картинку, и если да, то как?

Не знаю как в других браузерах, но в Chrome, судя по коду из гитхаба
Можно вставить картинку в консоль, также на основе CSS стилей:

function getBox(width, height) {
  return {
    string: "+",
    style: "font-size: 1px; padding: " + Math.floor(height / 2) + "px " + Math.floor(width / 2) + "px; line-height: " + height + "px;"
  }
}

console.image = function(url, scale) {
  scale = scale || 1;
  var img = new Image();

  img.onload = function() {
    var dim = getBox(this.width * scale, this.height * scale);
    console.log("%c" + dim.string, dim.style + "background: url(" + url + "); background-size: " + (this.width * scale) + "px " + (this.height * scale) + "px; color: transparent;");
  };

  img.src = url;
};

console.image('https://i.stack.imgur.com/8uqn6.jpg');

A: Для Вашего примера:
console.log ( '%c%s', 'color: red; font: 2rem/1 Tahoma;', 'Остановитесь!' );

Вывод в консоль сообщения осуществить можно с помощью console.log() и console.dir().
ИСТОЧНИК

Для того, чтобы задать оформление тексту, CSS-код нужно передать
  отдельным параметром, причем первым параметром в этом случае должна
  быть строка с указателями, вторым — строка с CSS, третьим — данные,
  которые нужно вывести.

%s — в виде строки;  %d или %i — в виде числа; %f — в виде
  числа с плавающей точкой; %o — в виде разворачиваемого DOM-элемента;
%O — в виде разворачиваемого JavaScript-объекта;  %c — оформляет
  вывод с соответствии с CSS, переданным дополнительным параметром.

Пример 1:
var str = 'Главный вопрос жизни вселенной и всего такого';
console.log ( '%c%s', 'color: green; font: 1.2rem/1 Tahoma;', str );

Результат:

Пример 2:
var str = 'Главный вопрос жизни вселенной и всего такого';
var style = ['padding: 1rem;',
             'background: linear-gradient( gold, orangered);',
             'text-shadow: 0 2px orangered;',
             'font: 1.3rem/3 Georgia;',
             'color: white;'].join('');

console.log ( '%c%s', style, str );

Результат:

console API reference

Поддержка: Chrome, FF


text:
Q: How to copy the recent updated multiple files in another directory in Solaris I want to copy the recently updated multiple file into another directory.
I am having 1.xml,2.xml,3.xml.... in this directory recently someone updated file  or added new file into the directory,So i want to copy those files into the destination directory ..Its like synchronization of 2 directories.
For that I have tried below commend
find home/deployment/server/services/ -type f  -mtime 1  | xargs cp  /home/application/

and below one also
find home/deployment/server/services/ -type f  -mtime 1  -exec cp  /home/application/

I am not getting any file into destination after updating 1.xml file,So I have added new file 4.xml even that also not updating in destination directory.
How to process recently updated or newly added multiple files.
Thanks in advance.

A: Short answer:
use xargs to mv the "find" directory into another directory
Long answer: As I recall (not tested) for exec syntax is
find . -type f --mtime 1 -exec cp {} /destination/path/ +

"{}" is an argument which came from command "find"
For xargs
find . -type f --mtime 1 | xargs -0 -I {} cp {} /destination/path/

A: I do this often but use \; instead of + and usually -cnewer rather than -mtime.
\; executes the cp command on files individually instead of as a group.
+ executes as a group with as many paths as xterm will take.  It may do this multiple time if there are a lot of files.
the \ in front of the ; option is required or bash will think it is the end of the command.
find ./ -mtime -1 -exec cp {} /path/ \; -print

Use the -print at the end to get a list of the files that were copied.


text:
Q: LetsEncrypt with Apache2 Redirect I have been asked to setup a Vhost (Domain#2) that needs its own block but points to the same directory as another Vhost (Domain#1).  I am using Chef to automate LetsEncrypt's challenge requests and SSL setup.
Currently when LetsEncrypt attempts to get its generated challenge file it will try to get it from the directory of Domain#2, which doesn't exist.  (ie:  Domain#2/.well-known/acme-challenge/)  Naturally this throws an invalid response of 404.
I notice when it gets the invalid response it cleans up the generated challenges it made in Domain#1's /.well-known/acme-challenge directory.
I wrote this Redirect block for the Vhost from what I was able to find online, but it still throws 404 and I am not 100% sure why.  (I have not ever used Redirect or its regex like style before)
What would be the proper way to get this working now?
RewriteEngine on
RewriteCond %{REQUEST_METHOD} ^(TRACE|TRACK)
RewriteRule .* - [F]
RewriteCond %{HTTP_HOST}   !^tc.DOMAIN#2.com$
RewriteRule ^(?!\.well-known(?:$|/)).* http://tc.DOMAIN#2.com/$1 [R=301]


text:
Q: SED incorrectly replaces only the first instance of a pattern on a line Hello: I have tab separated data of the form
customer-item description-purchase price-category
e.g. a.out contains:

1\t400 Bananas\t3.00\tfruit
2\t60 Oranges\t0.00\tfruit
3\tNULL\t3.0\tfruit
4\tCarrots\tNULL\tfruit
5\tNULL\tNULL\tfruit

I'm attempting to get rid of all the NULL fields. I can't rely on the simple replacement of the string "NULL" as it may be a substring; so I am attempting
sed -i 's:\tNULL\t:\t\t:g' a.out

when I do this, I end up with

1\t400 Bananas\t3.00\tfruit
2\t60 Oranges\t0.00\tfruit
3\t\t3.0\tfruit
4\tCarrots\t\tfruit
5.\t\tNULL\tfruit

what's wrong here is that #5 has only suffered a replacement of the first instance of the search string on each line.
If I run my sed command twice, I end up with the result I want:

1\t400 Bananas\t3.00\tfruit
2\t60 Oranges\t0.00\tfruit
3\t\t3.0\tfruit
4\tCarrots\t\tfruit
5.\t\t\tfruit

where you can see that line 5 has both  of the NULLs removed
But I don't understand why I'm suffering this?

A: Since tabs can't be inside strings in your case since that would imply a new field you might be able to do what you want simply by doing this;
sed ':start ; s/\tNULL\(\t\|$\)/\t\1/ ; t start' a.out

First the inner part s/\tNULL\(\t\|$\)/\t\1/ searches for tab NULL followed by a tab or end of line $ and replace with a tab followed by the character that did appear after NULL (this last part is done using \1). We'll call that expression
We now have:
sed ':start ; expression ; t start' a.out

This is effectively a loop (like goto). :start is a label. ; acts as a statement delimiter. I have described what expression does above. t start says that IF the expression did any substitution that a jump will be made to label start. The buffer will contain the substituted text. This loop occurs until no substitution can be done on the line and then processing continues.
Information on sed flow control and other useful tidbits can be found here

A: awk -F'\t' -v OFS='\t' '{
    for (i = 1; i <= NF; ++i) {
        if ($i == "NULL") {
            $i = "";
        }
    }
    print
}' test.txt

The straightforward solution is to use \t as a field separator and then loop over all of the fields looking for an exact match of "NULL". No substringing.
Here's the same thing as a one liner:
awk -F'\t' -v OFS='\t' '{for(i=1;i<=NF;++i) if($i=="NULL") $i=""} 1' test.txt

A: awk makes it simpler:
awk -F '\tNULL\\>' -v OFS='\t' '{$1=$1}1' file
1\t400 Bananas\t3.00\tfruit
2\t60 Oranges\t0.00\tfruit
3\t\t3.0\tfruit
4\tCarrots\t\tfruit
5\t\t\tfruit

A: From grep(1) on a recent Linux:
The Backslash Character and Special Expressions
The  symbols  \<  and  >  respectively  match  the empty string at the
beginning and end of a word.  The symbol \b matches the empty string at
the  edge  of a word [...]
--
So, how about:
sed -i 's:\<NULL\>::g' a.out