Q: Filter list within list to get all second numbers Im trying to filter the following list:
filtered = [[1.0, 3.0], [2.0, 70.0], [40.0, 3.0], [5.0, 50.0], [6.0, 5.0], [7.0, 21.0]]

To get every second number in the list within list, resulting in the following:
filtered = [[3.0], [70.0], [3.0], [50.0], [5.0], [21.0]]

I tried the following which does not work:
from operator import itemgetter
a = map(itemgetter(0), filtered)
print(a)

The following also doesn't work:
from operator import itemgetter
b = map(filtered,key=itemgetter(1))[1]
print(b)

In the last line of code i have shown, if I change map to max, it does find the largest value of all the second floats in the lists. So i assume that i am close to a solution?

A: You can use a list comprehension.
x = [[el[1]] for el in filtered]

or:
x = [[y] for x,y in filtered]

You can also use map with itemgetter. To print it, iterate over the iterable object returned by map. You can use list for instance.
from operator import itemgetter
x = map(itemgetter(1), filtered)
print(list(x))

A: You are not closer to a solution trying to pass a key to map. map only takes a function and an iterable (or multiple iterables). Key functions are for ordering-related functions (sorted, max, etc.)
But you were actually pretty close to a solution in the start:
a = map(itemgetter(0), filtered)

The first problem is that you want the second item (item 1), but you're passing 0 instead of 1 to itemgetter. That obviously won't work.
The second problem is that a is a map object—a lazily iterable. It does in fact have the information you want:
>>> a = map(itemgetter(1), filtered)
>>> for val in a: print(val, sep=' ')
3.0 70.0 3.0 50.0 5.0 21.0

… but not as a list. If you want a list, you have to call list on it:
>>> a = list(map(itemgetter(1), filtered))
>>> print(a)
[3.0, 70.0, 3.0, 50.0, 5.0, 21.0]

Finally, you wanted a list of single-element lists, not a list of elements. In other words, you want the equivalent of item[1:] or [item[1]], not just item[1]. You can do that with itemgetter, but it's a pretty ugly, because you can't use slice syntax like [1:] directly, you have to manually construct the slice object:
>>> a = list(map(itemgetter(slice(1, None)), filtered))
>>> print(a)
[[3.0], [70.0], [3.0], [50.0], [5.0], [21.0]]

You could write this a lot more nicely by using a lambda function:
>>> a = list(map(lambda item: item[1:], filtered))
>>> print(a)
[[3.0], [70.0], [3.0], [50.0], [5.0], [21.0]]

But at this point, it's worth taking a step back: map does the same thing as a generator expression, but map takes a function, while a genexpr takes an expression. We already know exactly what expression we want here; the hard part was turning it into a function:
>>> a = list(item[1:] for item in filtered)
>>> print(a)

Plus, you don't need that extra step to turn it into a list with a genexpr; just swap the parentheses with brackets and you've got a list comprehension:
>>> a = [item[1:] for item in filtered]
>>> print(a)


Q: How i can use script session outside script folder like home folder? I use script on my website like this localhost/panel/index.php
in index.php the script set session like this
$cookie_lifetime = ini_get('session.cookie_lifetime') ? ini_get('session.cookie_lifetime') : 0;
session_set_cookie_params($cookie_lifetime , rtrim(dirname($_SERVER["SCRIPT_NAME"]),"/") . "/", $_SERVER['SERVER_NAME'], $ssl, true);
session_start();

I need to use this session on localhost/index.php by using this session.

A: To set the session cookie path to a fixed location you don't need any calculation:
session_set_cookie_params($cookie_lifetime , '/index.php', $ssl, true);

It's worth noting that the default value is /.


Q: Decimal error on using linq function datacolumn I have a simple code that runs through all the text columns of a DataGrid. I use a for the create a LINQ statement that searches values on that column.
The problem I have is when the column has decimal values. I intent to make an if function asking if this column is decimal before going into the code. How can I check to see what column datatype it is?
    If String.IsNullOrWhiteSpace(Me.DisplayMemberPath) = False AndAlso mBindingListCollectionView IsNot Nothing AndAlso editableTextBox IsNot Nothing Then
        Dim str As New StringBuilder

        For Each item As DataGridTextColumn In Me.Columns
            Dim b As Binding = item.Binding
            If b IsNot Nothing AndAlso b.Path IsNot Nothing Then
                str.Append(" " & b.Path.Path & " LIKE '%" & editableTextBox.Text & "%' OR")
            End If
        Next

        Dim query As String
        If str.ToString.Trim.EndsWith("OR") Then
            query = str.ToString(0, str.Length - 2)
        Else
            query = str.ToString
        End If
        mBindingListCollectionView.CustomFilter = query

This is a CustomControl in WPF. The Customcontrol allows me to add datacolumns and then i hook up an itemsSource in my window. When I start typing, this little function searches all the columns available and sees what I have similar to the entered text.


Q: passing data between fragments when swiped I am newbie to android.I am trying to develop an application which contains a Viewpager with Tabs.My Aim is to pass the data entered in first fragment(i.e tab1) to second fragment.I am confused how to get the data in FragmentA and show it in FragmentB besides my viewpager is in Mainactivity.
some of my code is
mviewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

          //  Toast.makeText(getApplicationContext(),""+servloc,Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onPageSelected(int position) {
            mviewpager.setCurrentItem(position);
            int index = mviewpager.getCurrentItem();
            if(position==0) {
                Fragmentpageadapter adapter = (Fragmentpageadapter) mviewpager.getAdapter();

                CreateInspectionFragmentA ca= (CreateInspectionFragmentA) adapter.getFragment(index);
            }

above code is viewpage setonpagechangelistener..
and my pageadapter is
@Override
public Fragment getItem(int position) {
    switch (position) {
        case 0:
          CreateInspectionFragmentA createInspectionFragmenta=new CreateInspectionFragmentA();
            mPageReferenceMap.put(position, createInspectionFragmenta);
  return createInspectionFragmenta;
        case 1:
            CreateInspectionFragmentB createInspectionFragmentb = new CreateInspectionFragmentB();
          //  createInspectionFragmentb.deliverData(data1,data2);
         mPageReferenceMap.put(position,createInspectionFragmentb);
              return createInspectionFragmentb;

        case 2:
            CreateInspectionFragmentC createInspectionFragmentc = new CreateInspectionFragmentC();
             mPageReferenceMap.put(position,createInspectionFragmentc);
            return createInspectionFragmentc;
        default:
            return null;
    }
   }

my requirement is to pass the data i entered in FragmentA in edittext to be seen in FragmentB when swiped but not when button click or something.
posibilities:
1.if there is a way to get the UI controls of FragmentA in onpageselected i can bind the EditText view and get the data.
2. using Bundle.
please help me to resolve this problem.
Thanks in Advance.

A: You can try this. In FragmentA you put this code
    private static NameOfTheFragment instance = null;

    public static NameOfTheFragment getInstance() {
       return instance;
    }

Then create a function to return what you want, like a List View
    public ListView getList(){
       return list;
    }

Then in FragmentB you do this in onCreateView
    ListView list = NameOfTheFragment.getInstance().getList();

Then you show list in fragment B


Q: How to set Json string array to Java object using Java I have following JSON string that I need to set to the Java objects of POJO class.
What method should I follow?
 {"status":"FOUND","messages":null,"sharedLists":      [{"listId":"391647d","listName":"/???","numberOfItems":0,"colla   borative":false,"displaySettings":true}] }

I tried using Gson but it did not work for me.
Gson gson = new Gson();
SharedLists target = gson.fromJson(sb.toString(), SharedLists.class);

Following is my SharedLists pojo
 public class SharedLists {

@SerializedName("listId")
private String listId;

@SerializedName("listName")
private String listName;

@SerializedName("numberOfItems")
private int numberOfItems;

@SerializedName("collaborative")
private boolean collaborative;

@SerializedName("displaySettings")
private boolean displaySettings;

public int getNumberOfItems() {
    return numberOfItems;
}
public void setNumberOfItems(int numberOfItems) {
    this.numberOfItems = numberOfItems;
}
public boolean isCollaborative() {
    return collaborative;
}
public void setCollaborative(boolean collaborative) {
    this.collaborative = collaborative;
}
public boolean isDisplaySettings() {
    return displaySettings;
}
public void setDisplaySettings(boolean displaySettings) {
    this.displaySettings = displaySettings;
}

public String getListId() {
    return listId;
}
public void setListId(String listId) {
    this.listId = listId;
}

}

A: Following is your JSON string.
{
  "status": "FOUND",
  "messages": null,
  "sharedLists": [
    {
      "listId": "391647d",
      "listName": "/???",
      "numberOfItems": 0,
      "colla   borative": false,
      "displaySettings": true
    }
  ]
}

Clearly sharedLists is a JSON array within the outer JSON object.
So I have two classes as follows (created from http://www.jsonschema2pojo.org/ by providing your JSON as input)
ResponseObject - Represents the outer object
 public class ResponseObject {

        @SerializedName("status")
        @Expose
        private String status;
        @SerializedName("messages")
        @Expose
        private Object messages;
        @SerializedName("sharedLists")
        @Expose
        private List<SharedList> sharedLists = null;

        public String getStatus() {
            return status;
        }

        public void setStatus(String status) {
            this.status = status;
        }

        public Object getMessages() {
            return messages;
        }

        public void setMessages(Object messages) {
            this.messages = messages;
        }

        public List<SharedList> getSharedLists() {
            return sharedLists;
        }

        public void setSharedLists(List<SharedList> sharedLists) {
            this.sharedLists = sharedLists;
        }

    }

and the SharedList - Represents each object within the array
public class SharedList {

    @SerializedName("listId")
    @Expose
    private String listId;
    @SerializedName("listName")
    @Expose
    private String listName;
    @SerializedName("numberOfItems")
    @Expose
    private Integer numberOfItems;
    @SerializedName("colla borative")
    @Expose
    private Boolean collaBorative;
    @SerializedName("displaySettings")
    @Expose
    private Boolean displaySettings;

    public String getListId() {
        return listId;
    }

    public void setListId(String listId) {
        this.listId = listId;
    }

    public String getListName() {
        return listName;
    }

    public void setListName(String listName) {
        this.listName = listName;
    }

    public Integer getNumberOfItems() {
        return numberOfItems;
    }

    public void setNumberOfItems(Integer numberOfItems) {
        this.numberOfItems = numberOfItems;
    }

    public Boolean getCollaBorative() {
        return collaBorative;
    }

    public void setCollaBorative(Boolean collaBorative) {
        this.collaBorative = collaBorative;
    }

    public Boolean getDisplaySettings() {
        return displaySettings;
    }

    public void setDisplaySettings(Boolean displaySettings) {
        this.displaySettings = displaySettings;
    }

}

Now you can parse the entire JSON string with GSON as follows
Gson gson = new Gson();
ResponseObject target = gson.fromJson(inputString, ResponseObject.class);

Hope this helps.


Q: _WebTryThreadLock error I am facing an error while manipulation the UIWebView in ipad application. in that I have to fill the UIWebview with the HTML string and though the content is coming from the APi so I have to implement the process under Thread.
Below is the error message :
bool _WebTryThreadLock(bool), 0xb2aa410: Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread. Crashing now...

A: you are doing some graphical changes in secondary thread .. you must do all the graphical changes in your main thread. check you thread code.


Q: Rounded Border Corner I'm wondering about how to make the top-border like the red line on the picture below? I've tried border-radius, but I can't figure out how to round the bottom part of the top-border.

A: I would use :before to create a pseudo-element that you can style, as it is only used for presentation, so having an empty element would be unnecessarily verbose.
Here’s an example of how this could be done:

.splitter {
  border: 1px solid #ddd;
  border-top: 0;
}
  .splitter:before {
    content: ' ';
    display: block;
    position: relative;
    top: -5px;
    width: 100%;
    height: 8px;
    background-color: red;
    border-radius: 100px / 70px;
  }

.myContent {
  padding: 0 20px;
}

React or Angular

Lorem ipsum Mollit qui sunt consequat deserunt exercitation veniam.

Which can also be seen working on JS Bin:
http://jsbin.com/hoqizajada/edit?html,css,output

A: I think it's not possible with a single div. However, you can place a div above it and trick with border-radius.

.inbox {
  width: 200px;
}
#top-border {
  border: red 4px solid;
  border-radius: 4px;
}
#test{
  padding: 4px;
  height: 200px;
  background: #EEEEEE;
}
<!DOCTYPE html>

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

JSBIN: http://jsbin.com/pofolanuje/edit?html,css,output

A: Here is the complete code, hope this helps you;

.container{
  width:320px;
  height:520px;
  background:#fff;
  -webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
border:1px solid #e4e4e4;
}
.border-red{
  background:red;
  width:100%;
  height:10px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}


Q: Should I install PWA offline caching at the start of the development? As the question suggests, should I install/add Progressive Web Application (PWA) offline caching at the start of the development, or should I only add it after development is complete? Because I've heard/read that installing it at the start may impact how we develop our application and how we connect with the backend. However, the part where I'm most confused is that the data is "cached" throughout the development, and I may not be able to get "fresh" data immediately unless I use incognito.


Q: jQuery element value = $(this).value I would like to select the element with class of Level1 whose value is equal to $(this).val().  I read that you can't do $(.Level1[someAttribute=value]) which makes sense as val() isn't an available DOM attribute in that sense.  This may be an easy one, but I am stumped at the moment.  Unfortunately i do not have the ability to change how the HTML below is rendered.
$('.Level0').each(function () {
   var sortOfChildren = $('.Level1').val() = $(this).val //not real code

});

HTML

x

x

x

x

x

y

z

z

ANSWER
$('.Level0').each(function () {
    var targetValue = $(this).val();
    var matching = $(".Level1").filter(function() {
        return $(this).val() === targetValue;
    });
    // ...use `matching` here...
});

A: Your question talks about .val and the "value" of elements, but none of the elements in your question is a form field, and therefore they don't have values.
If they were form fields:

I read that you can't do $(.Level1[someAttribute=value]) which makes sense as val() isn't an available DOM attribute in that sense

Right, your only option is to loop, probably via filter:
$('.Level0').each(function () {
    var targetValue = $(this).val();
    var matching = $(".Level1").filter(function() {
        return $(this).val() === targetValue;
    });
    // ...use `matching` here...
});

Note that matching may have zero, or multiple, elements in it depending on how many .Level1 elements matched the value.
But because they aren't:
...you may want .text or .html instead of .val in the above, or possibly a :contains selector instead of filter.


Q: Using Tuples in map, flatmap,... partial functions If I do:
val l = Seq(("un", ""), ("deux", "hehe"), ("trois", "lol"))
l map { t => t._1 + t._2 }

It's ok.
If I do:
val l = Seq(("un", ""), ("deux", "hehe"), ("trois", "lol"))
l map { case (b, n) => b + n }

It's ok too.
But if I do:
val l = Seq(("un", ""), ("deux", "hehe"), ("trois", "lol"))
l map { (b, n) => b + n }

It will not work.
Why should I use "case" keyword to use named tuples?

A: The error message with 2.11 is more explanatory:
scala> l map { (b, n) => b + n }
<console>:9: error: missing parameter type
Note: The expected type requires a one-argument function accepting a 2-Tuple.
      Consider a pattern matching anonymous function, `{ case (b, n) =>  ... }`
              l map { (b, n) => b + n }
                       ^
<console>:9: error: missing parameter type
              l map { (b, n) => b + n }
                          ^

For an apply, you get "auto-tupling":
scala> def f(p: (Int, Int)) = p._1 + p._2
f: (p: (Int, Int))Int

scala> f(1,2)
res0: Int = 3

where you supplied two args instead of one.
But you don't get auto-untupling.
People have always wanted it to work that way.

A: This situation can be understand with the types of inner function.
First, the type syntax of parameter function for the map function is as follows.
Tuple2[Int,Int] => B //Function1[Tuple2[Int, Int], B]

The first parameter function is expand to this.
(t:(Int,Int)) => t._1 + t._2 // type : Tuple2[Int,Int] => Int

This is ok. Then the second function.
(t:(Int, Int)) => t match {
  case (a:Int, b:Int) => a + b
}

This is also ok. In the failure scenario,
(a:Int, b:Int) => a + b

Lets check the types of the function
(Int, Int) => Int // Function2[Int, Int, Int]

So the parameter function type is wrong.
As a solution, you can convert multiple arity functions to tuple mode and backward with the helper functions in Function object. You can do following.
val l = Seq(("un", ""), ("deux", "hehe"), ("trois", "lol"))
l map(Function.tupled((b, n) => b + n ))

Please refer Function API for further information.

A: The type of a function argument passed to map function applied to a sequence is inferred by the type of elements in the sequence. In particular,
scenario 1: l map { t => t._1 + t._2 } is same as l map { t: ((String, String)): (String) => t._1 + t._2 } but shorter, which is possible because of type inference. Scala compiler automatically inferred the type of the argument to be (String, String) => String
scenario 2: you can also write in longer form
l map { t => t match {
    case(b, n) => b + n
  }
}

scenario 3: a function of wrong type is passed to map, which is similar to
def f1 (a: String, b: String) = a + b

def f2 (t: (String, String)) = t match { case (a, b) => a + b }

l map f1 // won't work

l map f2


Q: Issue IN VS CODE I am a new vs code user. When I installed vs code and runned a C program "Hello World" and other programs but I face one issue undefined reference to winMain@16 I also have MinGW compiler. I searched for this issue in the whole internet but I didn't find anything regarding this visual studio code issue. If you have a solution to this please reply.
~~ Joydeep


Q: Comparing two datasets, to ensure an administrator can only edit users in their area I have created an app where users have many areas (through subscriptions).  Some users have the :admin role, and these users also have many administrative_areas (through administrations.  I'm struggling getting my head round the best way to ensure that given an admin of Area A goes to the users index page, they only see other users in Area A, but not those outside of this area.  My model is set up as follows:
class User < ActiveRecord::Base
  has_many :subscriptions
  has_many :areas, through: :subscriptions

  has_many :administrations
  has_many :administrative_areas, through: :administrations, :source => :area, :class_name => "Area"
end

class Area < ActiveRecord::Base
  has_many :subscriptions
  has_many :users, :through => :subscriptions

  has_many :administrations
  has_many :admins, :through => :administrations, :class_name => "User", :source => :user
end

I can successfully set up the users / admins, but am struggling with getting the right ActiveRecord Query to return only relevant users for the admin.
Any thoughts on solving this, or suggestions for a better approach?
Thanks!

A: Assuming @admin_user as some user with admin role.
  @admin_areas = User.joins(:subscriptions).where('subscriptions.area_id' => @admin_user.administrative_areas.map(&:id))

You can use cancan gem to manage roles and giving controls to different roles.
EDIT : You can try something like below
In user.rb
scope :users_to_manage, lambda{ joins(:subscriptions).where('subscriptions.area_id' => current_user.administrative_areas.map(&:id)) #if you have access current_user in model

In ability.rb
can :manage, Area.users_to_manage


Q: Why is my java app spending 30% of its time in young generation gc? I was looking at the gc log file for our Solr installation, and I noticed its taking 30% of its time doing young generation gc. The log snippet below spans about a second, and the gc times add up to .34 seconds.
My question is: is this a problem, and if so what's causing it?
I am running jdk 1.6.0_24 on Linux
1004626.109: [GC 1004626.109: [ParNew: 74847K->5219K(76672K), 0.0838750 secs] 10831779K-
10762151K(11525824K), 0.0841790 secs] [Times: user=0.24 sys=0.00, real=0.09 secs]
1004626.320: [GC 1004626.320: [ParNew: 73379K->5468K(76672K), 0.0527070 secs] 10830311K->10762874K(11525824K), 0.0529680 secs] [Times: user=0.20 sys=0.00, real=0.06 secs]
1004626.511: [GC 1004626.511: [ParNew: 73628K->4986K(76672K), 0.0591070 secs] 10831034K->10763002K(11525824K), 0.0593820 secs] [Times: user=0.20 sys=0.00, real=0.05 secs]
1004626.698: [GC 1004626.698: [ParNew: 73146K->5611K(76672K), 0.0523060 secs] 10831162K->10764169K(11525824K), 0.0525820 secs] [Times: user=0.21 sys=0.00, real=0.05 secs]
1004626.902: [GC 1004626.902: [ParNew: 73771K->6878K(76672K), 0.0653490 secs] 10832329K->10765868K(11525824K), 0.0656210 secs] [Times: user=0.22 sys=0.00, real=0.06 secs]

A: No, that's not a problem.  It means that your objects come and go - you create them in scope, use them, and then they're eligible for GC.  I don't think that's an indication that something's wrong.
The other extreme would be an issue: objects are created, age, and stick around too long.  That's where memory leaks and filled perm space happens.

A: I think you do have a problem here.
I'm not an expert on reading GC logs, but I think it is saying that you have a 'young' space of 76672K, and a total heap size of 11525824K.  Furthermore, the total heap usage after each GC cycle is 10765868K ... and growing.  And it is (apparently) spending ~30% of its time garbage collecting.
My diagnosis is that your heap is nearly full, and you are spending a significant (and increasing) percentage of time garbage collection as a direct result.
My advice would be restart the application (short term), and look for memory leaks (long term).  If there are no memory leaks (i.e. your application is using all of that heap space) then you need to look for ways to reduce you application's memory usage.
Your application does seem to be generating a fair bit of garbage, but that is not necessarily a worry.  The HotSpot GCs can reclaim garbage pretty efficiently.  It is the amount of non-garbage that it has to deal with that causes performance issues.


Q: The type or namespace name 'Input' does not exist in the namespace 'UnityEngine.Experimental' I am using unity's new input system and getting this error, I tried a lot to fix it but can't find the problem. Please help me.
Error:
Assets\Player01.cs(4,32): error CS0234: The type or namespace name 'Input' does not exist in the namespace 'UnityEngine.Experimental' (are you missing an assembly reference?)

Full Script(C#):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Experimental.Input;

public class Player01 : MonoBehaviour
{
    public InputMaster controls;

    void Awake ()
    {
        controls.Player01.Shoot.performed += _ => Shoot();
    }

    void Shoot ()
    {
        Debug.Log("We shot the sherif!");
    }

    private void OnEnable()
    {
        controls.Enable();
    }
    private void OnDisable()
    {
        controls.Disable();
    }
}

A: The problem is that there is no namespace of UnityEngine.Experimental.Input. But, it only says “'Input' does not exist in the namespace 'UnityEngine.Experimental'”. ‘Experimental’ does exist and ‘Input’ does not. However, ‘InputSystem’ does. And that is the one you are looking for, not ‘Input’. You should change the first line to this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Experimental.InputSystem;

public class Player01 : MonoBehaviour
...

A: Just in case, if the first solution did not work, Close vs studio / code if open, then go to Edit -> Project Settings -> Input System Manager. There will be only one option available. Click the button, save your scene. Open a script. This worked for me. A lot of tutorials do not mention this part.


Q: ToggleButton with custom image and custom text color I have this toggle:
<ToggleButton
    android:id="@+id/toggle_1"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:background="@drawable/custom_toggle_bg"
    android:gravity="bottom|center_horizontal" />

and this is drawable resources:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/active" android:state_checked="true"/>
    <item android:drawable="@drawable/default" android:state_checked="false"/>

</selector>

Now i would like that text of ToggleButton (on and off) change color when Toggle change state (only text, not background of entire ToggleButton).
How can i do?

A: You can add the attribute android:textColor="@drawable/color_selector" into your <ToggleButton>
//color_selector.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" color="@color/text_on" />
    <item android:state_checked="false" color="@color/text_off" />
</selector>

A: Make another selector in location ./res/color/my_selector.xml and set it to ToggleButton android:textColor="@color/my_selector"
example my_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item color="@color/text_active" android:state_checked="true"/>
    <item color="@color/text_default" android:state_checked="false"/>

</selector>

A: In your code, use an OnClickListener.
protected void onCreate(Bundle savedInstanceState) {
  final ToggleButton tb = new ToggleButton(DataHandler.getContext());
  tb.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
      if (tb.isChecked()) {
        tb.setTextColor(Color.GREEN);
      }
      else {
        tb.setTextColor(Color.RED);
      }
    }
  });
}


Q: RequestContext.RouteData and Request.UrlReferrer info is lost on FormMethod.Post I am trying to post a form with one of the variables being the Action of the previous URL, however whenever I POST it, the variable becomes null. How can I persist that info at least until it reaches the POST Action?
I've tried using both Url.RequestContext.RouteData.Values["action"] and Request.UrlReferrer to get the Action.
In my View I'm trying to POST a file, Action name, and an id:
Html.BeginForm("Edit", "Expenses", FormMethod.Post, new { enctype = "multipart/form-data", actionName = actionName, id = idInt })
If I keep it the way it is, the Action name is null, but if I remove the FormMethod.Post portion from the BeginForm method, the Action name is posted successfully and the file is null.

A: You are using the Html.BeginForm helper method incorrectly! You mixed route values and html attributes to a single object !
Your current call matches the below overload
public static MvcForm BeginForm(
    this HtmlHelper htmlHelper,
    string actionName,
    string controllerName,
    FormMethod method,
    IDictionary<string, object> htmlAttributes
)

The last parameter is the htmlAttributes. So with your code, it will generate the form tag markup like this
<form action="/Expenses/Edit" actionname="someActionName" enctype="multipart/form-data"
                                                                     id="22" method="post">

</form>

You can see that Id and action became 2 attributes of the form !
Try this overload where you can specify both route values and htmlAttributes
@using (Html.BeginForm("AddToCart", "Home",  new {  actionName = "Edit", id = 34 },
                                 FormMethod.Post,new { enctype = "multipart/form-data", }))
{
        <input type="submit"/>
}

which will generate the correct form action attribute value using the route values you provided.


Q: Prevent Jackson from accepting numbers into Date fields in the request body How can I stop Jackson from accepting numeric values into Date fields in the request body? Jackson seems to be treating them as timestamps and doing the conversion but I would rather have it return a Bad Request response instead.
The field is defined as follows:
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'")
private final Date someDate;

Example request:
{
    "someDate": 1
}

Is deserialized to:
1970-01-01 01:00:00 CET


Q: Unable to create database tables with Generate Database from Model I am using Entity Framework 4.1 and SQL Express. I have been trying to create models inside the emdx file and from that create the tables inside the a .mdf file. However, I am unable to get that work.
However, I am able to get the "Update Model from Database" to work, so there don't seem to be a problem with the connection string.
What am I doing wrong?

A: I tend to copy the generated SQL script and execute it myself using SQL (Enterprise manager 2008 in my case), gives you better feedback and more control.
Haven't really bothered setting it up so that it executes automatically, because EF sometimes makes mistakes in its scripting (e.g. trying to delete every FK twice. Once in the beginning, and then again before the containing table will be deleted).
Also, if you made a lot of changes or dropped some tables, sometimes the script isn't 100% compatible with deleting the existing database. I then just drop all FK's and tables (not just what the script tells me to) and then execute the script.
But that's just how I like to do it.


Q: Ignoring non-existent URLs with htmlParse() in R G'day Everyone,
I have a very long list of place names (~15,000) that I want to use to look up wiki pages and extract data from them. Unfortunately not all of the places have wiki pages and when htmlParse() hits them it stops the function and returns an error.
    Error: failed to load HTTP resource

I can't go through and remove every place name that creates a non-existent URL so I was wondering if there is a way to get the function to skip places that don't have a wiki page?
    # Town names to be used
    towns <- data.frame('recID' = c('G62', 'G63', 'G64', 'G65'),
                    'state' = c('Queensland', 'South_Australia', 'Victoria', 'Western_Australia'),
                    'name'  = c('Balgal Beach', 'Balhannah', 'Ballan', 'Yunderup'),
                    'feature' = c('POPL', 'POPL', 'POPL', 'POPL'))

    towns$state <- as.character(towns$state)

    towns$name <- sub(' ', '_', as.character(towns$name))

   # Function that extract data from wiki
   wiki.tables <- function(towns)  {
      require(RJSONIO)
      require(XML)
      u <- paste('http://en.wikipedia.org/wiki/',
                 sep = '', towns[,1], ',_', towns[,2])
      res <- lapply(u, function(x) htmlParse(x))
      tabs <- lapply(sapply(res, getNodeSet, path = '//*[@class="infobox vcard"]')
             , readHTMLTable)
      return(tabs)
    }

    # Now to run the function. Yunderup will produce a URL that
    # doesn't exist. So this will result in the error.
    test <- wiki.tables(towns[,c('name', 'state')])

    # It works if I don't include the place that produces a non-existent URL.
    test <- wiki.tables(towns[1:3,c('name', 'state')])

Is there a way to identify these non-existent URLs and either skip them or remove them?
Thanks for you help!
Cheers,
Adam

A: You can use the 'url.exists' function from `RCurl`

require(RCurl)
u <- paste('http://en.wikipedia.org/wiki/',
                 sep = '', towns[,'name'], ',_', towns[,'state'])
> sapply(u, url.exists)
   http://en.wikipedia.org/wiki/Balgal_Beach,_Queensland
                                                    TRUE
 http://en.wikipedia.org/wiki/Balhannah,_South_Australia
                                                    TRUE
           http://en.wikipedia.org/wiki/Ballan,_Victoria
                                                    TRUE
http://en.wikipedia.org/wiki/Yunderup,_Western_Australia
                                                    TRUE

A: Here's another option that uses the httr package. (BTW: you don't need RJSONIO). Replace your wiki.tables(...) function with this:
wiki.tables <- function(towns)  {
  require(httr)
  require(XML)
  get.HTML<- function(url){
    resp <- GET(url)
    if (resp$status_code==200) return(htmlParse(content(resp,type="text")))
  }
  u <- paste('http://en.wikipedia.org/wiki/',
             sep = '', towns[,1], ',_', towns[,2])
  res <- lapply(u, get.HTML)
  res <- res[sapply(res,function(x)!is.null(x))]   # remove NULLs
  tabs <- lapply(sapply(res, getNodeSet, path = '//*[@class="infobox vcard"]')
                 , readHTMLTable)
  return(tabs)
}

This runs one GET request and tests the status code. The disadvantage of url.exists(...) is that you have to query every url twice: once to see if it exists, and again to get the data.
Incidentally, when I tried your code the Yunderup url does in fact exist ??


Q: Cannot loop through array comparing text values, undefined result with Protractor I am new to protractor and JavaScript and struggling trying to compare a delimited string to an array.
What I am trying to do is to find a list of all elements and then from each element, loop through the arrays to compare the text values to the delimited string but the delimited string values are 'undefined'
element.all(by.css('.itemField')).then(function (allFieldItems) {
  var  toCompare= ["AGO", "9"]
  for (var i = 0; i < toCompare.length; i++) {
    var valueToCompare = toCompare[i]
    allFieldItems[i].getText().then(function (text) {
      if(text != valueToCompare[i]){
        console.log("Values don't match")
          }
        }.bind( i))
      }
})

The problem is that the line "if(text != valueToCompare[i]) the "valueToCompare[i]" is always 'undefined' and I am looking for help on how to  resolve this without using expect statements.

A: You can call getText() on the result of element.all() directly:
var toCompare = ["AGO", "9"];
element.all(by.css('.itemField')).getText().then(function (texts) {
    for (var i = 0; i < toCompare.length; i++) {
        if (texts[i] != toCompare[i]) {
            console.log("Values don't match");
        }
    }
});

Or, you may even expect it like this (not sure if this is what you are actually trying to do):
expect($$('.itemField').getText()).toEqual(toCompare);


Q: Do I need to make fields in schema.xml to use DataImportHandler I have many different column names and types that I want to import. Do I need to change my schema.xml to have entries for each of these specific field types, or is there a way for the importhandler to generate the schema.xml from the underlying SQL data?

A: You need to define the fields you need to import in the schema.xml.
The DIH does not autogenerate the fields and it is better to create the fields if the amount the fields are less.
Solr also allows you to define Dynamic fields, where the fields need not be explicitly defined but just needs to match the regex pattern.
<dynamicField name="*_i"  type="integer"  indexed="true"  stored="true"/>

You can also define a catch field with Solr, however the behaviour cannot be control as same analysis would be applied to all the fields.


Q: JPA Criteria Query for Left joins I am new to JPA and I have a Left Join scenario.
I have my native sql query as below and I am using left join to fetch the complete records from V_MONITORING table for st.id = 10001.
I have some null values for id_legislature which also needs to be selected and hence using a left join
select distinct
    mv.id_set, mv.id_travel, mv.id_legislature
from
   V_MONITORING mv
     left join v_set st on mv.id_set = st.id
     left join v_travel fg on mv.id_travel = fg.id
     left join v_legislature gg on mv.id_legislature = gg.id;

The same thing I am implementing using the JPA criteria query, I am unable to fetch the null records
Below is the code
Predicate predicate = cb.conjunction();
Root<MonitoringBE> mvRoot = criteriaQuery.from(MonitoringBE.class);
mvRoot.fetch(MonitoringBE.id_set, JoinType.LEFT);
mvRoot.fetch(MonitoringBE.id_travel, JoinType.LEFT);
mvRoot.fetch(MonitoringBE.id_legislature, JoinType.LEFT);

final Path<Object> serieneinsatzterminPath= mvRoot.get(MonitoringBE.id_set);
predicate = cb.and(predicate, cb.EqualTo(serieneinsatzterminPath.get(SetBE.GUELTIG_VON_DATUM), startSetDate));

criteriaQuery.multiselect(
   mvRoot.get(MonitoringBE.id_travel).alias("id_travel"),
   mvRoot.get(MonitoringBE.id_set).alias("id_set"),
   mvRoot.get(MonitoringBE.id_legislature).alias("id_legislature"))
.distinct(true).where(predicate);

Can some one guide me.

A: You have to replace the mvRoot.get(MonitoringBE.id_travel) and others in the multiselect-statement with mvRoot.join(MonitoringBE.id_travel, JoinType.LEFT). Otherwise they will end up in a inner join.


Q: Karate mock API: /__admin/stop endpoint not stopping mock service (standalone jar v1.3.0) I am running a mock service using the karate standalone jar version 1.3.0.
Mocking is working fine.
However, when I make a GET request to the /__admin/stop endpoint, the process registers that the endpoint has been called, closes the listen port, but does not stop.
Execution output and scripts...
on startup:
java -jar /opt/karate/karate.jar -m src/test/java/mocks/fs/john.feature -p 80
16:17:16.671 [main]  INFO  com.intuit.karate - Karate version: 1.3.0
16:17:17.315 [main]  INFO  com.intuit.karate - mock server initialized: src/test/java/mocks/fs/john.feature
16:17:17.425 [main]  DEBUG com.intuit.karate.http.HttpServer - server started: aad-9mpcfg3:65080

netstat on listen socket:
netstat -na | grep 65080
tcp6       0      0 :::65080                :::*                    LISTEN

submission of curl commands:
curl -v http://localhost:65080/john/transactionservice/ping

*   Trying 127.0.0.1:65080...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 65080 (#0)
> GET /john/transactionservice/ping HTTP/1.1
> Host: localhost:65080
> User-Agent: curl/7.68.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< content-type: application/json
< content-length: 49
< server: Armeria/1.18.0
< date: Mon, 28 Nov 2022 16:19:37 GMT
<
* Connection #0 to host localhost left intact
{"message":"this is the JOHN TransactionService"}

curl -v http://localhost:65080/__admin/stop

*   Trying 127.0.0.1:65080...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 65080 (#0)
> GET /__admin/stop HTTP/1.1
> Host: localhost:65080
> User-Agent: curl/7.68.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 202 Accepted
< content-type: text/plain; charset=utf-8
< content-length: 12
< server: Armeria/1.18.0
< date: Mon, 28 Nov 2022 16:19:54 GMT
<
* Connection #0 to host localhost left intact

output after curl commands:
java -jar /opt/karate/karate.jar -m src/test/java/mocks/fs/john.feature -p 80
16:17:16.671 [main]  INFO  com.intuit.karate - Karate version: 1.3.0
16:17:17.315 [main]  INFO  com.intuit.karate - mock server initialized: src/test/java/mocks/fs/john.feature
16:17:17.425 [main]  DEBUG com.intuit.karate.http.HttpServer - server started: aad-9mpcfg3:65080
16:19:37.312 [armeria-common-worker-epoll-2-1]  DEBUG com.intuit.karate - scenario matched at line 3: pathMatches('john/transactionservice/ping') && methodIs('get')
16:19:54.603 [armeria-common-worker-epoll-2-2]  DEBUG com.intuit.karate.http.HttpServer - received command to stop server: /__admin/stop

At this point, netstat on listen port shows socket is closed, but the process continues to run:
ps -ef | grep karate
matt     15070 15069  1 16:17 pts/3    00:00:03 java -jar karate-1.3.0.jar -m src/test/java/mocks/fs/john.feature -p 65080

This is the test mock that I am using (src/test/java/mocks/fs/john.feature):
Feature: JOHN TransactionService mock

Scenario: pathMatches('john/transactionservice/ping') && methodIs('get')
    * def response = {}
    * set response.message = 'this is the JOHN TransactionService'
    * def responseStatus = 200

Question:
Is there something else I should be doing to make the mock process stop? I think I'm following the guidance at https://github.com/karatelabs/karate/tree/master/karate-netty#stopping
Thank you in anticipation of responses.


Q: Angular2: How to use on the frontend "crypto.pbkdf2Sync" function from node.js There is a function crypto.pbkdf2Sync() in node.js API and I whant to use it in my Angular2 project.
I tried to import it and use it. Project compiles with no error, but in browser I get an error:

TypeError: webpack_require.i(...) is not a function
      at createHashSlow (hash.ts:4)

Here is the hash.ts module:
import { pbkdf2Sync } from 'crypto';
import { CONFIG } from '../config';

export function createHashSlow(password, salt) {
  return pbkdf2Sync(
    password,
    salt,
    CONFIG.crypto.hash.iterations,
    CONFIG.crypto.hash.length,
    'SHA1'
  ).toString('base64');
};

What did I do wrong? How to make it work?

A: The crypto module is based on OpenSSL that is not available in the browser

The crypto module provides cryptographic functionality that includes a set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign and verify functions.

I suggest to use WebCryptographyApi that is available in all modern browsers. See an example here Angular JS Cryptography. pbkdf2 and iteration


Q: Variable Never Assigned to C# I'm missing something simple here, I know it. My private variables are "not assigned," but from my (limited) knowledge they are. What am I missing? I've looked at the other similar questions, but I don't quite understand the answers (or even the questions!). Please help.
public class Weapon
{
    private string mName;
    private double mRange;
    private double mDamage;

    public string Name
    {
       get { return mName; }
       set { mName=value; }
    }

    public double Range
    {
       get { return mRange; }
       set
       {
          if (value >= 0)
              mRange=value;
          else
              throw new ArgumentException("Invalid Range");
       }
    }

    public double Damage
    {
       get { return mDamage; }
       set
       {
          if (value >= 0)
              mDamage=value;
          else
              throw new ArgumentException("Invalid Damage");
       }
    }

    public Weapon(string n, double d)
    {
       n = Name;
       d = Damage;
    }
    public Weapon (string n, double r, double d)
    {
       n = Name;
       r = Range;
       d = Damage;
    }

A: You have your constructor assignments backwards.
This:
public Weapon(string n, double d)
{
    n = Name;
    d = Damage;
}
public Weapon (string n, double r, double d)
{
    n = Name;
    r = Range;
    d = Damage;
}

Should be this:
public Weapon(string n, double d)
{
    Name = n;
    Damage = d;
}
public Weapon (string n, double r, double d)
{
    Name = n;
    Range = r;
    Damage = d;
}

A: Try this:
public class Weapon
{
    private string _name;
    private double _range;
    private double _damage;

    public string Name
    {
        get
        {
            return _name;
        }
        set
        {
            _name = value;
        }
    }

    public double Range
    {
        get
        {
            return _range;
        }
        set
        {
            if (value >= 0)
                _range = value;
            else
                throw new ArgumentException("Invalid Range");
        }
    }

    public double Damage
    {
        get
        {
            return _damage;
        }
        set
        {
            if (value >= 0)
                _damage = value;
            else
                throw new ArgumentException("Invalid Damage");
        }
    }

    public Weapon(string n, double d)
    {
        Name = n;
        Damage = d;
    }
    public Weapon(string n, double r, double d)
    {
        Name = n;
        Range = r;
        Damage = d;
    }
}


Q: how to avoid ugly composer hell of folders? ... the problem is about use clause position and path, at my projetc/src folder where I run composer require jenssegers/imagehash now I have as ls:
composer.json  composer.lock   sync.php
/vendor
  autoload.php
  /composer
  /jenssegers
       /imagehash
          composer.json  README.md
          /src
              ImageHash.php  Implementation.php  /Implementations

Them, at my projects folder I run php sync.php ... ERROR
PHP Fatal error:  Uncaught Error:  Class 'Jenssegers\ImageHash\ImageHash' not found
How to fix? ... And how to organize or install correctly all folders with KISS and Convention over configuration principles?

At sync.php I have PHP code,
use Jenssegers\ImageHash\ImageHash;  // after composer update
$hasher = new ImageHash;
die("\ndebug\n");

A: Add
require __DIR__ . '/vendor/autoload.php';

to sync.php. You can read more about it here.


Q: How to use a razor variable mixed with html ID text? I am getting an error because the razor and html is getting confused by the compiler I imagine.

My model variable is:
Model.MyLabel

The "Cars" is just raw text that should be in the HTML.
So say Model.MyLabel's value is "123" the ID should be:
id="123Car"

How can I seperate the model's variable name and HTML?

A: You could use regular string add operator

Or C# 6's string interpolation.

A: What you want is to use the <text></text> pseudo tags
<div id="@Model.MyLabel<text>Cars</text>" ...>


Q: In Vue router, why would this happen? this$1.pending !== route In most cases, when I use this.$router.push() everything works fine. However, there is one case where I'm doing that that throws an exception. The page changes just fine - it is just that the message vue-router.esm.js?8c4f:2007 Uncaught (in promise) appears in the console.
I don't see anything different in the way I call this particular route than any other.
The code below is where it fails in the router. this$1.pending1 and route are both objects. I put a breakpoint there and checked the following: JSON.stringify(this$1.pending) === JSON.stringify(route) and that returns true, so they have identical data.
In javascript, objects are not considered equal unless they are the same, but I don't know why, in this case, the object is a clone instead of being identical.
  runQueue(queue, iterator, function () {
    var postEnterCbs = [];
    var isValid = function () { return this$1.current === route; };
    // wait until async components are resolved before
    // extracting in-component enter guards
    var enterGuards = extractEnterGuards(activated, postEnterCbs, isValid);
    var queue = enterGuards.concat(this$1.router.resolveHooks);
    runQueue(queue, iterator, function () {
      if (this$1.pending !== route) { // EXCEPTION ON THIS LINE
        return abort()
      }
      this$1.pending = null;
      onComplete(route);
      if (this$1.router.app) {
        this$1.router.app.$nextTick(function () {
          postEnterCbs.forEach(function (cb) {
            cb();
          });
        });
      }
    });
  });

A: This isn't exactly an answer, but here's a discussion of other people who have run into the same thing: https://github.com/vuejs/vue-router/issues/2932
It doesn't sound like there is a resolution, but since it appears harmless, (except for the message in the console), I'm going to not worry about it at the moment.


Q: UITableViewCell Contents Are Lost When Scrolling I have a Parser object that contains 15 items from the internet (articles).
I am trying to load this items in my TableView. My problem is that I have 8 items visible at start (4 inch retina simulator) but when it starts scrolling, almost all my contents are lost and I cannot see the rest of the 7 items. Not sure what I am doing wrong, this is my code:
- (void)viewDidLoad
{
    [super viewDidLoad];

    parser = [[Parser alloc] init];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[parser items] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ArticleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ArticleCell"];
    Article *article = [parser items][indexPath.row];

    cell.title.text = article.title;
    cell.date.text = article.date;

    return cell;
}

Edit:
This is what it shows when scrolling, if I log the data before returning the cell inside cellRowAtIndexPath:
2013-09-29 13:37:05.341 Inter[3685:a0b] Article for index: 0 . Title: Cagliari-Inter, tutte le curiosità
 ; date: (null) .
2013-09-29 13:37:05.343 Inter[3685:a0b] Article for index: 1 . Title: Cerrone "Oggi abbiamo vinto da squadra"
 ; date: (null) .
2013-09-29 13:37:05.344 Inter[3685:a0b] Article for index: 2 . Title: Le immagini del 10° "Memorial Prisco"
 ; date: (null) .
2013-09-29 13:37:05.345 Inter[3685:a0b] Article for index: 3 . Title: Primavera, Udinese-Inter 0-1
 ; date: (null) .
2013-09-29 13:37:05.345 Inter[3685:a0b] Article for index: 4 . Title: Tutte le immagini della vigilia di Cagliari-Inter
 ; date: (null) .
2013-09-29 13:37:05.346 Inter[3685:a0b] Article for index: 5 . Title: Udinese-Inter Primavera, 0-0 a fine primo tempo
 ; date: (null) .
2013-09-29 13:37:05.347 Inter[3685:a0b] Article for index: 6 . Title: Mazzarri "Rischio buccia di banana in un momento di euforia"
 ; date: (null) .
2013-09-29 13:37:05.348 Inter[3685:a0b] Article for index: 7 . Title: Inter Campus in Bosnia Erzegovina: passi avanti per i progetti a Sarajevo e Domanovici
 ; date: (null) .
2013-09-29 13:37:11.053 Inter[3685:a0b] Article for index: 8 . Title: (null) ; date: (null) .
2013-09-29 13:37:28.181 Inter[3685:a0b] Article for index: 9 . Title: (null) ; date: (null) .
2013-09-29 13:37:29.499 Inter[3685:a0b] Article for index: 10 . Title: (null) ; date: (null) .
2013-09-29 13:37:29.591 Inter[3685:a0b] Article for index: 11 . Title: (null) ; date: (null) .
2013-09-29 13:37:35.642 Inter[3685:a0b] Article for index: 1 . Title: (null) ; date: (null) .
2013-09-29 13:37:35.767 Inter[3685:a0b] Article for index: 0 . Title: (null) ; date: (null) .

Edit:
Complete code here.

A: Try changing the property from (nonatomic, weak)
NSMutableString *title;
NSMutableString *date;

to (nonatomic, strong) should solve your problem.

A:  -(void) ViewDidLoad {
  [super ViewDidLoad];
    parser = [Parser alloc] init];

You Reallocated  and reinitialised parser, is there any part of the code that you are reloading data?  If not your data store will be empty.

A: My suggestions:

*

*Please check, if your tableView's delegate and dataSource are set up correctly. I haven't seen that in your code.

*Please check, what cell class is registered to your table view. I mean, you need to use tableView's registerClass:forCellReuseIdentifier: or registerNib:forCellReuseIdentifier: somewhere.

Anyway, I'm used to work with GUI without IB or storyboards (so, I'm doing everything programmatically), so it's possible that you don't need to do that.
Good luck.

A: I have similar issue before. the cause of my problem is that my view controller get released after I scroll my table view, can you please check if you have same cause?

A: Try to do the below:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * MyIdentifier = @"ArticleCell";
    ArticleCell *cell = [tableView dequeueReusableCellWithIdentifier: MyIdentifier];
    Article *article = [parser items][indexPath.row];

    cell.title.text = article.title;
    cell.date.text = article.date;

    return cell;
}

A: The problem is that the identifier used should be static string
So declare an identifier which is statisc and assign it
static NSString *cellId = @"cellIdentifier";
ArticleCell *cell = [tableView dequeueReusableCellWithIdentifier: cellId];

Also make sure the storyboard cell has the same identifier value.ie here 'cellIdentifier'

A: Check what happens with [[parser items] count] when you scroll. My guess is that it decreases which decrease the row count in your table.
I may be wrong here because I don't know what's Parser (probably your custom class?) but in case if it is used to parse HTTP response, perhaps item count decreases when the parsing has been done?
To check parser item count, add the following to your tableView:cellForRowAtIndexPath:
NSLog(@"Parser item count: %d", parser.items.count);


Q: How to configure Pomelo.EntityFrameworkCore.MySql in XML configuration? I am trying to set up Entity Framework Core, with a Pomelo provider, in a .NET Framework (4.6.2) project. At runtime I get an error message

The Entity Framework provider type 'Pomelo.EntityFrameworkCore.MySql, Pomelo.EntityFrameworkCore.MySql' registered in the application config file for the ADO.NET provider with invariant name 'MySqlConnector' could not be loaded.

I am just guessing at the "invariantName" to use.  According to Microsoft documentation,

invariantName identifies the core ADO.NET provider that this EF provider targets

I am also uncertain what class within the DLL is the actual data provider.
Here is configuration in Web.config at the moment:
<entityFramework>
  <providers>
    <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    <provider invariantName="MySqlConnector" type="Pomelo.EntityFrameworkCore.MySql, Pomelo.EntityFrameworkCore.MySql" />
  </providers>

I've been unable to find documentation for setup in XML config files among the Pomelo pages. Any help would be appreciated.


Q: How to create directories using foreach in chef (with attributes) How do I create multiple directories if my array has attributes in it?
From the chef directory resource documentation I have tested with sample code below and this works. However, I am having trouble if the array contains attributes, and I am not quite sure how to see what it's doing.
%w( /foo /foo/bar /foo/bar/baz ).each do |path|

I have printed all of my variables and observed node.default[:user_home] to be /home/chefuser
# this creates /home/chefuser/.local
directory 'for storing local binaries' do
  path "#{node.default[:user_home]}/.local"
  owner 'chefuser'
  group 'chefuser'
  mode '0755'
  action :create
end

# this does not create /home/chefuser/.local or /home/chefuser/.local/bin (however it doesn't fail)
["#{node.default[:user_home]}/.local", "#{node.default[:user_home]}/.local/bin"].each do |path|                                                                                directory 'for storing local binaries' do
    owner 'chefuser'
    group 'chefuser'
    mode '0755'
    action :create
  end
end

A: The issue is because the name property of the resource is only one (for storing local binaries), and it does not iterate over the attributes passed as array.
For this foreach loop to work, you need to use the loop variable path in the resource.
Example of using it as "resource name":
[
  "#{node.default['user_home']}/.local",
  "#{node.default['user_home']}/.local/bin"
].each do |path|
  directory path do
    owner 'chefuser'
    group 'chefuser'
    mode '0755'
    action :create
  end
end


Q: gradle overwrite plugin repository from init script How can I overwrite all plugin repositories in gradle via the init script?
allprojects {
    repositories {
        maven { url "foo" }
    }
}

only works for regular repositories - not for plugin repositories.
Plugins are registerd via the old buildscript{ repositories { }} notation

A: simply adding:
allprojects {
    buildscript{
        repositories{
          maven { url "https://foo.com" }
        }
    }
    repositories {
        maven { url "https://foo.com" }
    }
}

is the solution


Q: Converting data to panel format using forloops vba-excel My data set looks like:
AUS, UK, USA, GERMANY, FRANCE, MEXICO, DATE
R1, R1,   R1,    R1  ,   R1  , R1    ,  1
R2, R2,   R2,    R2  ,   R2  , R2    ,  2
...

And so on. I want to convert it so that it looks like
COUNTRY, RETURNS, DATE,
AUS,     R1,       1
AUS,     R2,       2
...,    ...,     ...,
UK,     R1,        1,
UK,     R2,        2,
...     ...      ...,
MEXICO, R1,        1,
MEXICO, R2,        2,
...     ...      ...

I feel like this should be possible with a simple nested forloop.
I tried:
    sub panel()
'dim variables
Dim i As Integer
Dim j As Integer
Dim reps As Integer
Dim country As String
Dim strfind As String
Dim obs As Integer

'count the number of countries
reps = Range("D1:AL1").Columns.Count

'count the number of observations per country
obs = Range("C4:C5493").Rows.Count

'copy and paste country into panel format
For i = 1 To reps
    'set country name
    country =Range("D1").Cells(1, i)
    For j = 1 To obs
    'copy and paste country values
    Range("AS2").Cells(j, 1) = country
    Next j
Next i

but after the j loops finishes, and the new country name is set, the new values replace the old values in the first batch of cells.

A: Consider an SQL solution using UNION queries to select each column for long format. If using Excel for PC, Excel can connect to the Jet/ACE SQL Engine (Windows .dll files) via ADO and run SQL queries on worksheets of current workbook.
With this approach, you avoid any for looping, nested if/then logic, and other data manipulation needs for desired output. Below example assumes data resides in tab called DATA and an empty tab called RESULTS.
Sub RunSQL()
    Dim conn As Object, rst As Object
    Dim strConnection As String, strSQL As String
    Dim i As Integer

    Set conn = CreateObject("ADODB.Connection")
    Set rst = CreateObject("ADODB.Recordset")

    ' CONNECTION STRINGS (TWO VERSIONS)
'    strConnection = "DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};" _
'                      & "DBQ=C:\Path\To\Workbook.xlsm;"
    strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" _
                       & "Data Source='C:\Path\To\Workbook.xlsm';" _
                       & "Extended Properties=""Excel 8.0;HDR=YES;"";"
    strSQL = " SELECT 'AUS' AS COUNTRY, AUS AS RETURNS, [DATE] FROM [DATA$]" _
            & " UNION ALL SELECT 'UK', UK AS Country, [DATE] FROM [DATA$]" _
            & " UNION ALL SELECT 'USA', USA AS Country, [DATE] FROM [DATA$]" _
            & " UNION ALL SELECT 'GERMANY', GERMANY AS Country, [DATE] FROM [DATA$]" _
            & " UNION ALL SELECT 'FRANCE', FRANCE AS Country, [DATE] FROM [DATA$]" _
            & " UNION ALL SELECT 'MEXICO', MEXICO AS Country, [DATE] FROM [DATA$];"

    ' OPEN CONNECTION & RECORDSET
    conn.Open strConnection
    rst.Open strSQL, conn

    ' COLUMN HEADERS
    For i = 1 To rst.Fields.Count
        Worksheets("RESULTS").Cells(1, i) = rst.Fields(i - 1).Name
    Next i
    ' DATA ROWS
    Worksheets("RESULTS").Range("A2").CopyFromRecordset rst

    rst.Close: conn.Close
    Set rst = Nothing: Set conn = Nothing
End Sub

Output
COUNTRY     RETURNS     DATE
AUS         R1          1
AUS         R2          2
UK          R1          1
UK          R2          2
USA         R1          1
USA         R2          2
GERMANY     R1          1
GERMANY     R2          2
FRANCE      R1          1
FRANCE      R2          2
MEXICO      R1          1
MEXICO      R2          2

A: Okay, I fixed it. Probably not the best code, but it works :).
Sub replicate_dates()
'declare variables
Dim i As Double
Dim j As Double
Dim reps As Integer
Dim country As String
Dim strfind As String
Dim obs As Integer
'set strfind value
strfind = "-DS Market"

'count the number of countries
reps = Range("D1:AL1").Columns.Count

'count the number of observations per country
obs = Range("C4:C5493").Rows.Count

i = 0
'copy and paste country into panel format
For k = 1 To reps
    'set country name and clean string
    country = Replace(Range("D1").Cells(1, k), strfind, "")
    For j = i + 1 To obs + i
    'copy and paste country values
    Range("AS5").Cells(i, 1) = country
    i = 1 + i
    Next j

Next k

End Sub
Edit: Nvm, this fails to work outside a very specific case.


Q: How to pass parameter to calling form? Here is the code with Form with Singleton pattern.
private Form1(int number = -1)
        {
            test_number = number;
            InitializeComponent();
        }
        private static Form1 _Instance;
        public static Form1 Instance
        {
            get
            {
                if (_Instance == null)
                    _Instance = new Form1();
                return _Instance;
            }
        }

I set int number = -1 in constructor because without it it doens't work here :
if (_Instance == null)
                        _Instance = new Form1();

But when I want to call this form in other form:
Form1 f = new Form1(n);

But here's the error:
Error   2   'KR.Form1' does not contain a constructor that takes 1 arguments

How to pass parameter with Singleton pattern?

A: It seems you want your Singleton to store a variable. Make a function that sets the variable and leave the constructor empty.

A: Don't use a default value in the constructor.  For your singleton, just pass the default value of zero if you don't want to use it.  Or, define two constructors, one without your argument, and one with it.
Also, if you want to use the constructor from another Form (or any other class), it cannot be defined as private.  Define it as public instead.
public Form1(int number) : this() //call the default constructor so that InitializeComponents() is still called
{
    test_number = number;
}

public Form1()
{
    InitializeComponent();
}


Q: Unable to modify Webform field type in Drupal 7 We are working on Drupal 7 and we need to modify the "webform field type" of an existing webform. But we are unable to do that. We have also tried by deleting the existing field "form key" and tried creating a new field with the same "form key" but the data of the existing column gets deleted.

A: @Ravi, you can use the following module to migrate data from the old field to the new field, you just need to map the fields. The module contains an example:
https://www.drupal.org/project/migrate_d2d
If the previous option is too complicated, you can do the following trick:
export the old field table as INSERT format from the database, the table name will looks like this:
field_data_field_name
Then, just replace the name table from the old field to the new field table.
Finally, just execute those insert into your database.
This is an example, how an insert statement looks from a drupal field
INSERT INTO field_data_field_name(entity_type,bundle,deleted,entity_id,revision_id,`language`,delta,field_address_type_value,field_address_type_format) VALUES
('entityform','solicitud_facturacion',0,656,656,'und',0,'AVENIDA',NULL);

I hope you understand this!


Q: Issues Overloading CTOR's in Scala Im having an issue over loading the constructors in Scala. Each time I try to pass a value for the over loaded CTOR I get the error
Example:
    var client : Client = Client(*variable type List[String]()*);

 Unspecified value parameter clientList.

My goal is to have an object created using 2 different data types. One a NodeSeq and the Other a List. Never Both. Am I over loading the CTOR correctly or is there a more efficient way to achieve my goal?
package api
import xml._

case class Client(clientNode: NodeSeq, clientList: List[String]) {

  def this(clientNode: NodeSeq) = this(clientNode, null)
  def this(clientList: List[String]) = this(null, clientList)

  var firstName: String
  var lastName: String
  var phone: String
  var street: String
  var city: String
  var state: String
  var zip: String
  var products = List[String]()
  var serviceOrders = List[String]()

  if (clientList == null) {
    firstName = (clientNode \\ "firstname").text
    lastName = (clientNode \\ "lastname").text
    phone = (clientNode \\ "phone").text
    street = (clientNode \\ "street").text
    city = (clientNode \\ "city").text
    state = (clientNode \\ "state").text
    zip = (clientNode \\ "zip").text

    (clientNode \\ "products").foreach(i => products = i.text :: products)

    (clientNode \\ "serviceOrders").foreach(i => serviceOrders = i.text :: serviceOrders)

  } else {
    firstName = clientList(0)
    lastName = clientList(1)
    phone = clientList(2)
    street = clientList(3)
    city = clientList(4)
    state = clientList(5)
    zip = clientList(6)
  }

  override def toString(): String = {
    return "Name : " + firstName + " " + lastName +
      "\nAddress : " +
      "\n\t" + street +
      "\n\t" + city + ", " + state + " " + zip
  }

}

A: You didn't post working code; you can't have undefined vars.
Anyway, the problem is that even though you have overridden the constructors, you have not overridden the builders in the companion object.  Add this and it will work the way you want:
object Client {
  def apply(clientNode: NodeSeq) = new Client(clientNode)
  def apply(clientList: List[String]) = new Client(clientList)
}

(if you're using the REPL, be sure to use :paste to enter this along with the case class so you add to the default companion object instead of replacing it).
But a deeper problem is that this is not the way you should be solving the problem.  You should define a trait that contains the data you want:
trait ClientData {
  def firstName: String
  def lastName: String
  /* ... */
}

and inherit from it twice, once for each way to parse it:
class ClientFromList(cl: List[String]) extends ClientData {
  val firstName = cl.head
  . . .
}

or you could turn the NodeSeq into a list and parse it there, or various other things.  This way you avoid exposing a bunch of vars which are probably not meant to be changed later.

A: Auxiliary constructors are for simple one-liners and aren't suitable in this case. More idiomatic way would be to define factory methods in a companion object:
case class Client(firstName: String,
                  lastName: String,
                  products: List[String] = Nil)

object Client {

  import scala.xml.NodeSeq

  def fromList(list: List[String]): Option[Client] =
    list match {
      case List(firstName, lastName) =>
        Some(Client(firstName, lastName))
      case _ => None
    }

  def fromXml(nodeSeq: NodeSeq): Option[Client] = {
    def option(label: String) =
      (nodeSeq \\ label).headOption.map(_.text)
    def listOption(label: String) =
      (nodeSeq \\ label).headOption.map {
        _.map(_.text).toList
      }
    for {
      firstName <- option("firstname")
      lastName <- option("lastname")
      products <- listOption("products")
    } yield Client(firstName, lastName, products)
  }
}

I also took the liberty of improving your code by eliminating mutability and making it generally more runtime safe.


Q: I want an extensive table (left->right) but with the first column fixed I am creating a "gant chart" style table, so it means that it has to have the first column fixed, and it can be a very long table , from left to right.
I have tried to  :
1. use simple HTML;
2. use DIVs and CSS;
3. use TH and CSS;
no good results so far
The div was the closest one, but the first column is overflown and the table is not aligned anymore.

            2019

&nbsp
            9

 Department - Team
            4
            5
            6
            7
            8
            9
            10
            11
            12
            13
            14
            15
            16
            17

    Corporate Development - Fundraisin
    7.67
    7.67
    7.67
    7.67
    7.67
    7.67
    7.67
    7.67
    7.67
    7.67
    7.67
    7.67
    7.67
    7.67

    Corporate Development - Marketing
    1.25
    1.25
    1.25
    1.25
    1.25
    1.25
    1.25
    1.25
    1.25
    1.25
    1.25
    1.25
    1.25
    1.25

    FAS - Team A
    10.00
    10.00
    10.00
    10.00
    10.00
    10.00
    10.00
    10.00
    10.00
    10.00
    10.00
    5.00
    5.00
    5.00

    BF Server - Server .
    4.75
    4.75
    4.75
    4.75
    4.75
    4.75
    4.75
    4.75
    4.75
    4.75
    4.75
    1.75
    1.75
    1.75

I expect to see a simple table, but I cannot fit these three outcomes at once:
* very long from left to right;
* the first column is always visible;
* no text overflow (in case of using divs)

A: Some kind of solution, but I am disappointed to not be able to make the header selectable.
The core of my proposal is using a non visible copy of your headlines to make room for the fixed header and then use z-index property to hide the non usable horizontal scrollbar of the .header-container.

.chart {
  position: relative;

/*   simulate horizontal scrolling, to remove */
  width: 700px;
}

.chart-wrapper {
  display: flex;

  overflow-x: scroll;
}

.header-container {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;

  overflow-x: scroll;

  z-index: -1;
}

.data-container {
  display: flex;

  pointer-events: none;
}

.header, .header-spacing {
  flex-shrink: 0;

  display: flex;
  flex-direction: column;

  font-weight: bold;
  text-align: center;
}

.header {
  position: absolute;
  top: 0;
  bottom: 0;

  z-index: 1;

  background: white;
}

.header-spacing {
  visibility: hidden;
}

.data {
  z-index: -2;
}

.row {
  display: flex;

  width: 100%
}

.row > div, .header > div {
  flex-grow: 1;

  min-width: 50px;

  margin: 1px;
}

 Department - Team

Corporate Development - Fundraisin

Corporate Development - Marketing

FAS - Team A

BF Server - Server .

 Department - Team

Corporate Development - Fundraisin

Corporate Development - Marketing

FAS - Team A

BF Server - Server .

4

5

6

7

8

9

10

11

12

13

14

15

16

17

7.67

7.67

7.67

7.67

7.67

7.67

7.67

7.67

7.67

7.67

7.67

7.67

7.67

7.67

1.25

1.25

1.25

1.25

1.25

1.25

1.25

1.25

1.25

1.25

1.25

1.25

1.25

1.25

10.00

10.00

10.00

10.00

10.00

10.00

10.00

10.00

10.00

10.00

10.00

5.00

5.00

5.00

4.75

4.75

4.75

4.75

4.75

4.75

4.75

4.75

4.75

4.75

4.75

1.75

1.75

1.75


Q: snimpy.snmp.SNMPNoSuchObject: No such object was found I'm having an exception raised, but I don't get why
snimpy.snmp.SNMPNoSuchObject: No such object was found

Code
from snimpy import manager as snimpy

def snmp(hostname, oids, mibs):
    logger.debug(hostname)
    logger.debug(oids)
    logger.debug(mibs)
    for mib in mibs:
        snimpy.load(mib)

    session = snimpy.snmp.Session(hostname, "public", 1)
    details = session.get(*oids)

    return [{
                'oid': '.' + '.'.join(repr(node) for node in oid[0]),
                'value': oid[1]
            } for oid in details]

oids = ['.1.3.6.1.2.1.25.3.2.1.3.1', '.1.3.6.1.2.1.43.10.2.1.4.1.1.1.3.6.1.2.1.1.4.0', '.1.3.6.1.2.1.1.1.0', '.1.3.6.1.2.1.1.5.0', '.1.3.6.1.2.1.1.3.0']
hostname = '192.168.2.250'
mibs = ['DISMAN-EVENT-MIB', 'HOST-RESOURCES-MIB', 'SNMPv2-MIB', 'SNMPv2-SMI']
snmp(hostname, oids, mibs)

Error
>>> scanner.get_device_infos('192.168.2.250')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "~/project/daemon/api/scanner.py", line 62, in get_device_infos
    infos = self.network_tools.snmp(hostname, oids, mibs)
  File "~/project/daemon/api/network_tools.py", line 26, in snmp
    logger.debug(type(oids))
  File "~/project/env/lib/python3.5/site-packages/snimpy/snmp.py", line 286, in get
    return self._op(self._cmdgen.getCmd, *oids)
  File "~/project/env/lib/python3.5/site-packages/snimpy/snmp.py", line 278, in _op
    return tuple([(oid, self._convert(val)) for oid, val in results])
  File "~/project/env/lib/python3.5/site-packages/snimpy/snmp.py", line 278, in <listcomp>
    return tuple([(oid, self._convert(val)) for oid, val in results])
  File "~/project/env/lib/python3.5/site-packages/snimpy/snmp.py", line 249, in _convert
    self._check_exception(value)
  File "~/project/env/lib/python3.5/site-packages/snimpy/snmp.py", line 217, in _check_exception
    raise SNMPNoSuchObject("No such object was found")  # nopep8
snimpy.snmp.SNMPNoSuchObject: No such object was found

Doing it in bash works
Reaching the equipment using bash and snmpget command works fine:
declare -a oids=(
'.1.3.6.1.2.1.25.3.2.1.3.1'  # HOST-RESOURCES-MIB::hrDeviceDescr.1
'.1.3.6.1.2.1.43.10.2.1.4.1.1'  # SNMPv2-SMI::mib-2.43.10.2.1.4.1.1 page count
'.1.3.6.1.2.1.1.4.0'  # SNMPv2-MIB::sysContact.0
'.1.3.6.1.2.1.1.1.0'  # SNMPv2-MIB::sysDescr.0
'.1.3.6.1.2.1.1.5.0'  # SNMPv2-MIB::sysName.0
'.1.3.6.1.2.1.1.3.0'  # DISMAN-EVENT-MIB::sysUpTimeInstance
)

for oid in ${oids[@]}; do
    echo "$oid"
    snmpget -v 1 -t .3 -r 2 -c public 192.168.2.250 -m +SNMPv2-MIB "$oid"
    echo
done

output:
.1.3.6.1.2.1.25.3.2.1.3.1
HOST-RESOURCES-MIB::hrDeviceDescr.1 = STRING: Brother HL-5250DN series

.1.3.6.1.2.1.43.10.2.1.4.1.1
SNMPv2-SMI::mib-2.43.10.2.1.4.1.1 = Counter32: 22629

.1.3.6.1.2.1.1.4.0
SNMPv2-MIB::sysContact.0 = STRING:

.1.3.6.1.2.1.1.1.0
SNMPv2-MIB::sysDescr.0 = STRING: Brother NC-6400h, Firmware Ver.1.01  (05.08.31),MID 84UZ92

.1.3.6.1.2.1.1.5.0
SNMPv2-MIB::sysName.0 = STRING: BRN_7D3B43

.1.3.6.1.2.1.1.3.0
DISMAN-EVENT-MIB::sysUpTimeInstance = Timeticks: (168019770) 19 days, 10:43:17.70

Question
What's the matter here?

A: One of the oid seem to trigger the error (cf. '.1.3.6.1.2.1.43.10.2.1.4.1.1'  # SNMPv2-SMI::mib-2.43.10.2.1.4.1.1 page count), moving it to last fix the error. But this is a dubious solution.
oids = [
    '.1.3.6.1.2.1.25.3.2.1.3.1',  # HOST-RESOURCES-MIB::hrDeviceDescr.1
    '.1.3.6.1.2.1.1.4.0',  # SNMPv2-MIB::sysContact.0
    '.1.3.6.1.2.1.1.1.0',  # SNMPv2-MIB::sysDescr.0
    '.1.3.6.1.2.1.1.5.0',  # SNMPv2-MIB::sysName.0
    '.1.3.6.1.2.1.1.3.0',  # DISMAN-EVENT-MIB::sysUpTimeInstance
    # ugly duckling
    '.1.3.6.1.2.1.43.10.2.1.4.1.1'  # SNMPv2-SMI::mib-2.43.10.2.1.4.1.1 page count
]


Q: Force docker compose to pull latest image for a container I've a system running on docker, my system has an specific test environment which might need to update the image version several times on a day...
So every time a new version need to be placed, i need to open the compose.yml file, look the container and edit the image version, then re-run docker compose up -d
So to skip this boring process of edit the compose.yml file, I had one idea: in the pipeline which builds and publishes the docker image, i create a new tag $image_name:latest-test and a new step which publishes the image to this tag
so on any image update in my pipeline two tags are created, one with the version number and other with the latest-test... both are published to dockerhub and this process works like a charm
but even when a new image is published to dockerhub and i run docker compose up -d no matter if the container is running or not, docker doesn't check if the image we have cached is really the one on dockerhub... it assumes the cache is the latest one and dont update
THE QUESTION IS:
1 - is there any way to force docker to check if the cached image has been updated on dockerhub?
2 - is there any other workaround i can do to keep a specific tag on my compose.yml file and update the image when needed without needing to edit the file 1000 times a day?
thanks

A:
is there any way to force docker to check if the cached image has been updated on dockerhub?

No.

is there any other workaround i can do to keep a specific tag on my compose.yml file and update the image when needed without needing to edit the file 1000 times a day?

Just use latest and use docker-compose pull to pull the images.


Q: Is there any way to save variable and its values during debugging in intellij? I am struggling with an error. I cannot find it. Is there a way to compare the debugging results before and after a change in intellij. Other solutions will be also welcomed.
I am explaining my scenario here.
I am debugging a class and at a break point, there are three variables. I named it variableA, variableB and variableC. For example, the debugger stops when the variableA gets its values. At that time, I would like to save the content of variableA. In this way, I can compare the content of variableA before and after the change.

A: I think the only thing, you can do in your case, open all the values of a variable and select all and copy-paste like the Mark pointed out in his comment.

A: Would a print statement work? you could use a global counter to keep track of which pass you are at and then compare the values in the consoles.


Q: C | Pointer | Segmentation fault I have this code:
My problem is that, whenever I call this function ma_init(); I get a segmentation fault on footer->status = FREE; I would appreciate it if somebody points me into the right direction here cause after some googling for some hours, I can't seem to figure this out.
Edit: header file:

A:
typedef unsigned char byte;

This is unreadable. Consider including <stdint.h>  and using uint8_t.

My problem is that, whenever I call this function ma_init(); I get a segmentation fault on footer->status = FREE;

Please learn to compile with all warnings & debug info (e.g. gcc -Wall -Wextra -g with GCC...) then use the debugger (gdb) ...
You are initializing header  to the address of mem_pool.
Then you do some questionable (that is wrong) pointer arithmetic
 mem_chunk_header * footer = header + header->size + sizeof(mem_chunk_header);
 // the + above are likely to be wrong

You are adding to a pointer header so the + is in terms of pointed element size (not bytes), that is in units of sizeof(mem_chunk_header) which certainly is at least 2 and probably more (on my Linux/x86-64 desktop it is 8). Your footer  is far away.
With a debugger, you would have noticed that (by querying the values of header, footer, mem_pool). Consider also using valgrind
BTW, if you are coding a memory allocator à la malloc you'll better base it on operating system specific primitives (generally system calls) modifying your virtual address space. On Linux you would use mmap(2) and friends.

points me into the right direction here cause after some googling for some hours

You need to spend weeks reading some good C programming book. Hours of work are not enough in your case.


Q: Firebase Realtime Database data is loaded too late I get my data in the table on Firebase Realtime Database. However, when there is a lot of data, it takes minutes to load. Like 5-6 minutes for 500 data.
How can I solve this?
Thanks, best regards.
  private void initCustomAdapter() {

        mPeriodsReference.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                mPeriodsReference.keepSynced(true);
                OnlinePeriod period = dataSnapshot.getValue(OnlinePeriod.class);
                dataList.add(period);
            pageNum = 1;
                Collections.reverse(dataList);
            resfreshListView();
            Log.d("TAG","list coming" + dataList);
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                throw error.toException();
            }

        });
        mPeriodsRecycler.setLayoutManager(new GridLayoutManager(mContext, 1));//
        mPeriodsRecycler.addItemDecoration(new GridSpacingItemDecoration(Utils.convertDPToPixel(mContext, 3)));
        mTrackAdapter = new TrackListAdapter(mContext, filterDataList);//new ArrayList<CategoryModel>()
        mPeriodsRecycler.setAdapter(mTrackAdapter);
    }

A: From what I can deduce by looking at the code given, first you are loading the data into the list dataList and then you are reversing the entire list using Collections.reverse(dataList); which is an expensive operation.
So, a way around is make your own reversing function to reverse the arraylist because the default .reverse() provided by the Collections class is not very efficient.
You can try the below code to reverse the list in-place (same ArrayList is used ,hence making it efficient):
public ArrayList<Integer> revArrayList(ArrayList<Integer> list)
    {
        for (int i = 0; i < list.size() / 2; i++) {
            Integer temp = list.get(i);
            list.set(i, list.get(list.size() - i - 1));
            list.set(list.size() - i - 1, temp);
        }

        return list;
    }


Q: Can you permanently add to an array in Javascript? Forgive me, I'm very new to programming in general, especially Javascript. I've basically got an array as shown simplified below.
var recipes = [
    { "recipeName":"Recipe1" , "ingredient1":"Recipe1Ingredient1" , "ingredient2":"Recipe1Ingredient2" , "ingredient3":"Recipe1Ingredient3"},
    { "recipeName":"Recipe2" , "ingredient1":"Recipe2Ingredient1" , "ingredient2":"Recipe2Ingredient2" , "ingredient3":"Recipe2Ingredient3"},
];

On one page, users can search for recipes. On another, they can add recipes to the array via an HTML form. I have the following which pushes the new data to the array.
recipes.push({"recipeName":newRecipeName , "ingredient1":newIngredient1 , "ingredient2":newIngredient2 , "ingredient3":newIngredient3});

This works fine initially, but if I refresh the page or go back to the find page, the new recipe is removed from the array. I want the new recipe to be added permanently to the array.
I'm guessing the solution for this isn't so simple, but I've been looking into this for a while and done a lot of searching to no avail. Can anybody point me in the right direction? Again apologies for my inexperience, I'm very new to programming.

A: The main thing you need to keep in mind here is that each time the page is refreshed it has no knowledge of the data that was on the previous page. As was mentioned in a previous comment, persistent storage is what you're looking for. This might come in the form of a full-on (NoSQL/RDBMS) database or in some other semi-permanent form stored only within the browser.
You can either start using a full-on database or if you want something more light weight, you can use local storage or cookies.  One thing to note is that, unless you implement something server side, eg: a database, the changes will be persistent only to the user and only so long as they don't clear the cache.


Q: Importing multiple files named sequentially in Python I have about 50 Python files in a directory, all named in a sequential order, for example: myfile1, myfile2.....myfile50. Now, I want to import the contents of these files inside another Python file. This is what I tried:
i = 0
while i < 51:
    file_name = 'myfile' + i
    import file_name
    i += 1

However, I get the following error:
ImportError: No module named file_name

How may I import all these sequentially named files inside another Python file, without having to write import for each file individually?

A: You can't use import to import modules from a string containing their name. You could, however, use importlib:
import importlib
i = 0
while i < 51:
    file_name = 'myfile' + str(i)
    importlib.import_module(file_name)
    i += 1

Also, note that the "pythonic" way of iterating a set number of times would be to use a for loop:
for i in range(0, 51):
    file_name = 'myfile' + str(i)
    importlib.import_module(file_name)

A: The other answer by @Mureinik is good, but simply doing - importlib.import_module(file_name) is not enough. As given in the documentation of importlib -

importlib.import_module(name, package=None)
Import a module. The name argument specifies what module to import in absolute or relative terms (e.g. either pkg.mod or ..mod). If the name is specified in relative terms, then the package argument must be specified to the package which is to act as the anchor for resolving the package name (e.g. import_module('..mod', 'pkg.subpkg') will import pkg.mod). The specified module will be inserted into sys.modules and returned.

importlib.import_module simply returns the module object, it does not insert it into the globals namespace, so even if you import the module this way, you cannot later on use that module directly as filename1.<something> (or so).
Example -
>>> import importlib
>>> importlib.import_module('a')
<module 'a' from '/path/to/a.py'>
>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

To be able to use it by specifying the name, you would need to add the returned module into the globals() dictionary (which is the dictionary for the global namespace). Example -
gbl = globals()
for i in range(0, 51):
    file_name = 'myfile{}'.format(i)
    try:
        gbl[file_name] = importlib.import_module(file_name)
    except ImportError:
        pass #Or handle the error when `file_name` module does not exist.

It might be also be better to except ImportError incase file_name modules don't exist, you can handle them anyway you want.

A: @Murenik and @Anand S Kumar already gave a right answers, but I just want to help a little bit too :) If you want to import all files from some folder, it's better to use glob function instead hardcoded for cycle. It's pythonic way to iterate across files.
# It's code from Anand S Kumar's solution
gbl = globals()
def force_import(module_name):
    try:
        gbl[module_name] = importlib.import_module(module_name)
    except ImportError:
        pass #Or handle the error when `module_name` module does not exist.

# Pythonic way to iterate files
import glob
for module_name in glob.glob("myfile*"):
    force_import( module_name.replace(".py", "") )


Q: How to get log by using logog in DLL API's in C++ How to write log inside DLL API?
In my program I am using two threads with one main thread. I am initializing:
LOGOG_INITIALIZE();

logog::LogFile errFile("log.txt");

Into my main thread and using INFO, ERR in main thread other two threads. My main thread is using C++ DLL API's. I am perfectly getting log from main thread and two other running thread but my problem is I am not able to get log from DLL API's flow. How to get log by using logog in DLL API's. I would like to clear here if I am using INFO in DLL API. it is crashing but if I do LOGOG_INITIALIZE(); inside DLL API, INFO executes but does not log anything.

A: If i get it correct, your situation is as follows: You have, for example, one application (EXE) which uses a shared library (DLL). From both, the EXE and the DLL, you want to be able to log.
Last time i checked out the logog library i run in problems with the situation described above. Maybe now it is corrected?
Under windows (only!), the logog library doesn't export any symbols - it is simply not ready to be used as DLL. This forces you to build and use logog as static library - which leads to problems with static variables inside the logog library which should exist only once, but in reality are existing as many times as the static library was linked to a module (EXE or DLL).
The solution would be to build and use the logog library as DLL.
Maybe this covers your problem and you may take the effort to export the symbols of the logog library. Or you could get in contact with the library writer.


Q: knitr hook to separate 000's, but not for years I define a hook at the top of my rnw to separate '000s with commas:
knit_hooks$set(inline = function(x) {
      prettyNum(x, big.mark=",")
    })

However, there are some numbers that I don't want to format like this, such as years. Is there a better way to write the hook, or a way to override the hook when I print \Sexpr{nocomma} in the example below?
\documentclass{article}

\begin{document}

<<setup>>=
  library(knitr)
  options(scipen=999) # turn off scientific notation for numbers
  opts_chunk$set(echo=FALSE, warning=FALSE, message=FALSE)
  knit_hooks$set(inline = function(x) {
      prettyNum(x, big.mark=",")
    })
  wantcomma <- 1234*5
  nocomma <- "September 1, 2014"
@

The hook will separate \Sexpr{wantcomma} and \Sexpr{nocomma}, but I don't want to separate years.

\end{document}

Output:

The hook will separate 6,170 and September 1, 2,014, but I don’t want to separate years.

A: If the only things your don't want comma-separated are strings that have years in, use:
  knit_hooks$set(inline = function(x) {
      if(is.numeric(x)){
          return(prettyNum(x, big.mark=","))
      }else{
          return(x)
       }
   })

That works for your calendar string. But suppose you want to just print a year number on its own? Well, how about using the above hook and converting to character:
What about \Sexpr{2014}?   % gets commad
What about \Sexpr{as.character(2014)}?   % not commad

or possibly (untested):
What about \Sexpr{paste(2014)}?   % not commad

which converts the scalar to character and saves a bit of typing. We're not playing code golf here though...
Alternatively a class-based method:
  comma <- function(x){structure(x,class="comma")}
  nocomma <- function(x){structure(x,class="nocomma")}

  options(scipen=999) # turn off scientific notation for numbers
  opts_chunk$set(echo=FALSE, warning=FALSE, message=FALSE)
  knit_hooks$set(inline = function(x) {
      if(inherits(x,"comma")) return(prettyNum(x, big.mark=","))
      if(inherits(x,"nocomma")) return(x)
      return(x) # default
    })
  wantcomma <- 1234*5
  nocomma1 <- "September 1, 2014"  # note name change here to not clash with function

Then just wrap your Sexpr in either comma or nocomma like:
 The hook will separate \Sexpr{comma(wantcomma)} and \Sexpr{nocomma(nocomma1)}, but I don't want to separate years.

If you want the default to commaify then change the line commented "# default" to use prettyNum. Although I'm thinking I've overcomplicated this and the comma and nocomma functions could just compute the string format themselves and then you wouldn't need a hook at all.
Without knowing exactly your cases I don't think we can write a function that infers the comma-sep scheme - for example it would have to know that "1342 cases in 2013" needs its first number commad and not its second...


Q: Sprites don't stop dragging on MOUSE_UP I have Sprites that I want to have move around when I click and hold them and stop when I release them. I have methods that add Event listeners to the Sprites:
    public function layOutEventListeners():void
    {

        var addSpriteEventListener:Function =
        function(spr:Dictionary, index:int, vector:Vector.<Dictionary>)
        {
            spr["sprite"].addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
            spr["sprite"].addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
        }

        gridVec.forEach(addSpriteEventListener);
    }`

and methods to handle the events:
    public function mouseDownHandler(me:MouseEvent):void
    {
        trace(me.target.toString());
        trace(me.currentTarget.toString());

        this.drawSprite(me.target);
        this.growByTwo(me.target);
        me.stopImmediatePropagation();

        me.currentTarget.startDrag(me);
    }

    public function mouseUpHandler(me:MouseEvent):void
    {
        trace(me.target.toString());
        trace(me.currentTarget.toString());

        me.stopImmediatePropagation();
        this.originalSize(me.target);
        me.currentTarget.stopDrag();
    }`

My problem is: when I click on the Sprites, as soon as I move the cursor, the Sprite's registration point snaps to the cursor, and when I release the mouse the Sprite doesn't stop following the cursor. I initially thought it was a problem with pixel collision. I thought the cursor wasn't touching anything on MOUSE_UP, but that proved to be false after I experimented. I even replicated the exact same Event adding and handling methods by starting another project and found that I wasn't having this problem. The test Sprite was simply dragging and dropping like usual, not snapping to the registration point, and being dragged by the point I clicked.
The only difference I can see, and also my only suspicion, is that the Sprites in my original code are being added to a Sprite, which is then being added to the stage, whereas the Sprite in the test project is being added to the root DisplayObject. I'm thinking that somehow the Event propagating down to the container Sprite and dragging and dropping that without dropping the other Sprite. The weird snapping I'm seeing might be the cursor snapping to the object behind the other sprite. Another important thing: when I drop a Sprite on top of another Sprite, that Sprite stops moving like I want it to, but still trails the registration point.
Regardless, I'm really stumped and I really don't know that I'm running over. Any ideas?

A: This is usually because sometimes the mouse is not over the clip when MOUSE_UP occurs, either because of other clips getting in the way or maybe the player is not refreshing the stage fast enough, etc...
I'm not sure this is your case, but either way it is often recommended to assign the MOUSE_UP event to the stage, so you can safely assure it is always triggered. Make sure to remove the listener on the mouseUp handler though ;)
spr["sprite"].addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
public function mouseDownHandler(me:MouseEvent):void {
   stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
}
public function mouseUpHandler(me:MouseEvent):void {
   stage.removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
}

The down side is that you lose your clip reference on mouseUp, but you can create a reference by hand on mouseDown, or do the whole thing internally (within the sprite's code).