text:
Q: how i can pass value from input type file into url in ajax function guy's i have a problem with passing input type file value into ajax url=url,
i hope someone can help me with this.
i have code like this

var data;
$.ajax({
  type: "GET",
  url: "js-tutorials.com_sample_file.csv",
  dataType: "text",
  success: function(response) {
    data = $.csv.toArrays(response);
    generateHtmlTable(data);
  }
});

Read CSV file using JavaScript

      <form class="form-inline">

          Upload a CSV formatted file:
          <input type="file" id="files" class="form-control" accept=".csv" required />

          <button type="submit" id="submit-file" class="btn btn-primary">Upload File</button>

      </form>

i will explain it from my code.
i want to pass the url from file that have choose from input type file from my html into the url: "js-tutorial.com_sample_file.csv";.


text:
Q: ViewModel has no zero Argument constructor. Have AndroidEntryPoint Hey all I am having problems figuring out hilt with android. Ive googled around and I can't find this specific problem.  I seem to getting a "View Model has no zero argument constructor". I saw on another post that it was for a missing @AndroidEntryPoint annotation in their main activity however I added that and at this point I am a little stumped.
So far I have an application class
@HiltAndroidApp
class RecipeApplication: Application() {
}

The main activity
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            MaterialTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = primaryBackgroundColor
                ) {
                    RecipeBookApp()
                }
            }
        }
    }
}

The View model
@HiltViewModel
class RecipeViewModel @Inject constructor(
    private val recipeRepo: RecipeRepo
) : ViewModel() {....}

and then the Composable setting up my UI.
@Composable
fun RecipeBookApp(
    navController: NavHostController = rememberNavController()
) {
    Log.d("GetRecipe", "Still in Recipe Screen About to make the call")

    val recipeViewModel = viewModel(modelClass = RecipeViewModel::class.java)

    var editMode by remember { mutableStateOf(false) }
    Scaffold(
        backgroundColor = primaryBackgroundColor,
        topBar = {
            val title = "Edit"
            Column {
                Row(Modifier.padding(10.dp)) {
                    NiceButton(title = title) {
                        editMode = !editMode
                    }
                }
            }
        },
        bottomBar = {
        }) { innerPadding ->
        NavHost(
            navController,
            RecipeScreen.Start.name
        ) {
            composable(route = RecipeScreen.Start.name) {
                RecipeGridScreen(
                    onGridButtonClick = {
                        navController.navigate(RecipeScreen.RecipePage.name)
                    }
                )
            }
            composable(route = RecipeScreen.RecipePage.name) {
                val state = recipeViewModel.recipeState.collectAsState()
                RecipeView(state.value)
            }
        }
    }
}

RecipeRepo
class RecipeRepo @Inject constructor(
    private val recipeApi: RecipeApi
    ) {
    suspend fun getAllRecipes(): RecipeList {
        return recipeApi.getRecipes()
    }
}

RecipeApi
interface RecipeApi {
    @GET("recipe/getRecipes")
    suspend fun getRecipes(): RecipeList
}

RecipeApiModule
@Module
@InstallIn(SingletonComponent::class)
object RecipeApiModule {

    @Provides
    @Singleton
    fun provideApi(builder: Retrofit.Builder): RecipeApi {
        return builder
            .build()
            .create(RecipeApi::class.java)
    }

    @Provides
    @Singleton
    fun provideRetrofit(): Retrofit.Builder {
        return Retrofit.Builder()
            .baseUrl(RECIPE_URL)
            .addConverterFactory(GsonConverterFactory.create())
    }
}

Process: com.bunkware.bunkyrecipe, PID: 6287
java.lang.RuntimeException: Cannot create an instance of class
com.bunkware.bunkyrecipe.ui.recipe.RecipeViewModel
at
androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.kt:204)
at
androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:322)
at
androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:304)
at
androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:278)
at
androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.kt:128)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:187)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:153)
at
androidx.lifecycle.viewmodel.compose.ViewModelKt.get(ViewModel.kt:215)
at
androidx.lifecycle.viewmodel.compose.ViewModelKt.viewModel(ViewModel.kt:156)
at
com.bunkware.bunkyrecipe.ui.RecipeGridScreenKt.RecipeGridScreen(RecipeGridScreen.kt:30)
at
com.bunkware.bunkyrecipe.ui.recipe.RecipeScreenKt$RecipeBookApp$2$1$1.invoke(RecipeScreen.kt:63)
at
com.bunkware.bunkyrecipe.ui.recipe.RecipeScreenKt$RecipeBookApp$2$1$1.invoke(RecipeScreen.kt:62)
at
androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:116)
at
androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:34)
at
androidx.navigation.compose.NavHostKt$NavHost$4$2.invoke(NavHost.kt:163)
at
androidx.navigation.compose.NavHostKt$NavHost$4$2.invoke(NavHost.kt:162)
at
androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:107)
at
androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:34)
at
androidx.compose.runtime.CompositionLocalKt.CompositionLocalProvider(CompositionLocal.kt:228)
at
androidx.compose.runtime.saveable.SaveableStateHolderImpl.SaveableStateProvider(SaveableStateHolder.kt:84)
at
androidx.navigation.compose.NavBackStackEntryProviderKt.SaveableStateProvider(NavBackStackEntryProvider.kt:65)
at
androidx.navigation.compose.NavBackStackEntryProviderKt.access$SaveableStateProvider(NavBackStackEntryProvider.kt:1)
at
androidx.navigation.compose.NavBackStackEntryProviderKt$LocalOwnersProvider$1.invoke(NavBackStackEntryProvider.kt:52)
at
androidx.navigation.compose.NavBackStackEntryProviderKt$LocalOwnersProvider$1.invoke(NavBackStackEntryProvider.kt:51)
at
androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:107)
at
androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:34)
at
androidx.compose.runtime.CompositionLocalKt.CompositionLocalProvider(CompositionLocal.kt:228)
at
androidx.navigation.compose.NavBackStackEntryProviderKt.LocalOwnersProvider(NavBackStackEntryProvider.kt:47)
at
androidx.navigation.compose.NavHostKt$NavHost$4.invoke(NavHost.kt:162)
at
androidx.navigation.compose.NavHostKt$NavHost$4.invoke(NavHost.kt:141)
at
androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:116)
at
androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:34)
at
androidx.compose.animation.CrossfadeKt$Crossfade$5$1.invoke(Crossfade.kt:133)
at
androidx.compose.animation.CrossfadeKt$Crossfade$5$1.invoke(Crossfade.kt:128)
at
androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:107)
at
androidx.compose.runtime.internal.ComposableLambdaImpl.invoke(ComposableLambda.jvm.kt:34)
at androidx.compose.animation.CrossfadeKt.Crossfade(Crossfade.kt:142)
at androidx.compose.animation.CrossfadeKt.Crossfade(Crossfade.kt:73)
at androidx.navigation.compose.NavHostKt.NavHost(NavHost.kt:141)
at androidx.navigation.compose.NavHostKt$NavHost$5.invoke(Unknown
Source:13)
at androidx.navigation.compose.NavHostKt$NavHost$5.invoke(Unknown
Source:10)
at
androidx.compose.runtime.RecomposeScopeImpl.compose(RecomposeScopeImpl.kt:145)
2023-02-04 11:45:31.431  6287-6287  AndroidRuntime
com.bunkware.bunkyrecipe             E      at
androidx.compose.runtime.ComposerImpl.recomposeToGroupEnd(Composer.kt:2375)
at
androidx.compose.runtime.ComposerImpl.skipCurrentGroup(Composer.kt:2643)
at
androidx.compose.runtime.ComposerImpl$doCompose$2$5.invoke(Composer.kt:3260)
at
androidx.compose.runtime.ComposerImpl$doCompose$2$5.invoke(Composer.kt:3238)
at
androidx.compose.runtime.SnapshotStateKt__DerivedStateKt.observeDerivedStateRecalculations(DerivedState.kt:341)
at
androidx.compose.runtime.SnapshotStateKt.observeDerivedStateRecalculations(Unknown
Source:1)
at androidx.compose.runtime.ComposerImpl.doCompose(Composer.kt:3238)
at
androidx.compose.runtime.ComposerImpl.recompose$runtime_release(Composer.kt:3203)
at
androidx.compose.runtime.CompositionImpl.recompose(Composition.kt:771)
at
androidx.compose.runtime.Recomposer.performRecompose(Recomposer.kt:1031)
at
androidx.compose.runtime.Recomposer.access$performRecompose(Recomposer.kt:125)
at
androidx.compose.runtime.Recomposer$runRecomposeAndApplyChanges$2$2.invoke(Recomposer.kt:534)
at
androidx.compose.runtime.Recomposer$runRecomposeAndApplyChanges$2$2.invoke(Recomposer.kt:503)
at
androidx.compose.ui.platform.AndroidUiFrameClock$withFrameNanos$2$callback$1.doFrame(AndroidUiFrameClock.android.kt:34)
at
androidx.compose.ui.platform.AndroidUiDispatcher.performFrameDispatch(AndroidUiDispatcher.android.kt:109)
at
androidx.compose.ui.platform.AndroidUiDispatcher.access$performFrameDispatch(AndroidUiDispatcher.android.kt:41)
at
androidx.compose.ui.platform.AndroidUiDispatcher$dispatchCallback$1.doFrame(AndroidUiDispatcher.android.kt:69)
at
android.view.Choreographer$CallbackRecord.run(Choreographer.java:1229)
at
android.view.Choreographer$CallbackRecord.run(Choreographer.java:1239)
at android.view.Choreographer.doCallbacks(Choreographer.java:899)
at android.view.Choreographer.doFrame(Choreographer.java:827)
at
android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1214)
at android.os.Handler.handleCallback(Handler.java:942)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7872)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)
Suppressed: kotlinx.coroutines.DiagnosticCoroutineContextException:
[androidx.compose.runtime.PausableMonotonicFrameClock@dfc23f4,
androidx.compose.ui.platform.MotionDurationScaleImpl@a07d71d,
StandaloneCoroutine{Cancelling}@64f9d92, AndroidUiDispatcher@2d4c363]
Caused by: java.lang.InstantiationException:
java.lang.Class<com.bunkware.bunkyrecipe.ui.recipe.RecipeViewModel>
has no zero argument constructor
at java.lang.Class.newInstance(Native Method)
at
androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.kt:202)
... 71 more

A: Your error message says RecipeGridScreen inside your NavHost is calling viewModel(). As per the Hilt and Navigation Compose docs, you must always use hiltViewModel() when inside a NavHost so that Hilt can find the correct factory.
So:

*

*Add the hilt-navigation-compose dependency to your build.gradle file:

implementation("androidx.hilt:hilt-navigation-compose:1.0.0")

*Change all calls to viewModel() to hiltViewModel(). This is only required inside your NavHost, but it works everywhere, so you can do a find/replace of all instances if you'd like.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pause Open vSwitch (OVS) with the POX controller I am trying to pause an OVS with POX as described in
http://www.openvswitch.org/support/dist-docs/ovs-ofctl.8.txt
The respective add-flow command is (thanks to pchaigno for his answer):
sudo ovs-ofctl add-flow c2 "dl_dst=00:00:00:00:00:01,actions=controller(pause)"

(switch name c2)
But, I cannot find in the POX documentation a way of sending such command to the switch.


text:
Q: Monthly Growth - Bigquery I need your help again. I need to calculate the monthly growth for the trips.
The query that I have written is below:
SELECT EXTRACT(YEAR FROM DATE (stoptime)) AS Year, EXTRACT(MONTH FROM DATE (stoptime)) AS Month,
    COUNT(bikeid) AS Trips,
    ROUND(100* (COUNT(bikeid)- LAG(COUNT(bikeid),1,0) OVER (PARTITION BY 'Year' ORDER BY 'Year', 'Month'))/lag(COUNT(bikeid),1) OVER
    (PARTITION BY 'Year' ORDER BY 'Year', 'Month')) ||'%' AS growth
FROM `bigquery-public-data.new_york_citibike.citibike_trips`
WHERE end_station_name LIKE '%University%'
GROUP BY Year, Month
ORDER BY Year DESC, Month DESC

However, the query below cannot give me the right output. The output from the query above as below:

I do not know which part of my query is wrong. Kindly help me with this.
My desired output example:

Thank you!

A: and if you are calculating monthly growth, why aren't you calculating the number of trips in eahc month :
SELECT
    EXTRACT(YEAR FROM DATE (stoptime)) AS YEAR
    , EXTRACT(MONTH FROM DATE (stoptime)) AS MONTH
    , COUNT(bikeid) AS Trips
    , ROUND(100* (COUNT(bikeid)- LAG(COUNT(bikeid),1,0) OVER (PARTITION BY 'Year','Month' ORDER BY 'Year', 'Month' desc))
                 /lag(COUNT(bikeid),1) OVER (PARTITION BY 'Year','Month' ORDER BY 'Year', 'Month' desc)) ||'%' AS growth
FROM `bigquery-public-data.new_york_citibike.citibike_trips`
WHERE end_station_name LIKE '%University%'
GROUP BY Year, Month
ORDER BY Year DESC, Month DESC


text:
Q: MacBook Air number pad keyboard alternative? Is there any way to set the keyboard on a MacBook Air laptop so that I can toggle between normal keys and a number pad?
Seems a little ridiculous to use the mouse for calculator entry and while the number row is adequate for normal typing, it seems like there should be a way to add this functionality.
(FWIW: late 2012 i7 Intel MBAir, OSX Sierra)

per Tom's Comment, as of 12/29/2016 according to their website, "Karabiner does not work on macOS Sierra at the moment" & just last week there was an update released for Ukulele. Here is an old website with some additional suggestions for how to cross this bridge.


text:
Q: What's the SELECT list and the subquery that is ignored in an EXISTS statement? This is a quote from http://dev.mysql.com/doc/refman/5.0/en/exists-and-not-exists-subqueries.html: "If a subquery returns any rows at all, EXISTS subquery is TRUE, and NOT EXISTS subquery is FALSE. For example:
SELECT column1 FROM t1 WHERE EXISTS (SELECT * FROM t2);

Traditionally, an EXISTS subquery starts with SELECT *, but it could begin with SELECT 5 or SELECT column1 or anything at all. MySQL ignores the SELECT list in such a subquery, so it makes no difference."
What do the last two sentences mean?  Can I have an example of why this is important?  I've realized that regardless of what I use in my initial SELECT, I get all columns in my result sets.  Is that what this is talking about?

A: These sentences are not about the SELECT column... part but ONLY about the ... EXISTS (SELECT *... part. The two sentences tell you that the following statements are equivalent:
SELECT column1 FROM t1 WHERE EXISTS (SELECT * FROM t2);
SELECT column1 FROM t1 WHERE EXISTS (SELECT 5 FROM t2);
SELECT column1 FROM t1 WHERE EXISTS (SELECT 42 FROM t2);
SELECT column1 FROM t1 WHERE EXISTS (SELECT random() FROM t2);
SELECT column1 FROM t1 WHERE EXISTS (SELECT column FROM t2);
SELECT column1 FROM t1 WHERE EXISTS (SELECT NULL FROM t2);
SELECT column1 FROM t1 WHERE EXISTS (SELECT 1/0 FROM t2);

No more no less.
Since your returned relation is specified in the first SELECT column1 part, the second SELECT has no influence on the returned rows.

A: The last two sentences are basically saying that, as long as the subquery returns something that is NOT an empty table, then what you put in that SELECT statement is moot as you are merely checking for existence. Example:
SELECT DISTINCT store_type FROM stores
  WHERE EXISTS (SELECT 'poop' FROM cities_stores
                WHERE cities_stores.store_type = stores.store_type);

We will get poop for every row that is returned in the second SELECT. Again, as long as there exists at least one row in cities_stores where store_type equals the initial SELECT's store_type, then that table WILL exist.
Importance? In this example, say we own a lot of stores of varying types. All of a sudden we want to know all the different store types that we have in existence with a couple of caveats: the store type is a type found in a city (represented by cities_stores), and also NOT ones that are in the works, but the ones that actually are open (represented by our stores table). Well, we would use this query to get a list of all the store_types.
And the reason you are getting all the columns is because of the *, which means all columns in the table(s) you SELECTed FROM.

A: When using EXISTS you only check for the existence of a row, independent of the values. The SELECT part is important if you use IN.
So the selected columns for EXISTS can be ignored, whereas for an IN subquery it is important.

A: It's says that if you have following select:
SELECT a1,b1,c1,...,z1 FROM t1 WHERE EXISTS (SELECT a2,b2,c3,...,z2 FROM t2)

The column list a2,b2,c3,...,z2 is ignored as it's value is not necessary to decide if a row exists or not. It's saves memory and computation time.
edit:
To make things clearer: EXISTS tests for non emptyness of the query result. Since one doesn't need to know WHAT was returned by the query to know if it returned something or not, the select columns can be ignored.

A: I think you are confusing un-correlated subqueries (what your code is), where the subquery can be evaluated independendly of the "outer" query.  "Indepentently evaluable subqueries"--subquery which can be evaluated without the context of the superquery:
SELECT column1
FROM t1
WHERE EXISTS
      ( SELECT *
        FROM t2
      )

with correlated subqueries, where the subquery cannot stand on their own.  The correlated-subquery code analogous to the above uncorrelated subquery code is:
SELECT column1
FROM t1
WHERE EXISTS
      ( SELECT *
        FROM t2
        WHERE t2.somecolumn = t1.somecolumn
      )

and can usually be written also as:
SELECT column1
FROM t1
WHERE somecolumn IN
      ( SELECT somecolumn
        FROM t2
      )


text:
Q: How to print same value in a column while maintaining file in R? I have a file that looks like this (file.txt):
column1 column2 column3 column4 column5 column6 column7 column8 column9 column10    column11    column12    column13    column14    column15    column16
1 chr1_10000044_A_T_b38 ENSG00000280113.2 171773 29 30 0.02 0.33 0.144 0.14 chr1 10000044 A T chr1 10060102
2 chr7_10000044_A_T_b38 ENSG00000178585.14 -58627 29 30 0.024 0.26 0.16 0.15 chr7 10000044 A T chr7 18054785
4 chr1_10000044_A_T_b38 ENSG00000280113.2 89708 29 30 0.0 0.03 -0.0 0.038 chr1 10000044 A T chr1 18054638
5 chr1_10000044_A_T_b38 ENSG00000231181.1 -472482 29 30 0.02 0.16 0.11 0.07 chr1 10000044 A T chr1 18052645
6 chr8_304959_A_T_b38 ENSG00000178585.14 -586 60 30 0.026 0.76 0.16 0.15 chr7 10000044 A T chr7 18054785

I want to print the same values in column 3 so that the output looks like this. For one unique value one output would be:
column1 column2 column3 column4 column5 column6 column7 column8 column9 column10    column11    column12    column13    column14    column15    column16
1 chr1_10000044_A_T_b38 ENSG00000280113.2 171773 29 30 0.02 0.33 0.144 0.14 chr1 10000044 A T chr1 10060102
4 chr1_10000044_A_T_b38 ENSG00000280113.2 89708 29 30 0.0 0.03 -0.0 0.038 chr1 10000044 A T chr1 18054638

For the second unique value in column 3 it should be
column1 column2 column3 column4 column5 column6 column7 column8 column9 column10    column11    column12    column13    column14    column15    column16
2 chr7_10000044_A_T_b38 ENSG00000178585.14 -58627 29 30 0.024 0.26 0.16 0.15 chr7 10000044 A T chr7 18054785
6 chr8_304959_A_T_b38 ENSG00000178585.14 -586 60 30 0.026 0.76 0.16 0.15 chr7 10000044 A T chr7 18054785

A: Update
You can split by each unique value using group_split, which will print the groups.
library(dplyr)

group_split(df, column3)

Or in base R:
split(df, f = df$column3)

Output
[[1]]
# A tibble: 2 × 16
  column1 column2               column3            column4 column5 column6 column7 column8 column9 column10 column11 column12 column13 column14 column15 column16
    <int> <chr>                 <chr>                <int>   <int>   <int>   <dbl>   <dbl>   <dbl>    <dbl> <chr>       <int> <chr>    <lgl>    <chr>       <int>
1       2 chr7_10000044_A_T_b38 ENSG00000178585.14  -58627      29      30   0.024    0.26    0.16     0.15 chr7     10000044 A        TRUE     chr7     18054785
2       6 chr8_304959_A_T_b38   ENSG00000178585.14    -586      60      30   0.026    0.76    0.16     0.15 chr7     10000044 A        TRUE     chr7     18054785

[[2]]
# A tibble: 1 × 16
  column1 column2               column3           column4 column5 column6 column7 column8 column9 column10 column11 column12 column13 column14 column15 column16
    <int> <chr>                 <chr>               <int>   <int>   <int>   <dbl>   <dbl>   <dbl>    <dbl> <chr>       <int> <chr>    <lgl>    <chr>       <int>
1       5 chr1_10000044_A_T_b38 ENSG00000231181.1 -472482      29      30    0.02    0.16    0.11     0.07 chr1     10000044 A        TRUE     chr1     18052645

[[3]]
# A tibble: 2 × 16
  column1 column2               column3           column4 column5 column6 column7 column8 column9 column10 column11 column12 column13 column14 column15 column16
    <int> <chr>                 <chr>               <int>   <int>   <int>   <dbl>   <dbl>   <dbl>    <dbl> <chr>       <int> <chr>    <lgl>    <chr>       <int>
1       1 chr1_10000044_A_T_b38 ENSG00000280113.2  171773      29      30    0.02    0.33   0.144    0.14  chr1     10000044 A        TRUE     chr1     10060102
2       4 chr1_10000044_A_T_b38 ENSG00000280113.2   89708      29      30    0       0.03   0        0.038 chr1     10000044 A        TRUE     chr1     18054638

If you need to write each unique dataframe to a file, then you can use lapply. Here, I use the unique names from column3 to give a name to each txt file.
mylist <- split(df , f = df$column3)

lapply(names(mylist), function(x) write.table(mylist[[x]], file=paste(x,".txt"), sep="\t"))

Data
df <- structure(list(column1 = c(1L, 2L, 4L, 5L, 6L), column2 = c("chr1_10000044_A_T_b38",
"chr7_10000044_A_T_b38", "chr1_10000044_A_T_b38", "chr1_10000044_A_T_b38",
"chr8_304959_A_T_b38"), column3 = c("ENSG00000280113.2", "ENSG00000178585.14",
"ENSG00000280113.2", "ENSG00000231181.1", "ENSG00000178585.14"
), column4 = c(171773L, -58627L, 89708L, -472482L, -586L), column5 = c(29L,
29L, 29L, 29L, 60L), column6 = c(30L, 30L, 30L, 30L, 30L), column7 = c(0.02,
0.024, 0, 0.02, 0.026), column8 = c(0.33, 0.26, 0.03, 0.16, 0.76
), column9 = c(0.144, 0.16, 0, 0.11, 0.16), column10 = c(0.14,
0.15, 0.038, 0.07, 0.15), column11 = c("chr1", "chr7", "chr1",
"chr1", "chr7"), column12 = c(10000044L, 10000044L, 10000044L,
10000044L, 10000044L), column13 = c("A", "A", "A", "A", "A"),
    column14 = c(TRUE, TRUE, TRUE, TRUE, TRUE), column15 = c("chr1",
    "chr7", "chr1", "chr1", "chr7"), column16 = c(10060102L,
    18054785L, 18054638L, 18052645L, 18054785L)), class = "data.frame", row.names = c(NA,
-5L))


text:
Q: JFreechart, Line Chart with filled Areas I am trying to create chart like below:

While I've almost achieved everything by simply creating a line chart and customizing shape/paint for Renderer, I can't seem to find a way to fill the areas under the series line.
Any clues, how can I do this?

A: You could create your chart with a StackedXYAreaRenderer. Specify AREA_AND_SHAPES in the constructor and enable outlines. See the ChartFactory code for createStackedXYAreaChart() as an example.
StackedXYAreaRenderer r = new StackedXYAreaRenderer(XYAreaRenderer.AREA_AND_SHAPES);
r.setOutline(true);

Given a renderer, you can set the outline paint and stroke as desired.


text:
Q: Нахождение целых корней диофантового уравнения(генетический алгоритм) Пытаюсь заполнить массив public int[] alleles = new int[4]; класса Gene рандомными числами от 0 до result, но при обращении к этому массиву из функции solve() класса Diafant, выдаёт ошибку NullPointerException. Строка, где возникает исключение, помечена в коде.
Класс Gene:
public class Gene {
    public int[] alleles = new int[4];
    int fitness;
    float likelihood;

    // Test for equality.
    public boolean equalOperator(Gene gene) {
        for(int i = 0; i < 4; i++) {
            if (gene.alleles[i] != alleles[i]) {
                return false;
            }
        }
        return true;
    }
}

Класс Diofant:
public class Diofant {
final int MAXPOPULATION = 25;
int ca, cb, cc, cd;   //coefficients
int result;
Gene[] population = new Gene[MAXPOPULATION];  //MaxPopulation

public Diofant(int a, int b, int c, int d, int res) {
    this.ca = a;
    this.cb = b;
    this.cc = c;
    this.cd = d;
    this.result = res;
}

public Gene getGene(int i) {
    return population[i];
}

int solve() {
    int fitness = -1;
    // Generate initial generation
    for(int i = 0; i < MAXPOPULATION; i++) {
        for(int j = 0; j < 4; j++) {
            population[i].alleles[j] = (int) (Math.random() * (result + 1)); //ИСКЛЮЧЕНИЕ ЗДЕСЬ !!!!
        }
    }

    if (fitness == createFitnesses()) {
        return fitness;
    }

    int iterations = 0;   // keep track of the iterations
    while (fitness != 0 || iterations < 50) {
        generateLikelihoods();
        createNewPopulation();
        if (fitness == createFitnesses()) {
            return fitness;
        }
        iterations++;
    }
    return -1;
}


text:
Q: How and when does viewport change happen in OpenGL? (glViewport) I have a question about computer graphics pipeline.
In OpenGL, we usually use glViewport function in reshape callback.
I heard glViewport is related to viewport transformation.
In our vertex shader, we usually calculate our vertices and make these vertices to be defined in clipping coordinate(Normalized clipping cube).
When does viewport transformation work?
I guess if the vertex shader output the vertices information to rasterizer, then the pipeline translate these vertices information.
X(v) = (x + 1)/2 * width + left
y(v) = (y + 1)/2 * height + bottom.
(viewport transformation)
Consequently, I thought glViewport just set how to work viewport transformation after finishing vertex shader work.
Is it right?

A:
In OpenGL, we usually use glViewport function in reshape callback

No, "we" don't. glViewport belongs into the display function.

Consequently, I thought glViewport just set how to work viewport transformation after finishing vertex shader work.

Yes, that's how it works. Essentially the viewport is just another variable, not very different from a uniform, that contains parameters for the vertex transformation step. However since the last steps of the transformation, the homogenous divide and clipping are hardwired and the viewport transform happens after that, it has to be set individually.


text:
Q: Use underscore (_) in joomla menu alias I want to use underscore in menu alias in joomla. For a menu item called "Residential Storage" I want to use "residential_storage" as alias but when I save this it becomes "residential-storage", so underscore is being replaced by hyphen. How can I use hyphen?

A: Normally the alias should consist of lowercase letters and hyphens (-). No blank spaces or underscores are allowed.But to use  underscore check the link below.This method will replace all (-)  to (_).
http://forum.joomla.org/viewtopic.php?f=618&t=638854


text:
Q: pgadmin4 is very slow to open empty tables of database I installed PostgreSQL 9.6.3-1 on my windows 10 laptop. The processor of my laptop is Intel(R)Core (TM)i7-5500U CPU @ 2.4GHZ and installed Memory is 8.00GB.
pgadmin 4 is too slow to open table of my databases. I have just made schema of table and i haven't import any data but it is slow to open my database.
What should I do? should I install any Prerequisite application or downgrade to pgadmin3?

A: I am confronted with the same problem by installing PostgreSQL 9.6.
Just install PgAdmin3 1.22.2 and everything will become normal again


text:
Q: how to send data from table to jsp I want to get table data from table to new database through jsp servlet this is my sample code in jsp this table contains database elements
I struggled for a week. Please help me.
I want to get table data from table to new database through jsp servlet this is my sample code in jsp this table contains database elements
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="Servlets.Db"%>
<%@page import="java.sql.ResultSet"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  <title>Insert title here</title>
  <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">

Place your Order

        <form action="order" method="post">

              id
              name
              quantity

            <%
              Connection con=Db.getCon();
              String sql="SELECT * FROM drugs";
              PreparedStatement ps=con.prepareStatement(sql);
              ResultSet rs=ps.executeQuery();
              while(rs.next()) {
            %>

              <input type="text" name="id" value="<%=rs.getInt("id") %>">
              <input type="text" name="name" value="<%=rs.getString("name") %>">
              <input type="text" name="quntity">

            <%
              }
            %>

          <input type="submit" value="submit order">
        </form>

      <%@ include file="WEB-INF/Footer.jsp" %>

A: The work you done is get data from database and show data in jsp,if you want to put data into database,you should change sql to "add" and jsp to "input".


text:
Q: Theos tweak MSHookFunction I followed http://brandontreb.com/beginning-jailbroken-ios-development-building-and-deployment
to make a tweak.
but after i done successfully with the helloworld tweak.
I hook the fopen using  MSHookFunction
and then i meet a linking error
Making all for tweak hw...
 Preprocessing Tweak.xm...
 Compiling Tweak.xm...
 Linking tweak hw...
Undefined symbols for architecture armv7:
  "_MSHookFunction", referenced from:
      global constructors keyed to Tweak.xm.mmin Tweak.xm.51941273.o
ld: symbol(s) not found for architecture armv7
collect2: ld returned 1 exit status
make[2]: *** [.theos/obj/hw.dylib.ba964c90.unsigned] Error 1
make[1]: *** [internal-library-all_] Error 2
make: *** [hw.all.tweak.variables] Error 2

this is Tweak.xm
#import "substrate.h"

static FILE * (*s_orig_fopen) ( const char * filename, const char * mode );
static FILE * my_fopen ( const char * filename, const char * mode ){
    return s_orig_fopen(filename, mode);
}

static void entry(void)  __attribute__ ((constructor));
static void entry(void) {
    MSHookFunction(fopen, my_fopen, &s_orig_fopen);
}

does anyone know how to fix it?

A: You can try this:
#import "substrate.h"

static FILE * (*s_orig_fopen) ( const char * filename, const char * mode );
static FILE * my_fopen ( const char * filename, const char * mode ){
    return s_orig_fopen(filename, mode);
}

%ctor {
    MSHookFunction(fopen, my_fopen, &s_orig_fopen);
}


text:
Q: Mootools WMD editor doesn't properly quote content I'm using the mootools WMD editor but it seems like there's an error in the script and it doesn't properly format selected content after I hit the quote button.

A: command was not defined. I saw no references in the script to command and I looked at a nearby function that did the formatting.
I simply changed line 1916:
            command.wrap(chunk, mooWMD.Config.lineLength - 2);

to
            chunk.wrap( mooWMD.Config.lineLength -2 );

Which seems to do the trick.


text:
Q: How I would Add the Int in this Variable to each int in this list I need to add the int in Offset to each number in Code
This is How i made the Offset
num1 = (randint(33,126))
num2 = (randint(33,126))
num3 = (randint(33,126))
num4 = (randint(33,126))
num5 = (randint(33,126))
num6 = (randint(33,126))
num7 = (randint(33,126))
num8 = (randint(33,126))
key1 = chr(num1)
key2 = chr(num2)
key3 = chr(num3)
key4 = chr(num4)
key5 = chr(num5)
key6 = chr(num6)
key7 = chr(num7)
key8 = chr(num8)
characterkey = (key1 + key2 + key3 + key4 + key5 + key6 + key7 + key8)
Label(window2, text = characterkey, font = font, bg = "Dim grey", fg = "cyan").place(x = 130, y = 300)
offset = int(num1+num2+num3+num4+num5+num6+num7+num8)
offset = int(offset/8)
offset = int(offset - 32)
print(offset)

I have converted a text file into its ASCII Code here
Code =" ".join(str(ord(char))for char in readFile)

But i need to add the Offset to each Converted Ascii Code in Code and after the offset is added if it equals more then 126 it will minus 94

A: I am not entirely sure what you want to do, but here is my guess:
If you want to be able to quickly see what it does:
Code = " ".join(map(str, [char + offset - 94 if char + offset > 126 else char + offset for i in map(ord, readFile)]))

Or when you care for speed (because char + offset gets calculated twice in the above example):
Code = " ".join(map(str, [(lambda x: x if x <= 126 else x - 94)(char + Offset)) for char in map(ord, readFile)]))


text:
Q: actualizar tabla en SQL Hola buenas nose si me podríais ayudar, estoy haciendo una consulta SQL para actualizar unos datos de una tabla atreves de php, pero no consigo que funcione y tampoco me da ningún error, por lo que en apariencia no encuentro el problema. La cosa es que a través de un formulario y pasándole por Get el id del post que quiero actualizar una vez cambiados los datos en el formulario lo envió y no me da error, pero no se actualiza ni siquiera en la base de datos.
$errores=''; //declaramos la variable de errores en vacio para luego podeer montar los errores

if(isset($_POST['submit'])){ //le prefuntamos si a seteado la variable super --(que se halla dado al boton )
    //saneamos los datos
    $id=$sanearDato($_POST['id']);
    $titulo=$sanearDato($_POST['titulo']);
    $presentacion=$sanearDato($_POST['presentacion']);
    $descripcion=$sanearDato($_POST['descripcion']);

    $recorrido=$sanearDato($_POST['recorrido']);
    $elevacion=$sanearDato($_POST['elevacion']);
    $distancia=$sanearDato($_POST['distancia']);
    $dificultad=$sanearDato($_POST['dificultad']);

    $imagen_guardada=$sanearDato($_POST['imagen_guardada']);

    $imagen=$_FILES['imagen'];

    if(empty($titulo)){
        $errores.='
Debes rellenar el Título
';
    }

    if(empty($presentacion)){
        $errores.='
Debes rellenar la presentacion
';
    }

    if(empty($descripcion)){
        $errores.='
Debes rellenar La Descripción
';
    }

    if(empty($recorrido)){
        $errores.='
Debes rellenar el recorrido
';
    }

    if(empty($elevacion)){
        $errores.='
Debes rellenar la elevacion
';
    }

    if(empty($distancia)){
        $errores.='
Debes rellenar la distancia
';
    }

    if(empty($dificultad)){
        $errores.='
Debes rellenar la dificultad
';
    }

        if(empty($imagen['tmp_name'])){//si no hay imagen sera la que tengamos almacenada
            $imagen=$imagen_guardada; //si no se sube una nueva imagen se respetara la que ya tenemos
        }else{
             $comprobar=getimagesize($imagen["tmp_name"]); //con este metodo comprobamos que sea una imagen

            if($comprobar==false){ // si da false sacamos el error)
                 $errores.='
El archivo no es una imagen
';
            }else{//en caso contrario subimos el archivo
                 $rutaDestino=$admin_config['rutaImg'].$imagen['name'];

                 move_uploaded_file($imagen['tmp_name'], $rutaDestino);//esto lo almacena en un estapacio temporal del servidor
                 $imagen=$imagen['name'];

            }
        }

        $id=$recogerId(); //capturamos el id

        if(empty($errores)){ //si no hay errores editamos la ruta
            $editarPost($id,$titulo,$presentacion,$descripcion,$recorrido,$elevacion,$distancia,$dificultad,$imagen,'rutas');
            header("Location:admin.index.php");
        }

}else{ //en caso contrario traemos las rutas para pintarlas
    $id=$recogerId(); //capturamos el id

    if(!$id){ //si no hay rutas con ese id nos lleva al index del admin
        header("Location:admin.index.php");
    }

    $single=$recogerRutasPorId($id,'rutas'); //recogemos la ruta

    if(!$single){ //si no hay rutas(post) nos lleva al index del admin
        header("Location:admin.index.php");

}

}

$editarPost=function($id, $titulo, $presentacion, $descripcion, $recorrido,$elevacion, $distancia, $dificultad, $imagen, $tabla) use($conexion) {

    $stmt=$conexion()->prepare("UPDATE $tabla SET titulo=:titulo,presentacion=:presentacion,descripcion=:descripcion,recorrido=:recorrido,elevacion=:elevacion,distancia=:distancia,dificultad=:dificultad,imagen=:imagen WHERE id=:id");
    $stmt->execute([
        ':titulo'=>$titulo,
        ':presentacion'=>$presentacion,
        ':descripcion'=>$descripcion,
        ':recorrido'=>$recorrido,
        ':elevacion'=>$elevacion,
        ':distancia'=>$distancia,
        ':dificultad'=>$dificultad,
        ':imagen'=>$imagen,
        ':id'=>$id,
    ]);
};

A: Puede ser que al obtener el objeto $conexion (imagino que estás usando PDO), no esté configurado para que genere las excepciones.
Puedes hacer esto de la siguiente manera:
    // Ejemplo de conexión a la base de datos
    $dbConnection = new PDO($dsn, $user, $pass);

    // Establecer las propiedades, establecer en modo de Excepción
    $dbConnection->setAttribute(PDO::ERRMODE_EXCEPTION);


text:
Q: Not getting response from server, leaf xnet Using leaf xnet to make a request, but Im getting the could not get a response from server. Tried using postman and its working fine, but c# is giving me that error.
            var request = new HttpRequest();
            string response = request.Get("XXXX").ToString();
            Console.WriteLine(response);

Leaf.xNet.HttpException: 'Could not receive the message body of the response HTTP-server
I tried making that protocol attribute true, nothing works.

A: try to turn to add UserAgent header + put the following code :
Request.IgnoreProtocolError = true


text:
Q: DragSortListView setOnItemClickListener and setOnItemLongClickListener I have added the DragSortListView Library from Bauer and it works. The only problem that I have encountered is the ItemClickListeners. As they aren't doing anything. I have researched around and there are still no working answers.
Some answer I came across to solving my situation are
    android:focusable="false"
    android:focusableInTouchMode="false"
    dslv:drag_start_mode="onMove"

but it didn't work
XML part
<com.mobeta.android.dslv.DragSortListView
    xmlns:dslv="http://schemas.android.com/apk/lib/com.mobeta.android.dslv"
    android:layout_width="match_parent"
    android:layout_height="435dp"
    android:id="@+id/listView2"
    android:focusable="false"
    android:focusableInTouchMode="false"
    dslv:drag_start_mode="onMove"
    dslv:drag_enabled="true"
    dslv:collapsed_height="2dp"
    dslv:drag_scroll_start="0.33"
    dslv:max_drag_scroll_speed="0.5"
    dslv:float_alpha="0.6"
    dslv:slide_shuffle_speed="0.3"
    dslv:track_drag_sort="false"
    dslv:use_default_controller="true"
    dslv:sort_enabled="false"
    dslv:remove_enabled="true"
    dslv:remove_mode="flingRemove"/>

my Fragment class
    db = new MySQLiteHelper(getActivity());
    data = db.getAllMeal();
    lv = (DragSortListView) v.findViewById(R.id.listView2);
    final ArrayAdapter<RecipeDAO> adapter = new ArrayAdapter<RecipeDAO>(getActivity(),android.R.layout.simple_list_item_1, data);
    lv.setAdapter(adapter);

    lv.setDropListener(new DragSortListView.DropListener() {
        @Override
        public void drop(int from, int to) {
            if (from != to) {
                RecipeDAO item = adapter.getItem(from);
                adapter.remove(item);
                adapter.insert(item, to);
                db.updateMealList(data);
                adapter.notifyDataSetChanged();
            }
        }
    });

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,final int position, long id) {
            //db.deleteRecipe(data.get(position).getRecipeID());
            Crouton.makeText(getActivity()," deleted", Style.CONFIRM).setConfiguration(new Configuration.Builder().setDuration(700).build()).show();
            Toast.makeText(getActivity()," deleted", Toast.LENGTH_SHORT).show();
        }
    });

A: I think you may have to declare a drag handle.
If you are only using this for remove, perhaps GestureListener would be a better solution.


text:
Q: c# datagridview filtered data to livechart private void btn_gider_bilgi_getir_Click(object sender, EventArgs e)
    {
        string veritabaniyolu = "Data source=veritabani.db";
        string ay = cbox_g_gun.Text;
        string yil = cbox_g_yil.Text;

        SQLiteConnection baglanti = new SQLiteConnection(veritabaniyolu);
        baglanti.Open();
        string sql_tarih_sorgula = $"SELECT * FROM Gelirler WHERE GelirTarihi BETWEEN '{yil}-{ay}-01' AND '{yil}-{ay}-31'";
        SQLiteDataAdapter da = new SQLiteDataAdapter(sql_tarih_sorgula, baglanti);
        DataTable dt = new DataTable();
        da.Fill(dt);
        bunifuDataGridView1.DataSource = dt;
        baglanti.Close();

        Func<ChartPoint, string> fu = x => string.Format("{0},{1:P}", x.Y, x.Participation);
        SeriesCollection series = new SeriesCollection();

        foreach (var item in bunifuDataGridView1)
        {
            //PieSeries pie = new PieSeries();
            //pie.Title = item;
            //pie.Values = new ChartValues<int> { (int)item };
            //pie.DataLabels = true;
            //pie.LabelPoint = fu;
            //series.Add(pie);
            //pieChart1.Series = series;
        }
    }

I want to transfer the data from the SQLite database to the pie chart by filtering the dates.The area where I have a problem is the "foreach" loop. How can I transfer the information from the database to the pie chart?sorry for my bad english...enter image description here

A: You can try the following code to convert the information from datagridview to the pie chart.
  private void Form1_Load(object sender, EventArgs e)
    {
        dataGridView1.AllowUserToAddRows = false;

    }

    private void button1_Click(object sender, EventArgs e)
    {
        dataGridView1.DataSource = null;
        SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite");
        m_dbConnection.Open();
        string sql = string.Format("Select * From example where birthdate between '{0}-{1}-01' AND '{0}-{1}-31'",textBox1.Text,textBox2.Text);
        SQLiteDataAdapter adapter = new SQLiteDataAdapter(sql, m_dbConnection);
        DataTable dt = new DataTable();
        adapter.Fill(dt);
        dataGridView1.DataSource = dt;
        m_dbConnection.Close();
        Func<ChartPoint, string> labelPoint = chartPoint => string.Format("{0} ({1:P})", chartPoint.Y, chartPoint.Participation);
        // Define a collection of items to display in the chart
        SeriesCollection piechartData = new SeriesCollection();
        var collection=dataGridView1.Rows.Cast<DataGridViewRow>().GroupBy(x=> x.Cells[1].Value).Where(g=>g.Count()>0).Select(y => new { Element = y.Key, Counter = y.Count() }).ToList();
        foreach (var item in collection)
        {
            piechartData.Add(new PieSeries { Title =Convert.ToDateTime( item.Element).ToShortDateString(), Values = new ChartValues<double> { item.Counter }, DataLabels = true, LabelPoint = labelPoint });
        }
        // You can add a new item dinamically with the add method of the collection
        // Useful when you define the data dinamically and not statically
        // Define the collection of Values to display in the Pie Chart
        pieChart1.Series = piechartData;
        // Set the legend location to appear in the Right side of the chart
        pieChart1.LegendLocation = LegendLocation.Right;
    }

Result:


text:
Q: How to assign post to category I have created custom post type and created two post category This Month and Next Month and assigned sample posts to each category. When I preview the category archive ../category/this-month a page said Nothing Found so I assume that the page exist but the post is not display. The question is how can I make any post that is assign to post category show on say /category/this-month?
// Register Custom Post Type
function activity() {

    $labels = array(
        'name'                  => _x( 'Activity', 'Post Type General Name', 'twenty_two' ),
        'singular_name'         => _x( 'Activity', 'Post Type Singular Name', 'twenty_two' ),
        'menu_name'             => __( 'Activity', 'twenty_two' ),
        'name_admin_bar'        => __( 'Activity', 'twenty_two' ),
        'archives'              => __( 'Item Archives', 'twenty_two' ),
        'attributes'            => __( 'Item Attributes', 'twenty_two' ),
        'parent_item_colon'     => __( 'Parent Product:', 'twenty_two' ),
        'all_items'             => __( 'All Activity', 'twenty_two' ),
        'add_new_item'          => __( 'Add New Activity', 'twenty_two' ),
        'add_new'               => __( 'New Activity', 'twenty_two' ),
        'new_item'              => __( 'New Item', 'twenty_two' ),
        'edit_item'             => __( 'Edit Activity', 'twenty_two' ),
        'update_item'           => __( 'Update Activity', 'twenty_two' ),
        'view_item'             => __( 'View Activity', 'twenty_two' ),
        'view_items'            => __( 'View Items', 'twenty_two' ),
        'search_items'          => __( 'Search Activity', 'twenty_two' ),
        'not_found'             => __( 'No Activity found', 'twenty_two' ),
        'not_found_in_trash'    => __( 'No products found in Trash', 'twenty_two' ),
        'featured_image'        => __( 'Featured Image', 'twenty_two' ),
        'set_featured_image'    => __( 'Set featured image', 'twenty_two' ),
        'remove_featured_image' => __( 'Remove featured image', 'twenty_two' ),
        'use_featured_image'    => __( 'Use as featured image', 'twenty_two' ),
        'insert_into_item'      => __( 'Insert into item', 'twenty_two' ),
        'uploaded_to_this_item' => __( 'Uploaded to this item', 'twenty_two' ),
        'items_list'            => __( 'Items list', 'twenty_two' ),
        'items_list_navigation' => __( 'Items list navigation', 'twenty_two' ),
        'filter_items_list'     => __( 'Filter items list', 'twenty_two' ),
    );
    $args = array(
        'label'                 => __( 'Activity', 'twenty_two' ),
        'description'           => __( 'Display activities post', 'twenty_two' ),
        'labels'                => $labels,
        'supports'              => array( 'title', 'editor', 'thumbnail' ),
        'taxonomies'            => array( 'category', 'post_tag' ),
        'hierarchical'          => false,
        'public'                => true,
        'show_ui'               => true,
        'show_in_menu'          => true,
        'menu_position'         => 5,
        'show_in_admin_bar'     => true,
        'show_in_nav_menus'     => true,
        'can_export'            => true,
        'has_archive'           => 'activities',
        'exclude_from_search'   => false,
        'publicly_queryable'    => true,
        'capability_type'       => 'page',
    );
    register_post_type( 'activity', $args );

}
add_action( 'init', 'activity', 0 );

A: You have to register built-in "category" taxonomy for the "Activity" post type:
<?php
function add_categories_to_activities()
{
    register_taxonomy_for_object_type( 'category', 'activity' );
}

add_action( 'init', 'add_categories_to_activities' );

See register_taxonomy_for_object_type() in the Code Reference.


text:
Q: System of particles in classical mechanics and classical statistical mechanics $\bullet$ Both classical mechanics and classical statistical mechanics can describe the properties of a system of classical particles.
$\bullet$ In classical statistical mechanics, we assume that we do not know the microstate of a system at any given time. Therefore, we consider all possible microstates at any time, an ensemble.
$\bullet$ In classical mechanics, we do not consider such an ensemble i.e., a large number of copies of the same system. We consider only one system, and still get some correct results.
Below are a few questions.

*

*Do you assume that we know the microstate (i.e., position coordinates and momenta of each particle) for a system of particles in classical mechanics? But since that is not true, why does the classical mechanical description work? At least it describes some properties of the system if not all.

*Why doesn't the notion of temperature arise in the discussion of system of particles in classical mechanics?

*Why is it that some properties of a system of particles can be described by the classical mechanical approach i.e., no ensemble? Why are some properties cannot be described by classical mechanical approach i.e. use of ensembles and microstates?
For me the holistic picture is missing. If someone could help! I am not currently asking about quantum systems just to simplify matters.

A: 1) If we use some definite values of positions to find their past/future values or to find some other physical quantity, then we are doing mechanics. If we do not use any definite values of positions, then we cannot achieve the above but we can still search for probabilistic characteristics, like averages, second moments, etc. - then we are doing statistical physics. Classical mechanics description works in many situations, but not all of them. It is just a theory that helps us to understand and (in case of simple systems) predict their behaviour.
2) Which discussion? In discussion of kinetic theory, it does. Effective kinetic temperature of a system is based on average kinetic energy of the particles of that single system. However, it takes immense number of particles to make this a useful concept, so one usually uses the probabilistic description.
3) Mechanical properties of a single system such as energy, momentum, and their averages over time are mechanical concepts, so mechanics is sufficient. Probabilistic concepts such as expectated average of energy, momentum over many measurements on many different systems are probabilistic concepts, and their study requires probabilistic theory.
If you are confused about this, take it easy, first learn mechanics, then do some probability problems, then apply probability thinking to mechanics.

A: One class of systems that are of particular interest are ergodic systems. These are systems for which the time average of the phase space evolution in classical mechanics (for a fixed initial condition) is equal to the microcanonical ensemble average (an average over the energy surface in phase space)
$$
\frac{1}{T} \int^T dt\, O(x_i(t),p_i(t)) =
 \langle O(x_i,p_i) \rangle_E
$$
Basically, statistical mechanics is useful for these systems because the object on the right is easier to compute than the object on the left. Indeed, we realize that it is even easier to pass to a canonical ensemble (introduce temperature) and compute the right hand side using the equivalence between the microcanonical and the canonical ensemble. Proving ergodicity is hard, but in classical mechanics we learn about possible obstructions (integrability and invariant tori), and possible paths to ergodicity.

A: Ok to answer your first question:
in principle Classical Mechanics is capable of describing the system completely(at leas as long as we do not reach the scale of quantum world) the reason we use statistical mechanics is that when we increase the number of particles in a CM system thereby some new feature rise for instance some behavior that only depands on the interaction between the particles of our manybody system , also another difficulty is related to the chaos phenomena you can wikipedia that , and naivley speaking that occurs when we try to asymptotically use CM so these are some issues regarding to use CM that motivate people to use SM instead.
to your second question the notion of temperature arise when we talk about heat and again naively speaking heat is the energy in transfer not a specific kind of energy that most of the time it is related to the concept of friction so we use heat and therefore temperature when we do not want to specifically talking about the friction itself that one of the strength of SM that we substitute the difficult concept of friction with heat and temperature so thats why we dont talk about it in CM because there we do not seek for asymptotic answer but rather the exact one so we use friction itself .
and to your last question ensemble theory serve as a helpful tool when we cannot solve the system exactly and that is either because the equations are quite large that we do not have the computation power to do so so we use SM and ensemble theory to have some estimation of the answer the point is in principle CM is enough but because of the reasons I provide and so many others we use SM for estimation.


text:
Q: How to prevent the following regex to match things between two ( )s? This regex:
\v\(.*\)\ze\s\-\>

Matches this (including the parenthesis):
functionDefinition = (matchedArgs) ->

Everything OK. The problem arises here:
$(window).on "scroll", (e) ->

The (char) aren't matched individually but together, like this:
$<<(window).on "scroll", (e)>> ->

How can I fix the regex so that they are matched individually? Like this:
$<<(window)>>.on "scroll", <<(e)>> ->

A: I would change it to the following:
\v\(.{-}\)\ze\W

It does a non-greedy match .{-} between parentheses followed by any non-letter character \W.

UPDATE
I thought you wanted to match also first pair of parens. Use this one instead:
\v\([^)]*\)\ze\s-\>

UPDATE 2: For explanation
Of course: \v means very magic so it avoids to escape many especial characters like parentheses, curly braces and so on. This \([^)]*\) matches some content between parentheses in non-greedy mode. \ze\s-\> is a zero-width assertion with content that follows but without matching.


text:
Q: ListView OnClick within AppWidget I want to make a scrollable stick note widget like this one.
For that I'm using a ListView with only one item. The user should be able to click anywhere on the widget to edit the text and some other settings. But I don't know how to add an OnClick listener for the empty space of the listview. So when you tap on that area nothing happens.
I already tried giving my root view an onClick listener, but that doesn't work if there's a view on top of it. Is there a fix for that?
Here's how I added the listener:
remoteViews.setOnClickPendingIntent(R.id.widget, getPendingSelfIntent(context, CLICK_TAG));
appWidgetManager.updateAppWidget(id, remoteViews);

public PendingIntent getPendingSelfIntent(Context context, String action) {
        Intent intent = new Intent(context, NoteWidget.class);
        intent.setAction(action + id);
        intent.putExtra(NoteWidget.EXTRA_ID, id);
        return PendingIntent.getBroadcast(context, 0, intent, 0);
    }

This is the layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/widget"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clickable="true"
    android:orientation="vertical">

    <ListView
        android:id="@+id/listViewWidget"
        style="@android:style/Widget.AbsListView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp" />

    <TextView
        android:id="@+id/empty_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text=""
        android:textColor="@color/colorText"
        android:textSize="20sp"
        android:visibility="gone" />
</FrameLayout>


text:
Q: How do I resolve the: Please install Android target: "android-25" issue? When I run meteor run android I see the below error message:

When I write: echo $ANDROID_HOME I get:
/home/sirbt/Android/Sdk
When I write: echo $PATH I get:
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/home/sirbt/Android/Sdk/platform-tools:/home/sirbt/Android/Sdk/platform-tools:/home/sirbt/Android/Sdk/platform-tools:/home/sirbt/Android/Sdk/platform-tools:/home/sirbt/Android/Sdk/platform-tools

According to this article from: https://github.com/meteor/meteor/issues/8464 Its suggested that one can replace the tool folder in Android/Sdk with tools_r25.2.3-linux.zip from: https://dl.google.com/android/repository/tools_r25.2.3-linux.zip Which i have done, to no avail!
My working environment is:

*

*Ubuntu 15.10

*OS type: 32-bit

*Meteor 1.5


text:
Q: Split string on periods '.' I think the basic rule for the following is only split on periods not contained by brackets, but I'm having trouble translating that into the proper regex logic.
I have a string like this:
x['a.ab.w'].two['0'].three

And my best current pattern is
\.(?!\w*['"]\])

This is in javascript, and I'm trying split the sample string so that it returns as
x['a.ab.w']
two['0']
three

The regex I list above works for the case of x['a.ab'] but fails when there are 2 or more periods in that section of the string. The output in this case is:
x['a
ab.w']
two['0']

A: I can see a way to do this using a mixture of match and map..
"x['a.ab.w'].two['0'].three"
    .match(/(?:^|\.)((?:[^'.]*|'[^']*')+(?=\.|$))/g)
        // ["x['a.ab.w']", ".two['0']", ".three"]
    .map(function (e) {
        if (e.charAt(0) === '.') return e.slice(1);
        return e;
    });
        // ["x['a.ab.w']", "two['0']", "three"]

Using split with this RegExp will give you similar results, except with extra empty entries "" before, after and between each.
Graphic of the RegExp

A: Try the following:
/\.(?![\w.]*['"\]])/

This seemed to work in the Regexp tester I was using.
And it also works in my JSFiddle.
I simply changed \w* to [\w.]*


text:
Q: Solving a differential equation using Euler's method: my answer does not match key Here is the problem:

Assume that the deer population of a park is governed by the
  differential equation $$\frac{dy}{dt} = 0.2y(e^{1-\frac y5}-1)$$ where
  y is in hundreds of deers and t is in years. Using Euler's method with
  20 steps, estimate the population 20 years later if the initial
  population is 150.

Here is my solution:
We have the initial value problem, $\frac{dy}{dt} = 0.2y(e^{1-\frac y5}-1), y(0) = 150$. To use Euler's method with $n = 20$, we set $\Delta t = 1$ so that we have $t_1 = 1, t_2 = 2, \dots, t_{20} = 20$. We compute y successively using $y_n = y_{n-1} + f(t_{n-1}, y_{n-1})\Delta t$, where $f(t, y) = \frac{dy}{dt}$. We get the following values:
t   y
0   150
1   120
2   96.0000000025
3   76.8000002414
4   61.440009104
5   49.1521611569
6   39.3231662824
7   31.4667442165
8   25.2050188497
9   20.2526350059
10  16.3938355394
11  13.4508482494
12  11.2569832176
13  9.6497222556
14  8.4812868483
15  7.6305244207
16  7.0061981559
17  6.5430739006
18  6.1955891025
19  5.9320561442
20  5.7302858354

So my answer is 573. But the key is 491. Where was I wrong?


text:
Q: Could not find method testRuntime() for arguments [org.junit.jupiter:junit-jupiter-engine] jdk 1.8.
Gradle 7.3
In my java project I want to write unit test by Kotlin. So I try this:
in build.gradle:
plugins {
    id 'application'
    id "com.nocwriter.runsql" version "1.0.3"
    id 'idea'
    id "io.spring.dependency-management" version "1.0.11.RELEASE"
    id 'org.jetbrains.kotlin.jvm' version '1.7.10'
}
apply plugin: "io.spring.dependency-management"
dependencies {
    // The dependencies in the BOM will be dependency constraints in our build, but the versions in the BOM are forced for used dependencies.
    implementation enforcedPlatform('org.springframework.boot:spring-boot-dependencies:2.7.2')

    // Use dependency defined in BOM.
    // Version is not needed, because the version defined in the BOM is a dependency constraint that is used.
    implementation 'org.xerial:sqlite-jdbc'
    implementation 'org.jetbrains.kotlin:kotlin-stdlib'
    testImplementation(
            'org.assertj:assertj-core',
            'org.junit.jupiter:junit-jupiter-api'
    )
    testRuntime('org.junit.jupiter:junit-jupiter-engine')

    // This version will be overridden by the one found in the BOM
    implementation 'log4j:log4j:1.2.17'
    implementation 'com.toedter:jcalendar:1.4'

}

Usage:
./gradlew build

But I get error in this line:
testRuntime('org.junit.jupiter:junit-jupiter-engine')

Error:
 What went wrong:
A problem occurred evaluating project ':app'.
> Could not find method testRuntime() for arguments [org.junit.jupiter:junit-jupiter-engine] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

A: Change to
testImplementation "org.junit.jupiter:junit-jupiter-engine"


text:
Q: Yaml instance not created when constructor argument is passed I am using snakeyml to read yml file and load it in Java objects.
Issue:
When I do a Yaml yml = new Yaml(), yml instance is created. But when I pass the constructor argument, the yml instance is not created. I don't see an exception either. This is the complete code.
private static YamlConfig readStatsConfig()
        throws IOException {

    InputStream input = new FileInputStream(new File(configFile));
    Constructor constructor = new Constructor(YamlConfig.class);

    TypeDescription description = new TypeDescription(YamlConfig.class);
    description.putListPropertyType("resources", YamlConfig.Resource.class);
    constructor.addTypeDescription(description);

    TypeDescription description = new TypeDescription(
                    YamlConfig.Resource.class);
    description.putListPropertyType("stats", YamlConfig.StatsInfo.class);
    constructor.addTypeDescription(description);

    Yaml yaml = new Yaml(constructor);

    YamlConfig cfg = (YamlConfig) yaml.load(input);

    mainLogger.info(cfg);

    return cfg;
}

Code exit in the following statement:
Yaml yaml = new Yaml(constructor);

A: I fixed the issue by excluding snakeyml dependency in TestNG JARs. All we need to do is to add the following in the project POM has dependency with TestNG.

<dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.3.1</version>
             <type>jar</type>
            <exclusions>
                <exclusion>
                    <artifactId>snakeyaml</artifactId>
                    <groupId>org.yaml</groupId>
                </exclusion>
            </exclusions>
        </dependency>


text:
Q: Group Action and Free Product of Groups I am struggling on the problem related to the free product of groups.

Let $G$ be a group acting on a set $X$ and let $H$ be a group generated by two subgroups $G_1, G_2$ of $G$ with $\lvert G_1 \rvert \geq 3, \lvert G_2 \rvert \geq 2$. Suppose that there exist two nonempty subsets $X_1$ and $X_2$ of $X$ such that $X_2 \not\subset X_1, g(X_2) \subseteq X_1$, and $g'(X_1) \subseteq X_2$ for any nontrivial $g \in G_1$ and $g' \in G_2$. Show that $H \simeq G_1 \ast G_2$.

I think I have to use the universal property of the free product of groups, but I have no idea on how to apply it.
Any comments or hints are welcomed.

A: To prove that $H = G_1*G_2$, it is enough to prove that any nonempty alternating product of nontrivial elements from $G_1$ and $G_2$ is nontrivial in $G$.
The assumptions $|G_1| \ge 3$ and $|G_2| \ge 2$ imply that any such element of $G$ has a conjugate $g$ of the form $a_0b_1a_1b_2a_2\cdots b_ka_k$ for some $k \ge 0$ with each $a_i \in G_1 \setminus \{1\}$ and $b_i \in G_2 \setminus \{1\}$.
Let $x \in X_2 \setminus X_1$. Then the assumptions imply that $g(x) \in X_1$, so $g(x) \ne x$ and hence $g \ne 1$, and so the original element, a conjugate of $g$, is also nontrivial.


text:
Q: reference error in ASP.Net 5 I play around with some commands like dnvm and dnu, and now when I create an empty ASP.NET 5 solution, I get reference error like this:
Dependency Microsoft.AspNet.Server.IIS >= 1.0.0-beta5 could not be resolved
Dependency Microsoft.AspNet.Server.WebListener >= 1.0.0-beta5 could not be resolved

A: Since ASP.NET Core beta 8, these two references have changed.

*

*Microsoft.AspNet.Server.IIS has been replaced by Microsoft.AspNet.IISPlatformHandler

*Microsoft.AspNet.Server.WebListener has been replaced by Microsoft.AspNet.Server.Kestrel
And RC1 is available now. ;)


text:
Q: Scraping new price with python I have been creating a code that will automatically get me all needed information for listed houses in my area, and then prints it to a .CSV file for me to check.
Its works fine all but on part where there is new price following old price.
When it works:

Hinta
97 500 €

When it does not work:

Hinta
299 000 €arrow_downward329 000 €

By this I get prize for all others(where list is only two numbers long):
prize_number_list = re.findall("\d+", prize_line) =====>  ['299', '000', '329', '000']

prize = ''.join(prize_number_list)  ========> 299000329000

How can I separate first two numbers from the list, and combine them to one number like this 299000?
Thanks

A: This can be done by only joining the first two items of the list,
prize_number_list = ['299', '000', '329', '000']

prize = ''.join(prize_number_list[:2])

print(prize)

A: price_list = ['299', '000', '329', '000','429','000']

for i in zip(price_list[::2],price_list[1::2]):
    print(i[0]+i[1])


text:
Q: How can I open a new view from a background thread without knowing what the current/main-view is? From what I understand any new view that is opened needs to have a parent/super view.
I have a background thread that communicates with a server and according to the server's response it needs to popup an alert and in response to that alert it needs to bring up some UI. This can happen 'anywhere' within my App and so I find it hard to provide this new view with a parent/super view.
Is it possible to open this new view with no knowledge of what's currently being displayed? Is there a non-intrusive way to detect the current view and use that as the parent/super?
One of the targets is not to require anything from the Delegate and other views.

A: The way to get the currently visible view depends on the setup of the controllers, eg. whether you use a tab bar, navigation controller etc. I think the easiest way would be if your background thread sent a notification (using NSNotificationCenter) on the main thread whenever you need the UI changes to happen. The View Controllers can then subscribe to this notification and handle the UI changes.
Notifications are just one way of communication though, basically what you want is to have your model background thread somehow message the currently active view controller on your main thread. How you exactly go about this will largely depend on your application (see first sentence again).

A: Actually you don't need a view, you can add it as a subview of your app delegate's window.
In your application delegate:
- (void) showView {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,480)];
    view.backgroundColor = [UIColor redColor ];
    [self.window addSubview:view];
    [view release];
}

Then, when you want to show the view:
MyAppDelegate *d = [[UIApplication sharedApplication] delegate];
[d showView];

You'll need a way to dismiss the view once you are done with it, you can use
[self removeFromSuperview]


text:
Q: Anchor links are not working in android Web links are not clickable in android chrome and firefox. But in Opera it is working. It is created with Twitter bootstrap :
http://questionfriends.com/

A: Even in computer if you resize the browser to minimum width the links doesnt seem to work. It has something to do with the scalfolding javascript that is making the links as simple "#" .
While if you maximize it on desktop the link seems working. Some scalfolding code is removing the hyperlinks with dummylinks. Just check if any javascript is doing it,


text:
Q: How to define a dataclass so each of its attributes is the list of its subclass attributes? I have this code:
from dataclasses import dataclass
from typing import List

@dataclass
class Position:
    name: str
    lon: float
    lat: float

@dataclass
class Section:
    positions: List[Position]

pos1 = Position('a', 52, 10)
pos2 = Position('b', 46, -10)
pos3 = Position('c', 45, -10)

sec = Section([pos1, pos2 , pos3])

print(sec.positions)

How can I create additional attributes in the dataclass Section so they would be a list of the attribute of its subclass Position?
In my example, I would like that the section object also returns:
sec.name = ['a', 'b', 'c']   #[pos1.name,pos2.name,pos3.name]
sec.lon = [52, 46, 45]       #[pos1.lon,pos2.lon,pos3.lon]
sec.lat = [10, -10, -10]     #[pos1.lat,pos2.lat,pos3.lat]

I tried to define the dataclass as:
@dataclass
class Section:
    positions: List[Position]
    names :  List[Position.name]

But it is not working because name is not an attribute of position. I can define the object attributed later in the code (e.g. by doing secs.name = [x.name for x in section.positions]). But it would be nicer if it can be done at the dataclass definition level.
After posting this question I found a beginning of answer (https://stackoverflow.com/a/65222586/13890678).
But I was wondering if there was not a more generic/"automatic" way of defining the Section methods : .names(), .lons(), .lats(), ... ? So the developer doesn't have to define each method individually but instead, these methods are created based on the Positions object attributes?

A: You could create a new field after __init__ was called:
from dataclasses import dataclass, field, fields
from typing import List

@dataclass
class Position:
    name: str
    lon: float
    lat: float

@dataclass
class Section:
    positions: List[Position]
    _pos: dict = field(init=False, repr=False)

    def __post_init__(self):
        # create _pos after init is done, read only!
        Section._pos = property(Section._get_positions)

    def _get_positions(self):
        _pos = {}

        # iterate over all fields and add to _pos
        for field in [f.name for f in fields(self.positions[0])]:
            if field not in _pos:
                _pos[field] = []

            for p in self.positions:
                _pos[field].append(getattr(p, field))
        return _pos

pos1 = Position('a', 52, 10)
pos2 = Position('b', 46, -10)
pos3 = Position('c', 45, -10)

sec = Section([pos1, pos2, pos3])

print(sec.positions)
print(sec._pos['name'])
print(sec._pos['lon'])
print(sec._pos['lat'])

Out:
[Position(name='a', lon=52, lat=10), Position(name='b', lon=46, lat=-10), Position(name='c', lon=45, lat=-10)]
['a', 'b', 'c']
[52, 46, 45]
[10, -10, -10]

Edit:
In case you just need it more generic, you could overwrite __getattr__:
from dataclasses import dataclass, field, fields
from typing import List

@dataclass
class Position:
    name: str
    lon: float
    lat: float

@dataclass
class Section:
    positions: List[Position]

    def __getattr__(self, keyName):
        for f in fields(self.positions[0]):
            if f"{f.name}s" == keyName:
                return [getattr(x, f.name) for x in self.positions]
        # Error handling here: Return empty list, raise AttributeError, ...

pos1 = Position('a', 52, 10)
pos2 = Position('b', 46, -10)
pos3 = Position('c', 45, -10)

sec = Section([pos1, pos2, pos3])

print(sec.names)
print(sec.lons)
print(sec.lats)

Out:
['a', 'b', 'c']
[52, 46, 45]
[10, -10, -10]

A: After some more thinking I thought an alternative solution using methods:

from dataclasses import dataclass
from typing import List

@dataclass
class Position:
    name: str
    lon: float
    lat: float

@dataclass
class Section:
    positions: List[Position]

    def names(self):
        return [x.name for x in self.positions]

    def lons(self):
        return [x.lon for x in self.positions]

    def lats(self):
        return [x.lat for x in self.positions]

pos1 = Position('a', 52, 10)
pos2 = Position('b', 46, -10)
pos3 = Position('c', 45, -10)

sec = Section([pos1, pos2 , pos3])

print(sec.positions)
print(sec.names())
print(sec.lons())
print(sec.lats())

But I was wondering if there was not a more generic/"automatic" way of defining the Section methods : .names(), .lons(), .lats(), ... ?
So the developer doesn't have to define each method individually but instead, these methods are created based on the Positions object attributes?

A: The way I understood you, you'd like to declare dataclasses that are flat data containers (like Position), which are nested into a container of another dataclass (like Section). The outer dataclass should then be able to access a list of all the attributes of its inner dataclass(es) through simple name access.
We can implement this kind of functionality (calling it, for example, introspect) on top of how a regular dataclass works, and can enable it on demand, similar to the already existing flags:
from dataclasses import is_dataclass, fields, dataclass as dc

# existing dataclass siganture, plus "instrospection" keyword
def dataclass(_cls=None, *, init=True, repr=True, eq=True, order=False,
              unsafe_hash=False, frozen=False, introspect=False):

    def wrap(cls):
        # run original dataclass decorator
        dc(cls, init=init, repr=repr, eq=eq, order=order,
           unsafe_hash=unsafe_hash, frozen=frozen)

        # add our custom "introspect" logic on top
        if introspect:
            for field in fields(cls):
                # only consider nested dataclass in containers
                try:
                    name = field.type._name
                except AttributeError:
                    continue
                if name not in ("List", "Set", "Tuple"):
                    continue
                contained_dc = field.type.__args__[0]
                if not is_dataclass(contained_dc):
                    continue
                # once we got them, add their fields as properties
                for dc_field in fields(contained_dc):
                    # if there are name-clashes, use f"{field.name}_{dc_field.name}" instead
                    property_name = dc_field.name
                    # bind variables explicitly to avoid funny bugs
                    def magic_property(self, field=field, dc_field=dc_field):
                        return [getattr(attr, dc_field.name) for attr in getattr(self, field.name)]
                    # here is where the magic happens
                    setattr(
                        cls,
                        property_name,
                        property(magic_property)
                    )
        return cls

    # Handle being called with or without parens
    if _cls is None:
        return wrap
    return wrap(_cls)

The resulting dataclass-function can now be used in the following way:
# regular dataclass
@dataclass
class Position:
    name: str
    lon: float
    lat: float

# this one will introspect its fields and try to add magic properties
@dataclass(introspect=True)
class Section:
    positions: List[Position]

And that's it. The properties get added during class construction, and will even update accordingly if any of the objects changes during its lifetime:
>>> p_1 = Position("1", 1.0, 1.1)
>>> p_2 = Position("2", 2.0, 2.1)
>>> p_3 = Position("3", 3.0, 3.1)
>>> section = Section([p_1 , p_2, p_3])
>>> section.name
['1', '2', '3']
>>> section.lon
[1.0, 2.0, 3.0]
>>> p_1.lon = 5.0
>>> section.lon
[5.0, 2.0, 3.0]


text:
Q: add (assembly) instruction not working like I thought it should I have the line add (%ecx,%esi,4),%edx.
I am using gdb to look though code and notice that if use x/d to print the value in ecx, it prints 2 (if I use x/s it prints "/002", idk if this is relevent).
Then the register esi is holding 0x2.
I thought that add would work like edx = ecx + (esi * 4), which should be 0xA, but after this edx holds 0x6.
I have looked up the add syntax and I believe I had that right so I am wondering why it comes out as 0x6.

A: First your assembly is in AT&T Syntax, which means the instruction is like the following:
movl src,dest

The code given actually works like this

Then the register esi is holding 0x2. I thought that add would work like edx = ecx + (esi * 4), which should be 0xA, but after this edx holds 0x6.

It actually works like this: Add the value of edx to the value at address (ecx+esi*4)


text:
Q: Does Firebase's free tier expire? Many cloud services' free tiers expire within a certain number of months. For example, AWS free tier expires after 12 months.
I'm wondering if Firebase's free tier expire after a certain period of time given that I do not reach the free tier quota.

A: Firebase does not expire.
Only differences between paid and free account is, paid account gets more storage, bandwidth, hosting space etc than free account.
Reference : https://firebase.google.com/pricing/

A: No, there is no expiration.  Everything on the pricing page is exactly as stated, there are no hidden costs or limits that I'm aware of.  Please reach out to Firebase support for canonical billing details.


text:
Q: getting data from an object's array with vue.js I am trying to access the following data in Vue.js
{"id":1,"name":"Westbrook","created_at":"2017-06-10T16:03:07.336Z","updated_at":"2017-06-10T16:03:07.336Z","stats":[{"id":1,"player_id":1,"points":2558,"assists":840,"rebounds":864,"created_at":"2017-06-10T16:03:07.373Z","updated_at":"2017-06-10T16:03:07.373Z"}]}

self.player = response.name works. now i need self.point
methods: {
    fetchData: function() {
      var self = this;
      $.get("api/v1/players/1", function(response) {
        console.log(response);
        self.player = response.name;
        self.point = response.stats.points
      });
    }
  }

I have thus far tried response.stats["points"], response.stats[2], response.stats[ { points } ], response.stats[points]

A: The stats property in your json holds an array in which the first object has a property named points
So use response.stats[0].points

Keep in mind though that the stats is probably an array for a reason. It might hold more than one objects in the future, so always using the first element [0] might not be a valid approach.

A: I think it can help you
var json = JSON.parse(data);
json.stats[0].points

A: response = {"id":1,"name":"Westbrook","created_at":"2017-06-10T16:03:07.336Z","updated_at":"2017-06-10T16:03:07.336Z","stats":[{"id":1,"player_id":1,"points":2558,"assists":840,"rebounds":864,"created_at":"2017-06-10T16:03:07.373Z","updated_at":"2017-06-10T16:03:07.373Z"}]}

If you want to access the name
console.log(response.name) // Westbrook

If you want to access the stats data which contain list, simply target
let stats=response.stats[0] //By getting the first index in the list

Get the points in stats
console.log(stats.points) // 2588


text:
Q: How to store a json object as string in SQL database Using python, json, and pyodbc, is there a python function to store a json object in a Text field in a SQL database?
For example:
cnxn = pyodbc.connect( MY CONNECTION STRING )
cursor = cnxn.cursor()
cursor.execute("UPDATE TABLE1 SET FIELD1 = '" + json.dumps(pythonDictionary) + "' WHERE FIELD2 = 'some value'")

I always get syntax error because i am not properly escaping the special symbols in the json object, i simply want that json dump to be converted to proper sql string, is there a function in python to do that?!

A: Instead of escaping yourself, you should just use parameterized values:
cursor.execute("UPDATE TABLE1 SET FIELD1 = ? WHERE FIELD2 = 'some value'", (json.dumps(pythonDictionary)) )

How to use variables in SQL statement in Python?


text:
Q: Error when trying to interactively load data file saved by paused batch script In the process of debugging and solving my problem with retrieving attributes (Can I access R data objects' attributes without fully loading objects from file?), based on advice here on SO, I switched from using save() and load() to saveRDS() and readRDS(), correspondingly.
My investigation (via non-interactive debug printing) showed the following:

*

*immediately after initial saveRDS() the saved object contains the attribute in question;

*an interactive R session, performed after the initial run of the script, show the absence of the attribute from the saved object;

*the previous findings above explain the failure to retrieve the said attribute during the next run of the script, which I initially incorrectly attributed to save/load and saveRDS/readRDS behavior.
In order to manually confirm the presence of the attribute in the persistent object (saved in an .rds file) immediately after the initial saveRDS, I decided to pause the batch R script running in one terminal window using scan (readLine doesn't appear to work for this in batch R scripts):
if (DEBUG) {
  cat("Press [Enter] to continue")
  key <- scan("stdin", character(), n=1)
}

and, in another terminal window, to inspect the saved object via an interactive R session.
However, when, after the batch script has stopped as expected, loading the saved object from the .rds file in an interactive session failed with the following message:
> load("../cache/SourceForge/ZGV2TGlua3M=.rds")
Error: bad restore file magic number (file may be corrupted) -- no data loaded
In addition: Warning message:
file 'ZGV2TGlua3M=.rds' has magic number 'X'
  Use of save versions prior to 2 is deprecated

The following output describes my R environment at the time of investigation:
> sessionInfo()
R version 3.0.2 (2013-09-25)
Platform: x86_64-pc-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C
 [9] LC_ADDRESS=C               LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

The only plausible to me explanation is that the batch session (and, specifically, the pause via scan) somehow locks or modifies the environment that makes it impossible to properly access R objects from within the interactive session. Perhaps there exist other possible reasons for this situation. I would greatly appreciate any help or advice to solve this problem!
UPDATE:
After killing the batch R script's process (which after scan became unresponsive), I again tried to manually load the .rds file, expecting a success due to the absence of the pause in the batch script. However, to my surprise, I was greeted with the exact same error message. This makes me think that the .rds file is really corrupted (potentially due to my practice of stopping a running batch R script by repeatedly pressing Ctrl-C - I will need to come up with something more "gentle"). After figuring out a better way to stop a running script, I will try to reproduce the scenario and report here.
UPDATE 2:
After removing all (potentially corrupted) .rds files from the cache directory and following the scenario described above (loading R data file interactively with batch R script paused), the output presented exactly the same error message as before. At this point, I really need an advice to figure out what's going on.
UPADATE 3 (saving the object):
assign(dataName, srdaGetData())
data <- as.name(dataName)

# save hash of the request's SQL query as data object's attribute,
# so that we can detect when configuration contains modified query
attr(data, "SQL") <- base64(request)

# save current data frame to RDS file
saveRDS(data, rdataFile)

UPDATE 4 (reproducible example):
library(RCurl)

info <- "Important data"
request <- "SELECT info FROM topSecret"
dataName <- "sf.data.devLinks"
rdataFile <- "/tmp/testAttr.rds"

getData <- function() {
  return (info)
}

requestDigest <- base64(request)

# check if the archive file has already been processed
message("\nProcessing request \"", request, "\" ...\n")

# read back the object with the attribute
if (file.exists(rdataFile)) {
  # now check if request's SQL query hasn't been modified
  data <- readRDS(rdataFile)
  message("Retrieved object '", as.name(data), "', containing:\n")
  message(toString(data))

  requestAttrib <- attr(data, "SQL", exact = TRUE)
  message("\nObject '", data, "' contains attribute:\n\"",
                 base64(requestAttrib), "\"\n")

  if (identical(requestDigest, requestAttrib)) {
    message("Processing skipped: RDS file is up-to-date.\n")
    stop()
  }
  rm(data)
}

message("Saving results of request \"",
        request, "\" as R data object ...\n")

assign(dataName, getData())
data <- as.name(dataName)

# save hash of the request's SQL query as data object's attribute,
# so that we can detect when configuration contains modified query
attr(data, "SQL") <- base64(request)

# save current data frame to RDS file
saveRDS(data, rdataFile)

I expect the value of dataName variable to be saved, however the code saves the name of the variable.

A: If you save something using saveRDS, the equivalent loading function is readRDS/
If you save an object into an RData file, you should use load to load the object.
readRDS will allow you to specify the name of the object being loaded.
load loads the objects in an .RData file, and they will retain the names with which they were saved.
If "../cache/SourceForge/ZGV2TGlua3M=.rds" was saved using saveRDS, then
whatever <- readRDS("../cache/SourceForge/ZGV2TGlua3M=.rds")

will load the object as whatever
Running load on a file not saved in .RData format will result in the error message you posted.


text:
Q: Can use font on my tex editor, but not on sharelatex, why? So I can write using Georgian font on my computer's TeX programme (I think MikTex?).  For this I needed to write the command "\usepackage [georgian]{babel}" and allow my computer to download something.  If I use the sharelatex programme, it says it can't compile "because no Georgian font encoding has been loaded so far.  A font encoding should be declared before babel".
How can I solve this?  (Am  I asking how can I make sharelatex use the package above?)
Thanks!

A: from
\documentclass{article}

\usepackage{fontspec}
\setmainfont{Noto Serif Georgian}
\usepackage [georgian]{babel}

\begin{document}

გამარჯობა

\end{document}

I get

from xelatex despite a spurious warning about TU encoding.
You should be able to use the Noto fonts on Overleaf


text:
Q: how to configure android SDK with eclipse luna in ubuntu? I have download eclipse luna  then after i have doenload android-sdk-linux then after I have run tools/android update sdk --no-ui this command what next step I have done so I develop android application in my eclipse.
I have try to import my old android project this gives errors like:
Description Resource    Path    Location    Type
The project was not built since its build path is incomplete. Cannot find the class file for java.lang.Object. Fix the build path then try building this project    google-play-services_lib        Unknown Java Problem
The project was not built since its build path is incomplete. Cannot find the class file for java.lang.Object. Fix the build path then try building this project    gu10science     Unknown Java Problem
The type java.lang.Object cannot be resolved. It is indirectly referenced from required .class files    TestActivity.java   /gu10science/src/com/sparrow/gu10science    line 1  Java Problem
The type java.lang.Object cannot be resolved. It is indirectly referenced from required .class files    UnusedStub.java /google-play-services_lib/src/android   line 1  Java Problem

A: You can get your answer here: https://stackoverflow.com/a/9341736/1974306

(...) select Android API version (set to another one and valid, then restore the on you want and validate it -> it will force Eclipse to reload API). (...)


text:
Q: Variables for all views in Sinatra erb files What is the best way to assign variables in sinatra that can be used on all views(all erb files).
I know it can be done using global variables in the main file lets say app.rb but is there a better way to do it without using global variables?
eg in app.rb, i can do:
@@a = "hello"
get '/' do
    erb :index
end

get '/hi' do
    erb :page
end

and in index.erb and page.erb files:
<%= @@a %>

But is there a way to do so without using global variables or is global variables the best way to go about doing that?

A: Create a module with constants of all the strings/variables you want accessible. All views will have access to your modules:
module StringConstants
    LOGIN_PAGE = "Welcome to X"
    LOGOUT = "See you again soon"
end

then in your views:
<%= StringConstants::LOGIN_PAGE %>

A: Session variables are usually used for cross view access. In sinatra, it's just your standard hash:
session[:whatever] = "Hello"

And that can be accessed anywhere once set. It will persist independently per user session.
For example, a common helper I use is:
# set session[:user] = user's ID when they log in

def user
  @user ||= User.get(session[:user])
end

You'd access that in your views or controllers using user.


text:
Q: why is EventBus significantly faster while it compare with otto Both EventBus and Otto are event bus, and I found EventBus has this conclusion:

Benchmark results indicate that EventBus is significantly faster in almost every scenario:

here is origin page
My question is why EventBus is more faster than Otto. I has read the two source code, and don't found obvious difference. Here is what I found the difference:

*

*Otto use annotation process at runtime.

*EventBus use CopyOnWriteArrayList to store Subscription while Otto use Set.
Are there any other reasons? Is it the main reason that Otto use annotation process at runtime? Could someone explain the reason EventBus is significantly faster while it compare with otto?
Thanks in advance.


text:
Q: What should I look for when shopping for an ESD bench mat? I would like to get an anti-static mat for my bench top and found these two:

*

*DigiKey: Table mat ESD blue 2X4' rubber

*Mouser: Antistatic Control Products 2X4' blue table mat
What should I look for when shopping for an ESD bench mat?

A: If I happen to decide buy one (alread got one :P) I check for surface resistance (higher better) also side specs like heat resistance (You can easily burn the cheap ones during soldering if you are not careful, the first one I had was a cheapo that got a huge whole after I left my soldering iron on it for fraction of seconds).
You also have to make sure you connect grounding wire to a real ground, without that it is as good as nothing.
Any way the first one looks like one of those good blue ones, the second one doesn't have photo so I am out of fashion guess! Both are marked as 3M...I think it says enough! go for it if you really need one.

A: ESD precautions:

I would like to get an anti-static mat for my bench top

Buy the cheapest one in the size you need.
Suitable materials for ESD desktop sheets: Any somewhat conductive sheet of material that is grounded via a 1 to 10 megohm resistor will work as an anti electrostatic work surface.
 (Sheets with very low resistance per square risk conducting current when PCBs etc with exposed terminals are placed on them. (Ask me how I know :-) ).
Sheets need not be more than a trace conductive, although very conductive sheets will work. eg a thin sheet of galvanised steel would work well but be immensely inconvenient and potentially very dangerous as it allows instant conduction from anywhere on a work bench to anywhere else.
Better cheaper faster ... A potentially much cheaper than "real" solutions product is Butyl Rubber sheet sold for roofing and pool liner purposes. The conductivity in this material is caused by carbon-black which is integrated in the rubber and it is wise to check that at least some conductivity is present. Take an ohm meter set to say 10 megohm range with 2 sharp probes. Press probes into sheet just not touching so that probes penetrate sheet surface. If there is even a trace of resistance measurable then the sheet will work as an anti ESD sheet. Results may vary from megohms to a kilohm or so depending on carbon black loading.
Measured resistances: Notionally the "resistance per square" of a sheet of conductive material is the same at all scales so the resistance across say the diagonal of a square of material should be the same for a square of any length side. So if a 1cm side square measures 100k across the diagonal then so too should squares of 10cm or 100cm or 1m length sides (given the same thickness in each case). In practice results may vary somewhat, but this is a good enough gyide for ESD purposes - if you can see a reading in the megohms of less range at any distance (small or great) the sheet will probably work OK.
Wood: An older worn wooden desk will probably be an adequate ESD protective surface in its own right. A new coat of varnish may destroy this. An older wooden floored building will also probably be ESD safe. A new concrete floored building will not be and linoleum or carpet add their own potential problems.
Carpet: Some carpets generate enough "static electricity" to cause user shocks from sparks generated. Your electronics will die even when you just wave your hand near them if not well protected. Use of an antistatic spray on the carpet may stop users receiving shocks but induced voltages may still destroy ICs.
Especially sensitive devices include: LEDs, Schottky diodes, GaAs devices, MOSFET gates, unprotected CMOS, Gunn diodes (who?). Many modern devices have ESD protection built in - especially those which are especially sensitive if unprotected, but suitable care should stoll be taken. I have seen less sobvious ESD damage over decades than the salessmen would have led me to expect BUT I have seen certain ESD failures and in some cases could virtually guarantee device failure by following ceryain unsafe procedures.
Safety: Mats and wrist straps should have a high value resistor - usually 1 megohm but not critical - to avoid grounding users for power voltages and so creating a shock hazard.


text:
Q: Repurposing very old hardware (Apple ][ era) I still have my very first computer - an Apple ][ I was given back in grade school. Once I fix the drive cables and clean it up a bit, what could I reasonably use it for?

Obviously the stacks of 5¼" floppies might provide some entertainment and distraction as I go through them, but after that...? I've heard of people using them as email systems and dumb terminals, what else might a geek like me do with my first love?

I hope it's still running when I have kids. I'd love to teach them programming using Robot Odyssey

A: You could attempt to build a web server, that seems to be a very common project with very old systems. The third link I posted is a site hosted off one. You could also set up all your old favorite games to play. There are lots of resources out there of old computer projects.
Here are some resources to give you some ideas:
http://lostclassics.apple2.info/
http://a2gameserver.berlios.de/
http://servers.ld8.org/servers_apple2.html

A: If it were an Apple // GS I would suggest getting an SCSI or IDE interface card and putting proDOS AppleWorks GS and a couple of other applications on a hard drive. If you're into soldering you can build one. If it isn't a //gs, then you should back up all your floppies and use it only for games, like Eamon, or creating arty music videos.
As you've said you don't have an 80 column card, the 40 column text won't be all that well suited as either a (dumb) serial terminal nor as a way to work with AppleWorks 3. Perhaps you could use the original Killer App: VisiCalc.

A: I used a Cambridge Z88 as a serial console for my Linux PC for a few years, it was actually quite handy as such because with a long enough serial cable I could carry it around my room as I looked at books, made coffee or got back into bed. The Apple ][ obviously isn't so portable but can easily be used as a conversation-piece console.
The other option is to actually use it as an Apple ][. You mention teaching your kids programming, well how about seeing if you can get your favorite app to run in those 4Kb? I'm quite tempted to try a GTD app for the Z88 now.

A: Use it to learn 6502 Assembler.