text:
Q: Setting the adapter on a Listview in a custom view injected with Butterknife I have an Activity with a custom view in its Xml layout file:

<com.example.androidmontreal.mvp.infrastructure.views.AndroidRaceResultsView
    android:id="@+id/raceResults"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"/>
    ...

In the onCreate method of this activity I use Butterknife to inject my views:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mvp_main);

    ButterKnife.inject(this);

    ...

}

In my custom view I have a listview. Before adding Butterknife I used to set the adapter for the listview in the onFinishInflate method:
    @Override
protected void onFinishInflate() {
    super.onFinishInflate();

    ...

    listView.setAdapter(resultsAdapter);
}

Since adding Butterknife however, I get an NPE on the line where I set the adapter, because at that stage listview is Null.
My understanding is that the view is only instantiated when the Butterknife.inject() method in the Activity is called, but this happens after the view has been inflated.  What I can't figure out is when I should set the adapter for the listView.
Edit: It seems that the children views on my custom view is null, even after utterknife.inject() has been called on the activity. If I add a call to Butterknife.inject to my onFinishInflate method however, I get an error saying that java.lang.IllegalStateException: Required view with id '2131034112' for field 'listView' was not found

A: You can do it just after

ButterKnife.inject(this);

Internally it fills the listView variable, so it's become available for you.
Ensure that you have
@InjectView(R.id.raceResults)
AndroidRaceResultsView listView;

in you activity.


text:
Q: Seam insertion coordinates - Seam Carving I'm having some trouble understanding seam insertion for image enlarging with Seam Carving. AFIK to enlarge an image by k pixels it's necessary to remove k seams, recording their coordinates and using them to reproduce the process backwards, i.e. re-add the deleted seams but duplicating them and applying some kind of average with neighbouring seams (I'm not concerned with this, since it should be the easy part). My confussion comes with the correctness of the recorded coordinates: they are local to the image from which the seam was removed, so by 'restoring' the first seam every other recorded seam coordinates turn invalid. Am I supposed to correct these coordinates checking if every pixel coordinate of every remaining to add seam comes after the previously added seams? This seems rather cumbersome and highly inefficient, given that I've read inserting seams should be trivial once the seam removal part has been achieved (it has).
I'm not sure if I'm communicating my doubt properly. Let me know if that's not the case, although I tried to be as clear as possible.

A: As pointed out in the cooments, you have to fix indices anyway when inserting even if you can avoid "fixing" in removal part.
You can find a full implementation of seam carving and seam insertion in python here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Найти все .py файлы в папке и изменить их код Скачал с GitHub репозиторий для работы с языком (лингвистика), но к сожалению он написан на python 2, а у меня python 3 компилятор. Я знаю, что есть встроенная библиотека 2to3, которая меняет исходный код файла с python 2 на python 3 этой командой
C:\myDir>2to3 -w -n myFile.py

Файлов очень много, по этому мне хотелось бы узнать, возможно ли найти все файлы с расширением .py в этой папке или во всех дочерних и применить к ним эту команду

A: Пример из доки:

To translate an entire project from one directory tree to another use:

$ 2to3 --output-dir=python3-version/mycode -W -n python2-version/mycode


text:
Q: Locating error in source which is boost related I'm porting an old project from Boost 1.48 to Boost 1.61.  The project is compiled using MSVC 2013.  There are several reported errors during build which I think are boost related but unfortunately the bug reports are not very helpful at all.
3>  entry.cpp
4>c:\program files (x86)\microsoft visual studio 12.0\vc\include\xutility(2715): error C2220: warning treated as error - no 'object' file generated
4>c:\program files (x86)\microsoft visual studio 12.0\vc\include\xutility(2715): warning C4996: 'std::_Fill_n': Function call with parameters that may be unsafe - this call relies on the caller to check that the passed values are correct. To disable this warning, use -D_SCL_SECURE_NO_WARNINGS. See documentation on how to use Visual C++ 'Checked Iterators'
4>          c:\program files (x86)\microsoft visual studio 12.0\vc\include\xutility(2701) : see declaration of 'std::_Fill_n'
4>          c:\boost\boost_1_61_0\boost\random\detail\polynomial.hpp(114) : see reference to function template instantiation '_OutIt std::fill_n<boost::random::detail::polynomial_ops::digit_t*,size_t,boost::random::detail::polynomial_ops::digit_t>(_OutIt,_Diff,const _Ty &)' being compiled
4>          with
4>          [
4>              _OutIt=boost::random::detail::polynomial_ops::digit_t *
4>  ,            _Diff=size_t
4>  ,            _Ty=boost::random::detail::polynomial_ops::digit_t
4>          ]

I cannot see anything in the above that helps me identify where the problem is, there are no line numbers and the snippet of code is not from the compiled file.

A:
@Eljay, does it have a human readable text option I could locate in the IDE? – SPlatten 43 mins ago

The thing you posted IS human readable text. It actually describes a warning with a reference to documentation. ¯\(ツ)/¯ Maybe you can just tell the compiler you don't want to receive warnings
In addition, you can use the keywords to google additional information:

C++ Boost: what's the cause of this warning?

Many libraries in addition already have a warning-suppression header (look for e.g. boost/iostreams/detail/config/disable_warnings.hpp or boost/random/detail/disable_warnings.hpp). The fact that known benign warnings "slip through" might indicate that the library needs to update their suppressions, OR you might need to upgrade your boost version.


text:
Q: Failed to create sessionFactory object.org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [org.sqlite.JDBC] I'm trying to use Hibernate with sqlite.  I downloaded an SQLiteDialect.java file from GitHub which seems to be working fine, but I still get the "Unable to load class" error.  I think it has something to do with my application-context but I'm not sure what it could be.  Here's the full application-context.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="metrolink"/>

    <bean id="sessionfactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />

        <property name="annotatedClasses">
            <list>
                <value>Metrolink</value>
                <value>MetrolinkCalculator</value>
            </list>
        </property>

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.SQLiteDialect</prop>
                <prop key="hibernate.current_session_context_class">thread</prop>
            </props>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.sqlite.JDBC" />
        <property name="url" value="jdbc:sqlite:src/main/resources/metrolink.db" />
    </bean>

</beans>

and the pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org    /2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.mikemenne.launchcode</groupId>
  <artifactId>mqsa</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>Maven Quick Start Archetype</name>
  <url>http://maven.apache.org</url>

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.0.5.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
    </dependency>
<dependency>
  <groupId>org.hibernate</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>4.3.6.Final</version>
</dependency>
<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-annotations</artifactId>
   <version>3.5.6-Final</version>
</dependency>
 <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-validator</artifactId>
   <version>5.1.2.Final</version>
 </dependency>
</dependencies>

</project>

If you need anything else, please let me know.

A: You miss the sqlite-jdbc.jar add
<dependency>
    <groupId>org.xerial</groupId>
    <artifactId>sqlite-jdbc</artifactId>
    <version>3.6.20</version>
</dependency>

To your pom file


text:
Q: How do I modify this PostgreSQL table? I'm using PostgreSQL in my SBC, running Parabola (Arch and ALARM based). I was reading this tutorial so I can use PostgreSQL databases and make Postfix work with them. However, in this step I have to fill up some info in the tables I've created, right? How do I do that? Would be better if I can use pgAdmin3 or phpPgAdmin for this, but if I have to do in CLI, there's no problem.
Thanks.
EDIT: I'm a complete noob with PostgreSQL. I'm trying to learn about it, so if you need more info please tell me how to get it.

A: Short example, and you can run these from pgadmin3 etc as well as the command line.
create table tester (a int, b text);
insert into tester select generate_series(1,1000),'sometext';
select * from tester;

If you need random text, the easy way is to load something like a Shakespeare novel, and use random and substring to grab random sections from that one row in that one table.


text:
Q: Conditional Future in Scala Given these two futures, I need to run the first one only if a condition is true (see if y>2). But I get an exception Future.filter predicate is not satisfied. What does this mean and how to fix the example?
object TestFutures extends App {

  val f1 = Future {
    1
  }

  val f2 = Future {
    2
  }

  val y = 1

  val x = for {
    x1 <- f1 if y>2
    x2 <- f2
  }  yield x1 + x2

  Thread.sleep(5000)
  println(x)
}

A: The question contains some terminology issues.
Given the requirement, "I need to run the first (future) one only if a condition is true", then one possible implementation of the requirement would be:
val f1 = if (cond) Some(Future(op)) else None

This is because a Future will start its execution once it's defined.
Going back to the expression in the question:
val x = for {
  x1 <- f1 if y>2
  x2 <- f2
}  yield x1 + x2

This is saying "I want the result of f1 if(cond)" and not "I want to execute f1 if(cond)".
This would be a way: (note how the futures are defined within the for-comprehension, and the condition is outside):
val x = if (y > 2) {
  for {
      x1 <- Future(op1)
      x2 <- Future(op2)
  }  yield x1 + x2
} else ???

The proper use of guards in for-comprehensions is to evaluate an expression against values coming from the computation expressed by the for-comprehension. For example:
"I want to execute f2 only if the result of f1 is greater than y"
val x = for {
  x1 <- f1
  x2 <- Future(op) if x1 > y
}  yield x1 + x2

Note how the condition here involves an intermediate result of the computation (x1 in this case)

One side note: to wait for the result of a future, use Await.result(fut, duration) instead of Thread.sleep(duration)

A: filter is not really something you should be able to do on a Future - what would a Future that didn't pass the condition return? From your example: we still need to have a value for x1 (even if it fails the if) to use in the yield x1 + x2.
Therefore, the filter method on Future is designed to fail hard when the predicate evaluates to false. It is an "assert" of sorts. You probably would prefer something like this (that provides a default value for x1 if the condition fails):
val x = for {
  x1 <- if (y > 2) f1 else Future.successful(/* some-default-value-for-x1 */)
  x2 <- f2
}  yield x1 + x2


text:
Q: How to obtain frontmatter (meta) from .mdx in nextjs? I set up nextjs13 with ts support and mdx according to the docs.
Now I want to import the frontmatter in one file which was exported from another file. Is that possible?
pages/post.mdx contains
export const meta = {
  title: "some meta",
}

pages/index.tsx contains
import post from './post.mdx';
console.log(post.meta);

Output:
undefined

Expected output:
{ title: "some meta" }

A: Found the solution, while stepping over a github comment:
Wrong:
import post from './post.mdx';
console.log(post.meta);

Correct:
import post, { meta } from './post.mdx';
console.log(meta);

A: I use front-matter, an NPM package.
Example:
import React from "react";
import fm from "front-matter";

export default function SomeComponent({ markdown }) {
  const data = fm(markdown);

  return <div>{JSON.stringify(data)}</div>;
}


text:
Q: how to convert an array of objects to a collection of objects in javascript I hope I'm asking the right question.
I have an array like this:
var arr = [{item: 1}, {item: 2}, {item: 3}];

I need to convert it to an object collection that looks like this:
{item1: {item: 1}, item2:{item:2}, item3:{item:3}}

Is there an easy way to do this?

A: Just loop over arr and add the objects to an object.
var arr = [{item: 1}, {item: 2}, {item: 3}];
var obj = {};

for(var i = 0, len = arr.length; i < len; i++){
    obj['item'+i] = arr[i];
}

I'd suggest leaving this structure as an array unless you have a reason to have it be an object.


text:
Q: Editing assets on the fly App Model There are many times when I have a solution deployed and would like to change something in the CSS or JavaScript without having to go through a full deploy again. With Farm Solutions, you can open the web in SharePoint Designer or directly in the browser, make client side modifications, save and see you changes right away.
Developing in the app model, I can't seem to connect to the App Web's assets. I've tried hitting /_layouts/viewlsts.aspx, connecting via SPD and navigating directly to the /Scripts or /Content libraries. I am denied access through each technique.
Is there a  way to modify files on the fly when deploying a solution using the App model?

A: The App Web was specifically designed to prevent you from doing what you want to do. The App Web site template, the App Web master page, and the AppLockdown Feature are all designed to prevent users from accessing the internals of the App.
For more information watch An overview of developing SharePoint-hosted apps starting at 52:45.


text:
Q: Multaply.com - right click on the website is not working My new website: www.multaply.com. I am unable to do right click on it. Would it be because the developer might have blocked with some plugin? Your help will be much appreciated. Website is being built using WordPress CMS, I believe.

A: There is a JavaScript to prevent this at Line 81 to 90.
<script type="text/javascript">
function mousedwn(e) {
try { if (event.button == 2||event.button == 3) return false; }
catch (e) { if (e.which == 3) return false; }

}
    document.oncontextmenu = function() { return false; }
    document.ondragstart   = function() { return false; }
    document.onmousedown   = mousedwn;
    </script>

The event.button == 2 is your Right-Click. Just remove it...

A: The developer has installed the plugin "WP Content Copy Protection" on the site which includes some javascript that disables right click and various copy functions. You need to uninstall this plugin to re-enable right click.


text:
Q: What is UILocalNotification repeatCalendar used for and how is it used I have created a UILocalNotification I would like to know how ever what repeateCalendar can be used for?
This is my simple implementation of a UILocalNotification.
UILocalNotification *localNotification = [[UILocalNotification alloc] init];

// Set the fire date/time
[localNotification setFireDate:dateFromString];
[localNotification setTimeZone:[NSTimeZone defaultTimeZone]];

// Setup alert notification
localNotification.alertTitle = [NSString stringWithFormat:@"Reminder (%@)", amPm];
localNotification.alertBody = [NSString stringWithFormat:@"This is my alertBody"];
localNotification.userInfo = identificationDict;
localNotification.repeatInterval = NSWeekCalendarUnit;
//localNotification.repeatCalendar = what do I put here? and why;

localNotification.soundName=UILocalNotificationDefaultSoundName;
[localNotification setHasAction:YES];
app = [UIApplication sharedApplication];
[app scheduleLocalNotification:localNotification];

Currently Apple docs say

The calendar the system should refer to when it reschedules a
  repeating notification

However no discussion on why you would use it? In theory could I use it to define Weekday and Weekends?

A: Other than the most widely used calendar - Gregorian calendar, there are a few other calendars, for example in China, we have a Chinese calendar (NSCalendarIdentifierChinese) which is totally different from the Gregorian calendar. We use that calendar for our traditional holidays and astronomical dates. So if the users are mainly Chinese, then you probably need to set repeatCalendar to Chinese calendar, otherwise your notification might fire on the wrong date. Here is the docs from Apple talking about all different kinds of calendars.


text:
Q: How best to implement viewmodel with SwipeRefresh I'm creating my model with modelview and services. This is the best way to create with swipeRefresh
I don't know if I'm doing it the right way so I'm asking for your help
who can give feedback thank you very much.
In fact everything is working perfectly I'm just in doubt about this part:
val viewModel: MyViewModel = viewModel()
         val isRefreshing by viewModel.isRefreshing.collectAsState()

my method SwipeRefresh:
@Composable
    fun SwipeRefresh( content: @Composable (lists:ArrayList<ShoppingCart>) -> Unit){
        val viewModel: MyViewModel = viewModel()
        val isRefreshing by viewModel.isRefreshing.collectAsState()

        com.google.accompanist.swiperefresh.SwipeRefresh(
                state = rememberSwipeRefreshState(isRefreshing),
                onRefresh = { viewModel.refresh() },
                indicator = { state, trigger ->
                    SwipeRefreshIndicator(
                            // Pass the SwipeRefreshState + trigger through
                            state = state,
                            refreshTriggerDistance = trigger,
                            // Enable the scale animation
                            scale = true,
                            // Change the color and shape
                            shape = MaterialTheme.shapes.small,
                    )
                }

        ) {

            if(isRefreshing){
                if(tipos=="frutas"){
                    tipos = "fruta"
                }

                frutas.tipo=tipos
                frutas.getFrutas()

               when(tipos){
                    "saladas"->{
                        val s by frutas.saladasData.collectAsState(initial = emptyList())
                        list = ArrayList(s)
                    }
                    "fruta"->{
                        val f by frutas.frutaData.collectAsState(initial = emptyList())
                        list = ArrayList(f)
                    }
                    "temperos"->{
                        val t by frutas.temperosData.collectAsState(initial = emptyList())
                        list = ArrayList(t)
                    }
                }

            }
                Log.i("LIST",list.toString())
                val t = list.filter { it.product_title!="" }

                if(list.isNotEmpty() && t.isNotEmpty()){
                    content(list)
                }else{
                    helpers.loadingComponent()
                }

            }
        }

My ViewModel:
package com.example.quitanda.models

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

class FrutasViewModel(
    private val frutasServices: Services,
):ViewModel() {

    private val _frutasData: MutableStateFlow<List<ShoppingCart>> = MutableStateFlow(listOf(ShoppingCart()))
    val frutasData: StateFlow<List<ShoppingCart>>
    get() = _frutasData

    private val _frutaData: MutableStateFlow<List<ShoppingCart>> = MutableStateFlow(listOf(ShoppingCart()))
    val frutaData: StateFlow<List<ShoppingCart>>
        get() = _frutaData

    private val _saladasData: MutableStateFlow<List<ShoppingCart>> = MutableStateFlow(listOf(ShoppingCart()))
    val saladasData: StateFlow<List<ShoppingCart>>
        get() = _saladasData

    private val _temperosData: MutableStateFlow<List<ShoppingCart>> = MutableStateFlow(listOf(ShoppingCart()))
    val temperosData: StateFlow<List<ShoppingCart>>
        get() = _temperosData

    lateinit var tipo:String

    fun getFrutas(){
        viewModelScope.launch {
            try {
                when(tipo){
                    "fruta"->{
                        val fruta = frutasServices.getFrutas1()
                        _frutaData.value = fruta
                    }
                    "frutas"->{
                        val frutas = frutasServices.getFruta()
                        _frutasData.value = frutas
                    }
                    "saladas"->{
                        val saladas = frutasServices.getSaladas()
                        _saladasData.value = saladas
                    }
                    "temperos"->{
                        val temperos = frutasServices.getTemperos()
                        _temperosData.value = temperos
                    }

                }

            }catch (e:Exception){
                Log.d("Service error",e.toString())
            }
        }
    }

}

Service:
package com.example.quitanda.models

import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.http.GET

interface Services {
    @GET("category/")
    suspend fun  getFruta(): List<ShoppingCart>

    @GET("category/7")
    suspend fun  getFrutas1(): List<ShoppingCart>

    @GET("category/8")
    suspend fun  getSaladas(): List<ShoppingCart>

    @GET("category/9")
    suspend fun  getTemperos(): List<ShoppingCart>
}

val retrofit: Retrofit = Retrofit.Builder()
    .baseUrl("http://192.168.2.157:4000/")
    .addConverterFactory(MoshiConverterFactory.create())
    .build()

val frutasServices: Services = retrofit.create(Services::class.java)

My Activity:
package com.example.quitanda

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.ShoppingCart
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.NavController
import androidx.navigation.compose.*
import com.example.quitanda.classes.EntryAbstract
import com.example.quitanda.classes.Helpers
import com.example.quitanda.models.FrutasViewModel
import com.example.quitanda.models.ShoppingCart
import com.example.quitanda.models.frutasServices
import com.google.accompanist.pager.ExperimentalPagerApi
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

@Suppress("UNCHECKED_CAST")
@ExperimentalPagerApi
class MainActivity : ComponentActivity() {
    private val entryAbstract = EntryAbstract()
    private var counter = mutableStateOf(0)
    private var ids = mutableStateListOf<ShoppingCart>()
    private lateinit var listFrutas:ArrayList<ShoppingCart>
    private lateinit var listSaladas:ArrayList<ShoppingCart>
    private lateinit var listChas:ArrayList<ShoppingCart>
    private val helpers = Helpers()

    private val viewModel by viewModels<FrutasViewModel> {
        object : ViewModelProvider.Factory {
            override fun <T : ViewModel?> create(modelClass: Class<T>): T {
                return FrutasViewModel(frutasServices) as T
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent{

            if(intent.hasExtra("produtos")) {
                ids = remember { intent.getParcelableArrayListExtra<ShoppingCart>("produtos")!!
                    .toMutableStateList()}

                if (ids.isNotEmpty()) {

                    val aray = ids.count()
                    counter.value = aray
                }
            }

            viewModel.tipo="frutas"
            viewModel.getFrutas()
            val l by viewModel.frutasData.collectAsState(initial = emptyList())

            if (l.isEmpty()) {
                helpers.loadingComponent()
            } else {
                val i = l.filter { it.category_id==7 }
                val o = l.filter { it.category_id==8 }
                val p = l.filter { it.category_id==9 }

                listFrutas = ArrayList(i)
                listSaladas = ArrayList(o)
                listChas = ArrayList(p)
                entryAbstract.cart =ids
                entryAbstract.ccounter =counter
                entryAbstract.frutas = viewModel

                MainContent()
            }

        }
    }

ShoppingCart:
package com.example.quitanda.models

import android.os.Parcelable
import com.squareup.moshi.Json
import kotlinx.parcelize.Parcelize

@Parcelize
data class ShoppingCart(
    var count:Int=0,
    @field:Json(name="product_title")
    var product_title:String="",
    @field:Json(name="product_id")
    var product_id:Int=0,
    @field:Json(name="photo_photo")
    var photo_photo:String="",
    @field:Json(name="product_quant")
    var product_quant:Int=0,
    @field:Json(name="category_name")
    var category_name:String="",
    @field:Json(name="category_id")
    var category_id:Int=0,
    @field:Json(name="product_description")
    var product_description:String="",
    @field:Json(name="product_price_un")
    var product_price_un:String?="",
    @field:Json(name="product_price_kg")
    var product_price_kg:String?="",
    var tipos:String=""): Parcelable

A: I understand seeing my MyViewModel
class MyViewModel : ViewModel() {
    private val _isRefreshing = MutableStateFlow(false)

    val isRefreshing: StateFlow<Boolean>
        get() = _isRefreshing.asStateFlow()

    fun refresh() {
        // This doesn't handle multiple 'refreshing' tasks, don't use this
        viewModelScope.launch {
            // A fake 2 second 'refresh'
            _isRefreshing.emit(true)
            delay(2000)
            _isRefreshing.emit(false)
        }
    }
}

how I make a viewmodel with multiple returns is a little different


text:
Q: why am i seeing the error The app name is not available in wordpress site creation I am trying to create a WordPress website on azure but when I set the app name an error message of- The app name is not available.help!

A: It means that name has been taken and you need to choose another name for your app.The app name should be globally unique. Be as descriptive as possible while naming as its a good practice. You can follow this convention region-service-env-codename: WUS-WEBAPP-DEV-MYAPP. This should hopefully make it unique.


text:
Q: How to to modify grid gutter width in bootstrap sass for different resolutions? I am using Twitter Bootstrap SASS 3.
I want the grid gutter width to be 20px in tablets (screen-sm), 30px in desktop (screen-md and higher).
I have the variable $grid-gutter-width = 30
Then I wrote
@media (min-width: $screen-sm-min) {
   .row{margin-left:-10px; margin-right:-10px;}
   .col{padding-left:10px; padding-right:10px;}
}
@media (min-width: $screen-sm-min) {
    .row{margin-left:-$grid-gutter-width/2; margin-right:-$grid-gutter-width/2;}
    .col{padding-left:$grid-gutter-width/2; padding-right:$grid-gutter-width/2;}
}

after adding a col class to all my row childs (columns)
Does anyone know a smarter way of doing it?


text:
Q: SwiftUI ScrollView vertical and horizontal scroll I have a scrollview that i want change the orientation of the scroll based on a @State.
struct HomeScreen: View {
    @State var isVertical: Boolean = true

    var body: some View {
    VStack{
        Button(action: {
                self.isVertical.toggle()
            }) {
                Text("press me")
        }.padding()
        ScrollView(self.isVertical == true ? .horizontal : .vertical, showsIndicators: true){
                    if(self.isVertical){
                        HStack {
                            Text("a")
                            Text("b")
                            Text("c")
                            Text("d")

                            Spacer()
                        }
                    } else {
                        VStack{
                            Text("a")
                            Text("b")
                            Text("c")
                            Text("d")
                        }
                    }
                }.padding()
    }
}

When within the first time on this screen the scrollview is vertical, as soon as I click on the button and invert the state, the scrollview changes and goes crazy, scrolls both vertically and horizontally. What am I doing wrong? I would like that based on one you are scroll scrolling either vertically or horizontally. Thanks a lot

A: Here is fixed variant (also corrected handling of isVertical to align with meaning)
Tested with Xcode 11.4 / iOS 13.4
struct HomeScreen: View {
    @State var isVertical: Bool = true

    var body: some View {
        VStack{
            Button(action: {
                    self.isVertical.toggle()
                }) {
                    Text("press me")
            }.padding()
            ScrollView(self.isVertical ? .vertical : .horizontal, showsIndicators: true){
                        if(self.isVertical){
                            VStack {
                                Text("a")
                                Text("b")
                                Text("c")
                                Text("d")

                                Spacer()
                            }
                        } else {
                            HStack{
                                Text("a")
                                Text("b")
                                Text("c")
                                Text("d")
                            }
                        }
                    }.id(isVertical)       // << main part !!
                     .padding()
        }
    }
}


text:
Q: What are the equivalents of read-write locks in Python and equivalents for atomic data types in Python? Python seems to only have exclusive locks, but that is not a good choice when I protect some data where I want allow multiple reader threads to read some critical data at same time, while exclusive access to only one thread to modify the data.
The GIL Python doesn't allow multiple interpreter threads to execute at the same time. But still read-write locks would have been a great addition.
Also, atomic data types (such as atomic integer, atomic boolean) are really useful. For example, I may want to keep a variable for recording the size of data processed from some function, when the function is called from multiple threads and multiple times concurrently. An atomic integer or long perfectly fits the  bill, and relieves us from the expensive lock operations. Java has them, C++ has them, Go has them; I wish we will have them in Python as well.


text:
Q: reading the 'return' value of mruby program via C I am facing an issue with calling of mruby VM in C. I could invoke the mruby vm and execute the ruby code from C. I could also trigger the methods defined in the ruby code as well. But I am facing issue while trying to read the return value of the ruby method. I have provided my example scenario below.
CODE:
#include <stdlib.h>
#include <stdio.h>

#include <mruby.h>
#include <mruby/compile.h>

int main(void)
{
  mrb_state *mrb = mrb_open();
  char code[] = "def helloworld() return'OK' end";
  printf("Executing Ruby code from C!\n");

  mrb_load_string(mrb, code);
  mrb_load_string(mrb, "helloworld()");
  // How to read the return value?
  return 0;
}

I am not sure if this is the right way of calling the ruby methods? I couldnt find any documentation or examples on the web. Anyone who tried calling ruby code via c (using mruby) can you please help me?
Regards,

A: The return value of mrb_load_string() is the value of the last evaluated expression. But it's also mrb_undef_value() on failure that happened during parsing or code generation like a syntax error. In general the exc member of mrb_state is non-null if there was an uncaught exception:
mrb_value rv = mrb_load_string(mrb, "helloworld()");
if (mrb->exc) {            // if uncaught exception …
   if (!mrb_undef_p(rv)) { // … during execution/run-time
     mrb_print_error(mrb); // write backtrace and other details to stderr
   }
}
else {
  mrb_p(mrb, rv); // similar to Kernel#p
}

If you only want to call a method, the mrb_funcall() family of functions can be used:
mrb_value rv = mrb_funcall(mrb, mrb_top_self(mrb), "helloworld", 0);

Or:
mrb_value rv = mrb_funcall_argv(mrb, mrb_top_self(mrb), mrb_intern_cstr(mrb, "helloworld"), 0, NULL);

Then the parser and code generator won't be used, thus it'll be faster and unless they're used elsewhere, the executable or (shared) library will be much smaller too. Plus mrb_undef_value() isn't a possible return value, otherwise checking for an uncaught exception and retrieving the return value can be done in the same way.


text:
Q: Adding dropdown and collapse functions to mobile menu An issue that's been bugging me for a while is that by default in the mobile menu of my theme, ALL menu items auto expand so it makes it hard to navigate if you have a lot of sub-menu items.
I'm trying to have my sub-menu items collapse with a drop-down arrow. Something that seems fairly simple but there are no options for adjust this in WordPress.
I managed to find some code in Header.php that you will find below
Any ideas how I can modify this code to have my sub-menu items collapse with a dropdown arrow?
Thanks
Christian

A: You can do it easily by Bootstrap:
Bootstrap Dropdowns
or, You can also hide dropdowns in css:
li ul{
    display: none;
}

and show it on arrow click using jQuery:
$("li a").click(function(){
    $(this).parent().find("ul").toggle();
});

Demo:
https://codepen.io/seyyedmojtaba72/pen/VOgmdE

A: Pure js

let arr=[...document.querySelectorAll(".toggle")];

arr.map(a=> a.onclick = e => {
    a.nextElementSibling.classList.toggle('hide');
    a.innerHTML = a.innerHTML=='→' ? '↓' : '→';
});
.hide { display: none }
.toggle { cursor: pointer}

Home

      SubMenu A
      →

Dropdown 1

Dropdown 2

      SubMenu B
      →

Dropdown 3

Dropdown 4

Back

A: Sorry I had a hard time figuring out how to paste code without errors. Here is my code below. Any way to modify this code to have a collapsible drop down menu on mobile devices?

<!– Toggle button for Main Navigation on mobile –>
<button class="btn btn-primary header__navbar-toggler hidden-lg-up js-sticky-mobile-option" type="button" data-toggle="collapse" data-target="#shaka-main-navigation"> <?php esc_html_e( 'MENU' , 'shaka-pt' ); ?></button>
<!– Main Navigation –>
<nav class="header__navigation collapse navbar-toggleable-md js-sticky-desktop-option" id="shaka-main-navigation" aria-label="<?php esc_html_e( 'Main Menu', 'shaka-pt' ); ?>">
<?php
if ( has_nav_menu( 'main-menu' ) ) {
wp_nav_menu( array(
'theme_location' => 'main-menu',
'container' => false,
'menu_class' => 'main-navigation js-main-nav js-dropdown',
'walker' => new Aria_Walker_Nav_Menu(),
'items_wrap' => '
%3$s',
) );
}
?>
<?php


text:
Q: How to get response from foo.onload = function(){? I have a function that is triggered using .onload. I'd like return a value:
newImg.onload = function() {
    var height = newImg.height;
    var width = newImg.width;
    if(height > width){
        console.log(false);
        return false;
    } else {
        console.log(true);
        return true;
    }
 }
 newImg.src = imgSrc; // this must be done AFTER setting onload

Normaly I'd do something like
var foo = function(){...

but this doesn't work in this case. What should I do instead?

A: Asynchronous calls can not return values. You would need to use a callback like you would do in an Ajax request.
function loadImg (imgSrc, callback) {
    var newImg = new Image();
    newImg.onload = function() {
        var height = newImg.height;
        var width = newImg.width;
        if(height > width){
            console.log(false)
            if(callback) callback(false);
        } else {
            console.log(true)
            if(callback) callback(true);
        }
     };
     newImg.onerror = function () {
         if(callback) callback('error');
     };
     newImg.src = imgSrc;

}

loadImg("foo.gif", function(status) { console.log("Do Next Step"); })

A: You have two options;

*

*Set the value to another variable.
var foo;

newImg.onload = function () {
    foo = true;
};

// Sometime later read `foo`.

... albeit this is prone to disaster, as you can't guarantee when the variable will be set, as the image will take some amount of time to load.

*A better option would be to call another function, pass the value you want to pass, and handle it accordingly then.
newImg.onload = function () {
    foo(true);
};

function foo(result) {
    // do something with result
}


text:
Q: How to use "position: relative" properly in my case? I have recently started to code again after a long break and now I'm trying hard to see what is it that I'm doing wrong.
I made a JSFiddle here: http://jsfiddle.net/mtsgp3gg/
This is the output I'd like to see: http://puu.sh/jwi3d/233c917986.png
I have a container with 3 images:

I would like to put some little "tape thingies" over my main picture using position: relative; and top:0; but so far I failed.
Can anyone point out what I'm doing wrong please?

A: css position: is somewhat confusing, especially at the start (and it is misused almost 99% of all times).
You use position: relative because you want it to be relative to the container, right? Although this is the obvious behavior, it is not what css does.
position: relative means "I'll give you top/right/... values and want that the element is moved by that amount from where it would occur normally."
You almost always want to use position: absolute which basically means "pick the boundaries of the parent (being specific: the first parent that is not position: static which is the default) and move this element to what I define with top/right/...". (There are more implications like absolute removing the element from the document flow, but that's out of scope at the moment.)
This means you have to

*

*position your container not static. position: relative works fine here, as it does not alter the element if you don't specify top/... .

*position your items with position: absolute as they will then be defined relative to their container (not relative to their original position, as they would be with position: relative).

Your example would look like

body {
    background: gray;
}

.container {
    position: relative;
    margin-left: 20px;
    margin-top: 20px;
    width: 200px;
    height: 200px;
    background: navy;
}

.container [id] {
    position: absolute;
    top: -5px;
}

.container #one {
    left: -5px;
}

.container #two {
    right: -5px;
    transform: rotate(90deg);
}

A: You're using position:relative when you should be using position:absolute.

body {
  background: gray;
}
.container {
  margin-left: 20px;
  margin-top: 20px;
  width: 200px;
  height: 200px;
  background: navy;
  position: relative;
}
.container #one {
  position: absolute;
  top: 0;
  left: 0;
  transform: translate(-25%, -25%)
}
.container #two {
  position: absolute;
  top: 0;
  left: 100%;
  transform: translate(-75%, -25%) rotate(90deg);
}

That said, I'd prefer not to have presentational images in the HTML at all. So I'd be using pseudo-elements using the same techniques.

body {
  background: gray;
}
.container {
  margin-left: 20px;
  margin-top: 20px;
  width: 200px;
  height: 200px;
  background: navy;
  position: relative;
}
.container::before {
  position: absolute;
  content: '';
  width: 20px;
  height: 20px;
  background-image: url(http://fenrir.info.uaic.ro/~elena.chiosa/img/scoci.png);
  top: 0;
  left: 0;
  transform: translate(-25%, -25%);
  z-index: 1;
}
.container::after {
  position: absolute;
  content: '';
  width: 20px;
  height: 20px;
  background-image: url(http://fenrir.info.uaic.ro/~elena.chiosa/img/scoci.png);
  top: 0;
  left: 100%;
  transform: translate(-75%, -25%) rotate(90deg);
}

In this way, the presentational part is now in the CSS and the class can be re-used without having multiple instances of the tape image cluttering up your HTML.

A: Try to use position: absolute; instead of position: relative;
.container #one{
    position: absolute;
    top: 10px;
    left:20px;
}

.container #two{
    position: absolute;
    top: 10px;
    left:215px;

    transform: rotate(90deg);
}

Demo here


text:
Q: Jpa Entity Graph usage in JPARepository and EntityManager leads to different results I'm working on explore applications of Entity Graphs. When I tried to create few graphs via @NamedEntityGraphs for one entity I figured out, that for each graph I needed a separate method in my repository. So I decided to load data with help of EntityManager and its find method, instead of repository usage. But when I rewrote code, it provide different behavior in some cases. So I make a simple example, to demonstrate it.
I have two entities. The Profile and the Post. Each Profile may create Post or add existed Post to its favorites:
//Profile.java
@Entity
@NamedEntityGraphs({
        @NamedEntityGraph(
                name = "profile.post-fav-posts",
                attributeNodes = {
                        @NamedAttributeNode(value = "posts"),
                        @NamedAttributeNode(value = "favoritePosts")
                }
        )
})
public class Profile {
    @Id
    @GeneratedValue
    Long id;
    @ManyToMany
    Set<Post> favoritePosts = new HashSet<>();
    @OneToMany(mappedBy = "owner", fetch = FetchType.LAZY)
    Set<Post> posts = new HashSet<>();

    //... constructors
}

//Post.java
@Entity
public class Post{
    @Id()
    @GeneratedValue()
    Long id;
    String title;
    @ManyToOne
    Profile owner;

    //... constructors
}

I have a repositories for each entity:
//ProfileRepository.java
@Repository
interface ProfileRepository extends JpaRepository<Profile, Long> {

    @Query("SELECT p FROM Profile p WHERE p.id = :id")
    @EntityGraph(value = "profile.post-fav-posts", type = EntityGraph.EntityGraphType.LOAD)
    Profile findByIdWithPostsAndFavoriteProfiles(Long id);
}

//PostRepository .java
@Repository
interface PostRepository extends JpaRepository<Post, Long> {}

And a service for Entity manager usage:
@Service
public class ProfileService {

    @PersistenceContext
    EntityManager entityManager;
    @Autowired
    ProfileRepository profileRepository;

    Profile findByIdWithEntityManager(Long id) {
        Map<String, Object> properties = new HashMap<>();
        properties.put(QueryHints.HINT_LOADGRAPH, entityManager.getEntityGraph("profile.post-fav-posts"));

        return entityManager.find(Profile.class, id, properties);
    }

    Profile findByIdWithRepository(Long id) {
        return profileRepository.findByIdWithPostsAndFavoriteProfiles(id);
    }
}

Finally, I wrote a test to demonstrate the difference in behavior:
@SpringBootTest
public class SimpleTest {

    @Autowired
    ProfileService profileService;
    @Autowired
    ProfileRepository profileRepository;
    @Autowired
    PostRepository postRepository;
    @Autowired
    private PlatformTransactionManager transactionManager;
    private TransactionTemplate transactionTemplate;

    @BeforeEach
    void initTransactionTemplate() {
        transactionTemplate = new TransactionTemplate(transactionManager);
    }

    @Test
    void testEntityManager() {
        Profile profile1 = profileRepository.save(new Profile(1L));
        Profile profile2 = profileRepository.save(new Profile(2L));
        Post post1 =transactionTemplate.execute(status -> postRepository.save(new Post(3L, "Title 1", profile1)));
        Post post2 = transactionTemplate.execute(status -> postRepository.save(new Post(4L, "Title 2", profile2)));
        profile1.favoritePosts.add(post2);
        profileRepository.save(profile1);

        Profile result = profileService.findByIdWithEntityManager(profile1.id);

        System.out.println("Favorite profiles set size: " + result.favoritePosts.size());
        System.out.println("Posts set size: " + result.posts.size());
    }

    @Test
    void testJpaRepository() {
        Profile profile1 = profileRepository.save(new Profile(1L));
        Profile profile2 = profileRepository.save(new Profile(2L));
        Post post1 = transactionTemplate.execute(status -> postRepository.save(new Post(3L, "Title 1", profile1)));
        Post post2 = transactionTemplate.execute(status -> postRepository.save(new Post(4L, "Title 2", profile2)));
        profile1.favoritePosts.add(post2);
        profileRepository.save(profile1);

        Profile result = profileService.findByIdWithRepository(profile1.id);

        System.out.println("Favorite profiles set size: " + result.favoritePosts.size());
        System.out.println("Posts set size: " + result.posts.size());
    }
}

The SQL queries generated after calling find methods:
--Entity manager test:
select
    profile0_.id as id1_1_0_,
    favoritepo1_.profile_id as profile_1_2_1_,
    post2_.id as favorite2_2_1_,
    post2_.id as id1_0_2_,
    post2_.owner_id as owner_id3_0_2_,
    post2_.title as title2_0_2_,
    profile3_.id as id1_1_3_
from profile profile0_
    left outer join profile_favorite_posts favoritepo1_
    on profile0_.id=favoritepo1_.profile_id
    left outer join post post2_
    on favoritepo1_.favorite_posts_id=post2_.id
    left outer join profile profile3_
    on post2_.owner_id=profile3_.id
where profile0_.id=?

--Repository test:
select
    profile0_.id as id1_1_0_,
    posts1_.id as id1_0_1_,
    post3_.id as id1_0_2_,
    posts1_.owner_id as owner_id3_0_1_,
    posts1_.title as title2_0_1_,
    posts1_.owner_id as owner_id3_0_0__,
    posts1_.id as id1_0_0__,
    post3_.owner_id as owner_id3_0_2_,
    post3_.title as title2_0_2_,
    favoritepo2_.profile_id as profile_1_2_1__,
    favoritepo2_.favorite_posts_id as favorite2_2_1__
from profile profile0_
    left outer join post posts1_
    on profile0_.id=posts1_.owner_id
    left outer join profile_favorite_posts favoritepo2_
    on profile0_.id=favoritepo2_.profile_id
    left outer join post post3_
    on favoritepo2_.favorite_posts_id=post3_.id
where profile0_.id=?

select
    profile0_.id as id1_1_0_
from profile profile0_
where profile0_.id=?

So the questions is:

*

*Why doesn't EntityManager initialize one of relationships (Prodile.posts)?

*Is there any solutions to fetch data via entity graphs without annotations?


text:
Q: Spring boot service method returns page of interfaces Let's suppose that I have an interface Stuff like this:
public interface Stuff {
  Long getId();

  String getName();
}

and I have implemented this interface as StuffEntity:
@Entity
public class StuffEntity implements Stuff {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  protected Long id;
  protected String name;

  // constructors, getters (implement interface methods), setters, ...
}

and I have a service interface StuffService:
public interface StuffService {
  Page<Stuff> getStuff(Pageable pageable);
}

implemented as StuffServiceImpl:
@Service
public class StuffServiceImpl implements StuffService {
  @Autowired
  private StuffEntityRepository repository;

  @Overrride
  public Page<Stuff> getStuff(Pageable pageable) {
    Page<StuffEntity> stuffEntityPage = repository.findAll(pageable);
    return new PageImpl<>(stuffEntityPage.getContent().stream()
      .map(Stuff.class::cast)
      .collect(
        Collectors.toList()),
        stuffEntityPage.getPageable(),
        stuffEntityPage.getTotalElements()
      );
}

I don't like casting here and creating new instance of PageImpl, so I tried something like this:
public interface StuffService {
  Page<? extends Stuff> getStuff(Pageable pageable);
}

@Service
public class StuffServiceImpl implements StuffService {
  @Autowired
  private StuffEntityRepository repository;

  @Overrride
  public Page<? extends Stuff> getStuff(Pageable pageable) {
    return repository.findAll(pageable);
}

As I've already said, I don't like casting and creating new PageImpl instance in my service class, but I like how my code looks cleaner that way. The other approach does not need casting or creating new PageImpl instance in my service class, but I am little worried about service's client side, because now I return wildcard instead of an interface.
Which approach do you think is better?

A: It is always good practice to not use wildcard type as return type.

It is highly recommended not to use wildcard types as return types.
Because the type inference rules are fairly complex it is unlikely the
user of that API will know how to use it correctly.
Let's take the example of method returning a "List<? extends Animal>".
Is it possible on this list to add a Dog, a Cat, ... we simply don't
know. And neither does the compiler, which is why it will not allow
such a direct use. The use of wildcard types should be limited to
method parameters.
This rule raises an issue when a method returns a wildcard type.

Source


text:
Q: How to make particular tab in FragmentTabHost has multiple fragment navigations like tabgroupactivity I created three tabs using FragmentTabHost. Now I need to make all the navigation are under the tabs. How can I get this. I need to get what we get using TabGroupActivity.
Tab1
   --->frag1-->frag2
Tab2
   --->frag3
Tab3
   --->frag4--->frag5
I have used fragmentTransaction.add(), fragmentTransaction.remove(), fragmentTransaction.replace(). These three methods but nothing give solution.
Replace  method shows new fragment view on top of existing fragment view.
Remove and Add, from these two remove only works, add does not works.
Thanks in advance.
TabHostMain.java
    @Override
    protected void onCreate(Bundle savedInstanceState)
 {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.bottom_tabs);

mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
                mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
            View view;
    view=getTabView(R.drawable.ic_launcher);

    Bundle b = new Bundle();
    b.putString("key", "Simple");
    mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator(view),Fragment1.class, null);

    b = new Bundle();
    b.putString("key", "Contacts");
    view=getTabView(R.drawable.ic_launcher);
    mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator(view), Fragment2.class, null);

    b = new Bundle();
    b.putString("key", "Custom");
    view=getTabView(R.drawable.ic_launcher);
    mTabHost.addTab(mTabHost.newTabSpec("custom").setIndicator(view),Fragment3.class, null);

}

Fragment3.java
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {

        View view=LayoutInflater.from(getActivity()).inflate(R.layout.activity_second, null);

        ((TextView)view.findViewById(R.id.second_act_text)).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                FragmentManager fm=getChildFragmentManager();
                FragmentTransaction fragmentTransaction=fm.beginTransaction();
                fragmentTransaction.replace(R.id.second_activity, new Fragment1()).addToBackStack(null).commit();
            }
        });
        return view;
    }

A: The concept of different fragment navigation stacks in each tab has been discussed quite a few times on stackoverflow, one example for instance:
Separate Back Stack for each tab in Android using Fragments
One simple/crude way of achieving this without having to manage your own custom navigation back stack is to have a root fragment under each tab, and then whenever a root fragment wants to navigate to another fragment (fragment B) simply show a new Activity initially with fragment B and that Activity will have its own fragment navigation back stack.
Tab1 --->root frag1 --> Activity (own nav back stack) --> frag2
Tab2 --->root frag3
Tab3 --->root frag4 --> Activity (own nav back stack) --> frag5 --> frag6 --> frag7
An example of an app that does something like this is actually the StackAnywhere app. It makes heavy use of tabs, but when you navigate within those tabs it generally moves the navigation to a new Activity. YMMV with this approach, however.


text:
Q: How can I schedule tasks in a WinForms app? QUESTION: How can I schedule tasks in a WinForms app?   That is either (a) what is the best approach / .NET classes/methods to use of (b) if there is an open source component that does this well which one would be recommended.
BACKGROUND:

*

*Winforms app (.NET v3.5, C#, VS2008)

*I'm assuming I will run the winforms application always, and just minimise to the system tray when not in use

*Want a simple approach (didn't want to get into separate service running that UI winforms app talks to etc)

*Want to be able to let the user select how often to schedule the sync (e.g. hourly, daily - pick time, etc)

*Ability to at the times when the scheduler fires to run a chunk of code (assume it could be wrapped as a backgroundworker task for example)

*The application is always running & appears in the system tray

A: If you don't want a Windows service then starting the application with windows is an option. You can use the following code to do that.
Dim regKey As RegistryKey
regKey = Registry.CurrentUser.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", True)
regKey.SetValue(Application.ProductName, Application.ExecutablePath)
regKey.Close()

What did you mean by schedule the sync? Is it a diff service? Then you can use the timer and then store the user settings in an xml file or a DB. If you want a simple storage then you can use My.Settings.
Edit: I think the only way is to check for the date when the app starts and then check the date periodically. Another option is to use the task scheduler programatically. Task Scheduler Managed Wrapper is an open source wrapper which you can try out.

A: There's actually something directly built into Windows that will do just that. It's called the Windows Task Scheduler! Rather than having a Windows application that sits and waits for the right time to run a piece of code, you'd be better off just using an underlying system utility and storing the piece of code to run in a separate executable: it's easier and more efficient.
I've used the Task Scheduler before to configure my applications to start on a pretty specific schedule. The best way to do it out of a .NET application is to use this handy little library.
Basically, to accomplish what you've stated in your question, you need to make a Windows application that provides a GUI. This GUI should have options that regulate the creation and alteration of a Task. The Task should launch the code you have to run (you should store it in a separate executable, probably as a WinForms app that's transparent and, thus, hidden.)
Here's some code from the CodeProject article of the library itself that illustrates how to create a task:
//Get a ScheduledTasks object for the local computer.
ScheduledTasks st = new ScheduledTasks();

// Create a task
Task t;
try {
    t = st.CreateTask("D checker");
} catch (ArgumentException) {
    Console.WriteLine("Task name already exists");
    return;
}

// Fill in the program info
t.ApplicationName = "chkdsk.exe";
t.Parameters = "d: /f";
t.Comment = "Checks and fixes errors on D: drive";

// Set the account under which the task should run.
t.SetAccountInformation(@"THEDOMAIN\TheUser", "HisPasswd");

// Declare that the system must have been idle for ten minutes before
// the task will start
t.IdleWaitMinutes = 10;

// Allow the task to run for no more than 2 hours, 30 minutes.
t.MaxRunTime = new TimeSpan(2, 30, 0);

// Set priority to only run when system is idle.
t.Priority = System.Diagnostics.ProcessPriorityClass.Idle;

// Create a trigger to start the task every Sunday at 6:30 AM.
t.Triggers.Add(new WeeklyTrigger(6, 30, DaysOfTheWeek.Sunday));

// Save the changes that have been made.
t.Save();
// Close the task to release its COM resources.
t.Close();
// Dispose the ScheduledTasks to release its COM resources.
st.Dispose();

NOTE: The priority option never worked for me, always crashing the app. I recommend you leave it out; usually, it doesn't make that big a difference.
There are more code samples on the article page, some of which show how to change the settings of a Task, list all Scheduled Tasks, etc.

A: So you want to run tasks that are predefined code in your app and not external exes?

*

*Make a winforms app with a system tray icon.  If you are deploying using click once, make the Publisher name "Startup" so a shortcut installs in the Startup directory.

*Use a timer to check against the schedule and launch threads if needed.  Store you local schedule in an XML file so it can be easily queried with LINQ.

*You are running your tasks with Background worker so threading is already in use.
If you wanted to use the Windows Task Scheduler however, there is an API for it.  Not a graceful module but it works well enough.


text:
Q: remove hash from url smoothscroll.js i have a problem in a one page scrolling template that used a plagin (smoothscroll.js)
i try to remove hash from url after user click on link but unfortunatly i cant do it.for example
*About Us url take the hush and target(section2) like this http://localhost/template/#section2
how can i remove #section2 form the url
here is the code
var linkHandler = function(ev) {
ev.preventDefault();

if (location.hash !== this.hash) window.history.pushState(null, null, this.hash);
// using the history api to solve issue #1 - back doesn't work
// most browser don't update :target when the history api is used:
// THIS IS A BUG FROM THE BROWSERS.
// change the scrolling duration in this call
smoothScroll(document.getElementById(this.hash.substring(1)), 1000, function(el) {
    location.replace('#' + el.id);
    // this will cause the :target to be activated.
});

}

A: remove section2 from URL:
location.hash = '';

edit
not sure why that's not working, but here's another, less efficient way:
location.href = location.href.split('#')[0];


text:
Q: How can we get the variable value from script tag of HTML response using javascirpt? I would like to get the value of g_listData from the following HTML response (Received this HTML response from FetchAPI request)
<html>
    <body>
    <script type="text/javascript">......</script>
    <script type="text/javascript">......</script>

    <script type="text/javascript">

       var g_deferData= "testdata";

       var g_listData = {"wpq":"","Templates":{},"ListData":{ "Row" : [
           {
            "ID": "85018",
            "FileLeafRef": "read only"
           },
           {
           "ID": "85091",
           "FileLeafRef": "completed"
           }
         ]}
       }

    </script>
    </body>
 </html>

A: You can try JSON.parse

const data = `<html>
    <body>
    <script type="text/javascript">

       var g\_deferData= "testdata";

       var g_listData = {"wpq":"","Templates":{},"ListData":{ "Row" : [
           {
            "ID": "85018",
            "FileLeafRef": "read only"
           },
           {
           "ID": "85091",
           "FileLeafRef": "completed"
           }
         ]}
       }

    <\/script>
    </body>
 </html>`

 const div = document.createElement("div")
 div.innerHTML=data;
 let g_listData = div.querySelector("script").textContent.split("g_listData =")[1]
 console.log(JSON.parse(g_listData))


text:
Q: Python tflearn: Load a zip file with folders containing images I have a zip file which has several hundred folders in it each containing 3-4 images. I want to use these images as the training data to recognize faces. How do I load these images?
And, what is the optimal way to load datasets? As a pkl file or something else?

A: I would unzip the file first then you have a folder structure and then you can easily do something like this:
import os
imgs = []
for directory in os.listdir(base_directory):
    for file in os.listdir(directory):
         imgs.append(scipy.misc.imread(base_directory + "/" + directory + "/" + file)

in case you have other files in there you can use os.path.isdir to check if it is a dir and file.endswith to check if it is a file with your image ending.


text:
Q: .htaccess rewrites results in www.www What I want to achieve should be quite simple:
Redirect all traffic to HTTPS and the www. subdomain.  And to achieve this I used the following rule:
# Canonical https/www
<IfModule mod_rewrite.c>
    RewriteCond %{HTTPS} off [OR]
    RewriteCond %{HTTP_HOST} ([^.]+)\.domain.com [NC]
    #RewriteCond %{HTTP_HOST} !^www\. [NC]
    #RewriteCond %{HTTP_HOST} ^(.*)$  [NC]
    RewriteRule ^(.*) https://www.%1/$1 [R=301,L]
</IfModule>

However, if I follow a link like this:
http://www.example.com
I end up here:
https://www.www.example.com
So then I found this question: .htaccess: http://www redirects to www.www
And I completely replaced the rule I used above with the rule suggested in the accepted answer:
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
RewriteRule ^(.*)$ https://www.%1%{REQUEST_URI} [R=301,L]

However now I get the ERR_TOO_MANY_REDIRECTS error, and the site completely refuses to load.
Can someone help me out here?

A: Check this rewrite in your .htaccess file, maybe it help
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www.example.com$ [NC]
RewriteRule (.*) https://www.example.com/$1 [R=301,L]


text:
Q: Connect with WCF to a WebService authenticated with username/password I created a proxy of a Web Service with Visual Studio 2008, and it created for me the following entry in the app.config:
<system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="MyNameHandlerSoapBinding" closeTimeout="00:01:00"
                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                    messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
                    useDefaultWebProxy="true">
                    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    <security mode="None">
                        <transport clientCredentialType="None" proxyCredentialType="None"
                            realm="" />
                        <message clientCredentialType="UserName" algorithmSuite="Default" />
                    </security>
                </binding>
            </basicHttpBinding>
        </bindings>
        <client>
          <endpoint address="http://www.***/***/***"
              binding="basicHttpBinding" bindingConfiguration="MyNameHandlerSoapBinding"
              contract="***.MyNameHandler" name="MyName">
          </endpoint>
        </client>
    </system.serviceModel>

The webservice is has username/password authentication so I need to add it somewhere here.
I'm a bit lost in the sea of WCF documentation, I think I have to change from basicHttpBinding to wsHttpBinding or customBinding to be able to add the authentication elements, but I don't really understand it. Could anybody give any quick tip or any useful link that says how to do so?
EDIT:
I changed the security section to:
<security mode="Transport">
    <transport clientCredentialType="Basic" proxyCredentialType="None"
         realm="" />
</security>

and added in the code:
ws.ClientCredentials.UserName.UserName = "";
ws.ClientCredentials.UserName.Password = "";

Now it seems it might be using the credentials but it's giving me the error:
the provided URI scheme 'http' is invalid URI expected 'https'
I don't even know if this is the right way to go...

A: The error message is right. WCF will not allow transport of usernames and passwords over an unprotected protocol. Your web service must be using HTTPS (with the attendant SSL certificate)
Once you have an SSL certificate you have two options on how the credentials are sent, transport or security and multiple options for the type of credential. MSDN has a good guide to all of the various options.

A: I post here the solution for future readers:
<system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="MyHandlerSoapBinding" closeTimeout="00:01:00"
            openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
            allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
            maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
            messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
            useDefaultWebProxy="true">
          <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
              maxBytesPerRead="4096" maxNameTableCharCount="16384" />
          <security mode="TransportCredentialOnly">
            <transport clientCredentialType="Basic"  />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://www.***/***/***/MyHandler"
          binding="basicHttpBinding" bindingConfiguration="MyHandlerSoapBinding"
          contract="***.MyHandler" name="MyHandler">
      </endpoint>

    </client>
  </system.serviceModel>

In the end I could use the default basicHttpBinding. The only difference from the code posted in the question is the security node.
Also note the mode="TransportCredentialOnly" option, this allows you to send username/password using http instead of https. This is necessary for testing environments as the one I'm using. Later on obviously you'll prefer https to send your credentials.
Afterwards in code you'll enter your username/password:
var ws = new ***.MyHandlerClient("MyHandler");
ws.ClientCredentials.UserName.UserName = "myUsername";
ws.ClientCredentials.UserName.Password = "myPassword";
var result = ws.executeMyMethod();

A: I had the same problem and tried the solution above
Somehow this didn't work for me
I was keep getting the message "No WS-Security header found"
After a long time of testing and trying I manage to get it work
I added the header code in the client as below and then it works!
<client>
    <endpoint address="http://your.service.com" binding="basicHttpBinding" bindingConfiguration="XXXBinding" contract="contract.XXX" name="XXXPort">
        <headers xmlns:wsse="http://your.xsd">
            <wsse:Security mustUnderstand="1">
                <wsse:UsernameToken>
                    <tenant>XXX</tenant>
                    <wsse:Username>XXX</wsse:Username>
                    <wsse:Password Type="http://www.xxxx.com/wss#PasswordText">XXX</wsse:Password>
                </wsse:UsernameToken>
            </wsse:Security>
        </headers>
    </endpoint>
</client>


text:
Q: Which algorithms most reliably solve substitution ciphers? I am studying a problem which reduces to the cryptanalysis of a lengthy monoalphabetic substitution ciphertext written in a known language. This problem is easy enough to be solved by hand using frequency analysis and word patterns, as described in Sinkov's Elementary Cryptanalysis. I'm having trouble finding a theoretically validated algorithm for it: Joux's Algorithmic Cryptanalysis doesn't even cover such rudimentary substitution, and I got nothing out of Gaines's Cryptanalysis: A Study of Ciphers and Their Solution (what other resources should I see?).
Some approaches are pretty obvious. Deciding on each substitution in sequence, then leveraging what is already known, works only if no mistake is made along the way.  Employing metaheuristic optimization -- for example, reassign letters until the number of valid words found is maximized -- makes it hard to tell when the search is over. Perhaps a dynamic programming approach to testing the variations would be best. Or, the answers to this question contain other possibly naïve methods.
What are the preferred algorithms for solving this kind of problem?

A: An exact maximum likelihood estimate for the independent letter model
If we assume (unrealistically) that each letter in a given language appears with some known probability independently of nearby letters, then the exact maximum likelihood estimate can be found fairly efficiently. This is about the best you could hope for with this model.
Let's suppose there are n letters in the message and k letters in the alphabet.
The basic idea is that we somehow come up with a numeric score for each of the k^2 possible letter pairs, and then look for a maximum-weight bipartite perfect matching on the two alphabets -- that is, we choose pairs of letters in such a way that every letter in one alphabet is paired with exactly one letter in the other, and the sum of the scores of the chosen pairs is maximised. There are 2 main issues: (1) How to define the score of a given pair; (2) How to solve the general problem of finding the highest-sum subset of pairs once we have decided on the individual scores.
Scoring pairs
The score of pairing the encoded letter x with the source letter y should be log(p(y)^freq(x)), where p(y) is the known probability of letter y in the language, and freq(x) is the number of times letter x appeared in the encoded input. Why? Because under this simple model of the source language that ignores the effect of nearby characters, the probability of generating any given n-character source-language string is equal to the product of the probabilities of the letters that appear in it, which you can also compute as the product of p(y)^freq(y) over all the letters y in the source alphabet. So to compute the probability of generating that string given that each x is "really" a y (and nothing else is a y), we change freq(y) to freq(x). If we then take logs, what we have is the sum of log(p(y)^freq(x)) over all letters y in the source alphabet -- and this sum is exactly what the maximum bipartite perfect matching algorithm will maximise.
Finding the optimal perfect matching
There are algorithms that solve the closely related maximum-weight bipartite matching problem in O(V^2E) time, which amounts to O(k^4) time here. This version of the problem looks to maximise the total sum of all chosen pairs while obeying the constraint that no item is matched with two or more other items in the other set, but without the requirement that every item is matched with some other item. Fortunately, we can turn this algorithm into an algorithm that solves the "perfect" variation we want to solve very simply, by adding a large number M to each score: Intuitively, this causes the algorithm to try to add as many edges as possible (since omitting even a single edge has a large cost, making such a solution much worse than even a "stupid" solution that contains a full set of k edges), while still forcing the algorithm to choose the best among all the k-edge solutions (since all of these solutions include the same kM contribution from the added weight).

A: This paper describes an algorithm to solve homophonic substitution ciphers of which alphabet of length 26 (a-z) is a special case. Their reference implementation in C++ is available here.
The basic idea behind the algorithm (hill climb using digram frequencies to avoid having to decipher more than once) comes from this paper and is (by the authors of the first paper) described as the fastest known algorithm to solve monoalphabetic substitution ciphers.


text:
Q: animateWithDuration not recognised? I'm trying to do a cross dissolve on three UILabels (display1, display2, display3), by using a block animation to fade out, change text and then fade them in one at a time. The code I'm using is:
[UIView animateWithDuration:1.0 delay: 1.0
    animations:^{
        display1.alpha = 0.0;
        display2.alpha = 0.0;
        display3.alpha = 0.0;
    }
    completion:^{
        [display1 setText:[NSString stringWithFormat:@"%@",[engine getstring]]];
        [display2 setText:[NSString stringWithFormat:@"%@",[engine getstring]]];
        [display3 setText:[NSString stringWithFormat:@"%@",[engine getstring]]];
        [UIView animateWithDuration:1.0 delay:1.0
            animations:^{
                display1.alpha = 1.0;
                [UIView animateWithDuration:1.0 delay:1.0
                    animations:^{
                        display2.alpha = 1.0;
                        [UIView animateWithDuration:1.0
                            delay:1.0
                            animations:^{
                                display3.alpha = 1.0;
                            } completion:nil];
                    } completion:nil];
        } completion:nil];
    }];

I get the following warnings:
Method '+animateWithDuration:delay:animations:completion:' not found*

and
'UIView' may not respond to method '+animateWithDuration:delay:animations:completion:'

I'm using Xcode 4.0 with an iOS Build Target of 4.3.

A: You want to use
+ animateWithDuration:delay:options:animations:completion:

instead. Note the options: in the middle.


text:
Q: open cart tax issue I'm new to Opencart. In fact I'm working in my first project that is in Opencart 2.3.0.2. It's almost done.
Now the client need the price of a product should be inclusive of tax.
now actually it's working like the tax is added with unit price. I need it to be included.
ex: Rs.100 (includes GST 18%)
incorrect:
Unit Price: 100
GST@18%: 18
Total: 118

Correct:
Unit Price: 84.75
GST@18%: 15.25
Total: Rs.100

instead of 100*18/100, we need to calculate 100*100/118
(100*100/118)-100 to get GST

A: Go to Admin->System->Settings, edit your Store, and select the Option tab.  There is a setting called "Display Prices With Tax."


text:
Q: $f \circ g = g \circ f$ $\iff$ $f$ and $g$ are two linear functions? Is $$f(x + y) = f(x) + f(y), g(x + y) = g(x) + g(y) \Leftrightarrow \ g\;o\;f = f\;o\;g $$ true?
I have a feeling that it must be true, at least the forward way, but I couldn't come up with a proof..
Any ideas?


text:
Q: Already checked checkboxes want to uncheck and unchecked check boxes want to check using master check box in jQuery I have a master check box, and also have a set of check boxes under it, some of them already checked and some of them unchecked. My query is If I will check the master check box then already checked check boxes want to uncheck and unchecked check boxes want to check.
eg:

A: As per your query

If I will check the master check box then already checked check boxes want to uncheck and unchecked check boxes want to check

Just try, it will work

  $('#master').on('click', function() {
 if($(this).is(':checked')){
      $('.branch').trigger('click');
    }
 });

<input type="checkbox" id="master">master

<input type="checkbox" class="branch">1
<input type="checkbox" class="branch">2
<input type="checkbox" class="branch" checked>3
<input type="checkbox" class="branch">4
<input type="checkbox" class="branch">5
<input type="checkbox" class="branch" checked>6
<input type="checkbox" class="branch">7
<input type="checkbox" class="branch">8
<input type="checkbox" class="branch" checked>9

A: Without triggering all inputs, try this:

var masterCheckbox = jQuery("#master");

masterCheckbox.on("change", function()
{
  if(masterCheckbox.is(":checked"))
  {
    var checkboxes = jQuery(".myCheckbox");

    //get all checked and unchecked
    var checked = checkboxes.filter(":checked");
    var notchecked = checkboxes.filter(":not(:checked)");

    checked.prop( "checked", false );

    notchecked.prop( "checked", true );
  }
});

<input type="checkbox" id="master" />

<input type="checkbox" class="myCheckbox" checked />
<input type="checkbox" class="myCheckbox" />
<input type="checkbox" class="myCheckbox" checked />
<input type="checkbox"  class="myCheckbox" />

A: With prop() method

$('#master').on('click', function() {
    $('.branch').each(function(){
        $(this).prop('checked',!$(this).prop('checked'))
    });
});

<input type="checkbox" id="master">master

<input type="checkbox" class="branch">1
<input type="checkbox" class="branch">2
<input type="checkbox" class="branch" checked>3
<input type="checkbox" class="branch">4
<input type="checkbox" class="branch">5
<input type="checkbox" class="branch" checked>6
<input type="checkbox" class="branch">7
<input type="checkbox" class="branch">8
<input type="checkbox" class="branch" checked>9


text:
Q: Is custom field option a Valueobject or an Entity in Domain Driven Design I am using EF Core and I have a scenario where the user can create a custom field and then creates options for that custom fields.
public class CustomField : Entity<long>
{
    [Required]
    public string Name { get; private set; }

    public bool IsRequired { get; private set; }

    public List<CustomFieldOption> customFieldOptions;
    public virtual IReadOnlyCollection<CustomFieldOption> CustomFieldOptions => customFieldOptions;

    protected CustomField()
    {
    }

    public CustomField(long id, string name, bool isRequired, List<CustomFieldOption> customFieldOptions)
    {
        Id = id;
        Name = name;
        IsRequired = isRequired;
        this.customFieldOptions = customFieldOptions;
    }
}

public class CustomFieldOption : Entity<long>
{
    [Required]
    [MaxLength(256)]
    public string Text { get; private set; }

    protected CustomFieldOption()
    {
    }

    public CustomFieldOption(string text)
    {
        Text = text;
    }
}

public class Client : Entity<long>
{
    public Name Name { get; set; }

    private List<ClientCustomFieldOptionValue> customFieldOptionValues { get; set; } = new List<ClientCustomFieldOptionValue>();
    public IReadOnlyCollection<ClientCustomFieldOptionValue> CustomFieldOptionValues => customFieldOptionValues;

    public Client(Name name)
    {

    }

    public Result AddCustomFieldOptionValues(List<ClientCustomFieldOptionValue> values)
    {
        return Result.Success();
    }

    public Result RemoveCustomFieldOptionValues(List<ClientCustomFieldOptionValue> values)
    {
        return Result.Success();
    }
}

public class ClientCustomFieldOptionValue
{
    public CustomFieldOption CustomFieldOption { get; private set; }

    protected CustomFieldOptionValue()
    {

    }

    public ClientCustomFieldOptionValue(CustomFieldOption customFieldOption)
    {
        CustomFieldOption = customFieldOption;
    }
}

CustomFieldOption seems to be a Value Object as the text it holds is something that doesn't need an Id. But then in terms of store persistency needs an Id to be stored in database on a different table where it can be queries by Id etc...
I am not sure if I shall add it as an Entity because ValueObjects do not have Id.
One other problem I have is validation. If it is an Entity how can I validate Text property. I know validation on constructor is a bad idea. If I validate it in the ApplicationLayer then wherever I create a new object I have to validate that is not empty and the length.
If I forget to add validation in one of the application services and pass null Text then I create an inconsistent state.
Update #1
A Client can select one or many options of a custom field. I suppose these needed to be stored on a separate table ClientCustomFieldOptionValue. In that case is this an entity or a valueobject? And  what about CustomFieldOption. Does it become an Entity? I am quite confused when to use Entity or ValueObjects

A: Try not to think of persistency details while designing domain model.
According to your description, CustomFieldOption expresses an individual property with no business relations to any other structure, thus:

*

*it should not hold a business identifier

*it should encapsulate its own validations

Meaning it fits the concept of a value-object (validation inside ctor).
When it comes to persistency, your repository model should be capable of storing CustomFieldOption objects in a child table (with DB identifier) referencing the parent table (CustomField objects)
On the query side, repository should be capable of aggregating data from these two tables into a single CustomField entity.
(How exactly you implement such DB capabilities depends on the ORM you choose to work with, EF in your case)

A: Just one observation, if you will use Ef Core and the containing entity has a one to many relationship with the value objects, you will have this limitation:
Owned Entity types, Ef Core

Owned types need a primary key. If there are no good candidates properties on the .NET type, EF Core can try to create one. However, when owned types are defined through a collection, it isn't enough to just create a shadow property to act as both the foreign key into the owner and the primary key of the owned instance

If you are mapping your entities and value objects using DbContext, you usually define an owned entity type for a value object or use a record type.
For owned entities, this creates a column in  your table like this: EntityName_ValueObject (i.e. Person_Address) but this works for a single value object not a collection when you don't know in advance the number of items in the collection.
It is correct that you should not concern with persistence when designing your domain, but is also correct to think that having a value object with an identity does not make sense.
Most important, you should be aware of this potential issue early on.


text:
Q: Silverlight notification from server to all clients without UDP I wonder how can I achieve this without UDP, I have a solution using UDP multicast: http://blogs.msdn.com/b/ncl/archive/2009/11/18/udp-multicast-in-silverlight-4.aspx
but since this is for a high profile customer who has an intranet with port TCP 80 and TCP 8080 only enabled this solution is not possible. Yes, the application runs in an intranet environment.
I need a simple example how to send messages to all Silverlight clients over WCF.
I found this solution, but I have no idea how to implement that into Silverlight:
http://idunno.org/archive/2008/05/29/wcf-callbacks-a-beginners-guide.aspx
I'm out of ideas guys, please help.

A: Instead of receiving notifications async the Silverlight client should use polling instead.
It can poll a WCF service that will fetch the data from a db...
This is the typical solution. Anyway, you have to handle the case in which the Silverlight client wasn't online and then it becomes online and need to know its state...
However, if you still want Silverlight to receive async notifications try searching for 'Full Duplex'.
Here are some starting points:
http://blog.developers.ba/post/2009/02/25/Silverlight-chat-application-using-WCF-full-duplex.aspx
http://weblogs.asp.net/dwahlin/archive/2008/06/16/pushing-data-to-a-silverlight-client-with-wcf-duplex-service-part-i.aspx
http://hindams.wordpress.com/2010/04/05/wcf-full-duplex-with-a-silverlight-application/


text:
Q: Validating email address domain in ASP.NET I want to create a web application using any technology that accepts an email address and checks if the domain of the email address exists. How do I go about doing this?

A: here is the C# code to check domain from email Id
var domain = emailaddress.Split('@')[1];
var server = Dns.Resolve(domain);


text:
Q: Manipulating a character vector by considering a grouping Q-matrix in r (3) I am trying to write code based on a Group variable, item.map that has item information that includes an q-matrix showing which item is associated with which group.
Group <- c(1,2)
item.map <- data.frame(
  item.id = c(21,41,61,72),
  group.1 = c(1,1,1,0),
  group.2 = c(0,1,0,1))

> item.map
  item.id group.1 group.2
1      21       1       0
2      41       1       1
3      61       1       0
4      72       0       1

In this item.map group.1 had 3 items while group.2 has two items. Using this item.map I wanted to assign those items within the chunk of code below but I was not able to plug the item.map information.
library(stringr)

# define df for all ids and group combinations
group_g <- paste("G", 1:length(Group), sep ="")
df <- data.frame(item.id = item.map$item.id, Group = rep(group_g, each = length(item.map$item.id)))

# empty vector
vec <- NULL

for(i in 1:nrow(df)) {

  res <- which(str_extract(df[i, "item.id"], "[0-9]{2,}") == item.map$item.id) # this part is for the item.id that has letters in it-not relevant in this example

  text <- paste("(", df[i, "Group"], ", ", df[i, "item.id"], ", fixed[", c(0:length(factor)) ,"]) = ", ifelse(res == 0:length(factor) | 0 == 0:length(factor), "1.0", "0.0"),";", sep = "")

  vec <- c(vec, text)
}

vec

 [1] "(G1, 21, fixed[0]) = 1.0;" "(G1, 21, fixed[1]) = 1.0;" "(G1, 41, fixed[0]) = 1.0;" "(G1, 41, fixed[1]) = 0.0;" "(G1, 61, fixed[0]) = 1.0;"
 [6] "(G1, 61, fixed[1]) = 0.0;" "(G1, 72, fixed[0]) = 1.0;" "(G1, 72, fixed[1]) = 0.0;" "(G2, 21, fixed[0]) = 1.0;" "(G2, 21, fixed[1]) = 1.0;"
[11] "(G2, 41, fixed[0]) = 1.0;" "(G2, 41, fixed[1]) = 0.0;" "(G2, 61, fixed[0]) = 1.0;" "(G2, 61, fixed[1]) = 0.0;" "(G2, 72, fixed[0]) = 1.0;"
[16] "(G2, 72, fixed[1]) = 0.0;"

So, in the desired output, G1 should not have item 72 and G2 should not have items 21 and 61
The desired output is:
 [1] "(G1, 21, fixed[0]) = 1.0;" "(G1, 21, fixed[1]) = 1.0;" "(G1, 41, fixed[0]) = 1.0;" "(G1, 41, fixed[1]) = 0.0;" "(G1, 61, fixed[0]) = 1.0;"
 [6] "(G1, 61, fixed[1]) = 0.0;"
[11] "(G2, 41, fixed[0]) = 1.0;" "(G2, 41, fixed[1]) = 0.0;" "(G2, 72, fixed[0]) = 1.0;"
[16] "(G2, 72, fixed[1]) = 0.0;"

Does anyone have any ideas?
Thanks


text:
Q: Problem with filling a matrix with a loop I am in my first steps of coding in R.
I am trying to fill a matrix, which is based on some vectors inside a matrix.
This is my matrix:
 OPEN  NET_CONTRIBUTION RETURN CONTRIBUTION_RETURN SAVING_RETURN CLOSE
[1,] 0     900              0.019  17.1                0             ?
[2,] 917.1 900              -0.006 -5.4                0             ?
[3,] ?     900              0.004  3.6                 0             ?
[4,] 903.6 900              0.004  3.6                 0             ?
[5,] 903.6 900              0.002  1.8                 0             ?
[6,] 901.8 900              0.002  1.8                 0             ?

NET_CONTRIBUTION is a vector with a constant  number.
Return is a vector of random values.

*

*CONTRIBUTION_RETURN is the calculation of NET_CONTRIBUTION *
(1+RETURN).

*SAVING_RETURN should be Open*(1+RETURN)

*CLOSE should be OPEN + NET_CONTRIBUTION + CONTRIBUTION_RETURN + SAVING RETURN

*OPEN is the CLOSE value for the upper row.
So I tried this code, and it doesn't work.
for (i in 1:444){
  Investment[i,5] <-  Investment[i,1]*(1+Investment[i,3]) #Saving Return
  Investment[i,6] <-  Investment[i,1] + Investment[i,2] + Investment[i,4] Investment[i,5] # CLOSE
  Investment[i+1,1] <-  (Investment[i,6]) # OPEN in the next row
}

I get the following message:
> > for (i in 1:444){
> +   Investment[i,5] <-  Investment[i,1]*(1+Investment[i,3])
> +   Investment[i,6] <-  Investment[i,1] + Investment[i,2] + Investment[i,4] Investment[i,5] Error: unexpected symbol in: "
> Investment[i,5] <-  Investment[i,1]*(1+Investment[i,3])
> Investment[i,6] <-  Investment[i,1] + Investment[i,2] +
> Investment[i,4] Investment"
> >   Investment[i+1,1] <-  (Investment[i,6])

Maybe I am not aprroaching in the right way this idea.
Thank you all for your help,
Tom

A: You just have a missing + symbol in the computation of the close (Investment[i,6])
You should have
Investment[i,6] <-  Investment[i,1] + Investment[i,2] + Investment[i,4] + Investment[i,5]

but instead you have
Investment[i,6] <-  Investment[i,1] + Investment[i,2] + Investment[i,4] Investment[i,5]

Note the missing + between Investment[i,4] and Investment[i,5]

A: In R we have this concept of vectorization, which applies whatever you do to the whole vector (or matrix). So you really do not need loops. Most stuff is way easier than you think. For example:
NET_CONTRIBUTION = rep(900, 444)
RETURN = runif(444)
CONTRIBUTION_RETURN = NET_CONTRIBUTION * (1+RETURN)

Then, you probably would not want to use matrix for the combination of these vectors. A data.frame seems more appropriate. Simply do:
MyDataFrame = data.frame(NET_CONTRIBUTION, RETURN, CONTRIBUTION_RETURN)