text:
Q: Angular NgModel reevaluate getter @Input We are working on an angular project where we have a component that generates a list loaded via a getter and the list generates inputs that uses the ngModel directive. Each time we change the value in the inputs, the list of items gets reevaluated for some reason and rerenders our components which we do not want.
Here's an example that shows this behavior.
import {NgModule,ChangeDetectionStrategy,Component,OnChanges,SimpleChanges,Input} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'my-app',
  template: `
    <div>
      <test-component [items]="getterList"></test-component>
    </div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class App implements OnChanges{
  staticList = ["a","b","c"];

  get getterList():string[]{
    console.log('getterList');
    return this.staticList.map(a=>a);
  }

  ngOnChanges(changes:SimpleChanges){
    console.log(changes);
  }
}

@Component({
  selector: 'test-component',
  template: `
    <div *ngFor="let item of items">
        {{item}}
        <input type="text" [(ngModel)]="testValue" placeholder="ngModel" />
        <input type="text" [value]="testValue" placeholder="no ngModel" />
    </div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class TestComponent {
  @Input() items:string[] = [];
  testValue:string="";
}

@NgModule({
  imports: [ BrowserModule,FormsModule ],
  declarations: [ App,TestComponent ],
  bootstrap: [ App ]
})
export class AppModule {}

(here's the plunker)
https://plnkr.co/edit/MigjRs3MULcNS55oKVpp?p=preview
In this example we have a list generated via a getter. Each element of the list generates 2 inputs; one with ngModel, the other without ngModel and we can see that the second input doesn't trigger the getter.
Why does the ngModel directive retriggers the getter ?

A: Well, the plunker was helpful. [(ngModel)] syntax is for 2-way binding. In your template, you use [(ngModel)]="testValue" which is the same for each iteration of the loop (the iterated element is item (of items, as per *ngFor). So basically all "first-inputs" in the loop's each iteration are all tied to one model property testValue. Because of 2-way binding it automatically updates the rest of the "first-input" fields. The second one is [value]="testValue" which uses only [] which is a one-way binding. hence it won't update the remaining fields.
If you remove () from [(ngModel)] so that it becomes just one-way binded like this, [ngModel], you can see the difference. It will behave much like the second input field. So in essence it has nothing to do with your getters, all the magic is happening with the 2-way [(ngModel)] binding. Hope it helps


text:
Q: Need to optimize mssql query for fastest speed Please help me on below query to optimize. "#oz" temp table has 16000 rows. Now this query runs for about 14 seconds.
DOWNLOAD QUERY WITH DATA
create table #oz (
    id int, from_sto_move bit, product_id int, [date] datetime,
    qty_orlogo decimal(30, 10), qty_zarlaga decimal(30, 10), cost_prev decimal(30, 10)
)

print 'Query started on: ' + CONVERT(nvarchar(30), GETDATE(), 126)
select
    oz1.product_id,
    oz1.id,
    oz1.from_sto_move,
    sum(isnull(oz2.qty_orlogo, 0) - isnull(oz2.qty_zarlaga, 0))
        qty_oz,
    oz1.cost_prev
from
    #oz oz1 left join
    #oz oz2 on
        oz1.product_id = oz2.product_id and
        oz1.[date] > oz2.[date]
group by oz1.product_id, oz1.id, oz1.from_sto_move, oz1.cost_prev
print 'Query finished on: ' + CONVERT(nvarchar(30), GETDATE(), 126)

I need less than 5 seconds.
Thanks

A: Can you please add an Clustered Index to the Table on the column "product_id" and include "id" and "from_sto_move" in it. And let me know if that helps.
Can you please add another index to the table  ?
CREATE NONCLUSTERED INDEX [_dta_index_oz_7_148195578__K3_K1_K2_K7_4] ON [dbo].[oz]
(
[product_id] ASC,
[id] ASC,
[from_sto_move] ASC,
[cost_prev] ASC
)
INCLUDE (   [date]) WITH (SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF) ON [PRIMARY]

Here is the second index which you can create :
CREATE NONCLUSTERED INDEX [_dta_index_oz_7_148195578__K3_K4_5_6] ON [dbo].[oz]
(
[product_id] ASC,
[date] ASC
)
INCLUDE (   [qty_orlogo],
[qty_zarlaga]) WITH (SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF) ON [PRIMARY]

and let me know how well that works.

A: The only expanded suggestion I have is to build a covering index, but then is the engine taking more time to prepare the index than run the query?
try creating an index on (product_id, [date], id, from_sto_move, cost_prev ).
Since this is a #temp table, I don't think that making the index clustered is critical as opposed to just having the key elements for the join/group.  Date is critical component to the join.
Also, you are showing the create temp table for #oz, but not how you are populating it.  Perhaps going up one level on how it is populated from the raw original data might also help by preparing in a pre-sorted order to temp table, then self-joining the results you are looking for.

A: This seems to work quite well, and from what I can tell it returns the exact same results (CHECKSUM_AGG(BINARY_CHECKSUM(*)) over both resultsets returns the same value).
;WITH src
  AS (SELECT oz1.product_id,
             oz1.id,
             oz1.from_sto_move,
             qty_oz = ISNULL((SELECT sum(isnull(oz2.qty_orlogo, 0) - isnull(oz2.qty_zarlaga, 0))
                                FROM  #oz oz2
                               WHERE oz2.product_id  = oz1.product_id
                                 AND oz2.[date] < oz1.[date]), 0),
             oz1.cost_prev
        FROM #oz oz1)

SELECT product_id,
       id,
       from_sto_move,
       sum(qty_oz) as qty_oz,
       cost_prev
  FROM src
 GROUP BY product_id,
          id,
          from_sto_move,
          cost_prev

The 'great' thing about it is that it doesn't rely on any indexes; in fact it even works quite well directly on the heap too so you don't lose time creating indexes.
That said, even when there is no real PK on a table (temp-table or not); I'd always make sure to add at least an IDENTIY() column when creating the table and put the clustered index on it before loading the data. In my experience it makes loading the data slightly faster.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error running Python on OpsWorks with Chef + Berkshelf I'm trying to get Python 2.7 working on my OpsWorks instance but I keep running into errors starting up.
My OpsWork stack is set up with Chef version 11.10 and Berkshelf version 3.2.0.
My metadata.rb has the following in it:
depends           "poise-python"
depends           "apt", ">= 1.8.2"

My Berksfile is set up with:
source "https://supermarket.chef.io"

cookbook 'poise-python'
cookbook 'apt'

Every time I launch I keep getting the following error and I'm not sure how to resolve it:

Halite is not compatible with no_lazy_load false, please set
  no_lazy_load true in your Chef configuration file.

I tried adding a chef/configuration.rb file to set no_lazy_load to true but it doesn't seem to be working. Frankly I'm new to OpsWorks and Chef so I may be missing something very basic.
More Info
The stack I'm taking over originally referenced python instead of poise-python but I had switched from that to resolve a different error (but, I guess, related) when I tried to run with that:

This resource is written with Chef 12.5 custom resources, and requires
  at least Chef 12.0 used with the compat_resource cookbook, it will not
  work with Chef 11.x clients, and those users must pin their cookbooks
  to older versions or upgrade.

I tried pinning to an older version of python but still couldn't get it to work. Basically, I know this instance can run (previous maintainer had it going) but I'm not sure what I'm missing.

A: After some Googling, I figured out how to make this work without upgrading Chef version. I added the following line to my Berksfile:
cookbook 'build-essential', '= 3.2.0'

A: My cookbooks aren't compatible with Chef 11, you'll have to upgrade your stack to Chef 12.


text:
Q: run as administrator bat file I have a "conf.bat" file which is set path so that I need to run as admin but I do not want create shortcut. I want to do in bat file by using command?
I want to run as bat file by run as admin I can do using command prompt. When I click bat file, It is run admin.
echo off
SETX /M PATH "<new path>;%PATH%"
goto son
:hata
@echo "Error conf.bat <Java dll>"
exit /B 1
:son

A: The only possible way that will fulfil your want is to use bat_to_exe converter (1.2Mb) that converts your batch file to exe and then you can right click and run as administrator. Also you can add administrator manifest to your exe!! Using winch you don't have to right click and run as Administrator every time.
You can also use Iexpress.exe that is preinstalled on your PC. (Its confusing and not that efficient)


text:
Q: Python converting string to UTF I have an OctetString value 0xe4c722d60a61 (it's a MAC address, actually) that my code is nerfing to UTF on conversion to a string e.g. 'äÇ"Ö\na'.
The code processes a lot of data and only a small subset is of this type.
How can I stop this from happening?
This is the output:
(Pdb) snmpVal
[ObjectType(ObjectIdentity(<ObjectName value object at 0x7f77d152eef0 tagSet <TagSet object at 0x7f77d620ba20 tags 0:0:6> payload [1.3.6.1.2.1.2.2.1.6.3]>), <PhysAddress value object at 0x7f77d152e7b8 encoding iso-8859-1 subtypeSpec <ConstraintsIntersection object at 0x7f77d61d7518 consts <ValueSizeConstraint object at 0x7f77d61d74e0 consts 0, 65535>> tagSet <TagSet object at 0x7f77d620b550 tags 0:0:4> payload [e4:c7:22:d6:0a:60]>)]
(Pdb) snmpVal[0][1]
<PhysAddress value object at 0x7f77d152e7b8 encoding iso-8859-1 subtypeSpec <ConstraintsIntersection object at 0x7f77d61d7518 consts <ValueSizeConstraint object at 0x7f77d61d74e0 consts 0, 65535>> tagSet <TagSet object at 0x7f77d620b550 tags 0:0:4> payload [e4:c7:22:d6:0a:60]>
(Pdb) str(snmpVal[0][1])
'äÇ"Ö\n`'
(Pdb) hex(snmpVal[0][1])
*** TypeError: 'PhysAddress' object cannot be interpreted as an integer

This is the code:
    cmdGen = cmdgen.CommandGenerator()
    errorIndication, errorStatus, errorIndex, snmpVal = cmdGen.getCmd(
        cmdgen.UsmUserData(user,
                        authKey=authKey,
                        privKey=privKey,
                        authProtocol=authProto,
                        privProtocol=privProto,
                        securityEngineId=None
                ),
        cmdgen.UdpTransportTarget((sHost, 161)),
        '1.3.6.1.2.1.2.2.1.6.3' )

A: If you need to deal with raw OCTET STRING value, just call .asOctets() on the object. You will end up with bytes (Py3) or str (Py2). From here you could run unicode decoder if you need to turn OCTET STRING into unicode (which I doubt is a good idea).
If you want human-friendly representation of the MAC address, just call .prettyPrint() on the object. If it has been already resolved against a MIB, then pysnmp knows that it's a PhysAddress kind of OctetString so .prettyPrint() will turn it into colon-separated hex form.

A: You don't want to convert that to a UTF string by the sounds of your description. Python has a built-in function called hex that you can use. It converts any int value into a hex string. From there you can just add the colons yourself with some list comprehension and string joining. Try this:
a = hex(0xe4c722d60a61)
print(':'.join(a+b for a,b in zip(a[::2],a[1::2]))[3:])


text:
Q: JAXB unmarshall issue I've to parse the following xml in a Java object:

<ArrayOfTranslateArrayResponse xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<TranslateArrayResponse>
    <From>it</From>
    <OriginalTextSentenceLengths xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
        <a:int>5</a:int>
    </OriginalTextSentenceLengths>
    <TranslatedText>Mom</TranslatedText>
    <TranslatedTextSentenceLengths xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
        <a:int>3</a:int>
    </TranslatedTextSentenceLengths>
</TranslateArrayResponse>
<TranslateArrayResponse>
    <From>it</From>
    <OriginalTextSentenceLengths xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
        <a:int>4</a:int>
    </OriginalTextSentenceLengths>
    <TranslatedText>Dad</TranslatedText>
    <TranslatedTextSentenceLengths xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
        <a:int>3</a:int>
    </TranslatedTextSentenceLengths>
</TranslateArrayResponse>

This the two class I've implemented:
@XmlRootElement(name="ArrayOfTranslateArrayResponse")
@XmlAccessorType(XmlAccessType.FIELD)
@Getter
@Setter
@ToString
public class TranslateResponse {

    @XmlElement(name="TranslateArrayResponse")
    private LinkedList<TranslatedResponseObject> translations;

}

and

@XmlAccessorType(XmlAccessType.FIELD)
@Getter
@Setter
@ToString
public class TranslatedResponseObject {

    @XmlElement(name="TranslatedText")
    private String translatedText;

}

With the unmarshall of the xml example provided, I received null for the field translations. What is wrong?

A: I've got the solutions, thanks to @klonq suggestion to debug the issue. It was necessary to add the namespace on each @XmlElement and @XmlRootElement, in this way:
@XmlRootElement(name="ArrayOfTranslateArrayResponse", namespace="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2")
@XmlAccessorType(XmlAccessType.FIELD)
@Getter
@Setter
@ToString
public class TranslateResponse {

    @XmlElement(name="TranslateArrayResponse", namespace="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2")
    private LinkedList<TranslatedResponseObject> translations;

}

@XmlAccessorType(XmlAccessType.FIELD)
@Getter
@Setter
@ToString
public class TranslatedResponseObject {

    @XmlElement(name="TranslatedText", namespace="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2")
    private String translatedText;

}

A: You can use a ValidationEventHandler to debug problems.
public class MyValidationEventHandler implements ValidationEventHandler {

    @Override
    public boolean handleEvent(ValidationEvent event) {

        switch (event.getSeverity()) {

            case ValidationEvent.WARNING:
            case ValidationEvent.ERROR:
            case ValidationEvent.FATAL_ERROR: {
                log.error("Validation event : {} in {} line {} col {}",
                          event.getMessage(),
                          event.getLocator().getURL(),
                          event.getLocator().getLineNumber(),
                          event.getLocator().getColumnNumber());
                return false;
            }
            default:
                return true;
        }
    }
}

And you use it like the following :
final JAXBContext jAXBContext = JAXBContext.newInstance(target);
final Unmarshaller unmarshaller = jAXBContext.createUnmarshaller();

unmarshaller.setEventHandler(new MyValidationEventHandler());

unmarshaller.unmarshal(file);


text:
Q: How to recover RAID0 with MegaCli64? I have a RAID0 drive consisted of two SSDs. I accidentally removed one SSD and insert it back immediately. How can I recover the data?
I marked the reinserted disk as good and cleared the foriegn state. But I don't know how to add it back to the RAID group. The info of the reinserted disk:
Enclosure Device ID: 12
Slot Number: 23
Enclosure position: 1
Device Id: 30
WWN: 5002538e4062d3d4
Sequence Number: 7
Media Error Count: 0
Other Error Count: 0
Predictive Failure Count: 0
Last Predictive Failure Event Seq Number: 0
PD Type: SATA

Raw Size: 3.638 TB [0x1d1c0beb0 Sectors]
Non Coerced Size: 3.637 TB [0x1d1b0beb0 Sectors]
Coerced Size: 3.637 TB [0x1d1b00000 Sectors]
Sector Size:  512
Logical Sector Size:  512
Physical Sector Size:  512
Firmware state: Unconfigured(good), Spun Up
Device Firmware Level: 1B6Q
Shield Counter: 0
Successful diagnostics completion on :  N/A
SAS Address(0): 0x5003048018219027
Connected Port Number: 0(path0)
Inquiry Data: S3YSNB0K800520R     Samsung SSD 860 EVO 4TB                 RVT01B6Q
FDE Capable: Not Capable
FDE Enable: Disable
Secured: Unsecured
Locked: Unlocked
Needs EKM Attention: No
Foreign State: None
Device Speed: 6.0Gb/s
Link Speed: 12.0Gb/s
Media Type: Solid State Device
Drive:  Not Certified
Drive Temperature :28C (82.40 F)
PI Eligibility:  No
Drive is formatted for PI information:  No
PI: No PI
Drive's NCQ setting : Enabled
Port-0 :
Port status: Active
Port's Linkspeed: 12.0Gb/s
Drive has flagged a S.M.A.R.T alert : No

Here is the info of the RAID0:
DISK GROUP: 3
Number of Spans: 1
SPAN: 0
Span Reference: 0x04
Number of PDs: 2
Number of VDs: 1
Number of dedicated Hotspares: 0
Virtual Drive Information:
Virtual Drive: 4 (Target Id: 4)
Name                :
RAID Level          : Primary-0, Secondary-0, RAID Level Qualifier-0
Size                : 7.276 TB
Sector Size         : 512
Is VD emulated      : No
Parity Size         : 0
State               : Offline
Strip Size          : 256 KB
Number Of Drives    : 2
Span Depth          : 1
Default Cache Policy: WriteBack, ReadAhead, Direct, No Write Cache if Bad BBU
Current Cache Policy: WriteBack, ReadAhead, Direct, No Write Cache if Bad BBU
Default Access Policy: Read/Write
Current Access Policy: Read/Write
Disk Cache Policy   : Disk's Default
Encryption Type     : None
Bad Blocks Exist: No
PI type: No PI

A: I fixed this problem using a trick from https://serverfault.com/a/779381.
The author said:

There is a trick to get your data back - just recreate RAID 0 with the same parameters as you had earlier and when it asks you to Initialize the array just say NO.

Mark the reinserted physical drive as good
MegaCli64 -PDMakeGood -PhysDrv [12:23] -aALL

Clear the foreign mark:
MegaCli64 -CfgForeign -Clear -aALL

Delete the original RAID 0 virtual drive (in my case, it's virtual drive 4):
MegaCli64 -CfgLdDel -L4 -a0

Recreate RAID 0 drive with the same config:
MegaCli64 -CfgLdAdd -r0 [12:12,12:23] WB Direct -a0


text:
Q: Where should class objects be declared? Should they be declared in the .cpp or .h files?
Example 1:
A.h
#include "B.h"
#include "C.h"

class A
{
    void someFunction();
    B   b;
    C   c;
}

Example 2:
A.cpp
#include "B.h"
#include "C.h"

A::someFunction()
{
    B   b;
    C   c;
    // Do something with b and c.
}

Example 3:
A.cpp
#include "B.h"
#include "C.h"

B   b;
C   c;

A::someFunction()
{
    // Do something with b and c.
}

Should they only be declared in the function that is using them (example 2) or can they be declared at the top of the file under the header includes like in example 3?

A: Declare them with the narrowest scope as possible. If a class is only used in a single translation unit, then declare and define it in the source file. Typically you'd only declare a class in a header file if it's declaration is required by more than one transation unit.
The normal way of dealing with circular dependencies is to use a forward class declaration.

A: All of those examples are for different use cases:
A.h
#include "B.h"
#include "C.h"

class A
{
    void someFunction();
    B   b;
    C   c;
}

This adds objects b and c of types B and C respectively to your class A. Any object of type A will now have access to these 2 other objects. (just not outside of the class since they're implcitly private). This is vastly different from example 2 & 3 since it doesn't actually define any variables yet until you instantiate an object of A.
Example 2:
A.cpp
#include "B.h"
#include "C.h"

A::someFunction()
{
    B   b;
    C   c;
    // Do something with b and c.
}

This is usually the best scenario when you only need to use b and c inside someFunction and their changes don't have to be visible to the outside of the function. Note that their lifetimes are until the end of the function.
Example 3:
A.cpp
#include "B.h"
#include "C.h"

B   b;
C   c;

A::someFunction()
{
    // Do something with b and c.
}

Here, b and c are both global variables, globals are usually frowned upon because they make it hard to track what part of your code is doing what modification to these variables. A better alternative would be passing them around and defining them in main() if their lifetime should be the for entirety of the program.


text:
Q: How to use comparator using ranges of values? Let's say I have a class Person with attributes age and name. I would like to order a list of person using age ranges, and inside that range by name for example.
These ranges could be of 10 years for example. A more graphic example:

*

*Person 1: 10 nick

*Person 2: 13 albert

*Person 3: 26 alex

*Person 4: 22 oliver

The comparator should return person 2 > person 1 > person 3 > person 4.
I tried about implementing a comparator using Math.abs(p1.age - p2.age) but it does not work as expected.
How can I implement a comparator to return a comparator using ranges of the age attribute in this case?

A: You need to divide the age by 10 - using integer division will just discard the "ones" part and leave you with easy to compare integers. Java 8's comparator syntax makes this quite elegant:
List<Person> people = /* initialize the list... */
people.sort(Comparator.comparingInt((Person p) -> p.getAge() / 10)
                      .thenComparing(Person::getName));


text:
Q: volley JSONObject cannot be converted to JSONArray? I got this error
Hi, i'm trying to retrieve data from my server and i thing successfully getting it but not able to set data inside list, there is something wrong with my code which i can't figured out
here's my code
CustomVolleyJsonArrayRequest jsonObjectRequest = new CustomVolleyJsonArrayRequest(Request.Method.POST, BaseURL.dboytoday_orders, params,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d("Tag", response.toString());

                    today_order_models.clear();

                    try {

                        for ( int k=0;k<response.length();k++) {

                            JSONObject response1=response.getJSONObject(k);
                            String status = response1.getString("status");
                            String message = response1.getString("message");
                            //  String order = response.getString("order_id");

                            if (status.contains("2")) {

                                progressDialog.dismiss();

                                String user_name = response1.getString("user_name");
                                String user_phone = response1.getString("user_phone");
                                String user_id=response1.getString("user_id");

                                Today_Order_Model todayOrderModel = new Today_Order_Model();

                                todayOrderModel.setUser_id(user_id);
                                todayOrderModel.setUser_name(user_name);
                                //      todayOrderModel.setOrderid(order);
                                todayOrderModel.setUser_phone(user_phone);

                                today_order_models.add(todayOrderModel);


text:
Q: Vite can't find the environment variables I have a workspace with NX that I am trying to migrate from workspace => vite.
I have some environment.ts file inside apps/core/src/environments In project.json
I have the following replacement
          "fileReplacements": [
            {
              "replace": "apps/core/src/environments/environment.ts",
              "with": "apps/core/src/environments/environment.prod.ts"
            }
          ],

The issue is, when I run my build or serve command, I am always getting
GET http://localhost:3001/@fs/apps/core/src/environments/environment.prod.ts net::ERR_ABORTED 404 (Not Found)
But the path is correct, so I am unsure what I am configuring wrong


text:
Q: Why subclass doesn't work in framework, but extension does in Swift? I've created a custom framework in Swift 3, with extensions (for String, UIColors, etc.) and subclass of UITableView and UIView.
Problem is that, when I try to use my subclasses in another project, it doesn't work and crash. And extensions's functions work perfectly...
Subclass doesn't appear in the list of "available classes" in the storyboard. (My class is not in the list of Custom Class, and Module section is empty)
In my framework, my subclasses are public. I also tried with open, and I had the same problem.
Hope it's clear enough and that anyone can help me :)
Edit:
To reproduce the problem:

*

*Create a Custom class that inherits from UIView like that:
public class CustomView: UIView {
    public var name: String = "MyName"
    public func sayMyName() { print("\(self.name)") }
}

*Create your framework

*Create a new project, and import your framework.

*Try to instantiate a CustomView in the storyboard.

A: First, you need to make sure your Framework target is accessible to your App project. Two options:

*

*Add the Framework .xcodeproj file to the project to allow editing either target as you wish. Be aware, only one Xcode project can use it at a time.

*Add the Framework .framework file to the project then make sure it is included in the app's Linked Frameworks and Libraries.

Now that you've added it to your Xcode's app project, you need to do this:

*

*If you want to access your open classes in code, use the syntax:
import [framework]

*If you wish to access your UIKit subclasses in a Storyboard, add their superclass control, then go to Identity Inspector and (1) select your framework as the Module and your subclass as the Class.


text:
Q: Database table as a job queue for multiple instances Let's say I have a table with some jobs that need to be executed, that is read by many instances of the same service.
I have a status column, and each instance is querying first row which is not taken yet (filtering by status) and then changing this status within the same transaction.
How do I prevent multiple instances reading the same job and then updating its status and executing it simultaneously?


text:
Q: Strong Name validation fails after enabling LARGEADDRESSAWARE I am building n C# executable that has to be built as a 32-bit application (due to other environment restrictions). As a post build step I'm using editbin.exe \LARGEADDRESSAWARE to allow the 32-bit application to utilize more than 2GB of memory; although I noticed that this is breaking Strong Name validation.
Before running the editbin.exe command I run sn.exe -vf to verify the Strong Name:
sn.exe -vf [my exe]

The output: Assembly '[my exe]' is valid
Then I run editbin.exe /LARGEADDRESSAWARE [my exe] which just exits without any message. I verify that it's enabled to use more than 2GB by checking the headers via dumpbin /headers [my exe].
Finally, I rerun the sn.exe command and get the following output:
Failed to verify assembly -- Strong name validation failed for assembly '[my exe]'

Any ideas how I can enable LARGEADDRESSAWARE functionality without breaking the Strong Name verification?

A: A strong name takes into account the hash of the file being strong named; by altering the file with editbin.exe \LARGEADDRESSAWARE, you're altering the file, therefore the hash of the file, and thus invalidating the strong name.
You need to alter your build steps, and ensure that the assembly is exactly as you want it before running the strong name step.  Depending on your build pipeline, this may mean not strong naming it within Visual Studio, and instead using the command line to do so instead.


text:
Q: How to find nodes being contained in a node's properties interval? I'm currently developing some kind of a configurator using neo4j as a backend. Now I ran into a problem, I don't know how to solve best.
I've got nodes created like this:
(A:Product {name:'ProductA', minWidth:20, maxWidth:200, minHeight:10, maxHeight:400})
(B:Product {name:'ProductB', minWidth:40, maxWidth:100, minHeight:20, maxHeight:300})
...
There is an interface where the user can input a desired width & height, f.e. Width=30, Height=250. Now I'd like to check which products match the input criteria. As the input might be any long value, the approach used in http://neo4j.com/blog/modeling-a-multilevel-index-in-neoj4/ with dates doesn't seem to be suitable for me. How can I run a cypher query giving me all the nodes matching the input criteria?

A: I don't know if I understand well what you are asking for, but if I do, here a simple query to get this:
Assuming the user wants width = 30 and height = 50
Match (p:Product)
WHERE
    p.minWidth < 30 AND p.maxWidth > 30 AND
    p.minHeight < 50 AND p.maxHeight > 50
RETURN
    p

If this is not what you are looking for, feel free to say it as comment.


text:
Q: arrow in plot matplotlib.pyplot I am unable to get the arrow to display like I want it.
Here is an example of what I am trying to do:
import matplotlib.pyplot as plt
import numpy as np

b = np.arange(5)*-1E-4
a = np.arange(5)

fig, ax = plt.subplots()
ax.plot(a,b, linewidth=3, color="k")
plt.arrow(1,-0.00010,0,-0.00005, shape='full', lw=3, length_includes_head=True, head_width=.01)
plt.show()

As far as I understand, this should produce an arrow starting at (1,-0.00010) and ending at (1,-0.00015)
But the result is a much longer line, no longer looking like an arrow, and not starting and stopping at the right points.

A: You can draw arrow with annotate.matplotlib docs
a = np.linspace(-2,2, 100)
plt.plot(a, a**2)
plt.annotate("here", xy=(0, 0), xytext=(0, 2), arrowprops=dict(arrowstyle="->"))

A: Because you are using such small scales, some arguments which you have not explicitly passed to plt.arrow, will use their defaults, which in your case will not give a nice outcome.
Looking at the documentation, if no value for width is passed then the default value is 0.001, then the head width will be 0.003 and the head length will be 0.0015. Because the head width is too small using the default values, and the head length is much too big you get the output seen in the question
Therefore, you need to pass in the arguments head_width and head_length:
plt.arrow(1, -0.00010, 0, -0.00005, length_includes_head=True,
          head_width=0.08, head_length=0.00002)

which gives:


text:
Q: CQL - find related rows in the same table? I am new to CQL. Using Cassandra 3.x
I have a basic university class table as
Class_ID         INT
Class_Name       VARCHAR
Class_Date       TIMESTAMP
Class_TimeHour   INT

Sample entries are
{1,"Bio 1","01/01/2018","700"}
{2,"MC 1" ,"01/01/2018","700"}
{3,"Bio 2","01/01/2018","815"}
{3,"MC 2" ,"01/01/2018","1100"}

700 represents 0700 hours in 24 hour notation.
I need to answer some basic queries, please advise on how to best setup the table and queries.

*

*Can i get a Class_TimeHour desc ordered list of classes?

*Can i get a Class_TimeHour desc ordered list of a particular class. Does this mean i need to setup a partition key differently from #1 ?

*Can i get a list of all Class_Name that are within 60 min window of each other. My results from above should be
{1,"Bio 1","01/01/2018","700"}
{2,"MC 1","01/01/2018","700"}
{3,"Bio 2","01/01/2018","815"}

*How many times does "Bio 1" occur per day

*Count of how many Class_Name       contain "MC" literal.

Thanks!


text:
Q: Android Studio Compile the project error I encounter the following error when I try to compile my project with gradle (the log length exceeds the limit, the following is only part of it):
15:53:22.406 [ERROR] [org.gradle.api.Project] AGPBI: {"kind":"error","text":"warning: Ignoring InnerClasses attribute for an anonymous inner class","sources":[{}]}
15:53:22.406 [ERROR] [org.gradle.api.Project] AGPBI: {"kind":"error","text":"(anet.channel.SessionCenter$1) that doesn\u0027t come with an","sources":[{}]}
15:53:22.406 [ERROR] [org.gradle.api.Project] AGPBI: {"kind":"error","text":"associated EnclosingMethod attribute. This class was probably produced by a","sources":[{}]}
15:53:22.406 [ERROR] [org.gradle.api.Project] AGPBI: {"kind":"error","text":"compiler that did not target the modern .class file format. The recommended","sources":[{}]}
15:53:22.406 [ERROR] [org.gradle.api.Project] AGPBI: {"kind":"error","text":"solution is to recompile the class from source, using an up-to-date compiler","sources":[{}]}
15:53:22.448 [ERROR] [org.gradle.api.Project] AGPBI: {"kind":"error","text":"indicate that it is *not* an inner class.","sources":[{}]}
15:53:22.448 [ERROR] [org.gradle.api.Project] AGPBI: {"kind":"error","text":"warning: Ignoring InnerClasses attribute for an anonymous inner class","sources":[{}]}
15:53:22.448 [ERROR] [org.gradle.api.Project] AGPBI: {"kind":"error","text":"(anet.channel.strategy.e) that doesn\u0027t come with an","sources":[{}]}
15:53:22.448 [ERROR] [org.gradle.api.Project] AGPBI: {"kind":"error","text":"associated EnclosingMethod attribute. This class was probably produced by a","sources":[{}]}
15:53:22.448 [ERROR] [org.gradle.api.Project] AGPBI: {"kind":"error","text":"compiler that did not target the modern .class file format. The recommended","sources":[{}]}
[org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter] Finished executing task ':app:transformClassesWithDexForRelease'
15:53:22.482 [LIFECYCLE] [class org.gradle.TaskExecutionLogger] :app:transformClassesWithDexForRelease FAILED
15:53:22.484 [DEBUG] [org.gradle.launcher.daemon.server.SynchronizedDispatchConnection] thread 215: dispatching class org.gradle.launcher.daemon.protocol.BuildEvent
15:53:22.486 [INFO] [org.gradle.execution.taskgraph.AbstractTaskPlanExecutor] :app:transformClassesWithDexForRelease (Thread[Daemon worker Thread 2,5,main]) completed. Took 4 mins 21.866 secs.
15:53:22.486 [DEBUG] [org.gradle.execution.taskgraph.AbstractTaskPlanExecutor] Task worker [Thread[Daemon worker Thread 2,5,main]] finished, busy: 4 mins 28.755 secs, idle: 0.052 secs
15:53:22.503 [DEBUG] [org.gradle.launcher.daemon.server.SynchronizedDispatchConnection] thread 215: dispatching class org.gradle.launcher.daemon.protocol.BuildEvent
15:53:22.505 [ERROR] [org.gradle.BuildExceptionReporter]
15:53:22.505 [ERROR] [org.gradle.BuildExceptionReporter] FAILURE: Build failed with an exception.
15:53:22.506 [ERROR] [org.gradle.BuildExceptionReporter]
15:53:22.506 [ERROR] [org.gradle.BuildExceptionReporter] * What went wrong:
15:53:22.506 [ERROR] [org.gradle.BuildExceptionReporter] Execution failed for task ':app:transformClassesWithDexForRelease'.
15:53:22.506 [ERROR] [org.gradle.BuildExceptionReporter] > com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: java.lang.UnsupportedOperationException
15:53:22.506 [ERROR] [org.gradle.BuildExceptionReporter]
15:53:22.506 [ERROR] [org.gradle.BuildExceptionReporter] * Exception is:
15:53:22.506 [ERROR] [org.gradle.BuildExceptionReporter] org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformClassesWithDexForRelease'.
15:53:22.506 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69)
15:53:22.507 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)
15:53:22.507 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)
15:53:22.507 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:66)
15:53:22.507 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
15:53:22.507 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:52)
15:53:22.507 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
15:53:22.507 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)
15:53:22.508 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
15:53:22.508 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:203)
15:53:22.508 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:185)
15:53:22.508 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:66)
15:53:22.508 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:50)
15:53:22.508 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:25)
15:53:22.508 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:110)
15:53:22.508 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
15:53:22.508 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
15:53:22.508 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
15:53:22.508 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
15:53:22.509 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
15:53:22.509 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
15:53:22.509 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
15:53:22.509 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.initialization.DefaultGradleLauncher$4.run(DefaultGradleLauncher.java:153)
15:53:22.509 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.internal.Factories$1.create(Factories.java:22)
15:53:22.509 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:91)
15:53:22.509 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:53)
15:53:22.509 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:150)
15:53:22.509 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.initialization.DefaultGradleLauncher.access$200(DefaultGradleLauncher.java:32)
15:53:22.509 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradleLauncher.java:98)
15:53:22.510 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradleLauncher.java:92)
15:53:22.510 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:91)
15:53:22.510 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:63)
15:53:22.510 [ERROR] [org.gradle.BuildExceptionReporter]    at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:92)
15:53:22.519 [ERROR] [org.gradle.BuildExceptionReporter]    at com.android.builder.core.DexByteCodeConverter.runDexer(DexByteCodeConverter.java:159)
15:53:22.519 [ERROR] [org.gradle.BuildExceptionReporter]    at com.android.builder.core.DexByteCodeConverter.convertByteCode(DexByteCodeConverter.java:146)
15:53:22.519 [ERROR] [org.gradle.BuildExceptionReporter]    at com.android.builder.core.AndroidBuilder.convertByteCode(AndroidBuilder.java:1386)
15:53:22.519 [ERROR] [org.gradle.BuildExceptionReporter]    at com.android.build.gradle.internal.transforms.DexTransform.transform(DexTransform.java:272)
15:53:22.520 [ERROR] [org.gradle.BuildExceptionReporter]    ... 81 more
15:53:22.520 [ERROR] [org.gradle.BuildExceptionReporter] Caused by: java.util.concurrent.ExecutionException: java.lang.UnsupportedOperationException
15:53:22.520 [ERROR] [org.gradle.BuildExceptionReporter]    at com.android.builder.core.DexByteCodeConverter.dexOutOfProcess(DexByteCodeConverter.java:206)
15:53:22.520 [ERROR] [org.gradle.BuildExceptionReporter]    ... 85 more
15:53:22.520 [ERROR] [org.gradle.BuildExceptionReporter] Caused by: java.lang.UnsupportedOperationException
15:53:22.520 [ERROR] [org.gradle.BuildExceptionReporter]    at com.android.ide.common.process.ProcessInfoBuilder$JavaProcessInfoImpl.getExecutable(ProcessInfoBuilder.java:349)
15:53:22.520 [ERROR] [org.gradle.BuildExceptionReporter]    at com.android.build.gradle.internal.process.GradleProcessResult.buildProcessException(GradleProcessResult.java:74)
15:53:22.520 [ERROR] [org.gradle.BuildExceptionReporter]    at com.android.build.gradle.internal.process.GradleProcessResult.assertNormalExitValue(GradleProcessResult.java:49)
15:53:22.520 [ERROR] [org.gradle.BuildExceptionReporter]    at com.android.builder.core.DexByteCodeConverter.lambda$dexOutOfProcess$1(DexByteCodeConverter.java:196)
15:53:22.520 [ERROR] [org.gradle.BuildExceptionReporter]

A: Add this line to proguard-rules.pro
-keepattributes EnclosingMethod


text:
Q: Mean independence and normality imply independence? Let $\varepsilon, X$ be real-valued random variables. Could you help me to show (if correct) that
(1) $E(\varepsilon)=E(\varepsilon\mid X)$
and
(2) $\varepsilon \sim N(0,1)$
imply that $\varepsilon\perp X$?
If the statement is wrong what would be the "corrected" version?

A: Suppose $X=\epsilon^2$, and $\epsilon\sim N(0,1)$.


text:
Q: obtaining an enum value public enum TimeOfDay
    {
        Morning = 0,
        Afternoon = 1,
        Evening = 2
    }

Question: When we want to obtain an enum value from its string, we can use:
TimeOfDay time = TimeOfDay.Afternoon;
Console.WriteLine((int)time);

But what does maen the code below (with the same answer)?
TimeOfDay time2 = (TimeOfDay) Enum.Parse(typeof(TimeOfDay), "afternoon", true);
Console.WriteLine((int)time2);

Thank you,
Mohsen

A: MSDN defines the Enum.Parse method as

Converts the string representation of the name or numeric value of one
  or more enumerated constants to an equivalent enumerated object.

That is, the method takes either the integer or string representation and returns corresponding object from the associated Enum. In this case, user supplies the string parameter "afternoon", Enum type "TimeOfDay" and sets the case insensitive flag to true. The method then does case-insensitive match against the objects in the Enum and returns the object which has name matching the user's parameter.


text:
Q: Hive: Usage of Concat in Column Name I am trying to get data from a table that has column name as: year_2016, year_2017, year_2018 etc.
I am not sure how to get the data from this table.
The data looks like:
| count_of_accidents | year_2016 | year_2017 |year_2018 |
|--------------------|-----------|-----------|----------|
| 15                 | 12        | 5         | 1        |
| 5                  | 10        | 6         | 18       |

I have tried 'concat' function but this doesn't really work.
I have tried with this:
select SUM( count_of_accidents * concat('year_',year(regexp_replace('2018_1_1','_','-'))))
from table_name;

The column name (year_2017 or year_2018 etc) will be passed as a parameter. So, I am not really able to hardcode the column name like this-
select SUM( count_of_accidents * year_2018) from table_name;

Is there any way I can do this?

A: You can do it using regular expressions. Like this:
--create test table
create table test_col(year_2018 string, year_2019 string);

set hive.support.quoted.identifiers=none;
set hive.cli.print.header=true;

--test select using hard-coded pattern
select year_2018, `(year_)2019` from test_col;
OK
year_2018       year_2019
Time taken: 0.862 seconds

--test pattern parameter
set hivevar:year_param=2019;

select year_2018, `(year_)${year_param}` from test_col;
OK
year_2018       year_2019
Time taken: 0.945 seconds

--two parameters
set hivevar:year_param1=2018;
set hivevar:year_param2=2019;

select `(year_)${year_param1}`, `(year_)${year_param2}`  from test_col t;
OK
year_2018       year_2019
Time taken: 0.159 seconds

--parameter contains full column_name and using more strict regexp pattern
set hivevar:year_param2=year_2019;

select `^${year_param2}$` from test_col t;
OK
year_2019
Time taken: 0.053 seconds

--select all columns using single pattern year_ and four digits
select `^year_[0-9]{4}$`  from test_col t;
OK
year_2018       year_2019

Parameter should be calculated and passed to the hive script, no functions like concat(), regexp_replace are supported in the column names.
Also column aliasing does not work for columns extracted using regular expressions:
 select t.number_of_incidents, `^${year_param}$` as year1 from test_t t;

throws exception:

FAILED: SemanticException [Error 10004]: Line 1:30 Invalid table alias
  or column reference '^year_2018$': (possible column names are:
  number_of_incidents, year_2016, year_2017, year_2018)

I found a workaround to alias a column using union all with empty dataset, see this test:
create table test_t(number_of_incidents int, year_2016 int, year_2017 int, year_2018 int);
insert into table test_t values(15, 12, 5, 1); --insert test data
insert into table test_t values(5,10,6,18);

--parameter, can be passed from outside the script from command line
set hivevar:year_param=year_2018;

--enable regex columns and print column names
set hive.support.quoted.identifiers=none;
set hive.cli.print.header=true;

--Alias column using UNION ALL with empty dataset
select sum(number_of_incidents*year1) incidents_year1
  from
    (--UNION ALL with empty dataset to alias columns extracted
     select 0 number_of_incidents, 0 year1 where false --returns no rows because of false condition
     union all
     select t.number_of_incidents, `^${year_param}$` from test_t t
    )s;

Result:
OK
incidents_year1
105
Time taken: 38.003 seconds, Fetched: 1 row(s)

First query in the UNION ALL does not affect data because it returns no rows. But it's column names become the names of the whole UNION ALL dataset and can be used in the upper query. This trick works. If you will find a better workaround to alias columns extracted using regexp, please add your solution as well.
Update:
No need in regular expressions if you can pass full column_name as a parameter. Hive substitutes variables as is (does not calculate them) before query execution. Use regexp only if you can not pass full column name for some reason and like in the original query some pattern concatenation is needed. See this test:
--parameter, can be passed from outside the script from command line
set hivevar:year_param=year_2018;

select sum(number_of_incidents*${year_param}) incidents_year1 from test_t t;

Result:
OK
incidents_year1
105
Time taken: 63.339 seconds, Fetched: 1 row(s)


text:
Q: How to use a static map of function pointer field in a template with using or typedef I have
template <class ElemType>
class FunctionNode : public ComputationNode<ElemType>
{
    typedef void(*TensorFunctionFunc)  (TensorView<ElemType>&);

    static const map <string, TensorFunctionFunc> fmap;

and in the cpp
template <class ElemType>
const map <string, TensorFunctionFunc> FunctionNode::fmap = FunctionNode::create_map();

However i get a variety of errors , tried using as well. Any ideas ? Also i don't think i can use std::function() since i'm using dlopen.
Quite a few similar questions but none covering a static map of function pointer , in a template .
This is not a duplicate of "Why can templates only be implemented in the header file? 12 answers" since even when using the header it does not work due to the static ! . This requires completely different initialization.  ( the answers there do not work) ..


text:
Q: Change caps-lock to control in virtual console on Ubuntu 17 I'd like to change the Caps Lock behavior in virtual terminals (tty e.g. CtrlAltF3) so it acts as a Control modifier. Ideally, I'd also like it to act as Escape when pressed alone, but just getting the Control behavior is proving difficult.
I'm running Ubuntu 17.04. I've read and tried numerous approaches to making this change, but none seem to apply to my system as described. I get the sense that systemd plays a part in this, but the particulars are unclear.
I've written a file, caps_control.kmap, that maps caps to control,
keymaps 0-255
keycode  58 = Control

If I run loadkeys caps_control.kmap from a virtual console, it works. Now I'd like to get it to load automatically upon boot/login/whatever...
I found references to using /etc/rc.local to do so, but my system has no such file, though it does have several directories like /etc/rc0.d/, /etc/rc1.d/, ...
It sounds like since Ubuntu 17 uses sytemd, I should use localectl to manage this sort of thing, but it's not clear to me how to do so. For example,
$ localectl status
   System Locale: LANG=en_US.UTF-8
       VC Keymap: n/a
      X11 Layout: us
       X11 Model: pc105
$ localectl list-keymaps
Couldn't find any console keymaps.

The man page for localectl mentions /etc/locale.conf and /etc/vconsole.conf, neither of which exist on my system.
I am totally at a loss. Can anyone point me in the right direction?

A: To turn Caps Lock into an additional Ctrl modifier, which is also effective in tty consoles, open /etc/default/keyboard for editing and set:
XKBOPTIONS=ctrl:nocaps

If you already have XKBOPTIONS set, append ctrl:nocaps to its existing value using a comma for separator, e.g.:
XKBOPTIONS="terminate:ctrl_alt_bksp,ctrl:nocaps"

Should be effective after next reboot or issuing the setupcon command.
The option should be present when running localectl status:
$ localectl status | grep caps
     X11 Options: ctrl:nocaps

And in the X session, another way to verify that it's set is:
$ gsettings get org.gnome.desktop.input-sources xkb-options
['ctrl:nocaps']


text:
Q: Having same Unit/UI tests for both project Targets? I want to add unit and UI testing to my iOS project on which it has 2 Targets A and B. A and B are flavors of the app with the same logic but with a different style (colors, fonts..).
When I try to add a Test target from the + button it asks me to choose a Target to be tested either A or B. my tests are the same on both targets.
This is where I am confused. How can I have same units tests across all targets? Thanks .

A: You can't have two host applications in single test target. You have to select (n)one.
But if the code is the same for both targets, it doesn't really matter which one you choose, I guess?
Of course you could do the same as you probably did for your logic code, that means to make the same (test) code "member" of two test targets. However I don't see the point in testing the same stuff twice.
It also seems to be possible to set up your tests, so that they don't depend on a specific host application, like described in the following link, but this also comes with some restrictions.
https://clean-swift.com/how-to-make-your-unit-tests-run-faster
I would go with the first approach: Just choose one host (app target), and go for it.

A: Instead of maintaining two targets for basically same code I will advise you two maintain a single target and customize each flavours with schemes and configs. This also allows you to share those schemes and configs in your single test target allowing you to test different flavours of the same app.


text:
Q: How to group array of objects with same key value pair I have an array of dictionaries with same key value pairs.
[
  { "amount": "10" },
  { "amount": "20" },
  { "amount": "30" },
  { "amount": "20" },
  { "amount": "10" },
  { "amount": "10" }
]

I need to group this based on same key values.
Expected sample result:
There are 3x 10's, 2x 20's and 1x 30's
How do I achieve this?

A: let array = [ ["amount": "10"], ["amount": "20"], ["amount": "30"], ["amount": "20"], ["amount": "10"], ["amount": "10"] ]
var result: [String: Int] = [:]
let key = "amount"
array.forEach {
    guard let value = $0[key] else { return }
    result[value, default: 0] += 1
}

print("\(result["10"])") // 3


text:
Q: Link to the exact line of a plain text file without using html Let's say I have a plain text file (the log file output of a programme say) hosted on a website. We link to that file. People open it in their browser. Is there some way to link to an extact line in that file? similar to the http://www.example.com/file.html#name URL scheme? The trick is that this file cannot easily be converted to HTML, so I'm looking for a way to do it with URLs (to go in a <a href=... code).
I am pretty sure this isn't in any HTML spec (even though it's not a HTML file). I'm just looking for a hack. The only browsers that will be used are Firefox & Chrome/Chromium. A little unsupported feature hack of those browsers will do fine.

A: In order to use hashtags, you would have to use HTML in your text file. You could create some sort of wrapper page that would read that text file in, beautify it and allow much better user interaction.


text:
Q: How to change a file after pull request is raised Let me rephrase the question - so I already have pushed the code to my branch A and its under review for file someTableEntries.csv. I would eventually like to merge it into the master branch.
At the same time "Another Coder" merges changes to someTableEntries.csv into the master branch.
Is there any way that I can resolve conflicts between the someTableEntries.csv I wanted to merge and the one "Another Coder" has already merged. Eventually I would like the file someTableEntries.csv within the master branch containing changes from both my work and that of "Another Coder". Is there something similar to perforce merge tool over here.

A: Yes, you just should commit and push your changes to the same branch. Pull request will be automatically updated since pull request is a relation of two branches, not a relation between a separate commit and the branch to merge to.

A: Yes, you can directly add new commit and push to the branch from that you have sent the pull request, but this works only if the pull request is not merged yet.
If pull request got merged before your newest commit then you have to send new pull request for this.

A: Yes you can just commit and push to your branch and the pull request will be updated if it's not merged yet.
A pull request is a request to merge all changes included in a source branch (A) to a target branch (B).
The owner of the target branch B is responsible for accepting the changes that are included in branch A, and allow merging it in branch B. All the changes that have been pushed to the source branch until then will be included in the merge.
At the end of the merging process of a pull request, the owner of the target branch B may decide that the source branch A is no longer needed and delete it afterwards.


text:
Q: Adding a virtual NIC in centos 7 not working on the cloud How can I add a virtual NIC with a specific MAC address on a cloud server?
I recently acquired a cloud based service with Centos 7 in it.
I have an application that runs on a specific MAC address only.
How can I clone this MAC address or add another virtual NIC with this MAC address?
I tried adding a virtual NIC like eth0:1 , it got added fine, but the MAC address is the same as eth0, however I need a different MAC address.

A: If you don't need to route any traffic over it, you could use the dummy interface
eg before:
$ ip link
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT qlen 1000
    link/ether 52:54:00:0c:d8:88 brd ff:ff:ff:ff:ff:ff

Now we use the dummy module, and get a new interface:
$ sudo modprobe dummy
$ sudo ip link set dummy0 address 10:20:30:40:50:60
$ ip link show dummy0
3: dummy0: <BROADCAST,NOARP> mtu 1500 qdisc noop state DOWN mode DEFAULT
    link/ether 10:20:30:40:50:60 brd ff:ff:ff:ff:ff:ff

This has created an interface called dummy0 with the MAC address we requested.
Another option could be to create a tap device:
$ sudo ip tuntap add dev tap0 mode tap
$ sudo ip link set tap0 address 10:20:30:40:50:61
$ ip link show tap0
4: tap0: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN mode DEFAULT qlen 500
    link/ether 10:20:30:40:50:61 brd ff:ff:ff:ff:ff:ff

With tap devices you can call it any name you like, even cheat and call it eth1.


text:
Q: SUM of products prices by cateogry as columns in MySQL I have 3 tables, customers, products, categories as follow :
customers :
id      last_name
-----------------
100     Terry
200     molly
300     John

products :
id  name        description     price   category_id     customer_id
-------------------------------------------------------------------
1   product1    lorem ipsum     150     10              100
2   product2    lorem ipsum     100     10              100
3   product3    lorem ipsum     300     20              200

categories :
id  name
---------
10  bags
20  toys
30  phones

The desired result :
customerID  customerLastName    bags    toys    phones
100         Terry               250     0       0
200         Molly               0       300     0
300         John                0       0       0

The desired result as you can see is the SUM of the products prices by category. so for the first customer, he only has products related to the category bags, so we should have a bags column with the SUM of the products price which is (100 for product1 and 150 for product2, which is 250 in total).
And if the customer doesn't have any product in a category, the value should be 0 in that category column.
I have tried this :
select
customers.id as customerID,
customers.last_name as customerLastName,
SUM(CASE WHEN products.category_id = 10 THEN 1 ELSE NULL END) AS 'bags',
SUM(CASE WHEN products.category_id = 20 THEN 1 ELSE NULL END) AS 'toys',
SUM(CASE WHEN products.category_id = 30 THEN 1 ELSE NULL END) AS 'phones'
from customers
left join products on products.customer_id = customers.id
left join categories on products.category_id = categories.id
group by customers.id

But I get this result :
customerID  customerLastName    bags    toys    phones
100         Terry               2       0       0
200         Molly               0       1       0
300         John                0       0       0

A: Change THEN 1 with THEN products.price in order to aggregate price values. Also, if you don't specify ELSE NULL, it will be by default NULL only.
select
  customers.id as customerID,
  customers.last_name as customerLastName,
  SUM(CASE WHEN products.category_id = 10 THEN products.price END) AS 'bags',
  SUM(CASE WHEN products.category_id = 20 THEN products.price END) AS 'toys',
  SUM(CASE WHEN products.category_id = 30 THEN products.price END) AS 'phones'
from customers
left join products on products.customer_id = customers.id
left join categories on products.category_id = categories.id
group by customers.id


text:
Q: Matplotlib > ValueError: 'c' argument must be a color, a sequence of colors, or a sequence of numbers, not [color list] I am trying to produce a simple scatterplot but I can't add the third column using the c argument. I don't know what's wrong:
plt.scatter(x=df['ratings'], y=df['viewership'], c=df['rating_categories'].to_list())

I am trying to encode the rating with 4 different categories based on value and I already mapped them with their specific colors in rating_categories. Rating categories is now a list:
>>> df['rating_categories'].to_list()

['orange',
 'lightgreen',
 'orange',
 'orange',
 'lightgreen',
 'orange',
 'lightgreen',
 'orange',
 'lightgreen',
 'lightgreen',
...
]

What am I doing wrong? Always getting this error:
ValueError: 'c' argument must be a color, a sequence of colors, or a sequence of numbers, not ['orange', 'lightgreen', 'orange', 'orange' ..., ]

I tried this using the color argument, too. Doesn't work.
However, the same columns work with Seaborn's scatterplot with its hue argument.

A: Use the hex color code instead of the color name.
example '#ff1500' for 'red' etc.

A: This is because c requires a 2d array I think.
https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.scatter.html
Enclosing the series object in a list worked for me with the series object being numerical. I think this should work
plt.scatter(x=df['ratings'], y=df['viewership'], c=[df['rating_categories']])


text:
Q: Find string in range and return its row number in Excel VBA I have a UserForm with a ListBox (lbxNames) of names. On the spreadsheet, I have a range of names (rngNames).
I want to find the row number of the name picked in the ListBox in the list rngNames and assign it to varRowNum. I can get the ListBox choice OK, but don't know where to go from there.

A: Solution: This worked for me.
Set TargetCell = Range("rngNames").Find(What:= ENTER_LISTBOXVALUE_HERE, _
    LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, _
    SearchDirection:=xlNext, MatchCase:= _
    False, SearchFormat:=False)
varRowNum = TargetCell.Row

In case you are looking for the relative row number within rngNames use this instead:
varRowNum = TargetCell.Row - Range("rngNames").Cells(1, 1).Row + 1

Result:
Absolute row number in worksheet:

Relative row number in rngNames:

Explanation: The .Find method will return a cell object of the first occurrence of the search term. The .Row property will give you the row number of the found cell within its worksheet. For the relative number, you can simply substract the row number of the first cell of the range (.Cells(1,1).Row) from the absolute row number.


text:
Q: initializing variables in ActiveRecord's classes How to initialize variables in ActiveRecord class?
Variables here is the variables that are outside the scope of database
such as:
class Product
  attr_accessor :used
end

I want to initially assign @used initially to false, later if some person access the product, i will change @used to true
First i thought of putting @used=false in initialize method, but it does not get called.

A: attr_accessor_with_default :used, false

Or if you want to use initialize approach you can define callback after_initialize
def after_initialize
  @used = false
end

Using attr_accessor_with_default with an object literal (e.g. attr_accessor_with_default :used, false) is unsafe to use with any mutable objects. Specifically, it means that different instances of your class will have the same object as their default value. This is sort of like trying to use a class variable (@@my_var) where you want an instance variable (@my_var). If you want to use a mutable object (e.g. a String, Array, or Hash), you must use the block syntax:
attr_accessor_with_default(:used) { Array.new }

A: Define a method called :after_initialize
class User < ActiveRecord::Base
  def after_initialize
    @used = false
  end
end

It will be called (ahem) after the initialize method
Hope this helps


text:
Q: Can individuals digitially sign Silverlight OOB apps for public release in their website name? I have read all the blog posts on digital signing and checked out GoDaddy, Thawte and a couple of others. All of these say that you need to be a registered company and have official documentation and proof on incorporation etc.
I don't have any of that - I am a Sole Trader based in Australia who runs a social network (PokerDIY.com) for poker players, and now I am releasing a free app (PokerDIY Tourney Manager) and I need to let users type whilst in fullscreen mode (it's almost ironic that I am doing all this just for this). So I am looking into digitally signing my .xap so that I can run in elevated trust whilst OOB. In legal eyes I am just a hobbyist developer.
So I have a couple of questions that I would like answered before spending $100 on a certificate that I might not be able to use:
1) Can I buy a SL code-signing certificate as an individual? (Jeff Wilcox's blog (which is the most useful I have read on this matter for developers in my situation) seems to imply that you can and the Ksoftware site (https://secure.ksoftware.net/code_signing.html) seems to imply the same. However this leads to Q2:
2) Can this be used commercially - ie. if I decide to charge for my app (it's available globally for free but I will probably have a ad-free version at some point) - can I use this individual certificate that I purchased?
3) And can I register it to PokerDIY (my domain name) which is NOT a registered company. I would rather not register it to my full real name - this would look odd to a user if it said - PokerDIY Tourney Manager- Publisher: My Name. This is probably the most important as I doing this all for the perception of being a reputable entity.
There's really not much info out there on this and I dont want to make a mistake when it comes to $100 for a year's cert! (I wont go into how annoying it is to have to pay to release a free app just so people can type in fullscreen mode ;)
Thanks!

A: Yes, you can sign as an individual and use it for any purpose, including commercial purposes, with companies such as the KSoftware - but the larger providers like Thawte will not allow just an individual to do so. I do not know the specifics for Australia however so there could be regional differences, different companies, or other restrictions specific to your situation.
Your publisher name (your actual name) will appear in the elevation dialog for the Silverlight application. So it may look less professional to some, but it will still serve a purpose of providing a code signing certificate and some level of assurance for your customers.
But understand that your name and the address you provide for verification will be present in that certificate for anyone to see (answers your 3rd question).
Authenticode signing certificates don't actually match to a site such as your domain - they only verify the code signer - so you can use it with any site.

A: A good option for you might be to self-sign your app.  This doesn't require a third party, and so no yearly fee.
You can also distribute a trusted XAP without signing it at all, but you won't be able to update it via the Silverlight updating mechanism.


text:
Q: Thymeleaf: Including Fragment With Inner HTML In Variable I want to do something like this:
<div th:insert="default_page :: entire_page">
    <p>
        Hello World
    </p>
</div>

<html th:fragment="entire_page">
    // Somehow get <p> Hello World </p> in here
</html>

In other words, I want to include the inner html of a fragment include into the actual fragment itself.
Is this possible?
EDIT
To be clear, I don't want to hardcode the 'Hello World' into a variable and then send it to the fragment. I literally want to be able to put html inside the fragment caller and have it appear in the fragment.
The idea would be that I have a body div that I just want to fill up with content on each page if that makes sense.


text:
Q: Problem with order by in MySQL subquery I'm running a query that runs in about 2 seconds when the subquery does not include the order by date_sold clause. However, when I add the order by clause, the query runs forever.
I'm confused, since it seems that I'm using a index for both queries, and as I've understood, the subquery should be able to use the index for the subquery. Any ideas where I went wrong?
EXPLAIN Select buyer_id as bid,
              (SELECT seller_id
               from sale USE INDEX(tester)
               where buyer_id = bid
               order by date_sold LIMIT 1)
         from sale where seller_id = 35514335;
+----+--------------------+-------+-------+-----------------------------------+--------+---------+-------+-------+--------------------------+
| id | select_type        | table | type  | possible_keys                     | key    | key_len | ref   | rows  | Extra                    |
+----+--------------------+-------+-------+-----------------------------------+--------+---------+-------+-------+--------------------------+
|  1 | PRIMARY            | sale  | ref   | seller_id,seller_id_index_asc,sub | sub    | 8       | const | 14933 | Using index              |
|  2 | DEPENDENT SUBQUERY | sale  | index | NULL                              | tester | 24      | NULL  |     1 | Using where; Using index |
enter code here

The table structure
| id               | int(11)    | NO   | PRI | NULL    | auto_increment |
| seller_id        | bigint(20) | NO   | MUL | NULL    |                |
| buyer_id         | bigint(20) | NO   | MUL | NULL    |                |
| date_acquired    | bigint(20) | NO   |     | NULL    |                |
| date_sold        | bigint(20) | NO   | MUL | NULL    |                |
| brand            | text       | NO   | MUL | NULL    |                |
| muncipality_code | bigint(20) | NO   | MUL | NULL    |                |
| new              | int(11)    | YES  |     | NULL    |                |
| car_regnumber    | varchar(6) | YES  |     | NULL    |                |
| gender           | varchar(1) | YES  |     | NULL    |                |

Tester index
| sale  |          1 | tester              |            1 | date_sold        | A         |       14840 |     NULL | NULL   |      | BTREE      |         |
| sale  |          1 | tester              |            2 | buyer_id         | A         |    11768564 |     NULL | NULL   |      | BTREE      |         |
| sale  |          1 | tester              |            3 | seller_id        | A         |    11768564 |     NULL | NULL   |      | BTREE      |         |

SHOW CREATE TABLE SALE
| sale  | CREATE TABLE `sale` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `seller_id` bigint(20) NOT NULL,
  `buyer_id` bigint(20) NOT NULL,
  `date_acquired` bigint(20) NOT NULL,
  `date_sold` bigint(20) NOT NULL,
  `brand` text NOT NULL,
  `muncipality_code` bigint(20) NOT NULL,
  `new` int(11) DEFAULT NULL,
  `car_regnumber` varchar(6) DEFAULT NULL,
  `gender` varchar(1) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `muncipality_code` (`muncipality_code`),
  KEY `brand` (`brand`(10)),
  KEY `seller_id` (`seller_id`),
  KEY `seller_id_index_asc` (`seller_id`),
  KEY `date_sold` (`date_sold`),
  KEY `tester` (`date_sold`,`buyer_id`,`seller_id`)
) ENGINE=MyISAM AUTO_INCREMENT=66390336 DEFAULT CHARSET=latin1 ROW_FORMAT=FIXED |

A: SUGGESTION #1 : Use a Different Index
ALTER TABLE sale ADD INDEX tester2 (seller_id,buyer_id,date_sold);

I suggest this order because seller_id in the query is a constant (35514335). That would make looking up all buyer_id values.
SUGGESTION #2 : Redesign the Query
From the looks of the query, you are retrieving first date_sold for buyer_id for seller_id 35514335.
SELECT buyer_id,MIN(date_sold) date_sold
FROM sale WHERE seller_id = 35514335
GROUP BY buyer_id;

If seller_id 35514335 has buyers who purchased from other sellers as well, then do this:
SET @given_seller_id = 35514335;
SELECT DISTINCT A.buyer_id,B.seller_id FROM
(
    SELECT buyer_id,MIN(date_sold) date_sold
    FROM sale WHERE seller_id = @given_seller_id
    GROUP BY buyer_id
) A LEFT JOIN sale B USING (buyer_id);

If you do not want to include seller_id 35514335 in the output, then do this:
SET @given_seller_id = 35514335;
SELECT DISTINCT A.buyer_id,B.seller_id FROM
(
    SELECT buyer_id,MIN(date_sold) date_sold
    FROM sale WHERE seller_id = @given_seller_id
    GROUP BY buyer_id
) A LEFT JOIN sale B USING (buyer_id)
WHERE B.seller_id <> @given_seller_id;

Give it a Try !!!

A: As per @Thomas Jones-Low advice, you can try adding two indexes:
ALTER TABLE sale
  ADD INDEX suggested_index_1
    (buyer_id, date_sold, seller_id),
  ADD INDEX suggested_index_2
    (seller_id, buyer_id) ;

And please, rewrite the query so it doesn't use this MySQL-only syntax of referencing Select aliases in places that they normally couldn't be referenced:
SELECT s.buyer_id AS bid,
      (SELECT s2.seller_id
       FROM sale AS s2
       WHERE s2.buyer_id = s.buyer_id
       ORDER BY s2.date_sold LIMIT 1)
FROM sale AS s
WHERE s.seller_id = 35514335 ;


text:
Q: SharePoint 2010 still looking for old version of solution assembly We have a SharePoint 2010 solution developed in Visual Studio, which when deployed adds an assembly to the GAC (let's say MySolution.dll, version = 1.0.0.0).
We make some changes and redeploy the updated assembly (MySolution.dll, version = 1.1.0.0). All works well, but we are getting assembly binding errors in the event log:

Event manager error:Could not load file or assembly 'MySolution, Version=1.0.0.0,
  Culture=neutral, PublicKeyToken=*' or one of its dependencies. The system cannot find
  the file specified.

The application also includes reuseable workflows created in SharePoint designer, and these are associated with content types that were originally defined in MySolution v1.0.0.0. One of the features in the solution was updated in the new version and the feature itself updated using Chris O'Brien's Feature Upgrade Kit.
We have added a binding redirect to the new version in the web.config file for the web application hosting the solution (and have done this on all servers in the farm), but the error is still being logged.
How do we ensure the latest version of the assembly is always used?

A: All the information in the .dwp (and .webpart) files including the assembly version is only a blueprint for which web part and corresponding properties to load when you select this web part from the WebPart gallary, SharePoints WebPartManager will then store these settings (possibly updated by user) in the content database. Each time the webpart page is loaded the information will be read from the content database.
So if you update the Assembly version all existing instances added to pages will try to load the old version and fail unless you've added bindingRedirects in web.config (see Web Part Versioning with assembly redirection) this is why most SharePoint developers update AssemblyFileVersion instead of AssemblyVersion


text:
Q: reload/refresh subViews - setNeedsDisplay doesnt work i have trouble with setNeedsDisplay. I have an UIView with a lot of sub UIViews, created in Inteface Builder. I have also an Button with IBAction. In this IBAction i want to redraw/reload all UIViews (or all UIElements, like UILabel, UIWebView and so on..)
I am doing this, which doesn't work for me, dont know why.. :
//redraw the UIViews
[self.view_card_0 setNeedsDisplay];
[self.view_card_1 setNeedsDisplay];
[self.view_card_stapel setNeedsDisplay];

//other UI Elements
[self.webView_0 setNeedsDisplay];
[self.webView_1 setNeedsDisplay];
[self.webView_stapel setNeedsDisplay];

[self.lblCardTitle_0 setNeedsDisplay];
[self.lblCardTitle_1 setNeedsDisplay];
[self.lblCardTitle_stapel setNeedsDisplay];

[self.img_card_0 setNeedsDisplay];
[self.img_card_1 setNeedsDisplay];
[self.img_card_stapel setNeedsDisplay];

What to do for redraw/reload/refresh all UIElements/UIViews and Subviews?
EDIT 1:
How i load the view:
detailViewController = [[DetailViewController alloc]
initWithNibName:@"DetailViewController_iPad" bundle:[NSBundle mainBundle]];

The detailviewcontroller has no viewcontroller, just uiviews, here the hierarchie:

*

*UIView
-- UIViewContainer
--- UIView0
--- UIView1
--- UIViewStapel

What i expect to do:
*I dont want to reset the UIView, i want to change the background and the content of them. *
I have in my detailview a lot of subviews (uiviews), see above hierarchie. I am displaying content in the UIViews, the content comes from coreData.
The view1 contains the current row of coreData.
The view0 contains the previous row of coreData.
The viewStapel contains the next row of coreData.
With IBAction i want to iterate the coreData rows, display the next row in current if the action is called..and so on..
In Log, the data is changed, but not displayed in the UIViews. Cause of this i need a redraw or reload or something like this, to get displayed the current data.
EDIT 2: SOLVED
I have put the code in a new method and calling this method have solved my problem.

A: Swift 2
This is a replica of Nick Lockwood's answer for some easy copy paste
let parent = self.view.superview
self.view.removeFromSuperview()
self.view = nil
parent?.addSubview(self.view)

A: Are you trying to reset your view and subviews to their default state in the nib file?
If so the approach above won't work. The only way to do that automatically is to re-load the views from the nib, but you'll need to be clearer about how you are loading the view in the first place before I can help.
If you are loading it into a view controller then the easiest way to refresh it is to remove the view controller from screen and re-create it, but you might be able to reload the view saying something like this (from within the controller):
UIView *parent = self.view.superview;
[self.view removeFromSuperview];
self.view = nil; // unloads the view
[parent addSubview:self.view]; //reloads the view from the nib

If you are loading the view directly from a nib using [[NSBundle mainBundle] loadNibNamed...] or equivalent, then best way to reload the view is just to throw it away and call that method again.

A: This might help someone, with paging within a container view. The above code gave me the idea to try this and it works.
[self.pageViewController.view removeFromSuperview];
self.pageViewController.view = nil; // unloads the view
[self performSegueWithIdentifier:@"pageViewSegue" sender:self];


text:
Q: Why aggregate rating isn't understood by google? I want google to show rich snippet with aggregate rating for the following html snippet:
http://goo.gl/IApGCs. But for some reason google doen't show aggregate rating for this snippet, but if I substitude the attribute itemtype="http://schema.org/Organization" for itemtype="http://schema.org/Restaurant" then google shows aggregate rating.
What I should to do to make google show the aggregate rating exactly with itemtype="http://schema.org/Organization"

A: Google generally does not display rich snippets for Organization rating markups, at least not at the present time.  They do, however, show the rating rich snippet for such things as hotels, restaurants, local businesses, and products.  So you can try using a different markup for your business if it's appropriate and hopefully the rich snippet will be generated.


text:
Q: Generic Web Api controller to support any model Is it possible to have a generic web api that will support any model in your project?
class BaseApiController<T> :ApiController
{
    private IRepository<T> _repository;

    // inject repository

    public virtual IEnumerable<T> GetAll()
    {
       return _repository.GetAll();
    }

    public virtual T Get(int id)
    {
       return _repositry.Get(id);
    }

    public virtual void Post(T item)
    {
       _repository.Save(item);
    }
    // etc...
}

class FooApiController : BaseApiController<Foo>
{
   //..

}

class BarApiController : BaseApiController<Bar>
{
   //..
}

Would this be a good approach?
After all, i m just repeating the CRUD methods ? Can i use this base class to do the work for me?
is this OK? would you do this? any better ideas?

A:  public class GenericApiController<TEntity> : BaseApiController
    where TEntity : class, new()
{
    [HttpGet]
    [Route("api/{Controller}/{id}")]
    public IHttpActionResult Get(int id)
    {
        try
        {
            var entity = db.Set<TEntity>().Find(id);
            if(entity==null)
            {
                return NotFound();
            }
            return Ok(entity);

        }
        catch(Exception ex)
        {
            return InternalServerError(ex);
        }
    }

    [HttpGet]
    [Route("api/{Controller}")]
    public IHttpActionResult Post(TEntity entity)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        try
        {
            var primaryKeyValue = GetPrimaryKeyValue(entity);
            var primaryKeyName = GetPrimaryKeyName(entity);
            var existing = db.Set<TEntity>().Find(primaryKeyValue);
            ReflectionHelper.Copy(entity, existing, primaryKeyName);
            db.Entry<TEntity>(existing).State = EntityState.Modified;
            db.SaveChanges();
            return Ok(entity);
        }
        catch (Exception ex)
        {
            return InternalServerError(ex);
        }
    }

    [HttpGet]
    [Route("api/{Controller}/{id}")]
    public IHttpActionResult Put(int id, TEntity entity)
    {
        try
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var existing = db.Set<TEntity>().Find(id);
            if (entity == null)
            {
                return NotFound();
            }
            ReflectionHelper.Copy(entity, existing);
            db.SaveChanges();
            return Ok(entity);
        }
        catch (Exception ex)
        {
            return InternalServerError(ex);
        }
    }

    [HttpDelete]
    [Route("api/{Controller}/{id}")]
    public IHttpActionResult Delete(int id)
    {
        try
        {
            var entity = db.Set<TEntity>().Find(id);
            if(entity==null)
            {
                return NotFound();
            }
            db.Set<TEntity>().Remove(entity);
            db.SaveChanges();
            return Ok();
        }
        catch (Exception ex)
        {
            return InternalServerError(ex);
        }
    }

    protected internal int GetPrimaryKeyValue(TEntity entity)
    {
        return ReflectionHelper.GetPrimaryKeyValue(entity);
    }

    protected internal string GetPrimaryKeyName(TEntity entity)
    {
        return ReflectionHelper.GetPrimaryKeyName(entity);
    }

    protected internal bool Exists(int id)
    {
        return db.Set<TEntity>().Find(id) != null;
    }
}

A: It's definitely possible. I've never had a reason to do that before, but if it works for your situation, it should be good.
If all of your models can be saved and retrieved in the exact same way, maybe they should just all be in the same controller instead though?

A: I did this for a small project to get something up and running to demo to a client. Once I got into specifics of business rules, validation and other considerations, I ended up having to override the CRUD methods from my base class so it didn't pan out as a long term implementation.
I ran into problems with the routing, because not everything used an ID of the same type (I was working with an existing system). Some tables had int primary keys, some had strings and others had guids.
I ended up having problems with that as well. In the end, while it seemed slick when I first did it, actually using it in a real world implementation proved to be a different matter and didn't put me any farther ahead at all.

A: Nothing wrong with this as long as you handle all the heavy lifting in your repositories. You may want to wrap/handle modelstate exceptions in your base controller.
I am actually doing something similar for a large project where users can define their own entities and APIs - ie: one user may want to have users and accounts while another may want to track cars and whatever else.  They all use the same internal controller, but they each have their own endpoints.
Not sure how useful our code is to you since we don't use generics (each object is maintained as metadata and manipulated/passed back and forth as JObject dictionaries) but here is some code to give you an idea of what we are doing and maybe provide food for thought:
[POST("{primaryEntity}", RouteName = "PostPrimary")]
public async Task<HttpResponseMessage> CreatePrimary(string primaryEntity, JObject entity)
{
   // first find out which params are necessary to accept the request based on the entity's mapped metadata type
   OperationalParams paramsForRequest = GetOperationalParams(primaryEntity, DatasetOperationalEntityIntentIntentType.POST);

   // map the passed values to the expected params and the intent that is in use
   IDictionary<string, object> objValues = MapAndValidateProperties(paramsForRequest.EntityModel, paramsForRequest.IntentModel, entity);

   // get the results back from the service and return the data to the client.
   QueryResults results = await paramsForRequest.ClientService.CreatePrimaryEntity(paramsForRequest.EntityModel, objValues, entity, paramsForRequest.IntentModel);
        return HttpResponseMessageFromQueryResults(primaryEntity, results);

}

A: If you have predefined design-time classes, like one that generated from EF model or Code First then this is too complicated for your system. This is great if you don't have predefined classes (like in my project where data entity classes are generated at run-time).
My solution (not yet correctly implemented) was to create custom IHttpControllerSelector which selects my generic controller for all requests, there i can set controller's descriptor type to concrete from generic via reflection setting generic parameter depending on request path.
Also a good starting point is http://entityrepository.codeplex.com/ (I've found this somewhere here on stackoverflow)

A: What you doing is definitely possible as others said. But for repository dependencies, you should use dependency injection. My typical controller(Api or MVC) would be as follows.
public class PatientCategoryApiController : ApiController
{

    private IEntityRepository<PatientCategory, short> m_Repository;
    public PatientCategoryApiController(IEntityRepository<PatientCategory, short> repository)
    {
        if (repository == null)
            throw new ArgumentNullException("entitiesContext is null");

        m_Repository = repository;
    }
}

This is the typical constructor injection pattern. You need to have a sound understanding of DI and containers like NInject or Autofac. If you dont know DI, then you have a long road ahead. But this is an excellent approach. Take a look at this book. https://www.manning.com/books/dependency-injection-in-dot-net


text:
Q: Extension not working on the Server. Magento 2 I created a simple extension to just add an extra Radio Button in checkout. my code is

CheckoutJazz/Radio/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'CheckoutJazz_Radio',
    __DIR__
);

CheckoutJazz/Radio/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="CheckoutJazz_Radio" setup_version="1.0.0" />
</config>

CheckoutJazz/Radio/view/frontend/layout/checkout_index_index.xml

<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="checkout" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

        <referenceBlock name="checkout.root">
            <arguments>
                <argument name="jsLayout" xsi:type="array">
                    <item name="components" xsi:type="array">
                        <item name="checkout" xsi:type="array">
                            <item name="children" xsi:type="array">
                                <item name="steps" xsi:type="array">
                                    <item name="children" xsi:type="array">
                                        <item name="billing-step" xsi:type="array">
                                            <item name="children" xsi:type="array">
                                                <item name="payment" xsi:type="array">
                                                    <item name="children" xsi:type="array">
                                                        <item name="payments-list" xsi:type="array">
                                                            <item name="component" xsi:type="string">CheckoutJazz_Radio/js/view/payment/list</item>
                                                        </item>
                                                    </item>
                                                </item>
                                            </item>
                                        </item>
                                    </item>
                                </item>
                            </item>
                        </item>
                    </item>
                </argument>
            </arguments>
        </referenceBlock>

</page>

CheckoutJazz/Radio/view/frontend/web/js/view/payment/list.js

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

define([
    'jquery',
    'underscore',
    'ko',
    'mageUtils',
    'uiComponent',
    'Magento_Checkout/js/model/payment/method-list',
    'Magento_Checkout/js/model/payment/renderer-list',
    'uiLayout',
    'Magento_Checkout/js/model/checkout-data-resolver',
    'mage/translate',
    'uiRegistry'
], function ($, _, ko, utils, Component, paymentMethods, rendererList, layout, checkoutDataResolver, $t, registry) {
    'use strict';

    return Component.extend({
        defaults: {
            template: 'CheckoutJazz_Radio/payment-methods/list',
            visible: paymentMethods().length > 0,
            configDefaultGroup: {
                name: 'methodGroup',
                component: 'Magento_Checkout/js/model/payment/method-group'
            },
            paymentGroupsList: [],
            defaultGroupTitle: $t('Select a new payment method')
        },

        // The below function is added by Asad
        show_hide_fun: function(){

             if( $("#show_hide_jazz").attr('checked') ) {
                $("#custom_jazz_s").show();
                $("#custom_jazz_m").show();
                // $("#custom_jazz_c").show();
                $("#myJazz").hide();
            } else {
                $("#custom_jazz_s").hide();
                $("#custom_jazz_m").hide();
                // $("#custom_jazz_c").hide();
            }
         },

        /**
         * Initialize view.
         *
         * @returns {Component} Chainable.
         */
        initialize: function () {
            this._super().initDefaulGroup().initChildren();
            paymentMethods.subscribe(
                function (changes) {
                    checkoutDataResolver.resolvePaymentMethod();
                    //remove renderer for "deleted" payment methods
                    _.each(changes, function (change) {
                        if (change.status === 'deleted') {
                            this.removeRenderer(change.value.method);
                        }
                    }, this);
                    //add renderer for "added" payment methods
                    _.each(changes, function (change) {
                        if (change.status === 'added') {
                            this.createRenderer(change.value);
                        }
                    }, this);
                }, this, 'arrayChange');

            return this;
        },

        /** @inheritdoc */
        initObservable: function () {
            this._super().
                observe(['paymentGroupsList']);

            return this;
        },

        /**
         * Creates default group
         *
         * @returns {Component} Chainable.
         */
        initDefaulGroup: function () {
            layout([
                this.configDefaultGroup
            ]);

            return this;
        },

        /**
         * Create renders for child payment methods.
         *
         * @returns {Component} Chainable.
         */
        initChildren: function () {
            var self = this;

            _.each(paymentMethods(), function (paymentMethodData) {
                self.createRenderer(paymentMethodData);
            });

            return this;
        },

        /**
         * @returns
         */
        createComponent: function (payment) {
            var rendererTemplate,
                rendererComponent,
                templateData;

            templateData = {
                parentName: this.name,
                name: payment.name
            };
            rendererTemplate = {
                parent: '${ $.$data.parentName }',
                name: '${ $.$data.name }',
                displayArea: payment.displayArea,
                component: payment.component
            };
            rendererComponent = utils.template(rendererTemplate, templateData);
            utils.extend(rendererComponent, {
                item: payment.item,
                config: payment.config
            });

            return rendererComponent;
        },

        /**
         * Create renderer.
         *
         * @param {Object} paymentMethodData
         */
        createRenderer: function (paymentMethodData) {
            var isRendererForMethod = false,
                currentGroup;

            registry.get(this.configDefaultGroup.name, function (defaultGroup) {
                _.each(rendererList(), function (renderer) {

                    if (renderer.hasOwnProperty('typeComparatorCallback') &&
                        typeof renderer.typeComparatorCallback == 'function'
                    ) {
                        isRendererForMethod = renderer.typeComparatorCallback(renderer.type, paymentMethodData.method);
                    } else {
                        isRendererForMethod = renderer.type === paymentMethodData.method;
                    }

                    if (isRendererForMethod) {
                        currentGroup = renderer.group ? renderer.group : defaultGroup;

                        this.collectPaymentGroups(currentGroup);

                        layout([
                            this.createComponent(
                                {
                                    config: renderer.config,
                                    component: renderer.component,
                                    name: renderer.type,
                                    method: paymentMethodData.method,
                                    item: paymentMethodData,
                                    displayArea: currentGroup.displayArea
                                }
                            )]);
                    }
                }.bind(this));
            }.bind(this));
        },

        /**
         * Collects unique groups of available payment methods
         *
         * @param {Object} group
         */
        collectPaymentGroups: function (group) {
            var groupsList = this.paymentGroupsList(),
                isGroupExists = _.some(groupsList, function (existsGroup) {
                    return existsGroup.alias === group.alias;
                });

            if (!isGroupExists) {
                groupsList.push(group);
                groupsList = _.sortBy(groupsList, function (existsGroup) {
                    return existsGroup.sortOrder;
                });
                this.paymentGroupsList(groupsList);
            }
        },

        /**
         * Returns payment group title
         *
         * @param {Object} group
         * @returns {String}
         */
        getGroupTitle: function (group) {
            var title = group().title;

            if (group().isDefault() && this.paymentGroupsList().length > 1) {
                title = this.defaultGroupTitle;
            }

            return title + ':';
        },

        /**
         * Checks if at least one payment method available
         *
         * @returns {String}
         */
        isPaymentMethodsAvailable: function () {
            return _.some(this.paymentGroupsList(), function (group) {
                return this.getRegion(group.displayArea)().length;
            }, this);
        },

        /**
         * Remove view renderer.
         *
         * @param {String} paymentMethodCode
         */
        removeRenderer: function (paymentMethodCode) {
            var items;

            _.each(this.paymentGroupsList(), function (group) {
                items = this.getRegion(group.displayArea);

                _.find(items(), function (value) {
                    if (value.item.method.indexOf(paymentMethodCode) === 0) {
                        value.disposeSubscriptions();
                        value.destroy();
                    }
                });
            }, this);
        }
    });
});

CheckoutJazz/Radio/view/frontend/web/template/payment-methods/list.html

Asad Testing

        <input type="radio" name="payment[method]" id="show_hide_jazz" data-bind="event: { change: show_hide_fun }">

    <each args="data: getRegion($group().displayArea), as: 'method'" render=""/>

now this extension works perfectly on my localhost but when I tried to run this extension on server then it do not run on checkout page the core file runs.
Note: on server I disabled all the extensions but still this extension do not run.

A: After uploading your files, have you run the following on your server:
php bin/magento setup:upgrade

php bin/magento setup:static-content:deploy

A: sometimes adding a component to checkout requires

php bin/magento setup:di:compile

and make sure you are in a developer mode and empty browser cache

A: Run the cache that are on server, for example :
sudo service php-fpm restart
sudo service varnish restart


text:
Q: Shell script user switch I am running a simple shell script which creates a user and then switches to it so that I can run a bunch of commands as the new user. The script below is ran as the root on a Debian 9 (Stretch) amd64 host and is not showing what I would expect. This is just a test script for me to see what's going on.
#!/bin/sh
adduser karl --gecos "First Last, RoomNumber, WorkPhone, HomePhone" --disabled-password
adduser karl sudo
echo 'karl:password123' | chpasswd
echo 'karl ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers.d/karl

echo
sudo su - karl
whoami # prints root?
echo

echo
sudo -u karl /usr/bin/whoami # prints karl
echo

exit 0