text:
Q: Python 3 - Unable to increment global variable inside function I got problem in a technical assessment. The base code(already written) looks someting like this.
count=0

def findthesum(a,n):
    global count
    sum=0

    '''
    write your code here
    '''

    return sum

def main():
    global count
    n=5
    a=[1,2,3,4,5]
    print(count)
    print(findthesum(a,n))

main()

I have to write my logic at specified position inside the code. My code looked something like this.
count=0

def findthesum(a,n):
    global count
    sum=0
    l=[]
    for i in range(31):
        l.append(2**i)

    for j in range(n):
        if(a[j] in l):
            count=count+1
            sum=sum+a[j]
    return sum

def main():
    global count
    n=5
    a=[1,2,3,4,5]
    print(count)
    print(findthesum(a,n))

main()

I was unable to increment the value of value of count variable even after declaring it global.
What the issue with this and how to fix this?

A: count=0

def findthesum(a,n):
    global count
    sum=0

    for i in range(n):
        sum+=a[i]
        count+=1
        print(count, end= '')

    print(f'  The sum is: ' + str(sum))

def main():
    global count
    n=5
    a=[1,2,3,4,5]
    print(count)
    print(findthesum(a,n))

main()

--> '12345  The sum is: 15'

A: Are You trying to sum all the element? If yes, then:
count=0
a=[1,2,3,4,5]
n=5
def counting(li, le):
    for i in range(le):
        try:
            count+=li[i-1]
    except:
        pass
    else:
        pass
    return count
counting(a, n)


text:
Q: What does "here goes nothing" mean? I regularly hear  the phrase "here goes nothing". For example when someone starts up a computer after doing stupid configuration and is not sure if it will start.
But I'm not sure about what it means, or when to use this sentence. Should I use it just before doing something stupid or when I'm uncertain while doing it?

A: Generally speaking, you say it before you attempt something risky, dangerous, something you are very likely to fail at.
It means roughly "I'm sure nothing good will come of it, but I'm going to do it anyway".

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to run write adb command result on host system not an emulator from python script The following command works fine when I run it through Terminal.
adb -s 192.168.100.101:5555 shell tcpdump -nnvvettU -s 0 -i eth1 > dump.txt

But when I try to run it from python script it try to write on emulator which fails as follow:
#Python script:
cmd_str = "adb -s 192.168.100.101:5555 shell tcpdump -nnvvettU -s 0 -i eth1 > dump.txt"
cmd = cmd_str.split()
call(cmd)

#Error:
/system/bin/sh: can't create dump.txt: Read-only file system

so how can I write the file on the host system not an emulator in python script?


text:
Q: How to bind collections with same type on same level in TreeView WPF I want to display the following collection in a Treeview
 private ObservableCollection<SectionHeader> _sections;
 public ObservableCollection<SectionHeader> Sections
 {
     get { return _sections ?? (_sections = new ObservableCollection<SectionHeader>()); }
     set { _sections = value; NotifyOfPropertyChange(() => Sections); }
 }

Here is how SectionHeader and nested types look like
 public class SectionHeader
{
    public string ID { get; set; }
    public string Name { get; set; }
    private ObservableCollection<SectionItem> _items;
    public ObservableCollection<SectionItem> Items { get { return _items ?? (_items = new ObservableCollection<SectionItem>()); } }
}

public class SectionItem
{
    public string Title { get; set; }
    public int ID { get; set; }

    private ObservableCollection<ProductCalculatorTemplate> _products;
    public ObservableCollection<ProductCalculatorTemplate> Products { get { return _products ?? (_products = new ObservableCollection<ProductCalculatorTemplate>()); } }

    private ObservableCollection<ProductCalculatorTemplate> _productsOptionTwo;
    public ObservableCollection<ProductCalculatorTemplate> ProductsOptionTwo { get { return _productsOptionTwo ?? (_productsOptionTwo = new ObservableCollection<ProductCalculatorTemplate>()); } }
}

public class ProductCalculatorTemplate
{
    public string Product { get; set; }
    public double NoOfCoats { get; set; }
    public double PackSize { get; set; }
}

And here is how my XAML code for TreeView looks like
<TreeView ItemsSource="{Binding Sections}" Background="GhostWhite">
            <TreeView.Resources>
                <HierarchicalDataTemplate DataType= "{x:Type ViewModels:SectionHeader}" ItemsSource = "{Binding Path=Items}">
                    <StackPanel Orientation="Horizontal" Tag="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}">
                        <TextBlock Text="{Binding Name}"/>
                    </StackPanel>
                </HierarchicalDataTemplate>

                <HierarchicalDataTemplate  DataType = "{x:Type ViewModels:SectionItem}" ItemsSource = "{Binding Path=Products}">
                    <StackPanel Orientation="Horizontal" Tag="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}">
                        <TextBlock Text="{Binding Title}"/>
                    </StackPanel>
                    <HierarchicalDataTemplate.ItemTemplate>
                        <DataTemplate DataType = "{x:Type ViewModels:ProductCalculatorTemplate}" >
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Text="{Binding Product}"/>
                            </StackPanel>
                        </DataTemplate>
                    </HierarchicalDataTemplate.ItemTemplate>
                </HierarchicalDataTemplate>
            </TreeView.Resources>
 </TreeView>

This is the output of the above code

But I want to display the information in a way that below Fenomastic there appears a child node named "Option 1" which should list down all Prdoucts and 2nd child of Fenomastic should be "Option 2" which should list down all ProductsOptionTwo member of SectionItem.

A: Using only the basic tree view in WPF the simplest option would be to introduce an Options Collection, that would contain Option 1 and Option 2 as items i.e.:
public class SectionItem
{
    public string Title { get; set; }
    public int ID { get; set; }

    private ObservableCollection<Option> _options;
    public ObservableCollection<Option> Options
    {
        get { return _options ?? (_options = new ObservableCollection<Option>()); }
    }
}

public class Option
{
    public string Name { get; set; }
    public ObservableCollection<ProductCalculatorTemplate> Products
    {
        get { return _products ?? (_products = new ObservableCollection<ProductCalculatorTemplate>()); }
    }
}

And adding another HierarchicalDataTemplate for the Option type
As the TreeView otherwise isn't suitable for listing a nonvariable amount of properties like your ProductsOption and ProductsOptionTwo properties are.


text:
Q: Select only unique, sequential rows in TSQL There have been a couple of previous questions (1 & 2) that are quite close to what I'm trying to do, but haven't been able to tease the answer out.
In my case, I have data that may contain multiple sequential duplicates, so starting from where Martin did:
e.g.
id      companyName
-------------------
1       dogs ltd
2       cats ltd
3       pigs ltd
4       pigs ltd
5       pigs ltd
6       cats ltd
7       cats ltd
8       dogs ltd
9       pigs ltd

I want to return
companyName
-----------
dogs ltd
cats ltd
pigs ltd
cats ltd
dogs ltd
pigs ltd

eliminating the sequential duplicates, but keeping the unique values in order. In all the previous questions, using the lead and lag functions, that would only look one ahead or behind, not allowing for 3 or more duplicated sequential values.

A: This will do it:
SELECT companyName
FROM
    (
        SELECT
            id
            , companyName
            , LEAD(companyName, 1, NULL) OVER (ORDER BY id) lead
        FROM yourTable
    ) Q
WHERE
    companyName <> lead
    OR lead IS NULL
ORDER BY id


text:
Q: Move one test resource to somewhere on disk in Maven I have a test resource that lives in resources/src/test/dir/sample.json, and it needs to move to /tmp/data/sample.json before unit tests can run.  I want to use Maven to automate moving this file, without interfering with other test resources that need to move to target. The reason for this is that in production this file comes from outside the jar.
Looking at Maven's resource:testResources goal here and also the plugin. I'm not sure where to specify the outputDirectory, especially without interfering with anything else.
Will post more as I research, but I'm particularly afraid there's going to be several ways to do this and it's not going to be obvious which is the most conventional.

A: Assuming you are packaging jar, you would have resources:testResources in your process-test-resources life cycle. You would need the default execution which copies test resources as usual and the extra execution to copy the specific resource to specific output directory.
<project>
  ...
  <build>
    <plugins>
      <plugin>
        <artifactId>resources</artifactId>
        <version>1.0</version>
        <executions>
          <execution>
            <id>execution1</id>
            <phase>process-test-resources</phase>
            <goals>
              <goal>testResources</goal>
            </goals>
          </execution>
          <execution>
            <id>execution2</id>
            <phase>process-test-resources</phase>
            <configuration>
              <outputDirectory>
                 ...
              </outputDirectory>
              <resources>
                 ...
              </resources>
            </configuration>
            <goals>
              <goal>testResources</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
  ...
</project>

See also


text:
Q: How can i preserve wordpress database encoding after using wp-cli search-replace with --export flag? I need to migrate a wordpress database to another server but first i need to change all old url's, stored inside any table, to new ones. To do that, i'm using wp-cli search-replace function with --export flag.
Everything regarding the search-replace method is working good except the encoding of all text of the entire dump. Is there any way to preserve the initial encoded text on the export process ? Like --default-character-set=utf8mb4 or something ?
Heres an example of the messy encode:

ATEN├ö├Â┬úÔö£┬║├ö├Â┬úÔö£├│O – Gestores de Acesso dos sistemas Ôö£├ÂÔö£├ºÔö£Ôöñ Mudan├ö├Â┬úÔö¼Ôòæas no Sistema de Gerenciamento e Permiss├ö├Â┬úÔö£├╝es Ôö£├ÂÔö£├ºÔö£Ôöñ (O n├ö├Â┬úÔö£Ôòæo sofrer├ö├Â┬úÔö£┬í essa altera├ö├Â┬úÔö¼Ôòæ├ö├Â┬úÔö£Ôòæo)

Thanks in advance.


text:
Q: How to retrieve the full dictionary in C# I have created a dictionary in Class A and would like to return the entire list (Key, Value) in class B. Are there any suggestions on how can I do this? I have tried a number of things from the internet but nothing seems to be working. I am trying to write a method in class A to retrieve the entire dictionary.
public class_A
{
  public static Dictionary<string, string> Dict_1 = new Dictionary();
  public add_dict(string name, string add)
  {
     Dict_1.Add(name, add);
  }

  public dict return_dictionary()
  {
    return (Dict_1); // I want to have a proper code to return this dictionary.
  }
}

A: If this dictionary is a private member in your class. You can access this Dictionary by an encapuslated method.
public class A
{
    private Dictionary<string, int> _items { set;get;}
    public Dictionary<string, int> GetItems()
    {
        return _items
    }
}

and in class B, Create an object and access it
A objA = new A();
Dictionary<string, int> thatItems=objA.GetItems();

EDIT : As per the edit in the question
You have some propblems in your code.
You can not write a class like this public class_A. It should be public class A
Your Dictionary declaration should be like this
public static Dictionary<string, string> Dict_1 = new Dictionary<string, string>();

Your add_dict method needs a return type. ( I am just adding void, you can have a bool or whatever you wish)
public void add_dict(string name, string add)
{
    Dict_1.Add(name, add);
}

Your method return type should be Dictionary<string, string>. They you are good.
public Dictionary<string, string> return_dictionary()
{
    return Dict_1;
}

But look into your code, Your Dict_1  property is a public property. So you another class dont even need your return_dictionary method to get the data. It can simply access the data like
A objA = new A();
Dictionary<string, string> stolenData = objA.Dict_1;

So Encapsulation concept is broken !
Better you should keep your member as private like this. I just changed your method names and variable names to follow some coding/naming conventions for better readability.
public class A
{
    private Dictionary<string, string> _dict = new Dictionary<string, string>();
    public void Add_dict(string name, string add)
    {
        _dict.Add(name, add);
    }
    public Dictionary<string, string> Return_dictionary()
    {
        return _dict;
    }
}

This is a good reading to understand Encapsulation http://www.csharp-station.com/Tutorials/lesson19.aspx


text:
Q: How to read data passed in routed url in component angular I am new to angular 2+, and trying to learn.
I have a routes in angular like
const routes: Routes = [{path:"home",component:HomeComponent},
                        {path:"designer",component:DesignerComponent},
                        {path:"designer/:id",component:DesignerComponent}];

Once I reach on the DesignerComponent using the path designer/:id, I want to fetch the value "id". How can I do that? I am using latest version of angular.

A: You need to add ActivatedRoute and inside will have snapshot.paramMap you will get the parameter which you have passed.
import {ActivatedRoute} from '@angular/router';
import {OnInit} from '@angular/core';

private userId = '';
constructor(private route: ActivatedRoute){

}

ngOnInit() {
   this.userId = this.route.snapshot.paramMap.get('id');
}

OR
ActivatedRoute.paramMap property is an Observable map of route parameters. The paramMap emits a new map of values that includes id when the user navigates to the component. In ngOnInit you subscribe to those values and set the ID.
ngOnInit() {
  this.route.paramMap.pipe(
   switchMap(params => {
     // (+) before `params.get()` turns the string into a number
     this.userId = +params.get('id');
   })
 );
}

A: You can do it in two way first is
constructor(private route: ActivatedRoute){
  this.userId=this.route.params.snapshot['id']
}

Other way you can subscribe to params like
constructor(private route: ActivatedRoute){
      this.route.params.subscribe(data=>this.userId=data['id']
 })
    }

Go with second approach if your param can change while you are on the same root

A: It is better to subscribe to the route, so you get the values everytime the /:id changes.
Add this code in the constructor of DesignerComponentclass:
constructor(private route: ActivatedRoute){
    this.route.params.subscribe(data => this.userId = data['id'])
});


text:
Q: C# bound textbox will not update using tableadapter update I am having problems getting a dataset to update changes to a database.
I start by filling a dataset using a FillBy query that I created on a table adapter.
"SELECT * FROM tblTest WHERE testID = (testID = @testId)
That will return a single record. I want to bind each column of the dataset.datatable to its own textbox on the form.
textBox1.DataBindings.Add("Text", dataset.datatable, dataset.datatable.NameColumn.ToString());

This loads the data fine. I make some changes to the data in the textbox. Then when I use the tableadapter.Update(dataset) to update the changes to the database, it does not update the record.
If I populate a datagrid with this dataset, make changes, and then run the tableadapter.update(dataset), it will update the record.
How can I use the tableadapter.update() without using the datagrid? Do I have to write a custom update for the tableadapter?

A: I did find out why the database was not updating. I checked the row state of the changed row and it was still in a "unmodified" state.
I changed the binding setup and created a new bindingsource with the datasource set as the dataset. and the datamember set as dataset.datatable. Then bound the control to a column in that bindingsource.
Before running the tableadapter.update(dataset) the following line is needed so that the row state changes
this.BindingSource.EndEdit();

Everything then updated properly


text:
Q: When I zoom in the browser, the document.body.clientWidth changed Suppose I adjust my browser window to 1000px, then I print the viewport width:
 document.body.clientWidth // 1000

then I zoom in my browser, which set it as 150% larger, then I print the viewport width again:
document.body.clientWidth // 667

Why it become narrow? What's more important is how the number 667 computed out? It seems narrow 1/3;

A: Isn't it 1000/150*100?
The size of browser window (the browser viewport, NOT including toolbars and scrollbars).
ClientWith only works in IE5-8 by the way. You could you use window.innerWidth for other modern browsers and above IE8


text:
Q: Android - Fitting 6 ImageButtons to layout I've been having a huge problem with fitting 6 image buttons to one screen.
I have tried Intellij and ADT but came up with nothing. I've also used two methods and played around them. One of them was inserting linear layouts to relative layout and inserting the image buttons inside them. This seemed well in the first place, however, i got bad results on big screens. The other method was to use regular alignment methods in xml but this gave me a lot worse results and I'm really stuck right now. I think I'm going to go with the first method but I want to get a good result since this is my senior project. You can find the two methods below. Can you help me what I'm doing wrong? Thank you very much.
---EDIT---
My intent is 3 lines, 2 buttons at each line. And screenshots are below. I have nexus 7 2013 and galaxy s2, and the results are similar to the ones below, so I assume the results below are correct.
This is the picture for 1st method:

This is the picture for 2nd method:

---END OF EDIT---
First method (inserting image buttons to 3 linear layouts in relative layout):
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginBottom="390dp"
        android:layout_alignParentBottom="true" android:layout_alignParentStart="true">

    <ImageButton
        android:id="@+id/apuButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:src="@drawable/apu"
        android:scaleType="fitCenter"
        />
    <ImageButton
        android:id="@+id/lmsButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:src="@drawable/lms"
        android:scaleType="fitCenter"
        />

</LinearLayout>

<LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentTop="true" android:layout_alignParentStart="true"
        android:layout_marginTop="140dp" android:layout_marginBottom="255dp" android:id="@+id/linearLayout">

    <ImageButton
        android:id="@+id/mailButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:src="@drawable/mail"
        android:scaleType="fitCenter"/>

    <ImageButton
            android:id="@+id/scaButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:src="@drawable/sca"
            android:scaleType="fitCenter"/>

</LinearLayout>
<LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginTop="119dp" android:layout_alignTop="@+id/linearLayout"
        android:layout_alignParentStart="true" android:layout_marginBottom="140dp" android:id="@+id/linearLayout2">

    <ImageButton
            android:id="@+id/libraryButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:src="@drawable/library"
            android:scaleType="fitCenter"/>

    <ImageButton
            android:id="@+id/ratingButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:src="@drawable/rating"
            android:scaleType="fitCenter"/>

</LinearLayout>
<LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignTop="@+id/linearLayout2" android:layout_alignParentEnd="true"
        android:layout_marginTop="127dp">
</LinearLayout>

Second method (using alignments):
<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
<ImageButton
        android:id="@+id/apuButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:src="@drawable/apu"
        android:scaleType="fitCenter"

        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true" />
<ImageButton
        android:id="@+id/lmsButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:src="@drawable/lms"

        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true" />

<ImageButton
        android:id="@+id/mailButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:src="@drawable/mail"
        android:scaleType="fitCenter"

        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        />

<ImageButton
        android:id="@+id/scaButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:src="@drawable/sca"
        android:scaleType="fitCenter"

        android:layout_alignParentRight="true"
        android:layout_centerVertical="true" />

<ImageButton
        android:id="@+id/libraryButton"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"

        android:src="@drawable/library"
        android:scaleType="fitCenter"

        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        />
<ImageButton
        android:id="@+id/ratingButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:src="@drawable/rating"
        android:scaleType="fitCenter"

        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        />

A: Check out this code, please comment if it works
 <LinearLayout
    android:id="@+id/grd_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="33"
        android:orientation="horizontal" >

        <ImageButton
            android:id="@+id/apuButton"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.5"
            android:scaleType="fitCenter"
            android:src="@drawable/ic_launcher" />

        <ImageButton
            android:id="@+id/lmsButton"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.5"
            android:scaleType="fitCenter"
            android:src="@drawable/ic_launcher" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="33"
        android:orientation="horizontal" >

        <ImageButton
            android:id="@+id/mailButton"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.5"
            android:scaleType="fitCenter"
            android:src="@drawable/ic_launcher" />

        <ImageButton
            android:id="@+id/scaButton"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.5"
            android:scaleType="fitCenter"
            android:src="@drawable/ic_launcher" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="33"
        android:orientation="horizontal" >

        <ImageButton
            android:id="@+id/libraryButton"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.5"
            android:scaleType="fitCenter"
            android:src="@drawable/ic_launcher" />

        <ImageButton
            android:id="@+id/ratingButton"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.5"
            android:scaleType="fitCenter"
            android:src="@drawable/ic_launcher" />
    </LinearLayout>
</LinearLayout>

A: // Try this way,hope this will help you to solve your problem...

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <ImageButton
            android:id="@+id/apuButton"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:src="@drawable/ic_launcher"
            android:scaleType="fitXY" />
        <ImageButton
            android:id="@+id/lmsButton"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:src="@drawable/ic_launcher"
            android:scaleType="fitXY"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <ImageButton
            android:id="@+id/mailButton"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:src="@drawable/ic_launcher"
            android:scaleType="fitXY"/>

        <ImageButton
            android:id="@+id/scaButton"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:src="@drawable/ic_launcher"
            android:scaleType="fitXY"/>

    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <ImageButton
            android:id="@+id/libraryButton"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:src="@drawable/ic_launcher"
            android:scaleType="fitXY"/>

        <ImageButton
            android:id="@+id/ratingButton"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:src="@drawable/ic_launcher"
            android:scaleType="fitXY"/>

    </LinearLayout>
</LinearLayout>

A: You'll want to use your first method with linear layouts and add in weights so that it doesn't become separated out like that.  Here is the modified code of yours that should fix that issue (you'll want to create bigger images for each device so that it comes out looking a bit cleaner too).
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.test.MainActivity$PlaceholderFragment" >

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:layout_alignParentStart="true"
    android:layout_weight="1"
    android:orientation="horizontal" >

    <ImageButton
        android:id="@+id/apuButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="fitCenter"
        android:src="@drawable/apu" />

    <ImageButton
        android:id="@+id/lmsButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="fitCenter"
        android:src="@drawable/lms" />
</LinearLayout>

<LinearLayout
    android:id="@+id/linearLayout"
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:layout_alignParentStart="true"
    android:layout_weight="1"
    android:orientation="horizontal" >

    <ImageButton
        android:id="@+id/mailButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="fitCenter"
        android:src="@drawable/mail" />

    <ImageButton
        android:id="@+id/scaButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="fitCenter"
        android:src="@drawable/sca" />
</LinearLayout>

<LinearLayout
    android:id="@+id/linearLayout2"
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:layout_alignParentStart="true"
    android:layout_weight="1"
    android:orientation="horizontal" >

    <ImageButton
        android:id="@+id/libraryButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="fitCenter"
        android:src="@drawable/library" />

    <ImageButton
        android:id="@+id/ratingButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="fitCenter"
        android:src="@drawable/rating" />
</LinearLayout>

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:layout_alignParentEnd="true"
    android:layout_marginTop="127dp"
    android:layout_weight="1"
    android:orientation="horizontal" >
</LinearLayout>


text:
Q: trying to make IOS standard ui to be in my language Im writing A none en App and i want my standard ui to be in my language, buttons like "edit", "Done" and so on can any boddy help?

A: In your info.plist file set Localization native development region to your language


text:
Q: VIPTELA SDWAN API call issue Need your expert advise on calling a API.
i was trying to build a script for calling a devices information in Viptela SDWAN. At my home lab script worked as expected, but moment i changed the URL to live office Vmanage hosted on AWS, it gives me error and script was not able to login. however via internet explorer i was able to login into Vmanage GUI.
below is the configuration and error msgs i was getting. any advise will be helpful.
Error's:
Traceback (most recent call last):
File "C:/Users/XXXXXXX/Desktop/New folder (2)/apicallproject.py", line 123, in <module>
my_login()
File "C:/Users/XXXXXXX/Desktop/New folder (2)/apicallproject.py", line 24, in my_login
response = session.post(url=login_url, data=login_credentials, verify=false)
NameError: name 'false' is not defined

Process finished with exit code 1

+++++++++++++++With Verification set to true++++++++++++++++++++++
Traceback (most recent call last):
File "C:/Users/XXXXXXX/Desktop/New folder (2)/apicallproject.py", line 123, in <module>
my_login()
File "C:/Users/XXXXXXXX/Desktop/New folder (2)/apicallproject.py", line 24, in my_login
response = session.post(url=login_url, data=login_credentials, verify=true)
NameError: name 'true' is not defined

Process finished with exit code 1

Below is the python script which is working fine at my home LAB:-
ur = input ("Enter the path to Vmanage :")

name = input("Please enter your user name:")
passw = input("Please enter your password:")

def my_login():

login_url = '%s/j_security_check'%ur
login_credentials = {'j_username': name, 'j_password': passw}

session = requests.session()

response = session.post(url=login_url, data=login_credentials, verify=false)

if b`'<html>'` in response.content:

print('Login Failed')

else:

print('Login Success')

A: Using True or False should work. Perhaps due to different python version.

A:
I made minor changes to your code and was able to run it in DevNet Sandbox Labs at version 20.4 You can try this code below in your environment.

import requests
import sys

requests.packages.urllib3.disable_warnings()

ur = input("Enter the path to Vmanage :")
name = input("Please enter your user name:")
passw = input("Please enter your password:")

def my_login():
  login_url = '%s/j_security_check' % ur
  login_credentials = {'j_username': name, 'j_password': passw}
  session = requests.session()
  response = session.post(url = login_url, data = login_credentials, verify=False)
  if b'<html>' in response.content:
    print(f"Login Failed, {response.status_code}")
    exit(0)
  else:
    print(f"Login Success, {response.status_code}")

my_login()

Enter the path to Vmanage :https://sandbox-sdwan-2.cisco.com
Please enter your user name:devnetuser
Please enter your password:RG!_Yw919_83
Login Success, 200


text:
Q: How can there be 8 pole trifasic motors? Shouldn't poles be a multiple of 6? How can there be trifasic motors with a number of poles non being a multiple of 6? I'd imagine poles in such motors would be 6 or 12 etc.

A: The magnetic fields of three phases are combined to make each pair of poles.


text:
Q: Can we have a form postback and use html controls for javascript validation of the controls? Can we have a form with method = "post" and use HTML controls and perform a javascript validation on the controls.
for ex:
<body>
<form method="post">
<div class="login">
  <input type="text" placeholder="Username" id="username">
  <input type="password" placeholder="Password" id="password">
  <input type="submit" value="Sign In">
</div>
</form>
</body>

Can we have a form like the above one and do basic validations using JS and after successful login redirect to another page.
How do I redirect to another page after successful validation?

A: You can validate the data filled in the form both in Javascript and in the backend, and I suggest you to mandatory do it in the backend. If data are valid you can then continue your work flow like redirecting to another page. Also for redirecting you can do it or in backend or in frontend.


text:
Q: Check the following hypothesis: $H_{0}: m_{1} = m_{2}$ against the alternative $H_{1}: m_{1} \ne m_{2}$ I am new in statistics and I have to solve a problem involving hypothesis testing (first of this kind for me). Any help would be much appreciated. Thank you.
The statement:
From two piles of pieces, each of them made by a different machine, has been extracted a selection of $n_{1} = 10$ pieces from the first and $n_{2} = 12$ pieces from the second. We notice the following results regarding diameter of pieces in each selection:
$$\begin{array}{c|c|c|c|}
x_{i} & 3.4 & 3.5 & 3.7 & 3.9 \\ \hline
n_{1i} & 2 & 3 & 4 & 1 \\ \hline
\end{array}$$
$$\begin{array}{c|c|c|}
x_{i} & 3.2 & 3.4 & 3.6 \\ \hline
n_{2i} & 2 & 2 & 8 \\ \hline
\end{array}$$
Where $x_{i}$ its the diameter of the piece, $n_{1i}$ it's the number of pieces from the first pile and $n_{2i}$ from the second pile.
Knowing that the diameter of the made pieces it's a normal random distributed variable, check the following hypothesis: $H_{0}: m_{1} = m_{2}$ against the alternative $H_{1}: m_{1} \ne m_{2}$

A: Comparing means of normally distributed samples is the classical job of Student's t-test. In R that would be:
one <- c(3.4, 3.4, 3.5,3.5,3.5, 3.7,3.7,3.7,3.7, 3.9)
two <- c(3.2,3.2, 3.4,3.4, 3.6,3.6,3.6,3.6,3.6,3.6,3.6,3.6)
t.test(one, two, var.equal = TRUE)

with the result
    Two Sample t-test

data:  one and two
t = 1.4484, df = 20, p-value = 0.163
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -0.04401711  0.24401711
sample estimates:
 mean of x mean of y
      3.6       3.5

This leads to the quite difficult to interpret p-value. Because that is larger then 0.05, one would usually not determine, that there is a difference.
If this was not for teaching but for real life problems, I'd consider an easier to read approach called BEST, which you can find here: http://www.sumsar.net/best_online/
but that is not what is taught to a beginner´.


text:
Q: Вставить код с помощью тернарного оператора $temp = '

'. $vname .' '. $vtype .'

    ';

Как я могу вставить код php (if($vname === "Qiwi"){echo "/wp-content/uploads/Qiwi.png"}) внутрь , с помощью тернарного оператора . .
Нашел способ вместо . использовать ;, но не сработало

A: Предварительно определите переменную, в которой вычислите название нужной картинки, а оптом вставьте в разметку.
$src = ($vname == "Qiwi") ? "Qiwi.png" :  "not-Qiwi.jpg";
$temp = "
$vname $vtype

";

Можете и прямо в разметку вставить тернарный оператор, но это будет смотреться громоздко.

не подскажете как сделать условие типа elseif

Если требуется несколько вариантов условий, то используйте switch или массив
switch($vname){
   case 'Qiwi': $src = "qiwi.jpg"; break;
   case 'Something': $src = "some_image.png"; break;
   default: $src = "image_not_found.jpg"; break;
}

либо
$images = ['Qiwi' => "qiwi.jpg", 'Something' => "some_image.png", ....];
$src = $images[$vname];

Упомянутый else-if, конечно, никто не запрещает использовать, наравне со switch.
ну или возможно, если все картинки назвать соответственно, то просто


text:
Q: Looking to merge/concatenate/groupby different rows in Pandas dataframe I will be iterating through a large list of dataframes of baseball statistics of different players. This data is indexed by year. What I am looking to do is group year while keeping salary the same and adding WAR. Also, I am looking to drop rows that are not single years. In my data set these entries are strings.
to group
for x in clean_stats_list:
    x.groupby("Year")

to eliminate rows
for x in clean_stats_list:
    for i in x['Year']:
        if len(i) > 4:
            x['Year'][i].drop()

      WAR         Year       Salary
 0    1.4         2008     $390,000
 1    0.9         2009     $418,000
 2    2.4         2010     $445,000
 3    3.6         2011   $3,400,000
 4    5.2         2012   $5,400,000
 5    1.3         2013   $7,400,000
 6    6.8         2014  $10,000,000
 7    3.8         2015  $10,000,000
 9    0.2         2015  $10,000,000
 11   5.5         2016  $15,833,333
 12   2.0         2017  $21,833,333
 13   1.3         2018  $21,833,333
 14  34.3   11 Seasons  $96,952,999
 16  25.4  CIN (8 yrs)  $37,453,000
 17   8.8  SFG (3 yrs)  $59,499,999

This is what I am expecting to achieve:
     WAR         Year       Salary
 0    1.4         2008     $390,000
 1    0.9         2009     $418,000
 2    2.4         2010     $445,000
 3    3.6         2011   $3,400,000
 4    5.2         2012   $5,400,000
 5    1.3         2013   $7,400,000
 6    6.8         2014  $10,000,000
 7    4.0         2015  $10,000,000
 11   5.5         2016  $15,833,333
 12   2.0         2017  $21,833,333
 13   1.3         2018  $21,833,333

A: To filter out based on length of column Year, why don't you try creating a mask and then select based on it.
Code:
mask_df = your_df['Year'].str.len() == 4
your_df_cleaned = your_df.loc[mask_df]

A: You can use regex for validate years for avoid filter values with length 4 and not years with Series.str.contains and boolean indexing:
#https://stackoverflow.com/a/4374209
#validate between 1000-2999
df1 = df[df['Year'].str.contains('^[12][0-9]{3}$')]
#validate between 0000-9999
#df1 = df[df['Year'].str.contains('^\d{4}$')]
print (df1)
    WAR  Year       Salary
0   1.4  2008     $390,000
1   0.9  2009     $418,000
2   2.4  2010     $445,000
3   3.6  2011   $3,400,000
4   5.2  2012   $5,400,000
5   1.3  2013   $7,400,000
6   6.8  2014  $10,000,000
7   3.8  2015  $10,000,000
9   0.2  2015  $10,000,000
11  5.5  2016  $15,833,333
12  2.0  2017  $21,833,333
13  1.3  2018  $21,833,333


text:
Q: SharePoint: Customize default NewForm.aspx and hide some fields according to given permissions My requirement is to restrict users to view/add/edit fields of a list as per their given group/permission. To achieve this objective as per my understanding I have to generate custom list forms. If anyone can help me to customize NewFrom.Aspx and code in such a way that we can check current user group/permission and hide fields which should not be accessible to him.
I have derived solution after googling and have thought to apply below thing after creating new custom list form. I want to know if this approach is good enough or give any optimal solution to it.
        var web = SPContext.Current.Web;
        web.AllowUnsafeUpdates = true;
        web.Update();
        var lists = web.Lists["SomeList"];
        var f = lists.Fields["SomeField"];
        if(){ //to check if user is in role
        f.ShowInEditForm = false;
        f.ShowInNewForm = false;
        f.Update();
        }

The same list will be used ac cross all the users so I think above solution might not be optimal.
Thanks in advance.

A: As SharePoint does not support Column level permissions, there are some third party tools available for column level permissions:

*

*Column Level Security

*SharePoint Column/View Permission
For Custom NewForm:

*

*You can develop the custom webpart for NewForm where you can display fields as per the permissions.

*Then set this webpart in place of default NewForm.aspx, so when ever user click on NewItem link of the list then rather than default sharepoint form it will open custom webpart.

*You can replace the default NewForm webpart with custom webpart with following code:

public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWeb currentWeb = (SPWeb)properties.Feature.Parent;
            try
            {
            SPLimitedWebPartManager NewForm = currentWeb.GetLimitedWebPartManager("Lists/listname1/NewForm.aspx", System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
            AddWebPart(NewForm);
            }
            catch (Exception)
            {
                throw;
            }
          }
protected void AddWebPart(SPLimitedWebPartManager MainPage)
    {
        MainPage.WebParts[0].Hidden = true;
        MainPage.SaveChanges(MainPage.WebParts[0]);
        try
        {
            var linqqry = from wp in MainPage.WebParts.Cast()
                          where wp.GetType() == typeof(Webpart1.Webpart1)
                          select wp;

        if (linqqry.Count() == 0)
        {
            //Create an instance of WPMenu Webpart and add in a Webpart zone
            Webpart1.Webpart1 wpWebPart = new Webpart1.Webpart1();
            MainPage.AddWebPart(wpWebPart, "Main", 0);
            MainPage.SaveChanges(wpWebPart);
        }
        }
        catch (Exception ex)
        {
        }
}


text:
Q: Choosing a Kernel type for arithmetic calculations From this wiki page https://help.ubuntu.com/community/UbuntuStudio/RealTimeKernel i see many type of linux kernel available for the ubuntu distro.
I use a lot of computation programs which use many arithmetic calculations. Which type do you think is the most performant in my case ?
I have an Intel i7 processor and an ubuntu 12.04 x64.

A:
I use a lot of computation programs which use many arithmetic calculations. Which type do you think is the most performant in my case ?

The low-latency or realtime kernels are NOT relevant for computation-heavy applications; their use is when instant response to events is needed --- think audio recording on one end, and the Space Shuttle on the other end. In fact, a very preemption-sensitive kernel (what all those you linked to are) can end up reducing the performance of compute-heavy programs (because of all the interrupts that are generated).
If this is a purely computational/server system which is NOT used (or rarely used) as an interactive desktop, what you want is a kernel compiled with the CONFIG_PREEMPT_NONE option, the help for which says:

Select this option if you are building a kernel for a server or scientific/computation system, or if you want to maximize the raw processing power of the kernel, irrespective of scheduling latencies.

You can also try setting a lower timer frequency than 1000 Hz (the default), but this will affect interactive performance (mouse/keyboard movements, etc.).
There are many other options you can tweak in the kernel config to incrementally improve performance for computation, but doing an overview of all of them is beyond the scope of an AskUbuntu answer :)
In short: stick with the regular kernel if you also use your computer as a desktop. The gains to be had with tweaking are usually minimal -- it's not like it will suddenly improve performance by 25%.


text:
Q: Question about a Möbius transformation/Conformal map I have a question about a conformal mapping. The map $f(z)=\frac{1+z}{1-z}$ takes the unit disk to the right half plane. Composing this map with $z^2$ gives $f(z)=(\frac{1+z}{1-z})^2$, which I think gives me the whole complex plane, except for the negative real axis. But how can I easily see (without trial and error computations) that the negative real axis will be excluded.
Thankful for any help with this!

A: If you include the boundary of the disk in your domain, then the boundary of the right half-plane will be in the image of $f$, and the negative real axis will be in the image of $z\mapsto f(z)^2$.
Your first function takes the upper half of the boundary to the upper half of the imaginary axis.  If you include the upper half of the circle, including $-1$ but excluding $1$, that maps to the upper half of the imaginary axis including $0$ but excluding $\infty$, and then squaring takes that to the negative real axis including $0$ but excluding $\infty$.


text:
Q: Moving a control by dragging it with the mouse in C# I'm trying to move the control named pictureBox1 by dragging it around. The problem is, when it moves, it keeps moving from a location to another location around the mouse, but it does follow it...
This is my code. and I would really appreciate it if you could help me
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    bool selected = false;
    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        selected = true;
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (selected == true)
        {
            pictureBox1.Location = e.Location;
        }
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        selected = false;
    }

}

A: try this to move pictureBox control at runtime using mouse
 private void pictureBox7_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                xPos = e.X;
                yPos = e.Y;
            }
        }

        private void pictureBox7_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            PictureBox p = sender as PictureBox;

            if (p != null)
            {
                if (e.Button == MouseButtons.Left)
                {
                    p.Top += (e.Y - yPos);
                    p.Left += (e.X - xPos);
                }
            }

        }

A: All you need:
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private Point MouseDownLocation;

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            MouseDownLocation = e.Location;
        }
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            pictureBox1.Left = e.X + pictureBox1.Left - MouseDownLocation.X;
            pictureBox1.Top = e.Y + pictureBox1.Top - MouseDownLocation.Y;
        }
    }

}

A: You can also use the extension:
public static class CmponentsExtensions
{
  //Management of mouse drag and drop
    #region Menu and Mouse
    private static bool mouseDown;
    private static Point lastLocation;

    /// <summary>
    /// To enable control to be moved around with mouse
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="control"></param>
    public static void moveItselfWithMouse<T>(this T control) where T: Control
    {
        control.MouseDown += (o, e)=> { mouseDown = true; lastLocation = e.Location; };
        control.MouseMove += (o, e) =>
        {
            if (mouseDown)
            {
                control.Location = new Point((control.Location.X - lastLocation.X) + e.X, (control.Location.Y - lastLocation.Y) + e.Y);
                control.Update();
            }
        };
        control.MouseUp += (o, e) => { mouseDown = false; } ;
    }

    public static void moveOtherWithMouse<T>(this T control, Control movedObject) where T : Control
    {
        control.MouseDown += (o, e) => { mouseDown = true; lastLocation = e.Location; };
        control.MouseMove += (o, e) =>
        {
            if (mouseDown)
            {
                movedObject.Location = new Point((movedObject.Location.X - lastLocation.X) + e.X, (movedObject.Location.Y - lastLocation.Y) + e.Y);
                movedObject.Update();
            }
        };
        control.MouseUp += (o, e) => { mouseDown = false; };
    }

    #endregion
}

Then you need to use it with some control:
In this case pictureBox1 moved the whole Form
pictureBox1.moveOtherWithMouse(this);

In this case you move only pictureBox:
pictureBox1.moveItselfWithMouse();


text:
Q: Order by statement - ordering by multiple columns I have table like this:
A       B       C
-----------------------
111     3
                777
333     1
555     2
                333
777     4
888     5

So, i have order by statement "order by B" and the I have result like this:
A       B       C
----------------------
333     1
555     2
111     3
777     4
888     5
                777
                333

However, what can I do to get this sorting:
A       B       C
-----------------------
333     1
                333
555     2
111     3
777     4
                777
888     5

In case when column C not null, I should put this row after row where A = C
Thanks!
So, in case of this:
with a(a,b,c) as (select 111,4, null from dual union all
                  select null,null,777 from dual union all
                  select 333,1,null  from dual union all
                  select 555,2, null from dual union all
                  select null,null, 333 from dual union all
                  select 777, 4, null from dual union all

                  select 444,null, 333 from dual union all

                  select 888, 5, null from dual union all
                  select null,null,777 from dual )

select a.*
  from a
 order by last_value(b ignore nulls)
       over (partition by CASE when b is null then c else a end order by b), b nulls last

I have that output (C 777 are after A 111, because of B values are the same = 4):
A    B     C
--------------------
333     1
444         333
            333
555     2
777     4
111     4
            777
            777
888     5

But I want to get this:
    A    B     C
    --------------------
    333     1
    444         333
                333
    555     2
    777     4
                777
                777
    111     4
    888     5

A: may be this help you :
with a(a,b,c) as (select 111,3, null from dual union all
                  select null,null,777 from dual union all
                  select 333,1,null  from dual union all
                  select 555,2, null from dual union all
                  select null,null, 333 from dual union all
                  select 777, 4, null from dual union all
                  select 888, 5, null from dual )

select a.*
  from a
 order by last_value(b ignore nulls) over (partition by nvl(a,c) order by b), b nulls last

output
333 1
        333
555 2
111 3
777 4
        777
888 5

7 rows selected
or as you say later, you can have both not null A and C columns, you can do like this:
with a(a,b,c) as (select 111,3, null from dual union all
                  select null,null,777 from dual union all
                  select 333,1,null  from dual union all
                  select 555,2, null from dual union all
                  select null,null, 333 from dual union all
                  select 777, 4, null from dual union all

                  select 444,null, 333 from dual union all

                  select 888, 5, null from dual )

select a.*
  from a
 order by last_value(b ignore nulls)
       over (partition by CASE when b is null then c else a end order by b), b nulls last

output
         A          B          C
       333          1
                             333
       444                   333
       555          2
       111          3
       777          4
                             777
       888          5

 8 rows selected

A: Do it like this:
select case when C in not null then C else A end as A,B,C from table

It same as like this:
Declare @c nchar(50)
Declare @a nchar(50)
set @c = 'record'
set @a = 'sample'
select case  when  @c is not null then @c else @a end as A,@c as C


text:
Q: Sails.JS how to get a HTTP GET method in the controller to work properly with URL parameters I'm having a controller in Sails.JS which needs to take URL parameters like the following: localhost:1337/api/test/[value1]/[value2]
How can I tell the controller to do exactly this? I've already tried to include a :value! or something like that localhost:1337/api/test/:value1 as suggested https://sailsjs.com/documentation/reference/request-req/req-params but the controller doesn't recognice the query to this localhost:1337/api/test/MyValue with req.param("value1").
Any suggestions here?
The routes.js file contains the following:
'get api/test/:value1': 'TestController.test',

and the controller method looks like this:
test: function(req, res) {
        sails.log("req.params = " + JSON.stringify(req.params.all()));
        if (req.method == "GET"){
            var value1 = req.param("value1");
            Test.findOne({"value1": value1).exec(function (err, value1){
                if(err) {
                    sails.log(err);
                    return res.serverError(err);
                }
                if(!value1){
                    //Some error
                }
                return res.ok(value1);
            });
        } else {
            var wrongHttpMethod = req.__('Wrong HTTP method');
            return res.notFound(wrongHttpMethod);
        }
    }

So the basic question is: How do I get a HTTP GET method to run with URL (or query) parameters?

A: Resolved by itself. Didn't find the error but it works.


text:
Q: How to wait until specified keys will be pressed in NASM? I'm creating custom MBR, that will load my message and after I press specified keys CTRL+ALT+ESC it will load original MBR, I have everything done except waiting for keys. I have found code that waits for any keypress, but I have specified keys, I know that I can use AL to set ASCII character of the button pressed, but I have 3 key combinations and also they are not ASCII character. So how can I realize this?
Here is part of my code, this is just example:
org 0x7c00
bits 16

    ; wait for key
    mov ah,0
    int 16h

    ; reboot
    int 19h

MBR_signature:
times 510-($-$$) db 0
db 55h,0aah

A: You can use Int 16/AH=00h to wait for the next keystroke. You can continue checking for keystrokes until ESCAPE is pressed. The scan code for ESCAPE is 01h. If it has been pressed then you can use Int 16/AH=02h to get the shift flags which include whether CONTROL and/or ALT are currently pressed. Bits 2 and 3 of AL will contain their current state. This code snippet should demonstrate detection of CONTROLALT ESCAPE:
org 0x7c00
bits 16

getkey:
    xor ah,ah          ; AH = 0
    int 16h            ; Wait for key
    cmp ah, 01h        ; Scan code 1 = Escape
    jne getkey         ; If Escape not pressed get another key

    mov ah,2h
    int 16h            ; Query keyboard status flags
    and al, 0b00001111 ; Mask all the key press flags
    cmp al, 0b00001100 ; Check if ONLY Control and Alt are pressed and make sure
                       ;    Left and/or Right Shift are not being pressed
    jne getkey         ; If not go back and wait for another keystroke
                       ;    Otherwise Control-Alt-Escape has been pressed
    ; reboot
    int 19h

MBR_signature:
times 510-($-$$) db 0
db 55h,0aah


text:
Q: Failed to Read data from Couchbase using Spark I have been trying to read data from couchbase , but failing to read due to authentication issue.
import com.couchbase.client.java.document.JsonDocument
import org.apache.spark.sql.SparkSession
import com.couchbase.spark._

object SparkRead {

def main(args: Array[String]): Unit = {

  // The SparkSession is the main entry point into spark
  val spark = SparkSession
    .builder()
    .appName("KeyValueExample")
    .master("local[*]") // use the JVM as the master, great for testing
    .config("spark.couchbase.nodes", "***********") // connect to couchbase on hostname
    .config("spark.couchbase.bucket.beer-sample","") // open the travel-sample bucket with empty password
    .config("spark.couchbase.username", "couchdb")
    .config("spark.couchbase.password", "******")
    .config("spark.couchbase.connectTimeout","30000")
    .config("spark.couchbase.kvTimeout","10000")
    .config("spark.couchbase.socketConnect","10000")
    .getOrCreate()

  spark.sparkContext
    .couchbaseGet[com.couchbase.client.java.document.JsonDocument](Seq("airline_10123")) // Load documents from couchbase
    .collect() // collect all data from the spark workers
    .foreach(println) // print each document content

 }
}

Below is the Build File
name := "KafkaSparkCouchReadWrite"

organization := "my.clairvoyant"

version := "1.0.0-SNAPSHOT"

scalaVersion := "2.11.11"

libraryDependencies ++= Seq(
  "org.apache.spark" %% "spark-core" % "2.1.0",
  "org.apache.spark" %% "spark-streaming" % "2.1.0",
  "org.apache.spark" %% "spark-sql" % "2.1.0",
  "org.apache.spark" % "spark-streaming-kafka-0-10_2.11" % "2.2.0",
  "com.couchbase.client" %% "spark-connector" % "2.1.0",
  "org.glassfish.hk2" % "hk2-utils" % "2.2.0-b27",
  "org.glassfish.hk2" % "hk2-locator" % "2.2.0-b27",
  "javax.validation" % "validation-api" % "1.1.0.Final",
  "org.apache.kafka" %% "kafka" % "0.11.0.0",
  "com.googlecode.json-simple" % "json-simple" % "1.1").map(_.excludeAll(ExclusionRule("org.glassfish.hk2"),ExclusionRule("javax.validation")))

ERROR LOG

17/12/12 15:18:35 INFO BlockManager: Initialized BlockManager: BlockManagerId(driver, 192.168.33.220, 52402, None)
        17/12/12 15:18:35 INFO SharedState: Warehouse path is 'file:/Users/sampat/Desktop/GitClairvoyant/cpdl3-poc/KafkaSparkCouchReadWrite/spark-warehouse/'.
        17/12/12 15:18:35 INFO CouchbaseCore: CouchbaseEnvironment: {sslEnabled=false, sslKeystoreFile='null', sslKeystorePassword=false, sslKeystore=null, bootstrapHttpEnabled=true, bootstrapCarrierEnabled=true, bootstrapHttpDirectPort=8091, bootstrapHttpSslPort=18091, bootstrapCarrierDirectPort=11210, bootstrapCarrierSslPort=11207, ioPoolSize=8, computationPoolSize=8, responseBufferSize=16384, requestBufferSize=16384, kvServiceEndpoints=1, viewServiceEndpoints=12, queryServiceEndpoints=12, searchServiceEndpoints=12, ioPool=NioEventLoopGroup, kvIoPool=null, viewIoPool=null, searchIoPool=null, queryIoPool=null, coreScheduler=CoreScheduler, memcachedHashingStrategy=DefaultMemcachedHashingStrategy, eventBus=DefaultEventBus, packageNameAndVersion=couchbase-java-client/2.4.2 (git: 2.4.2, core: 1.4.2), dcpEnabled=false, retryStrategy=BestEffort, maxRequestLifetime=75000, retryDelay=ExponentialDelay{growBy 1.0 MICROSECONDS, powers of 2; lower=100, upper=100000}, reconnectDelay=ExponentialDelay{growBy 1.0 MILLISECONDS, powers of 2; lower=32, upper=4096}, observeIntervalDelay=ExponentialDelay{growBy 1.0 MICROSECONDS, powers of 2; lower=10, upper=100000}, keepAliveInterval=30000, autoreleaseAfter=2000, bufferPoolingEnabled=true, tcpNodelayEnabled=true, mutationTokensEnabled=false, socketConnectTimeout=1000, dcpConnectionBufferSize=20971520, dcpConnectionBufferAckThreshold=0.2, dcpConnectionName=dcp/core-io, callbacksOnIoPool=false, disconnectTimeout=25000, requestBufferWaitStrategy=com.couchbase.client.core.env.DefaultCoreEnvironment$2@7b7b3edb, queryTimeout=75000, viewTimeout=75000, kvTimeout=2500, connectTimeout=5000, dnsSrvEnabled=false}
        17/12/12 15:18:37 WARN Endpoint: [null][KeyValueEndpoint]: Authentication Failure.
        17/12/12 15:18:37 INFO Endpoint: [null][KeyValueEndpoint]: Got notified from Channel as inactive, attempting reconnect.
        17/12/12 15:18:37 WARN ResponseStatusConverter: Unknown ResponseStatus with Protocol HTTP: 401
        17/12/12 15:18:37 WARN ResponseStatusConverter: Unknown ResponseStatus with Protocol HTTP: 401
        Exception in thread "main" com.couchbase.client.java.error.InvalidPasswordException: Passwords for bucket "beer-sample" do not match.
            at com.couchbase.client.java.CouchbaseAsyncCluster$OpenBucketErrorHandler.call(CouchbaseAsyncCluster.java:601)
            at com.couchbase.client.java.CouchbaseAsyncCluster$OpenBucketErrorHandler.call(CouchbaseAsyncCluster.java:584)
            at rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4.onError(OperatorOnErrorResumeNextViaFunction.java:140)
            at rx.internal.operators.OnSubscribeMap$MapSubscriber.onError(OnSubscribeMap.java:88)

A: Sample Code :
import com.couchbase.client.java.document.JsonDocument
import com.couchbase.spark._
import org.apache.spark.sql.SparkSession

object SparkReadCouchBase {

def main(args: Array[String]): Unit = {

val spark = SparkSession
  .builder()
  .appName("KeyValueExample")
  .master("local[*]") // use the JVM as the master, great for testing
  .config("spark.couchbase.nodes", "127.0.0.1") // connect to couchbase on hostname
  .config("spark.couchbase.bucket.travel-sample","") // open the travel-sample bucket with empty password
  .config("com.couchbase.username", "*******")
  .config("com.couchbase.password", "*******")
  .config("com.couchbase.kvTimeout","10000")
  .config("com.couchbase.connectTimeout","30000")
  .config("com.couchbase.socketConnect","10000")
  .getOrCreate()
println("=====================================================================================")
spark.sparkContext
  .couchbaseGet[JsonDocument](Seq("airline_10123")) // Load documents from couchbase
  .collect() // collect all data from the spark workers
  .foreach(println) // print each document content
println("=====================================================================================")

  }
}

POM.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.*******.*****</groupId>
<artifactId>KafkaSparkCouch</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>

<properties>
    <java.version>1.8</java.version>
    <spark.version>2.2.0</spark.version>
    <scala.version>2.11.8</scala.version>
    <scala.parent.version>2.11</scala.parent.version>
    <kafka.client.version>0.11.0.0</kafka.client.version>
    <fat.jar.name>SparkCouch</fat.jar.name>
    <scala.binary.version>2.11</scala.binary.version>
    <main.class>com.*******.demo.spark.couchbase.SparkReadCouchBaseTest</main.class>
</properties>

<dependencies>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-core_${scala.parent.version}</artifactId>
        <version>${spark.version}</version>
    </dependency>

    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-streaming_${scala.parent.version}</artifactId>
        <version>${spark.version}</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-streaming-kafka-0-10_${scala.parent.version}</artifactId>
        <version>${spark.version}</version>
    </dependency>

    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-sql_${scala.parent.version}</artifactId>
        <version>${spark.version}</version>
    </dependency>

    <dependency>
        <groupId>com.couchbase.client</groupId>
        <artifactId>spark-connector_${scala.parent.version}</artifactId>
        <version>${spark.version}</version>
    </dependency>

    <dependency>
        <groupId>org.apache.kafka</groupId>
        <artifactId>kafka-clients</artifactId>
        <version>${kafka.client.version}</version>
    </dependency>

    <dependency>
        <groupId>com.googlecode.json-simple</groupId>
        <artifactId>json-simple</artifactId>
        <version>1.1.1</version>
    </dependency>

    <dependency>
        <groupId>org.scala-lang</groupId>
        <artifactId>scala-library</artifactId>
        <version>${scala.version}</version>
    </dependency>

</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>${java.version}</source>
                <target>${java.version}</target>
            </configuration>
        </plugin>
        <!--Create fat-jar file-->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>2.4</version>
            <configuration>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
            </configuration>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.scala-tools</groupId>
            <artifactId>maven-scala-plugin</artifactId>
            <version>2.15.2</version>
            <executions>
                <execution>
                    <id>compile</id>
                    <goals>
                        <goal>compile</goal>
                    </goals>
                    <phase>compile</phase>
                </execution>

                <execution>
                    <id>test-compile</id>
                    <goals>
                        <goal>testCompile</goal>
                    </goals>
                    <phase>test-compile</phase>
                </execution>

                <execution>
                    <phase>process-resources</phase>
                    <goals>
                        <goal>compile</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>net.alchim31.maven</groupId>
            <artifactId>scala-maven-plugin</artifactId>
            <version>3.1.6</version>
            <configuration>
                <scalaCompatVersion>${scala.binary.version}</scalaCompatVersion>
                <scalaVersion>${scala.version}</scalaVersion>
            </configuration>
            <!-- other settings-->
        </plugin>
    </plugins>
</build>
<repositories>
    <repository>
        <id>mavencentral</id>
        <url>http://repo1.maven.org/maven2/</url>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
    <repository>
        <id>scala</id>
        <name>Scala Tools</name>
        <url>http://scala-tools.org/repo-releases/</url>
        <releases>
            <enabled>true</enabled>
        </releases>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>

<pluginRepositories>
    <pluginRepository>
        <id>scala</id>
        <name>Scala Tools</name>
        <url>http://scala-tools.org/repo-releases/</url>
        <releases>
            <enabled>true</enabled>
        </releases>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </pluginRepository>
</pluginRepositories>
<name>KafkaSparkCouch</name>

A: You will need to set the following couchbase configurations as system properties:
System.setProperty("com.couchbase.connectTimeout", "30000");
System.setProperty("com.couchbase.kvTimeout", "10000");
System.setProperty("com.couchbase.socketConnect", "10000");


text:
Q: Scikit Learn Variable Bias I am using Scikit to make some prediction on a very large set of data. The data is very wide, but not very long so I want to set some weights to the parts of the data. If I know some parts of the data are more important then other parts how should I inform SCikit of this, or does it kinda break the whole machine learning approach to do some pre-teaching.

A: The most straightforward way of doing this is perhaps by using Principal Component Analysis on your data matrix X. Principal vectors form an orthogonal basis of X, and they are each one a linear combination of the original feature space (normally columns) of X. The decomposition is such that each principal vector has a corresponding eigenvalue (or singular value depending on how you compute PCA) a scalar that reflects how much reconstruction can be made solely on the basis of that principal vector alone, in a least-squares sense.
The magnitude of coefficients of principal vectors can be interpreted as importance of the individual features of your data, since each coefficient maps 1:1 to a feature or column of the matrix. By selecting one or two principal vectors and examining their magnitudes, you may have a preliminary insight of what columns are more relevant, of course up to how much these vectors approximate the matrix.
This is the detailed scikit-learn API description. Again, PCA is a simple but just one way of doing it, among others.

A: This probably depends a bit on the machine learning algorithm you're using -- many will discover feature importances on their own (as elaborated via the feature_importances_ property in random forest and others).
If you're using a distance-based measure (e.g. k-means, knn) you could manually weight the features differently by scaling the values of each feature accordingly (though it's possible scikit does some normalization...).
Alternatively, if you know some features really don't carry much information you could simply eliminate them, though you'd lose any diagnostic value these features might unexpectedly bring. There are some tools in scikit for feature selection that might help make this kind of judgement.


text:
Q: How to link Eigen and BLIS I looked that Eigen can use with BLAS.
And BLIS is the BLAS-like dense linear algebra libraries.
Can Eigen link BLIS?  How to do it?
THX

A: Simply link to the BLAS compatibility layer of BLIS using the instructions you referenced: http://eigen.tuxfamily.org/dox-devel/TopicUsingBlasLapack.html, that is compile your application with -DEIGEN_USE_BLAS -lblis


text:
Q: PERL POE ReadWrite Wheel File IO Example? I'm having trouble finding an example of how to create and write to a file using a POE Wheel or whatever async process. I want to be able to write large files in a non blocking way. I'm looking for examples, but don't know where to start.

A: So, I didn't really find a straight forward example for file io. But, I managed to figure out this working code from the examples I did find. I think it's what I want. I'm adding it here so if anyone has any comments it might help me or other improve it. Or, if someone else is looking for an example they can see this one.
                $self->{FILEIO_SESSION} = POE::Session->create(
                inline_states => {
                    _start => sub {
                        my ( $kernel, $heap ) = @_[ KERNEL, HEAP ];
                        $kernel->alias_set($fileio_uuid);

                        $heap->{wheels}->{$fileio_uuid} = POE::Wheel::ReadWrite->new(
                            InputHandle => $infile_fh ,
                            OutputHandle => $outfile_fh,
                            Driver => POE::Driver::SysRW->new(),
                            Filter => POE::Filter::Line->new(),
                            InputEvent => 'readLineEvent',
                            ErrorEvent => 'errorEvent'
                        );
                    },
                    _stop => sub {
                        my ( $kernel, $heap ) = @_[ KERNEL, HEAP ];
                        print "Removing fileio session\n";
                        $kernel->alias_remove($fileio_uuid);
                    },
                    readLineEvent => sub {
                        my ( $kernel, $heap, $input ) = @_[ KERNEL, HEAP, ARG0 ];
                        print "read a line...writing to file...\n";
                        $heap->{wheels}->{$fileio_uuid}->put($input);
                    },
                    errorEvent => sub {
                        my ( $kernel, $heap ) = @_[ KERNEL, HEAP ];
                        print "Everything either went to hell or we got to the end.  Shutting down...\n";
                        delete $heap->{wheels}->{$fileio_uuid};
                        $kernel->yield("_stop");
                    }
                }
            );


text:
Q: Remove a constant from every cell of a column in an Excel equation I have a column of coefficients and values
(Column A) (column B)
0.5         17.0
0.2         15.0
1.0         21.0
0.7         30.0

And I want to sum a constant and each coefficients in the column, e.g.
(1.0-0.5)*17.0 + (1.0-0.2)*15.0 + (1.0-1.0)*21.0 + (1.0-0.7)*30.0

Here, the constant is 1.0. What is the equation that is needed to achieve that? I have tried something like
SUMPRODUCT((1-A:A),B:B)

Without success.

A: How about:
=COUNT(A:A)-SUM(A:A)

This for for the constant 1.  If the constant was 7 then use:
=7 * COUNT(A:A)-SUM(A:A)

EDIT#1:
Based on your Edit, I tried your proposed formula and it worked just fine!:


text:
Q: read argv[1] into say "key" using atoi. Should only accept int. If a non int like 3g is entered how do I reject is as non int How do I fix this. My program must not accept any alphabet.
Int must accept only valid numbers and reject the string if it contains a alphabet
int main(int argc, char *argv[])
{
    char str[1000];
    int i, ch, key;
    {
        if (argc != 2)
        {
             printf("key\n");
             return 1; // exit prog
        }
        // read argv value into key after argc valid
        //to prevent sementation error
        key = atoi(argv[1]);
        // do multi wrap arounds use leftover digit
        key = (key % 26);
            //check for positive number
        if (key < 1)
        {
        printf("key\n");
        return 1; // exit prog
        }
        // ask for text if pos number
        else if (key >= 0)
        {
        printf("text:");
        // check string and read in
        fgets(str, sizeof str, stdin);
        i = strlen(str);
}

If I type

*

*./name (no input, alphabet, two strings returns 1 as it should.)

*./name (number should work and return 0)

*./name a1 or b5 return 1 but 1a or 5b return 0 and should not.

In the debugger I can see it only reads the value of the number into argv as 1 or 5 not as 1a or 5b

A: Instead of the function atoi use another standard function strtol. For example
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

int main(void)
{
    const char *s1 = "3g";
    const char *s2 = "32";

    char *endptr;

    errno = 0;

    long key = strtol( s1, &endptr, 10 );
    if ( *endptr != '\0' || errno != 0 )
    {
        puts( "invalid value supplied" );
    }
    else
    {
        printf( "key = %ld\n", key );

    }

    endptr = NULL;
    errno = 0;

    key = strtol( s2, &endptr, 10 );
    if ( *endptr != '\0' || errno != 0 )
    {
        puts( "invalid value supplied" );
    }
    else
    {
        printf( "key = %ld\n", key );

    }

    return 0;
}

The program output is
invalid value supplied
key = 32

A: You can use strtol() to convert strings to integers and obtain the last position of converted string.
#include <limits.h>
#include <stdlib.h>
#include <errno.h>

// ...

int key;
// ...
char* end;
long key_temp;
// ...
errno = 0;
key_temp = strtol(argv[1], &end, 10);
if (argv[1][0] == '\0') {
    // no character exists
} else if (*end != '\0') {
    // invalid character exists
} else if ((errno == ERANGE && (key_temp == LONG_MIN || key_temp == LONG_MAX)) ||
key_temp < INT_MIN || INT_MAX < key_temp) {
    // too small or too big
} else if (key_temp == 0 && errno != 0) {
    // other error
} else {
    // looks OK
    key = (int)key_temp;
}

A:    //I did not want to rewrite my code from start so: I added the following into my
   //code just before the "key = atoi(argv[1]);" line

     else if(strspn(argv[1], "0123456789") == strlen(argv[1]))
     {
     }
     else if(strspn(argv[1], "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ./") == strlen(argv[1]))
    {  printf("key\n");
        return 1; }


text:
Q: Convert PNG image to TikZ code I am trying to convert this image here into a somewhat clean TikZ code

Now I downloaded potrace, and tried to convert the image to an eps, and then to use inkscape to convert it into TikZ code. Alas, potrace does not work for me. Either that or I can't make it work, it seems like it's rather complicated. Opening up the command window and typing in the path renders nothing. Anyway, does anyone here have any nice methods for converting images into TikZ code?

A: Just using the specs found in this Wikipedia page:
\documentclass{article}
\usepackage{xcolor}
\usepackage{tikz}
\definecolor{RedNo}{HTML}{EF2B2D}
\definecolor{BlueNo}{HTML}{002868}

\begin{document}
\begin{tikzpicture}[scale=.5]
\fill [RedNo]  (0,0) rectangle (6,6) ;
\fill [RedNo]  (0,10) rectangle (6,16) ;
\fill [RedNo]  (10,0) rectangle (22,6) ;
\fill [RedNo]  (10,10) rectangle (22,16) ;
\fill [BlueNo] (7,0) rectangle (9,16) ;
\fill [BlueNo] (0,7) rectangle (22,9) ;
\end{tikzpicture}
\end{document}

With the code
\definecolor{GreenIt}{HTML}{009246}
\definecolor{BWhiteIt}{HTML}{F1F2F1}
\definecolor{RedIt}{HTML}{CE2B37}

\begin{tikzpicture}[scale=2]
\fill [GreenIt]  (0,0) rectangle (1,2) ;
\fill [BWhiteIt] (1,0) rectangle (2,2) ;
\fill [RedIt]    (2,0) rectangle (3,2) ;
\end{tikzpicture}

one gets another beautiful flag

A: I was bored and tried something that I saw in the manual. It is the double line example on manual p.160 :  It is as if the blueish part was making a sharp cornered infinity sign outside the clipped part. So I used (with egreg's nice colors)
\documentclass{article}
\usepackage{xcolor}
\usepackage{tikz}
\definecolor{RedNo}{HTML}{EF2B2D}
\definecolor{BlueNo}{HTML}{002868}
\begin{document}
\begin{tikzpicture}
%\clip (0,0) rectangle (22mm,16mm);
\fill[RedNo] (0,0) rectangle (22mm,16mm);
\draw[smooth cycle, draw=white,double=BlueNo,line width=1mm,double distance = 2mm]
(8mm,8mm) -- (24mm,8mm) -- (24mm,18mm) -- (8mm,18mm)--%
(8mm,-2mm) -- (-2mm,-2mm) -- (-2mm,8mm) -- cycle;
\end{tikzpicture}
\end{document}

This is what you get.

Basically, the whole trick is the smooth cycle option. If you uncomment line in between you get the original flag. :)
EDIT : After having fun with the loops, as Torbjørn T. quickly noticed, one can also directly put two strokes of double line over a red rectangle without doing the loop around it.
\documentclass{article}
\usepackage{xcolor}
\usepackage{tikz}
\definecolor{RedNo}{HTML}{EF2B2D}
\definecolor{BlueNo}{HTML}{002868}
\begin{document}
\begin{tikzpicture}
\fill[RedNo] (0,0) rectangle (22mm,16mm);
\draw[draw=white,double=BlueNo,line width=1mm,double distance = 2mm]%
(8mm,0) -- (8mm,16mm) (0,8mm) -- (22mm,8mm);
\end{tikzpicture}
\end{document}

A: The nicest interface for tracing I've used is through Inkscape. Note that you don't need to use potrace first. Inkscape has a built in tracing tool, and can even output TikZ if you have the plugin for it. However, the image above is pretty straightforward to produce in TikZ just by hand coding it.
For example, a (very) rough version of the flag can be coded with only rectangles:
\begin{tikzpicture}[scale=0.5]
    \path[fill=red!90!black] (0,0) rectangle (22,16);
    \path[fill=white] (6,0) rectangle (10,16);
    \path[fill=white] (0,6) rectangle (22,10);
    \path[fill=blue!40!black] (0,7) rectangle (22,9);
    \path[fill=blue!40!black] (7,0) rectangle (9,16);
\end{tikzpicture}

Wikipedia gives the correct proportions and colours, so you can code it in really simply.


text:
Q: how to form fields section in xfd file I'm having problem to form the field section's structure into xfd files after analyse by issuing commnad "vutil32.exe -i -kx pogl.dad". I hope somebody could help me out how to form out field structure as highlighted in below. I've uploaded sample of my file known as "pglc.dad" i hope soneone could guide me how to form .xfd file from his expert skills and guide me.Thanks
Result from vutil32.exe
file size: 250880
record size (min/max): 121/1024 compressed(80%)
# of keys: 4
key size: 16:02 31:03 56:03 15
key offset: 0 0 0 1
duplicates okay: N N N N

block size: 512
blocks per granule: 1
tree height: 4/2/2.7
# of nodes: 200
# of deleted nodes: 1
total node space: 101800
node space used: 67463 (66%)
user count: 0

Key Dups Seg-1 Seg-2 Seg-3 Seg-4 Seg-5 Seg-6
(sz/of) (sz/of) (sz/of) (sz/of) (sz/of) (sz/of)

0 N 1/0 15/1
1 N 1/0 15/66 15/1
2 N 1/0 40/81 15/1
3 N 15/1

Here is my further construction of .xfd file.
XFD,02,PGLC,PGLC
00300,00041,004
1,0,013,00000
01
PGSTAT
3,0,004,00004,020,00021,004,00000
3
PGSTAT
PGDESC
PGLINE
3,0,004,00004,008,00013,004,00000
03
PGSTAT
PGDESC
PGLINE
1,0,012,00021
01
PGSTAT
000
0150,00150,00003 =================>> How can i form this field section.
00000,00013,16,00016,+00,000,000,PGSTAT
00000,00001,16,00001,+00,000,000,PGDESC
00001,00015,16,00015,+00,000,000,PGLINE

here is the link for my pglc.dad : http://files.engineering.com/getfile.aspx?folder=080fdad6-b1d5-4a37-8dd0-b89f9a985c69&file=PGLC.DAD
Thanks appopriate to someone could helps.

A: I know the XFD format intimately as I have written a couple of parsers of this file format in both Perl and Cobol.
Having said that, I would strongly recommend that you do not try to hand craft an XFD file from scratch.
If you have an AcuCobol (MicroFocus) compiler, and the source of the file's SELECT and FD definitions, then you can create a very small Cobol program that has just the SELECT and FD definitions and then compile the program using:
ccbl32.exe -Fx <program>

That will create an XFD file for the indexed file definition. Note, you can specify a directory for the created XFD file using the -Fo <directory> option.
If you don't have the source of the file definitions, then you are just going to be guessing what and where the fields are. The indexed file by itself will not tell you that information. I can see from extracting the data in your file (using the vutil -e option) that the file contains binary data as well as text, so without knowing exactly what PICture those fields are (COMP-?) you will be struggling to figure out the structure of those fields.


text:
Q: How do I rename a data-frame in a for-loop I am very new to programming with R, but I am trying to read in multiple files for a directory and give them each a unique name.  I am reading the files in using the Dendrochronology Program Library in R (package dpIR) and the read.tucson function.  Although I'm using a specific package, I think my question is fairly general:
Within the loop, I want to create files by concatenating a "t" with each individual files name.  So, if I have a file named "2503" in my directory, I want to create a dataframe in R called "t2503".  Next, I want to read the data in using the r.tucson function to each dataframe. Rather than assigning the read-in data to the dataframe, I'm just overwriting the concatenation with the data.  Can someone help me figure out what step I am missing?
Here is the code I am trying to use:
#set to appropriate directory
setwd("C:/work")

#get a list of files in the directory
files <- list.files()
numfiles <- length(files)

for (i in 1:numfiles)
{
    name<-paste("t",files[i],sep="")
    name<-read.tucson(files[i],header=NULL)
}

A: I think you gave the answer yourself: you have to use ?assign.
Try something like that:
for (i in 1:5) {
  assign(paste0("DF", i), data.frame(A=rnorm(10), B=rnorm(10)))
}

This loops through the integers from 1 to 5 and creates five data.frames "DF1" to "DF5". For your example, you should just replace
name<-read.tucson(files[i],header=NULL)

with
assign(name, read.tucson(files[i],header=NULL))

Note, however, that name is a base function in R, so I would use another naming convention or just skip the first line:
assign(paste("t",files[i],sep=""), read.tucson(files[i],header=NULL))

I hope this is what you are looking for.


text:
Q: How to disable hotkeys in bootstrap-wysiwyg? ASP MVC I have bootstrap-wysiwyg attached into my ASP MVC project, but i have problem with hotkeys. I don't want them, i use this shortcuts for something else (like special characters).
How to disable them?

A: According to the documentation, you can specify a hotkey map. Try supplying an empty map:
$('#editor').wysiwyg({
  hotKeys: {}
});

Or just omit the jQuery hotkeys script: <script src="jquery.hotkeys.js"></script> which it requires.


text:
Q: Use Marketing Cloud Connect without using the Salesforce Id in the Data Extensions We are starting to use Marketing Cloud with Sales Cloud (and Marketing Cloud Connect between them).
When the sync runs, it puts every Contacts I need in my Synchronized DE. That's fine.
Because our marketers are used to use another CustomerId, I created "marketing" Data Extensions with "CustomerId" as a primary key, and Subscriber relationship. This Data Extension receives data with a SQL activity (from our Synchronized DE to this Marketing DE).
It seemed to be a good idea to me, especially because marketers would be able to search their customers (in Contact Builder) using our CustomerId and not the Salesforce Id. You know, when you want to check one specific Customer, or perform some tests on your own Contact name...
Also, it allows our Mobile App to send our CustomerId to Marketing Cloud, instead of a SalesforceId (and our backoffice doesn't know this SF Id, we would have to send it to the backoffice).
So, when we send email, this CustomerId is filled in AllSubscribers AND in AllContacts (in Contact Builder).
So, let's say we have 1 million Contacts synchronized from SalesCloud (and directly sent to AllContacts)... then we will have another 1 million coming from AllSubcribers.
And that's a matter of $$$ because our contract says 1 million Contacts max...
Do you see any workaround to this ?
Thanks a lot for your help !
Kind regards,
David
Edit:
It seems I really have to use the Salesforce Id as a SubscriberKey, or my Individual Email Results will never be filled in Sales Cloud.
Even if it make sense, it's quite ennoying. Here is a consequence I can imagine : If someone just subscribes to our website : we want to send him a transactional message to say hello. For now, we used to send our CustomerId in the payload, so Marketing Cloud will be later able to know who received this email. In the future, I would have to know the Salesforce Id linked to this contact. I would mean that our website has to create the Contact in Salesforce first, then receive the SalesforceId, THEN send the transactionnal message.
I would be very happy to have any confirmation from your part. I'm only doing deductions from what I'm now understanding.

A: This is not an uncommon scenario in large enterprise system landscapes, where Sales Cloud isn't system of record for customer identity. This is not very optimal, but can be solved while maintaining a close-to-standard scope of features.
First of all, as you correctly state, Synchronised Data Extensions (leads, contacts, users) automatically count towards contact count based on the native Salesforce IDs. The only way to avoid this, is using import activity for providing a copy of Sales Cloud objects to Marketing Cloud, as per this example (In email Studio, go to Interactions > Import > Create:
This will provide a copy of your objects without automatically adding all records to Contacts in Marketing Cloud.
Another shortcoming in the inability of using native Journey Builder's Salesforce Entry Events, as these require the use fo native IDs as Contact/Subscriber key in SFMC. You can still use a code-free solution, but it requires a Salesforce Sales Cloud admin to design the "listener" in Process Builder rather than exclusively in Marketing Cloud. Alternative is entry about 1.5 hours after record change using scheduled automation, in which case all work can be done in Marketing Cloud.
You are also correct, when it comes to Individual Email Results (IER). They will not update when using anything but the native IDs. However, I very rarely recommend these anyway. Reason being, the records created in Sales Cloud are in 99% of the cases never looked at, they just use up valuable storage. Also, as the name states, these only cover the email channel. As most of SMFC clients use more than only that channel, the information of text messages sent, will not be included in IER.
What I normally suggest, is to provide this information as an external object, based on a Cloud Page Code Resource. Using the custom ID as a request parameter to the URL of said Code Resource, you can write Ampscript in there, which exposes information about the marketing activities and engagement (clicks/opens) across channels, for that particular individual. As this information is scattered across a number of data views, you might want to preprocess it in Query Activities within Automation Studio, to reduce waiting time when requesting the external object.
You will still be able to use UpdateSingleSalesforceObject and RetrieveSalesforceObjects, as these functions are not dependent on the nature of Contact Key in Marketing Cloud.


text:
Q: How can I make this CoffeeScript object work? I'm learning to use a small library called Bootbox in my Twitter Bootstrap-enabled Rails v4.2 application.
There are several examples on the main page in order to test some of the functionality. In these examples they reference a small JS file that contains an object called Example.
I converted this to CoffeeScript as the following:
# Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://coffeescript.org/

jQuery ->

  ###*
  # This tiny script just helps us demonstrate
  # what the various example callbacks are doing
  ###

  Example = ->
    'use strict'
    elem = undefined
    hideHandler = undefined
    that = {}

    that.init = (options) ->
      elem = $(options.selector)
      return

    that.show = (text) ->
      clearTimeout hideHandler
      elem.find('span').html text
      elem.delay(200).fadeIn().delay(4000).fadeOut()
      return

    that

  $("#search-link").click ->
    bootbox.dialog
      message: 'I am a custom dialog'
      title: 'Custom title'
      buttons:
        success:
          label: 'Success!'
          className: 'btn-success'
          callback: ->
            Example.show 'great success'
            return

There is no issue with the actual Bootbox functionality. However, I can see an error in the console when I click the button that within the dialog box:
Uncaught TypeError: Example.show is not a function

It seems pretty clear, I thought, that I have set up an object Example with a class method called "show". I am definitely no JS/CoffeeScript expert though, which is the reason for my question.

A:   Example = (->
    'use strict'
    elem = undefined
    hideHandler = undefined
    that = {}

    that.init = (options) ->
      elem = $(options.selector)
      return

    that.show = (text) ->
      clearTimeout hideHandler
      elem.find('span').html text
      elem.delay(200).fadeIn().delay(4000).fadeOut()
      return

    that
 )()
 Example.init({selector: JQUERY_SELECTOR})


text:
Q: Change SVG fill color on hover isn't working I am trying to change the color of an SVG image when hovering but it seems that I cannot make it work.
Here's the code:

.signup-icon {
  fill: #515151;
}

.signup-icon:hover {
  fill: #FFFFFF;
}
<svg class="signup-icon" width="20" height="20" viewBox="0 0 20 19" xmlns="http://www.w3.org/2000/svg">
      <path d="M19.6977 8.82624L10.6068 0.64442C10.4398 0.493657 10.2227 0.410156 9.99769 0.410156C9.77267 0.410156 9.55566 0.493657 9.38862 0.64442L0.297707 8.82624C0.128761 8.97975 0.0237846 9.19113 0.00357345 9.4185C-0.0166377 9.64588 0.0493999 9.87259 0.188621 10.0535C0.23709 10.1277 0.29872 10.1923 0.37045 10.2444C0.527528 10.3541 0.715218 10.4114 0.906783 10.408H2.72496V17.6808C2.72496 17.9219 2.82076 18.153 2.99124 18.3235C3.16173 18.494 3.39295 18.5899 3.63406 18.5899H16.3613C16.6024 18.5899 16.8337 18.494 17.0042 18.3235C17.1747 18.153 17.2704 17.9219 17.2704 17.6808V10.408H19.0886C19.2802 10.4114 19.4679 10.3541 19.625 10.2444C19.6967 10.1923 19.7583 10.1277 19.8068 10.0535C19.8728 9.96969 19.9222 9.87397 19.9522 9.77162C20.0045 9.60616 20.0082 9.42923 19.9631 9.2617C19.918 9.09417 19.826 8.94311 19.6977 8.82624ZM13.6341 16.7717H4.54315V9.49896C4.54315 9.25785 4.44741 9.02658 4.27692 8.85609C4.10643 8.6856 3.87516 8.58987 3.63406 8.58987H3.27955L9.99769 2.54439L16.7159 8.58987H16.3613C16.1202 8.58987 15.889 8.6856 15.7185 8.85609C15.548 9.02658 15.4522 9.25785 15.4522 9.49896V16.7717H13.6341Z"/>
    </svg>

I've tried adding !important but it doesn't work. Even the property when not hovered isn't taken in account.
Although, if I put some inline style on the SVG with the fill property, then it works. But I still cannot manage to make the hovering effect work.

A: It does work, however, it's pretty hard to see due to the white background and the white color you set on hover.

.signup-icon {
  fill: red;
}

.signup-icon:hover {
  fill: green;
}
<svg class="signup-icon" width="20" height="20" viewBox="0 0 20 19" xmlns="http://www.w3.org/2000/svg">
      <path d="M19.6977 8.82624L10.6068 0.64442C10.4398 0.493657 10.2227 0.410156 9.99769 0.410156C9.77267 0.410156 9.55566 0.493657 9.38862 0.64442L0.297707 8.82624C0.128761 8.97975 0.0237846 9.19113 0.00357345 9.4185C-0.0166377 9.64588 0.0493999 9.87259 0.188621 10.0535C0.23709 10.1277 0.29872 10.1923 0.37045 10.2444C0.527528 10.3541 0.715218 10.4114 0.906783 10.408H2.72496V17.6808C2.72496 17.9219 2.82076 18.153 2.99124 18.3235C3.16173 18.494 3.39295 18.5899 3.63406 18.5899H16.3613C16.6024 18.5899 16.8337 18.494 17.0042 18.3235C17.1747 18.153 17.2704 17.9219 17.2704 17.6808V10.408H19.0886C19.2802 10.4114 19.4679 10.3541 19.625 10.2444C19.6967 10.1923 19.7583 10.1277 19.8068 10.0535C19.8728 9.96969 19.9222 9.87397 19.9522 9.77162C20.0045 9.60616 20.0082 9.42923 19.9631 9.2617C19.918 9.09417 19.826 8.94311 19.6977 8.82624ZM13.6341 16.7717H4.54315V9.49896C4.54315 9.25785 4.44741 9.02658 4.27692 8.85609C4.10643 8.6856 3.87516 8.58987 3.63406 8.58987H3.27955L9.99769 2.54439L16.7159 8.58987H16.3613C16.1202 8.58987 15.889 8.6856 15.7185 8.85609C15.548 9.02658 15.4522 9.25785 15.4522 9.49896V16.7717H13.6341Z"/>
    </svg>


text:
Q: What is $10 \times 10-10+10$? I was just surfing a social site and found this question posted by someone. People were arguing or different answers like 80, 100, 120. So, what is the correct answer for $10 \times 10-10+10$?
I used order of operations (BODMAS) and got that the answer is 100.
Am I right?

A: The usual convention is to give addition and subtraction equal precedence, evaluating them from left to right.  So we start with multiplication ($10 \cdot 10$), then do the addition and subtraction from left to right to get $(100 - 10) + 10 = 100$.
If we were to take the acronym PEMDAS (BODMAS, BIDMAS, etc.) literally, it would seem that addition should be evaluated before subtraction.  In this case we would get $10 \cdot 10 - 10 + 10 = (10 \cdot 10) - (10 + 10) = 80$.  But this would not be correct; despite A being listed before S in the acronym, the intention is that they be given equal precedence and evaluated left to right.

A: It can be interpreted as an abbreviation of: $$(10.10+(-10))+10$$ as well as an abbreviation of: $$10.10+((-10)+10)$$ In both cases we find:

*

*$(10.10+(-10))+10=(100+(-10))+10=90+10=100$

*$10.10+((-10)+10)=100+0=100$

So our final conclusion is: $$10.10-10+10=100$$
No ambiguity arises, wich is a consequence of the fact that addition is associative.

A: Its 100. You will first execute the multiplication and then the minus and plus.

A: $$
10 \cdot 10-10+10 = 100 - 10+10 = 90 +10 = 100.
$$
Multiplication first, then addition and subtraction in the order they appear left to right is what you get by applying PEMDAS.