text:
Q: I cant see my images in my flutter project I did to make a simple pokedex application for trying myself. I completed my project and I did not get any issue in android studio.Other hand, When I started my application, I cant see images to get in my project in emulator. Can anyone help me for this issue .
Can look at this extension.
https://github.com/AlejandroTaichu/Pokedex.git
I want to see images in my project when I was opened my project.I am new on programming so I cant fix that.

A: You have forgotten extension of image in your code
child: Image.asset("images/${pokemon.name}")),

Change to below code
child: Image.asset("images/${pokemon.name}.png")),

Or add image extension(.png) in names of pokeList

A: You need to change the image name(path) according to the assets image path include the image type.

Next you need to create a future and call future on Future Builder widget.
  late final future = callPokemon();

class _PokemonHomepageState extends State<PokemonHomepage> {
  Future<List<Pokemons>> callPokemon() async {
    var pokeList = <Pokemons>[];

    var p1 = Pokemons(pokeId: 1, name: "Charmender.png", health: 100, power: 250);
    var p2 = Pokemons(pokeId: 2, name: "squirtle.png", health: 150, power: 300);
    var p3 = Pokemons(pokeId: 3, name: "balbazar.png", health: 300, power: 500);

    pokeList.add(p1);
    pokeList.add(p2);
    pokeList.add(p3);

    return pokeList;
  }

  late final future = callPokemon();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar:
          AppBar(title: const Text("POKEDEX"), backgroundColor: Colors.green),
      body: FutureBuilder<List<Pokemons>>(
        future: future,
        builder: (context, snapshot) {

Made a pr on git, you can merge it

A: I suggest you to use flutter_gen (https://pub.dev/packages/flutter_gen) for assets. I recently found this package & its really helpful when using multiple images from assets.
With flutter_gen you can just setup few things one time & you can directly get image widgets from this package.

*

*Setup flutter_gen

 dart pub global activate flutter_gen

*Add these runners in your dev dependencies

dev_dependencies:
  build_runner:
  flutter_gen_runner:

*Setup path of generated assets file

flutter_gen:
  output: lib/generated/

There are many options in this step. You can check their documentation.

*Set image folder path

assets:
    - assets/images/

*Put your images in the path added

*After doing these steps you just need to run
flutter packages pub run build_runner build

This file will generate an assets file name assets.gen.dart inside the lib/generated folder as we setup in step 3.
Note that you have to run this command whenever you change folder name or images to regerenated the assets.gen.dart
Thats it.
When you are done with these steps, you can directly get the images from this assets.gen.dart file like this
import 'package:flutter_boilerplate/generated/assets.gen.dart';

Padding(
  padding: const EdgeInsets.all(20),
  child: SizedBox(
    height: 200, child: Assets.images.cat1.image(width: 200),
  ),
),

The plus benefit is that these assets provided widget support intellisense, so there is no chance for spelling mistake. Plus you directly get a widget from this with all the properties of default Image widget.
It also supports advance image types like svg, lottie, flare as well.


text:
Q: How do you mock out the File Picker in the browser for unit testing? I am interested in how to globally mock out the file picker in the browser. Specifically, I am most interested in doing this in Firefox but would prefer a general solution.
I only care about preventing the file picker dialog from appearing. I do not need to be able to assert that it did open. The problem is that I have unit tests for JavaScript code that open the file picker. When the dialog opens, it halts the execution of the test suite.
An example situation is that I am testing the onRender method of a Backbone.View. That method renders a subview, which will open the File Picker when it is rendered. Since I am not directly testing that subview, I would prefer not to mock out portions of its behavior when I am only interested in unit testing some other part of the onRender method.
Example:
//Test file
it("should do something", function() {
  var view = new App.Views.SomeView();
  spyOn(view.modelBinder, "bind");
  view.render();
  expect(view.modelBinder.bind).toHaveBeenCalled();
});

//View file
onRender : function () {
  this.modelBinder.bind(this.el, this.model);
  this.$("#thing").html(this.subview.render().el); //This line has a side effect that opens file picker
}

Essentially, I do not want to explicitly mock out the behavior that causes the file picker to be opened because it is not what I am interested in testing here. Doing so will make the test suite much more brittle and difficult to maintain.

A: Use sinon to mock/spy/stub out the calls.  You can test for the calls being made instead of actually making the calls.
That way you can test that the function has been called without calling the actual function that displays the dialog.

A: To answer your question: Just don't.
I would replace subview.render() with an empty function to avoid the undesired side effect. You say however:

"I do not want to explicitly mock out the behavior that causes the
  file picker to be opened because it is not what I am interested in testing..."

Which is a little contradictory. If you want to Unit-Test App.Views.SomeView, you will have to mock out external collaborators, specially when not interesting, and including your file picker. On the other hand, you should not mess with the SUT when unit-testing it.
Mocking would in fact make your test more prone to be red, but is the only way to make sure your production code does not suffer from ill forms of coupling (IMHO, A common pitfall with Backbone.js apps.)
The only place in which you would need to avoid the file-picker to display, is when unit-testing your file-picker itself, in that case you could use sinon as sugested or leave it without coverage if you are using jQuery. Remember the "Never mock a type you don't own" rule.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Handle custom cookie expiration event I am creating a cookie inside a .net core application, and I want to find a way to handle the expiring event of this cookie on the "server side", not on the client side using js.
Basically, I want to call a method when the cookie expires. Note the fact that dis cookie is not an authentication cookie or some cookie generated by a service. Is a complete custom cookie created by me.
I have looked into some similar issues reported here, but the answers found there are solutions for authentication cookies and they don't suite me.

A: Cookie expiration isn't a one-time event . On each request the client can send cookie to server side . Server side will not notice whether your cookie is expired unless checking the cookie property on each request using middleware or somewhere  .
That means even you enable cookie expire time validation logic on server side , but if your client doesn't send request to server , server side will not know whether your cookie expires . That also depends on browsers , some browsers will delete the cookie if it expires .


text:
Q: Extrapolating sequence of numbers in R I would like to increment numbers from the last observed number to the last number i.e. the NA values should be replaced with 35, 36, 38, 39
How can I go about it?
library(tidyverse)

trialdata <- tibble(
  id = c(13, 8, 20, 34, 4, NA, NA, NA, NA, NA)
)

A: If your goal is to fill the NA id rows with a sequence that starts after the maximum non-NA value, then here's one way you could do it:
trialdata %>%
  mutate(
    id_filled = cumsum(is.na(id)) + max(id, na.rm = T),
    id_filled = coalesce(id, id_filled)
  )

      id id_filled
   <dbl>     <dbl>
 1    13        13
 2     8         8
 3    20        20
 4    34        34
 5     4         4
 6    NA        35
 7    NA        36
 8    NA        37
 9    NA        38
10    NA        39

A: Here is one option that could work on NAs that are between as well
library(dplyr)
library(tidyr)
library(data.table)
trialdata %>%
   mutate(id1 = id) %>%
   fill(id1, .direction = "downup") %>%
   group_by(grp = rleid(id1)) %>%
   mutate(id = id[!is.na(id)] + row_number() - row_number()[!is.na(id)]) %>%
   ungroup %>%
   select(-id1, -grp)

-output
# A tibble: 10 × 1
      id
   <dbl>
 1     4
 2     8
 3    13
 4    20
 5    34
 6    35
 7    36
 8    37
 9    38
10    39

On another data
trialdata1 <- structure(list(id = c(NA, 4, 10, NA, NA, 20, NA)),
class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -7L))

the output is
# A tibble: 7 × 1
     id
  <dbl>
1     3
2     4
3    10
4    11
5    12
6    20
7    21

A: Here is an alternative:
libaray(dplyr)
library(tidyr)

trialdata %>%
  mutate(id1 = row_number()) %>%
  arrange(id) %>%
  fill(id) %>%
  group_by(id) %>%
  mutate(id = ifelse(row_number()>1, id+row_number()-1, id)) %>%
  arrange(id1) %>%
  ungroup() %>%
  select(-id1)

     id
   <dbl>
 1    13
 2     8
 3    20
 4    34
 5     4
 6    35
 7    36
 8    37
 9    38
10    39

A: For trailing NAs, you could do something like this.
x[is.na(x)] <- (x[sum(x > 0, na.rm=TRUE)]) + seq(sum(is.na(x)))
x
# [1]  4  8 13 20 34 35 36 37 38 39

Data:
x <- c(sort(c(13, 8, 20, 34, 4)), NA, NA, NA, NA, NA)


text:
Q: React Native, add two return statements to useEffect hook How can I add two return statements to my useEffect hook? I would like to add an event listener to my current hook.
Event listener:
const subscription = AppState.addEventListener("change", nextAppState => {
  if (
    appState.current.match(/inactive|background/) &&
    nextAppState === "active"
  ) {
    console.log("App has come to the foreground!");
  }

  appState.current = nextAppState;
  setAppStateVisible(appState.current);
  console.log("AppState", appState.current);
});

return () => {
  subscription.remove();
};

Current hook:
useEffect(() => {

    async function checkRefresh() {
        if (
            daysDiffToNow(lastUpdatedTimestamp) > 0 &&
            appState.current.match(/inactive|background/) &&
            nextAppState === "active"
        ) {
            await onRefreshAppData();
        }
    }
    checkRefresh();

    const updateLastUpdatedTextCallback = (value) => {
        setState((prevState) => ({
            ...
        }));
    };
    const id = setInterval(() => {
        updateLastUpdatedTextCallback(lastUpdatedTimestamp);
    }, TIME_INTERVAL_IN_MILISECONDS);
    return () => clearInterval(id);
}, [lastUpdatedTimestamp]);

const close = () => {
    setState((prevState) => ({
        ...
    }));
};

A: You could simply put them top to bottom inside the useEffect and have a return function that would look like this (it executes at once the code for the two return statements needed):
return () => {
  subscription.remove(); // the first
  clearInterval(id); // the second
};


text:
Q: Searching for c# code to convert from UTM to WGS1984 (and back) I'm looking for code in c# that converts coordinates from UTM to WGS1984 (and preferably backwards as well). I need to convert coordinates from only one zone (36N).
I've found this and this, but they throw me 150-200 meters from the real point (The allowed diversion I'm aiming  for is 5 meters tops).
EDIT: Found this as well, but did not have an opportunity to check this for accuracy.
thanks in advance.
EDIT: Found this as well, but did not have an opportunity to check this for accuracy.

A: if you're willing to use the GDAL/OGR C# bindings, which you can get here assuming you use Windows, you can achieve what you want via the OSGeo.OSR library and proj4 projection expressions from spatialreference.org.
The specifics of finding and installing GDAL/OGR builds for your operating system are covered in other questions and several blog posts. But once you find a build that suits you, make sure you reference the osr_csharp.dll in your project.
Second, import the library with a using OSGeo.OSR; statement.
(Third ..and I'm not sure if this is always necessary, but in IIS, I had to use a 32-bit application pool before this worked. So if you run into issues, it's possible your app pool needs to be 32-bit.)
And finally, craft a method to perform coordinate conversion. The following is a recipe I have used to take X and Y values for ESRI 102697 as the srs projection, note the proj4 link at SpatialReference.org, and convert those projected values to WGS 1984 Long/Lat, i.e. the dst projection, returning the converted point values.
The lesson here is projection agnostic. Meaning you just need to find the appropriate src and dst proj4 expressions for your data, then adapt what you see below to your specific situation. I hope it's helpful. /elrobis
[WebMethod]
public string ReprojectPoint(string x, string y)
{
    // Replace this with your appropriate proj4 expression..
    string esri_102697_proj4 = @"+proj=tmerc +lat_0=35.83333333333334 +lon_0=-92.5 +k=0.9999333333333333 +x_0=500000.0000000002 +y_0=0 +ellps=GRS80 +datum=NAD83 +to_meter=0.3048006096012192 +no_defs";
    OSGeo.OSR.SpatialReference src = new OSGeo.OSR.SpatialReference("");
    src.ImportFromProj4(esri_102697_proj4);

    // Replace this with your appropriate proj4 expression..
    string epsg_wgs1984_proj4 = @"+proj=latlong +datum=WGS84 +no_defs";
    OSGeo.OSR.SpatialReference dst = new OSGeo.OSR.SpatialReference("");
    dst.ImportFromProj4(epsg_wgs1984_proj4);

    // Init the transformer object.
    OSGeo.OSR.CoordinateTransformation ct = new OSGeo.OSR.CoordinateTransformation(src, dst);

    double[] p = new double[3];
    p[0] = Convert.ToDouble(x);
    p[1] = Convert.ToDouble(y);
    p[2] = 0; // I don't remember if "Z" is required, but I didn't use it.

    ct.TransformPoint(p); // Mutate the point coordinates here..

    return "x:" + Convert.ToString(p[0]) + " y:" + Convert.ToString(p[1]) + " z:" + Convert.ToString(p[2]);
}

A: I made a port from a javascript library to C#, I have tested it and works perfectly, you can take a look at: https://github.com/owaremx/LatLngUTMConverter. It does not need any extra library. Just c# code

A: Some other options:

*

*DotSpatial has a Projections library

*Proj4 is ported to .net as:

*

*Proj4Net

*Proj.net
Altough I'm not sure how well maintained these are

A: MapGuide Open Source has an object-oriented .net wrapper API around the CS-Map coordinate system library that can be used outside of a MapGuide web application.
The API is available as NuGet package and can be installed like so
PS> install-package mapguide-api-base-x86

Or for 64-bit
PS> install-package mapguide-api-base-x64

Then you need a copy of the CS-Map dictionary files which you can grab form an installation of MapGuide Open Source, or you can nuget install a compact subset of these dictionaries
PS> install-package cs-map-dictionaries

A simple transformation example using this API would look like this
using OSGeo.MapGuide;

public void Transform(double x, double y, ref double tx, ref double ty)
{
    //Set the location of the dictionary files (only needs to be done once, just illustrated here for example purposes)
    Environment.SetEnvironmentVariable("MENTOR_DICTIONARY_PATH", "C:\\Program Files\\OSGeo\\MapGuide\\CS-Map\\Dictionaries", EnvironmentVariableTarget.Process);

    MgCoordinateSystemFactory csFactory = new MgCoordinateSystemFactory();
    //Create WGS84 coord sys
    MgCoordinateSystem wgs84 = csFactory.CreateFromCode("LL84");
    //Create UTM coord sys
    MgCoordinateSystem utm = csFactory.CreateFromCode("UTM-36N");
    MgCoordinateSystemTransform xform = csFactory.GetTransform(wgs84, utm);

    MgCoordinate transformed = xform.Transform(x, y);

    //MgCoordinate contains your transformed coordinates
    tx = transformed.GetX();
    ty = transformed.GetY();
}


text:
Q: Failed to establish a new connection Discord.py Hello in my code it break my request, i tried several time , but after 1-2 hours bot status no longer changed.
i hosting those files in ftp server.
import discord
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
import time
import random
from discord import Game
import math, time
import requests

Client = discord.client
client = commands.Bot(command_prefix = '!')
Clientdiscord = discord.Client()

@client.event
async def on_ready():

client.loop.create_task(scheduler())
print('project ready')

async def scheduler():
while True:
    # sleep until the next whole second
    now = time.time()
    await asyncio.sleep(math.ceil(now) - now)

    await client.change_presence(game=discord.Game(name='steady', type=3))
    await asyncio.sleep(5)
    await client.change_presence(game=discord.Game(name='ready', type=3))
    await asyncio.sleep(5)
    await client.change_presence(game=discord.Game(name='go', type=3))
    await asyncio.sleep(5)
    await client.change_presence(game=discord.Game(name='Total Used : '+requests.get('http://username.mydomain/project/total_visit/count.txt').text, type=3))
    await asyncio.sleep(10)
    await client.change_presence(game=discord.Game(name='Online : '+requests.get('http://username.mydomain/project/total_online/Live.php').text, type=3))
    await asyncio.sleep(10)
    await client.change_presence(game=discord.Game(name='Total Users : '+requests.get('http://username.mydomain/project/total_users/total.php').text, type=3))
    await asyncio.sleep(10)
    await client.change_presence(game=discord.Game(name='return again', type=3))

    #i tired to kill all request to start clear again.
    client.logout()
    client.close()
    await asyncio.sleep(20)

    client.run("client_token")

Task exception was never retrieved
  future:  exception=ConnectionError(MaxRetryError("HTTPConnectionPool(host='username.mydomain', port=80): Max retries exceeded with url: /project/total_visit/count.txt (Caused by NewConnectionError(': Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',))",),)>
  Traceback (most recent call last):
    File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\urllib3\connection.py", line 159, in _new_conn
      (self._dns_host, self.port), self.timeout, **extra_kw)
    File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\urllib3\util\connection.py", line 80, in create_connection
      raise err
    File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\urllib3\util\connection.py", line 70, in create_connection
      sock.connect(sa)
  ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
    File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\urllib3\connectionpool.py", line 600, in urlopen
      chunked=chunked)
    File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\urllib3\connectionpool.py", line 354, in _make_request
      conn.request(method, url, **httplib_request_kw)
    File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\http\client.py", line 1239, in request
      self._send_request(method, url, body, headers, encode_chunked)
    File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\http\client.py", line 1285, in _send_request
      self.endheaders(body, encode_chunked=encode_chunked)
    File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\http\client.py", line 1234, in endheaders
      self._send_output(message_body, encode_chunked=encode_chunked)
    File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\http\client.py", line 1026, in _send_output
      self.send(msg)
    File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\http\client.py", line 964, in send
      self.connect()
    File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\urllib3\connection.py", line 181, in connect
      conn = self._new_conn()
    File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\urllib3\connection.py", line 168, in _new_conn
      self, "Failed to establish a new connection: %s" % e)
  urllib3.exceptions.NewConnectionError: : Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
    File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\requests\adapters.py", line 449, in send
      timeout=timeout
    File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\urllib3\connectionpool.py", line 638, in urlopen
      _stacktrace=sys.exc_info()[2])
    File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\urllib3\util\retry.py", line 398, in increment
      raise MaxRetryError(_pool, url, error or ResponseError(cause))
  urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='username.mydomain', port=80): Max retries exceeded with url: /project/total_visit/count.txt (Caused by NewConnectionError(': Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
    File "C:\Users\Administrator\Desktop\bot.py", line 33, in scheduler
      await client.change_presence(game=discord.Game(name='Total Used : '+requests.get('http://username.mydomain/project/total_visit/count.txt').text, type=3))
    File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\requests\api.py", line 75, in get
      return request('get', url, params=params, **kwargs)
    File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\requests\api.py", line 60, in request
      return session.request(method=method, url=url, **kwargs)
    File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\requests\sessions.py", line 533, in request
      resp = self.send(prep, **send_kwargs)
    File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\requests\sessions.py", line 646, in send
      r = adapter.send(request, **kwargs)
    File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\requests\adapters.py", line 516, in send
      raise ConnectionError(e, request=request)
  requests.exceptions.ConnectionError: HTTPConnectionPool(host='username.mydomain', port=80): Max retries exceeded with url: /project/total_visit/count.txt (Caused by NewConnectionError(': Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it',))

A:
definitely you must to get error,, you made many get.requests.
to slove it, try (Close request) / (restart Bot [background Command])

hm im not good enough, but you can try my step's
1) add Full (urllib3 library)
import discord
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
import time
import random
from discord import Game
import math, time
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
import urllib3
import urllib3.contrib.pyopenssl
import certifi

2) add (Backgroundworker) Command [will restart your get.request every time.]
Client = discord.client
client = commands.Bot(command_prefix = '!')
Clientdiscord = discord.Client()

urllib3.contrib.pyopenssl.inject_into_urllib3()

@client.event
async def on_ready():
print('Project Runing..!')

async def task():
await client.wait_until_ready()
while True:

   await client.change_presence(game=discord.Game(name='Loading..!', type=3))

   print('Get_Url-Refresh')
   await asyncio.sleep(1)
   print('Total_Used')
   one = requests.get('http://username.mydomain/project/total_visit/count.txt', timeout=5)
   print('Total_Online')
   two = requests.get('http://username.mydomain/project/total_online/Live.php', timeout=5)
   print('Total_Users')
   three = requests.get('http://username.mydomain/project/total_users/total.php', timeout=5)
   await asyncio.sleep(1)
   print('Refresh Request')

   await asyncio.sleep(10)

   print('Running')
   await client.change_presence(game=discord.Game(name='steady', type=3))
   await asyncio.sleep(5)
   await client.change_presence(game=discord.Game(name='ready', type=3))
   await asyncio.sleep(5)
   await client.change_presence(game=discord.Game(name='go', type=3))
   await asyncio.sleep(5)
   print('Total Used..!')
   await client.change_presence(game=discord.Game(name='Total Used : ' + one.text, type=3))
   await asyncio.sleep(5)
   print('Online..!')
   await client.change_presence(game=discord.Game(name='Online : ' + two.text, type=1))
   await asyncio.sleep(5)
   print('Total Users..!')
   await client.change_presence(game=discord.Game(name='Total Users : ' + three.text, type=3))
   await asyncio.sleep(5)
   print('Refresh..!')

   def handle_exit():
print("Handling")
client.loop.run_until_complete(client.logout())
for t in asyncio.Task.all_tasks(loop=client.loop):
    if t.done():
        t.exception()
        continue
    t.cancel()
    try:
        client.loop.run_until_complete(asyncio.wait_for(t, 5, loop=client.loop))
        t.exception()
    except asyncio.InvalidStateError:
        pass
    except asyncio.TimeoutError:
        pass
    except asyncio.CancelledError:
        pass

   while True:
   @client.event
   async def on_message(m):
    if m.content == 'die':
        print("Terminating")
        raise SystemExit

client.loop.create_task(task())
try:
    client.loop.run_until_complete(client.start('You_Token_Here'))
except SystemExit:
    handle_exit()
except KeyboardInterrupt:
    handle_exit()
    client.loop.close()
    print("Program ended")
    break

print("Bot restarting")
client = discord.Client(loop=client.loop)

Credits to Dev I.A (Gamer's Control).


text:
Q: How to change Time.deltaTime value? Is there any way to change Unity's Time.deltaTime value with reflection or with some other method.
We have a replay system which we use mainly for bug hunting.
It stores all the input events and delta time values than we can simulate the game exactly the same . But to force delta time values we have to define and use a custom deltaTime variable. I want to get rid of that variable and also force unity's systems to use our value.
class SystemManager
{
     List<System> systems;
     void Update()
     {
          if(replay)
          {
               DTime.deltaTime = deltaTimeBuffer.GetValue();
          }else
          {
               DTime.deltaTime = Time.deltaTime;
          }

          foreach system in systems
               system.Update();

     }
}

class System
{
     void Update()
     {
          position += DTime.deltaTime * velocity;
          // I want to get rid of DTime.deltaTime and use Time.deltaTime
     }
}

A: Using reflection to change platform-wide known variable might lead to some weird bugs once for example "new developer" in team will not know about that feature and will have to know why his deltaTime is not what he expects to be.
Regardless of that digression - maybe not exactly changing deltaTime directly but You could change your target frame rate.
https://docs.unity3d.com/ScriptReference/Application-targetFrameRate.html
As delta time is just:

The interval in seconds from the last frame to the current one (Read Only).

Source: https://docs.unity3d.com/ScriptReference/Time-deltaTime.html
By calculating new target frame rate (if Your machine will be able to stably work on that frame rate) You could possibly get deltaTime that You want.


text:
Q: Novacode docx bookmarks does not render I am using Novacode docx to read bookmarks and replace them with my data. Looking at my docx file, I have a bookmark called 'UserID' and I try and replace it in my c# code as below
using (DocX doc = DocX.Load(oTemplate))
{
    doc.Bookmarks["UserID"].SetText("MyUser");
}

The error I get is "sequence contains more than one element"
When I look in the debugger the object of doc, there are actually two bookmarks with the name 'UserID' but in word there is only one. I am using word 2016. Anybody has any ideas what the problem could be?

A:             using (DocX document = DocX.Load(AchivoPlantilla))
            {

                Novacode.Image img = document.Images[0];

                int i = 0;
                foreach (Novacode.Bookmark bookmark in document.Bookmarks)
                {
                    var bookmarks = document.Bookmarks[i].Name;
                    if (bookmarks == "varNombreEmpleado") //Compara la marca con la varible de base de datos
                    {
                        document.Bookmarks[bookmark.Name].SetText(TextBox1.Text);

                    }
                    i++;
                }
                document.SaveAs(docSalida);
                Process.Start("WINWORD.EXE", "\"" + docSalida + "\"");
            }


text:
Q: Translational variance in convolutional neural networks Convolutional networks have been proven to work very well detecting a shape independently of where it is in the image, which is referred as translational invariance.
In the case where the position of an object in an image contains information for a classification problem, are convolutional networks still a good method? For example, if we have images of this kind:

The position of the cat in the images is related with the time of the day, and because of that, we can infer if the cat is having lunch or dinner.
Is convolution still a good candidate to solve this problem or are there more appropriate methods? In case convolution fits this purpose, might a fully connected layer be a better approach to solve the spatial variability?
Edit: This is an oversimplification of the problem where images contain entangled and complex patterns which cannot be easily isolated.

A: Yes, convolutional networks are still a good candidate. As you know, the way they work is detecting more and more complex features, starting from edges and colors and detecting textures and other concepts in deeper layers. To detect a feature (let's say a cat head), it is not enough to know that relevant lower level features are present in the region, but their relative position also plays a role (e.g. the eyes should be lower than ears). Convolutional networks do capture this information, and if the relative position of an object plays a role for classification, they should discover it.
As you already mentioned, fully-connected layers encode this positional information even better, and they are used after convolution layers in networks for classification. Possibly even better would be using a "locally-connected layer", which is a combination of a conv-layer and a fully-connected one: it performs a convolution operation, but at every position it learns a separate convolution kernel.
Finally, if you know that position of some objects is crucial for the classification, consider splitting the problem in two parts. Firstly, train a network that can detect these relevant objects (for example a fully convolutional network with low output resolution), and secondly add an extra layer on top of this (locally connected for example) to do the classification. It has been demonstrated by (Gulcehre and Bengio, 2013) that such subproblem splitting can make the difference between easy and impossible: Knowledge Matters: Importance of Prior Information for Optimization.

Finally, I would correct that the phenomenon you are referring to is not called translation invariance but equivariance. A great explanation of the difference is here:

Invariance to a transformation means if you take the input and transform it then the representation you get is the same as the representation of the original, i.e. represent(x) = represent(transform(x))
Equivariance to a transformation means if you take the input and transform it then the representation you get is a transformation of the representation of the original, i.e. transform(represent(x)) = represent(transform(x)).

A: I guess the simplest most intuitive way is to divide the original image to four sub-images then pass those images to the conv-net and see which one contains the image of the cat. And then keep applying the same method to each one of the sub-images depending on the precision of the position needed.
Another simple way would be to put in place another "module" (not necessarily a conv-net based one) that detects where a known shape is in the image. That way, once you've detected that a cat is present in the picture (with your conv-net), you'd call that module in order to get where the closest shape to a cat figure is in the image.


text:
Q: Java: ArrayList not compiling I am working on a Robot Maze where the robot finds the target without crashing into walls. I know I've missed something or done something incorrectly (most likely a couple of things haha) but I've been racking my brain over it for a couple of hours now and tried several alternatives. I'm pretty sure my error is either where and how I declared the ArrayList.
It cannot find the symbol for the passageDirections and nonwallDirections.
Any help is appreciated :)
PS: I am a beginner programmer, still learning so explain your answer as if you were to explain it to a three year old :)

A: Your problem is in the nonwallExits method - you cannot have any code after a return statement, as this statement terminates the method. Just move return nonwallExits; to be the last line of the method and you should be fine.

A: I for example see a problem here in this method:
/* Junction method states if there is more than one passage, it will randomly select one.
    If there is no passage, it will randomly select a nonwall/BeenBefore direction. */
public int junction(IRobot robot) {

    if (passageExits(robot) >= 1) {
        int randomPassage = ((Math.random())*(passageDirections.length()));
        passageDirections.get(randomPassage);
    } else {
        int randomNonwall = ((Math.random())*(nonwallDirections.length()));
        nonwallDirections.get(randomNonwall);
    }
}

Here you are using the lists 'passageDirections' and 'nonwallDirections' without declaring them first. I see that you have declared those lists in other functions as local variables, which means that they exist as long as the function is executing which they are declared in. So if you want to use them in other functions, you shouldn make them somehow global or pass them around as parameters...
Without fully understanding your code, I would suggest try to do something like this to make the code "compileable":
import uk.ac.warwick.dcs.maze.logic.IRobot;
import java.util.ArrayList;
import java.util.*;

public class Explorer2 {

    private ArrayList<Integer> passageDirections = new ArrayList<Integer>();
    private ArrayList<Integer> nonWallDirections = new ArrayList<Integer>();
    private Random random = new Random();

    public void controlRobot (IRobot robot) {
        int exits = nonwallExits(robot);
        int direction;

        if (exits < 2) {
            direction = deadEnd(robot);
        } else if (exits == 2) {
            direction = corridor(robot);
        } else if (exits == 3) {
            direction = junction(robot);
        } else {
            direction = crossroads(robot);
        }

        robot.face(direction);

    }

    /*  Deadend method will make the robot turn around except from the beginning.
        Because the robot can face any direction at the start, it will follow
        the one and only passage it will detect. */
    public int deadEnd (IRobot robot) {

        if (passageExits(robot) == 0)
            return IRobot.BEHIND;
        else
            return -1; //FIXME: return correct direction!!!

    }

    /* Corridor method will make the robot follow the one and only passage. */
    public int corridor (IRobot robot) {

        return -1; //FIXME: return correct direction!!!

    }

    /* Junction method states if there is more than one passage, it will randomly select one.
        If there is no passage, it will randomly select a nonwall/BeenBefore direction. */
    public int junction(IRobot robot) {

        if (passageExits(robot) >= 1) {
            int randomPassage = random.nextInt(passageDirections.size());
            return passageDirections.get(randomPassage);
        } else {
            int randomNonwall = random.nextInt(nonWallDirections.size());
            return nonWallDirections.get(randomNonwall);
        }

    }

    /* Crossroads method states if there is more than one passage, it will randomly select one.
        If there is no passage, it will randomly select a nonwall/BeenBefore direction. */
    public int crossroads (IRobot robot) {

        if (passageExits(robot) >= 1) {

            int randomPassage = random.nextInt(passageDirections.size());
            return passageDirections.get(randomPassage);
        } else {
            int randomNonwall = random.nextInt(nonWallDirections.size());
            return nonWallDirections.get(randomNonwall);
        }
    }

    //Calculates number of exits and stores the direction of the exits in an ArrayList
    private int nonwallExits (IRobot robot) {

        int nonwallExits = 4;

        if(robot.look(IRobot.AHEAD) == IRobot.WALL)
            nonwallExits--;
        if(robot.look(IRobot.LEFT) == IRobot.WALL)
            nonwallExits--;
        if(robot.look(IRobot.RIGHT) == IRobot.WALL)
            nonwallExits--;
        if(robot.look(IRobot.BEHIND) == IRobot.WALL)
            nonwallExits--;

        for(int direction = IRobot.AHEAD; direction < IRobot.LEFT; direction++) {
            if(robot.look(direction) != IRobot.PASSAGE)
                nonWallDirections.add(direction);
        }

        return nonwallExits;
    }

    //Calculates number of passages and stores the direction of the passages in an ArrayList
    private int passageExits (IRobot robot) {

        int passageExits = 0;

        if(robot.look(IRobot.AHEAD) == IRobot.PASSAGE)
            passageExits++;
        if(robot.look(IRobot.LEFT) == IRobot.PASSAGE)
            passageExits++;
        if(robot.look(IRobot.RIGHT) == IRobot.PASSAGE)
            passageExits++;

        for(int direction = IRobot.AHEAD; direction < IRobot.LEFT; direction++) {
            if(robot.look(direction) == IRobot.PASSAGE)
                passageDirections.add(direction);
        }

        return passageExits;
    }
}

This way you declare the lists to be instance variables, meaning that they represent the state of an Explorer2 object. Now all the instance methods operating on the Explorer2 objects can access these variables as this.passageDirections and this.nonWallDirections, where this refers to the object you are currently "working on". (and if there are no ambiguities you can skip the this. part).


text:
Q: Concurrent UPDATE's on MySQL TRIGGER I have this TRIGGER in MySQL:
CREATE DEFINER = CURRENT_USER TRIGGER `test`.`view_AFTER_INSERT` AFTER INSERT ON `views` FOR EACH ROW
BEGIN
UPDATE metrics SET met_nu_vie = met_nu_vie + 1 WHERE usp_id = NEW.usp_id;
END

Basically, when an user receives a 'view' from another user in a web application, the system creates a new row in table 'views', and after insert, increments a counter value in another table (metrics).
My question is: If the user receives 10 concurrent views from 10 different users... ¿is this UPDATE safe?
All tables on my schema are INNODB.
Thanks.

A: If the user receives X concurrent views, then the counter eill be incremented by X with the update statement in the question.
As mysql manual on innodb locks explains:

UPDATE ... WHERE ... sets an exclusive next-key lock on every record
  the search encounters. However, only an index record lock is required
  for statements that lock rows using a unique index to search for a
  unique row.

Mysql manual on exclusive locks says:

If a transaction T1 holds an exclusive (X) lock on row r, a request
  from some distinct transaction T2 for a lock of either type [exclusive or shared] on r
  cannot be granted immediately. Instead, transaction T2 has to wait for
  transaction T1 to release its lock on row r.

To sum it up: the viewers may be concurrent at your application level, but at mysql level updates are serialised using exclusive locks.


text:
Q: Searching for multiple strings in dataframe, bottom up in if conditional? I have a dataframe with multiple columns lets call it dat1, and I need to extract strings in certain columns based on a lot of conditions.
There are arunt 350 rows per subject, and I need to find the last of a certain string in a certain column, per subject, containing a certain name, e.g. "green", and take the value from another string in the same row.
subject   type    value
111       yellow   354
111       green    584
111       yellow   584
111       blue     492
111       green    493
222       blue     459
222       green    583
222       yellow   539
222       blue     392
222       yellow   394

Say I need the last value of "green" for each subject, how can I do this?
After doing that, I also need to get the value that is above the last "green", preferably saving them in two separate vectors.
last_green    before_last_green
   493          492
   583          459

I have tried to make multiple if-statements while also grouping by subject, but without even getting near succeeding. I also have not been able to find any examples of this before.
Is it possible to search for the first "green" from the bottom of each subject? Or how else can this be performed?

A: Code
The  tidyverse is your friend:
library(tidyverse)
d <- structure(list(subject   = c(111L, 111L, 111L, 111L, 111L,
                                  222L, 222L, 222L, 222L, 222L),
                    type      = c("yellow", "green", "yellow", "blue", "green",
                                  "blue", "green", "yellow", "blue", "yellow"),
                    value     = c(354L, 584L, 584L, 492L, 493L,
                                  459L, 583L, 539L, 392L, 394L)),
                    row.names = c(NA, -10L),
                    class = c("tbl_df", "tbl", "data.frame"))

d %>%
  group_by(subject) %>%
  filter(type == "green") %>%
  summarise_all(last)

# A tibble: 2 x 3
#   subject type  value
#     <int> <chr> <int>
# 1     111 green   493
# 2     222 green   583

Explanation

*

*with group_by you will do the following per unique value of subject

*with filter you look only for rows with type equal to green

*with summarise you finally select only the last entry

A: Answering both questions:
df=data.frame("subject"=c(rep(111,5),rep(222,5)),
           "type"=c("yellow","green","yellow","blue","green",
                    "blue","green","yellow","blue","yellow"),
           value=c(354,584,584,492,493,459,583,539,392,394),
           stringsAsFactors = FALSE)
   subject   type value
1      111 yellow   354
2      111  green   584
3      111 yellow   584
4      111   blue   492
5      111  green   493
6      222   blue   459
7      222  green   583
8      222 yellow   539
9      222   blue   392
10     222 yellow   394

Create filter df:
filter_=df%>%rownames_to_column()%>%group_by(subject)%>%
  filter(type=="green")%>%slice(n())

last_green=filter_$value
before_last_green=df$value[as.numeric(filter_$rowname)-1]

Results:
> last_green
[1] 493 583
> before_last_green
[1] 492 459

Explanation:
We first create rownames to keep track of the position of the last green appearance for each subject. Then, we group by subject and filter by type we take the last element per group with slice(). We then return the value in last_green and the value of the row with the position of these previous samples - 1 (the previous).

A: You can do it this way:
library(tidyverse)

dat %>%
  rownames_to_column() %>%
  group_by(subject) %>%
  filter(type == 'green') %>%
  summarise(
    last_green        = last(value),
    before_last_green = dat$value[as.numeric(last(rowname)) - 1]
    )

What is going on here:

*

*you move rownames of your data.frame into variable rowname (see latter why);

*you group your data by subject, to apply following operations upon subsets of your data, related to particular subject;

*you filter your data, leaving only greens;

*and finally:

*

*you summarize your data, taking last value for each previously filtered subset, and assigning it to value_green;

*you borrow your whole, untransformed dat from environment, subsetting the value from the dat by rows corresponding to the last(ronwame) - 1 of your . data, i.e. data which came into summarize through the pipes.

Which evaluates to:
# A tibble: 2 x 3
  subject last_green before_last_green
    <int>      <int>             <int>
1     111        493               492
2     222        583               459

Your data:
dat <- read.table(
  text = "subject   type    value
111       yellow   354
111       green    584
111       yellow   584
111       blue     492
111       green    493
222       blue     459
222       green    583
222       yellow   539
222       blue     392
222       yellow   394",
  header = T, stringsAsFactors = F
)


text:
Q: ADO Connection Timeout I am seeing a timeout error for some users w/large transactions. I am not clear the implications of:

*

*Using cnn.ConnectionTimeout vs cnn.CommandTimeout?

*Setting a very long timeout period (how long is too long?)

*Setting timeout = 0 (indeterminate?)

Here is a snippet:
Set cnn = New ADODB.Connection

'cnn.ConnectionTimeout = 30
'cnn.CommandTimeout = 30

cnn.CursorLocation = adUseClient
cnn.ConnectionString = "driver={SQL Server}; server=" & myIP & ";Trusted_Connection=no;Database=" & myDatabase & ";UID= " & myUser & ";PWD= " & myPass & "
cnn.Open

strSQL = "uspDeleteAreaCommon @InvID = '" & myInvID & "';"
Set rs = cnn.Execute(strSQL)

Any suggestions/cautions??
Thanks!

A: No replies.
I used cnn.CommandTimeout = 0  (infinite timeout?)
With no complaint, though I am still not clear the implications of this setting...


text:
Q: Extracting and Processing GPUTemperature Information Using Regexp I need to extract and process graphic card temperature integer the following output from Linux Ubuntu application, sensors:
amdgpu-pci-0c00
Adapter: PCI adapter
fan1:        1972 RPM
temp1:        +50.0°C  (crit =  +0.0°C, hyst =  +0.0°C)

amdgpu-pci-0600
Adapter: PCI adapter
fan1:        1960 RPM
temp1:        +47.0°C  (crit =  +0.0°C, hyst =  +0.0°C)

amdgpu-pci-0200
Adapter: PCI adapter
fan1:        1967 RPM
temp1:        +52.0°C  (crit =  +0.0°C, hyst =  +0.0°C)

pch_skylake-virtual-0
Adapter: Virtual device
temp1:        +33.0°C

amdgpu-pci-0900
Adapter: PCI adapter
fan1:        1893 RPM
temp1:        +51.0°C  (crit =  +0.0°C, hyst =  +0.0°C)

amdgpu-pci-0300
Adapter: PCI adapter
fan1:        1992 RPM
temp1:        +53.0°C  (crit =  +0.0°C, hyst =  +0.0°C)

coretemp-isa-0000
Adapter: ISA adapter
Package id 0:  +24.0°C  (high = +80.0°C, crit = +100.0°C)
Core 0:        +23.0°C  (high = +80.0°C, crit = +100.0°C)
Core 1:        +21.0°C  (high = +80.0°C, crit = +100.0°C)

Suppose I want to extract information that associates with amd gpu temperature, which are 50, 47, 52, 51, and 53. So far what I have is executing the following code:
sensors|grep temp| grep -Eo '\+[0-9]{0,9}'

and I got:
+50
+0
+0
+47
+0
+0
+52
+0
+0
+32
+51
+0
+0
+53
+0
+0

So I need to figure it out:

*

*The regexp look-around  assertion so that it captures integers that has + sign in the beginning of the number, without displaying the + (plus) sign.

*A way to grab only amdgpu information, so that it won't grab other info.

*A way to process those temperature numbers, for example I could write a bash script to process the numbers whereas if the temperature is less than 30, do this, if more than 70, do that. Should I put the result in an array and do a loop, or is there any other practical way?

Please help.
regards

A: There you have desired temperatures stored in an array, you can then do the math with them.
arr=( $( IFS=$'\n' gawk 'BEGIN{ RS="\n\n"} { if($0 ~ /amdgpu/) print $0 }' test.txt | gawk 'BEGIN{ FS="[+.]" } { if($1 ~ /temp1:/) print $2 }' ) )
echo "${arr[*]}"
50 47 52 51 53
test.txt contains your sample output. Getting input from sensors command (not tested)
arr=( $( sensors | IFS=$'\n' gawk 'BEGIN{ RS="\n\n"} { if($0 ~ /amdgpu/) print $0 }' | gawk 'BEGIN{ FS="[+.]" } { if($1 ~ /temp1:/) print $2 }' ) )
echo "${arr[*]}"
50 47 52 51 53

A: You can also get the temps with a single grep, if you're willing to use Perl-like regexp:
sensors | grep -oP 'temp\d:\s+\+\K\d+'

Where we grep for temp followed by a digit and a colon, then a at least one whitespace character and a plus-sign, after that we give the lookbehind assertion \K which discards everything before it, and the final capture is just \d+ (one or more digits).


text:
Q: Webpack externals not requiring In my environment (aws-lambda) I have the aws-sdk set up, so in the webpack.config i've added:
externals: {
    'aws-sdk': 'aws-sdk'
  },

When building it seems to set it as module.exports = aws-sdk; instead of module.exports = require('aws-sdk'); weird thing was it was working fine before, just randomly stopped, any ideas?
(using serverless-webpack and webpack)

A: Finally figured out by finding these docs: https://webpack.github.io/docs/configuration.html#externals
Had to have output: { libraryTarget: "commonjs" }, set


text:
Q: Asp .Net Mvc Delete Doesnt work Hi everyone I'm trying to add edit and delete but delete doesnt work here is my index code for listing;
@foreach (var item in Model.Haberler)
                            {

                                            <button type="button" class="btn btn-xs purple dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-delay="1000" data-close-others="true">
                                                İşlem
                                            </button>

Düzenle

Sil

                                    @item.Title

                            }

Here is my controller Delete;
public ActionResult Delete(int? Id)
    {
        if (!Id.HasValue)
            return Json(new { IsComplete = false });

        try
        {
            var item = Db.Haberler.FirstOrDefault(p => p.Id == Id.Value);
            UrunSil(item);
        }
        catch
        {
            return Json(new { IsComplete = false });
        }

        return Json(new { IsComplete = true });
    }

And I send to AdminBaseController to delete ;
   public void DosyaSil(string yol)
    {
        try
        {
            System.IO.File.Delete(Server.MapPath("~" + yol));
        }
        catch { }
    }
    public void UrunSil(News item)
    {

        DosyaSil(item.ResimBuyuk);
        DosyaSil(item.ResimKucuk);
        Db.Haberler.Remove(item);
        Db.SaveChanges();
    }

Break points doesnt work when I click on delete icon it does nothing just like empty
what could be the problem ?
When I click the delete button I get this error on console;
Uncaught ReferenceError: bootbox is not definedglobal.js:113 (anonymous function)jquery-1.10.2.min.js:5 x.event.dispatchjquery-1.10.2.min.js:5 v.handle

A: The delete isn't work beacause The delete method isn't work beacause you is calling the wrong way, if you wanna call a delete action like this you need to redirect to another action process and return to "the Current View/Action". You can do this really simple with Ajax and Jquery, this is a sample:

Sil

And the js you need to do this:
 $(function(){
    $(".delete").click(function () {
       $.ajax({
           type: "DELETE",
           url: $(this).attr("data-url") + "?Id=" + $(this).attr("data-id"),
           success: function (data) {
             //Remake the search
          },
          error: function(jqXHR, exception, a, b){
                 alert(jqXHR.responseText);
           }
      });
   });
});

The Delete method don't recive the body of message and the Http verb use is Delete because the name of your action. So the parameter need to be in queryString on the Url.

A: Add class name for  as below:

Sil

Use ajax to call the controller as below  :
$(function(){
   $(".delete").click(function () {
     $.ajax({
       url: $(this).attr("data-url"),
        data: "Id="+$(this).attr("data-id"),
       success: function (data) {
        // do stuff
       }
     });
  });
});


text:
Q: Fixing an unmuxed image/jpeg stream from webcam using gstreamer I made a broken footage using the following pipeline:
gst-launch-1.0 v4l2src ! filesink location=encode.mjpeg

Somehow gstreamer can still play it back:
gst-launch-1.0 filesrc location=encode.mjpeg ! jpegdec ! videoconvert ! xvimagesink

However as I by mistake didn't use any container, the stream is played back at a very fast pace framerate=(fraction)0/1. Is there any way to convert my broken file into an .avi or any other container without recompression?
The following trivial muxing didn't work as expected:
gst-launch-1.0 filesrc location=encode.mjpeg \
    ! 'image/jpeg,framerate=30/1,width=1280,height=720' ! avimux \
    ! filesink location=encode.avi . -v

Somehow gstreamer plays encode.avi back very slowly at ~1 FPS without consuming significant CPU. And neither Vlc` nor Adobe Aftereffects can import it - they only display a correctly decoded stipe of the first frame at the top.

A: The problem you're having with muxing into avi is related to the fact that filesrc is providing buffers to avimux that are not properly aligned to the mjpeg frames, so avimux is creating samples with wrong alignment internally, making it harder for players to use them later during playback.
This can be fixed by using a mjpeg parser after the capsfilter (jpegparse?). Another option is to decode and reencode the samples to get them aligned and muxed properly. The following pipeline should work:
gst-launch-1.0 filesrc location=encode.mjpeg \
! 'image/jpeg,framerate=30/1,width=1280,height=720' ! decodebin ! videoconvert ! \
<some encoder> ! <some muxer> ! filesink location=outputfile

You can select the encoder and muxer you like, you can even encode them back to jpeg and mux into avi, as you wanted initially.
Edit: To attempt to mux the content into avi without decoding, try something like:
gst-launch-1.0 filesrc location=encode.mjpeg \
    ! 'image/jpeg,framerate=30/1,width=1280,height=720' ! jpegparse ! avimux \
    ! filesink location=encode.avi . -v

If jpegparse does it job very well, the ''image/jpeg,framerate=30/1,width=1280,height=720'' shouldn't be required.


text:
Q: Same code, different behaviour in sending email through Lotus Domino I'm trying to send an email on port 465 with SSL.
Running in a stand-alone application in Eclipse, everything works well.
Running in a Domino Java Agent I'm getting an SSLHandshakeException. Below you can see the code and SSLHandshakeException.
Lotus Domino Release 8.5.1 FP5
Can you help me understand what's the problem?
    private static final Object SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

    public static void main(String[] args) {
        final String username="username";
        final String password="password";
        Properties prop=new Properties();
        prop.put("mail.smtp.auth", "true");
        prop.put("mail.smtp.host", "xxx");
        prop.put("mail.debug", new Boolean("true").toString());
        prop.put("mail.smtp.port", "465");
        prop.put("mail.smtp.ssl.enable", "true");
        prop.put("mail.smtp.starttls.enable", "false");
        prop.put("mail.smtp.socketFactory.fallback", "false");
        prop.put("mail.smtp.socketFactory.class", SSL_FACTORY);

        Session session = Session.getDefaultInstance(prop,
                new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
        try {
            String htmlBody = "TEST";
            String textBody = "This is a Text Message.";
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("a@b.com"));
            message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("xxx@yyy.com"));
            message.setSubject("Testing Subject");
            MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
            mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
            mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
            mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
            mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
            mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
            CommandMap.setDefaultCommandMap(mc);
            message.setText(htmlBody);
            message.setContent(textBody, "text/html");
            Transport.send(message);

            System.out.println("Done");

        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

Running in a Domino Java Agent I got this error:
javax.mail.MessagingException: Exception reading response;   nested
   exception is:  javax.net.ssl.SSLHandshakeException: com.ibm.jsse2.util.g:
   Violated path length constraints
   at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:1462)
   at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1260)
   at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
   at javax.mail.Service.connect(Service.java:297)
   at javax.mail.Service.connect(Service.java:156)
   at javax.mail.Service.connect(Service.java:105)
   at javax.mail.Transport.send0(Transport.java:168)
   at javax.mail.Transport.send(Transport.java:98)
   at JavaAgent.NotesMain(JavaAgent.java:60)
   at lotus.domino.AgentBase.runNotes(Unknown Source)
   at lotus.domino.NotesThread.run(Unknown Source)
   Caused by:
     javax.net.ssl.SSLHandshakeException: com.ibm.jsse2.util.g: Violated path   length constraints
   at com.ibm.jsse2.n.a(n.java:36)
   at com.ibm.jsse2.sc.a(sc.java:154)
   at com.ibm.jsse2.gb.a(gb.java:89)
   at com.ibm.jsse2.gb.a(gb.java:283)
   at com.ibm.jsse2.hb.a(hb.java:260)
   at com.ibm.jsse2.hb.a(hb.java:171)
   at com.ibm.jsse2.gb.n(gb.java:140)
   at com.ibm.jsse2.gb.a(gb.java:123)
   at com.ibm.jsse2.sc.a(sc.java:320)
   at com.ibm.jsse2.sc.g(sc.java:198)
   at com.ibm.jsse2.sc.a(sc.java:478)
   at com.ibm.jsse2.e.read(e.java:7)
   at com.sun.mail.util.TraceInputStream.read(TraceInputStream.java:97)
   at java.io.BufferedInputStream.fill(BufferedInputStream.java:229)
   at java.io.BufferedInputStream.read(BufferedInputStream.java:248)
   at com.sun.mail.util.LineInputStream.readLine(LineInputStream.java:75)
   at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:1440)

A: It looks like the IBM JVM is being more strict about SSL certificates that it accepts than whatever JVM you have in Eclipse. Assuming the destination SMTP server is under your control, you can accept this as a good thing and fix whatever problem exists in that server's certificate chain. (Or if the problem is actually in the Domino server's certifcate chain, which I guess might be the complaint even though the stacktrace indicates the exception was thrown while reading the response from the destination, then you could fix the problem in Domino's keyring.)  If neither of those is an option, then you would have to - and I am not recommending this - find a way to bypass the JVM's certificate validation. Here's a link to an article about that, with sample code.

A: According to this is possible to turn off SSL check.
Restart Domino server after the first send (that will fail, but will disable SSL)
Thanks Richard


text:
Q: Create a procedure in DB2 I created a simple procedure using DB2 in .sql file and executed the script with Shell (Unix). I got an error : SQLSTATE 42601.
DB20000I  The SQL command completed successfully.
CREATE OR REPLACE PROCEDURE PROC_SAMPLE1()
BEGIN
update EMP set ENAME='ALLAIN' where EMPNO=7789
DB21034E  The command was processed as an SQL statement because it was not a
valid Command Line Processor command.  During SQL processing it returned:
SQL0104N  An unexpected token "END-OF-STATEMENT" was found following "IN'
where EMPNO=7789".  Expected tokens may include:  "<psm_semicolon>".  LINE
NUMBER=3.  SQLSTATE=42601

There is the procedure :
CREATE OR REPLACE PROCEDURE PROC_SAMPLE1()
BEGIN
update EMP set ENAME='ALLAIN' where EMPNO=7789;
END
/

A: If this is contained in a file you need to change the batch terminator.  Since the SP lines end with ; the batch ends with /, you need to specify this on the command line.
eg
db2 -td/ -f <your file>.sql

I like to use # since it does not mess with unix shells like / will.  Here replace your last character with # in the file and use -td#

A: I added '--#SET TERMINATOR /' before the procedure creation and the problem is solved.
--#SET TERMINATOR /
CREATE OR REPLACE PROCEDURE PROC_SAMPLE1()
BEGIN
update EMP set ENAME='ALLAIN' where EMPNO=7789;
END
/


text:
Q: create .html or .txt file instead of .jpx file in spring roo I want to create .html or .txt file instead of .jpx file in spring roo but i am unable to do this.
web mvc setup
web mvc all --package com.visualinsights.web

This commands in spring roo create the .jpx file internally and I don't know how.
If I want to create my own html file with .html extension in the time when I put commands in roo shell and I don't want .jpx file then what I have to do?
Please help me.

A: If you use web mvc all or web mvc scaffold commands roo will generate .jspx files on web layer... is not possible to specify format of generated files...
If you want to report as improvement on Spring Roo project, you can do it on:
https://jira.spring.io/browse/ROO
Best Regards,


text:
Q: What is the difference between early binding and late binding in C++? Since i'm studying object oriented programming language it is quite better than C and pretty new concepts. I'm confused with  early binding and late binding
so my question is

What is the difference between early binding and late binding in C++?

A: Consider the following code:
void foo()
{
  std::cout << "A\n";
}
void bar()
{
  std::cout << "B\n";
}

// returns a callable object which either refers to foo or bar
// depending on user input during runtime
std::function<void()> maker()
{
  std::cout << "Please give a number:\n";
  auto x = 0.0;
  if (std::cin >> x && x > 50.0)
  { // if we get a valid value from the console and if it is > 50
    // we return a callable that refers to foo
    return{ &foo };
  }
  // otherwise we return a callable that refers to bar
  return{ &bar };
}

A simple call to foo or bar can be resolved at compile time (the function binding can happen early/during compilation) but using maker() will result in late binding because it is actually unknown to the compiler which function will be called:
auto f = maker();
f(); // whether foo or bar is called depends
     // on the user input during maker execution

The same is true for all other methods of dynamic dispatching (i.e. virtual function calls).
If the compiler is not able to prove (at compile time) that (indepedant of the runtime information) a specific function is to be called at a certain point of the program flow, late function binding is used to resolve the appropriate action at runtime. Otherwise early function binding is used to resolve the call at compile time (which may not necessarily be an actual call but can also be done via inlining).

Edit: Given the following source, gcc (according to godbolt) is performing late binding with -O0 for both, foo and bar while from -O2 the assembly output show a

call    t_deriv_1::f() const

in the assembly of bar because make_bar is known when bar is compiled and is examined to find that the type which is actually returned is always t_deriv_1.
struct t_base
{
  virtual int f() const = 0;
  virtual ~t_base() {}
};
struct t_deriv_1 : t_base
{
  int f() const override final;
};
struct t_deriv_2 : t_base
{
  int f() const override final;
};

t_base * make_foo();
t_base * make_bar()
{
  return new t_deriv_1;
}

void foo()
{
  t_base * p = make_foo();
  p->f();
  delete p;
}

void bar()
{
  t_base * p = make_bar();
  p->f();
  delete p;
}

A: During early binding the compiler can resolve exactly which function will be called and therefore use the functions address for the function call.
During late binding the compiler can not deduce the exact function which will be called, usually because of polymorphsim. And therefore the function call is resolved during runtime.

A: 'Early binding' applies to method overloads. The compiler can determine which of the available overloads is applicable, based on the types of the arguments.
'Late binding' applies to method overrides. The compiler cannot determine which override is applicable, as it depends on the runtime type of the object the method is being invoked on. So a runtime despatch via a virtual-function-table mechanism or similar is required.

A: Let us consider an example
int add(int a, int b){
    return a + b;
}

int main(){
    int sum = add(1, 2);
    return 0;
}

Here it is early binding, because compiler could directly know the address of add and uses it in the function call.
Late binding can occur in two cases

*

*Pointer to a function

int add(int a, int b){
    return a + b;
}

int sub(int a, int b){
    return a - b;
}

int main(){
    int(*p)(int, int);
    char op; //either `+` or `-`
    cin >> op;
    p = (op == '+')?add:sub;
    int result = p(10, 5);
    return 0;
}

Here the function call is intermediated by a function pointer p which is based on op at run time, so the compiler cannot know the address while compiling, the address is known while running (runtime). It s late binding.

*A method of a derived object is called using a base class pointer

class Base
{
public:
    void x() {cout << "base ";}
    virtual void y() {cout << "base ";}
};

class Derived : public Base
{
    void x() {cout << "derived ";}
    virtual void y() {cout << "derived ";}
};

int main()
{
    Base* b = new Derived;
    b->x();
    b->y();
}

Here the output will be
base derived

b->x() invokes the bass class function because it is not virtual, but b->y() invokes the derived class function because it is virtual. Here the look up takes up with the intermediate help of vtables while running (runtime). So it is late binding.
Rule of thumb:
1. Whatever can be evaluated by the compiler and substitutes at compile time are early binding
2. Whatever can't be evaluated by the compiler at compile time and only could be evaluated at run time are late binding

A: Early binding is basically a concept of object programming language where what type of object is known at compile time and if don't know about  type of object at compile time that phenomenon is known as late binding and run time binding.

A: Let's understand it with reference to the concept of overloaded and overriden methods....so early binding also known as static binding ( compile time polymorphism ) says that the calls to the overloaded functions is resolved at the compile time i.e which version of  overloaded function must be called is decided at the compile time of program execution.
Now in case of late binding also known as dynamic binding ( runtime polymorphism ) says that the calls to the overriden function is resolved at the runtime i.e which version of the overriden function must be called is decided at the runtime of program execution.

A: Basically Early binding happens at compile time also called static binding where as late binding is at run time also called dynamic binding.
In Early binding objects are nearly a strong type of objects or static type objects.Its advantage is that it is used for ease of development and its efficient performance.It reduces the number errors at run time.
Whereas in late binding methods,objects,variables are checked at run time.
The most popular example for late binding is the use of reflection and use of dynamic binding.

A: Most of the function calls the compiler encounters will be direct function calls. e.g.,
 int sum(int a, int b) {
    return a + b;
}

int main() {
    std::cout << sum(2, 3); // This is a direct function call
    return 0;
}

Direct function calls can be resolved using a process known as early binding. Early binding (also called static binding) means the compiler is able to directly associate the identifier name (such as a function or variable name) with a machine address. Remember that all functions have a unique machine address. So when the compiler encounters a function call, it replaces the function call with a machine language instruction that tells the CPU to jump to the address of the function.
Late Binding
Compiler doesn't know until runtime which function to invoke.
In some programs, it's not possible to know which function will be called until runtime. This is known as late binding (or dynamic binding). In C++, one way to get late binding is to use function pointers or the other way is the use of virtual functions in inheritance. e.g.,
int add(int x, int y) {
    return x + y;
}

int subtract(int x, int y) {
    return x - y;
}
int main() {
    int x, y;
    std::cin >> x >> y;

    int operation;
    std::cout << "choose 0 for add & 1 for subtract\n";
    std::cin >> operation;

    int (*p)(int, int);  // Function Pointer

    // Set p to point to the function the user chose
    switch (operation) {
        case 0 : p = add;
                     break;
        case 1 : p = subtract;
                     break;
    }

    // Call the function that p is pointing to
    std::cout << "The answer is: " << p(x, y) << std::endl;

    return 0;
}

A: I would recommmend you to go through this. It perfectly explains everything you need to know
http://www.learncpp.com/cpp-tutorial/124-early-binding-and-late-binding/

When a C++ program is executed, it executes sequentially, beginning at
  the top of main(). When a function call is encountered, the point of
  execution jumps to the beginning of the function being called. How
  does the CPU know to do this?
When a program is compiled, the compiler converts each statement in
  your C++ program into one or more lines of machine language. Each line
  of machine language is given its own unique sequential address. This
  is no different for functions -- when a function is encountered, it is
  converted into machine language and given the next available address.
  Thus, each function ends up with a unique address.
Binding refers to the process that is used to convert identifiers
  (such as variable and function names) into addresses. Although binding
  is used for both variables and functions, in this lesson we're going
  to focus on function binding.


text:
Q: What exactly is wind? What is wind?
I think it is kind of a vibration of air particles.
If so, is it a longitudinal or a transverse wave?
Or is it just a bunch of air particles being pushed?
Smells disperse in wind so the latter explanation might be a better.
And breath also consists of movement of air particles.
But how can wind travel so far without stopping? Can it be the pressure produced by temperature difference pushing it? So could you say it can be attributed to a wave?
Any help would be appreciated, thank you.

A: Wind is a solar powered flow of the atmosphere.
The atmosphere is not uniformly heated: different areas have different solar power input. This uneven heating arises because some areas are in daylight, whereas others are in night, and different regions have different amounts of cloud cover and different colored terrain, so the albedo is uneven.
Uneven heating means that the atmospheric pressure is different at different points: these pressure differences pump air from one region to another. Moreover, the Earth's rotation through the incident sunlight - cyclic day and night - means that no region has a time-steady heat input. Therefore, the flows can never quite bring the system to steady state: you might think that a hot region's higher pressure would pump air to surrounding colder regions and equalise pressures, but no sooner does this happen than the day-night cycle switches the roles of these regions.
There is a great deal more to this story, in particular the Earth's rotation gives rise to Coriolis effects. But the flows ultimately come from nonuniform, nonsteady temperature arising from changing heat power inputs to different regions of the atmosphere.

A: How is wind formed?
So first I'll just quickly explain how wind is formed
Wind is caused by difference in atmospheric pressure.
Atmospheric pressure is a measurement that is given for the amount that air is pressing down on the Earth's surface.
There are differences in atmospheric pressure because the particles in liquids and gases can move around, they move from areas of higher level particle density to areas of lower level particle density.
As gases heat they become less dense and therefore rise above the denser gasses, this essentially this is what changes the atmospheric pressure and forms wind.
How far can wind travel?
Air will always move from areas of high and low pressure to negate the differences in atmospheric pressure and this will go on until pressure has balanced. So wind will travel as far as it needs to before this happens.
Some winds blow across huge distances, take the Trade Winds that are caused by a combination of the differences in atmospheric pressure between the poles and the equator and the Coriolis effect. The Trades are a almost constant winds that blow across the globe.
Would I say wind is a wave?
Wind is not a wave it is just air moving to areas of low pressure. But moving air can cause waves in the air much like the water in the oceans is not always moving in waves.


text:
Q: Array give [object object] after pushing object inside The array show as [object object] after I push the object inside it even though the object that are inside the array show up as what I want it to be . I tried searching google and YouTube but didn't find anything
let arr = []
let list = ""
let rev = {}
const btn = document.getElementById("savel")
btn.addEventListener("click", function() {
                 val1 = name.value
                 val2 = age.value
                shh ()
                console.log(val1)
})

function shh () {
     rev = {
                names: val1,
                ages: val2
}
showname.textContent = rev.names
showage.textContent = rev.ages
   arr.push(rev)
   console.log(arr)
   uul ()
}

function uul () {
                for (i=0; i<arr.length; i++) {
                                list = arr[i]
                }
                ul.innerHTML += `
                <li> ${list} </li>
                `
}
console.log(rev)

A: You're appending to the list array after the for loop ends.
Change the uul function to:
function uul () {
    for (i=0; i<arr.length; i++) {
        list = arr[I];
        ul.innerHTML += '<li> ${list} </li>';
    }           `
}

A: You should use JSON.stringify().
If I have the following array and I try to show it in an alert
var myArray = [{name: "Jack"}, {name: "John"}];
alert(myArray);

The output will be [object Object],[object Object],
But if I use JSON.stringify:
alert(JSON.stringify(myArray))

the output will be [{"name":"Jack"},{"name":"John"}].
The same logic applies to your code and into the ul.innerHTML. Read more about here.


text:
Q: Query for below issue I want to insert one row for each unique b_id if the b_id doest have any row with data = x. The value for the new row will be same for
b_id, b_name but the value for data will be x and sequence will be 1 and existing sequence for that b_id should be updated by 1
DECLARE
  CURSOR b_id_cursor IS
    SELECT DISTINCT b_id
    FROM md_details;
BEGIN
  FOR b_id_rec IN b_id_cursor LOOP
    IF NOT EXISTS (SELECT 1 FROM md_details WHERE b_id = b_id_rec.b_id AND data = 'INIT') THEN
      INSERT INTO md_details (b_id, b_name, data, sequence)
      SELECT b_id, b_name, 'INIT', 1
      FROM md_details
      WHERE b_id = b_id_rec.b_id
      AND ROWNUM = 1;

      UPDATE md_details
      SET sequence = sequence + 1
      WHERE b_id = b_id_rec.b_id;
    END IF;
  END LOOP;
END;

A: import java.util.ArrayList;
import java.util.List;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
public class AdGroupFinder {
private DirContext dirContext;

public AdGroupFinder(DirContext dirContext) {
    this.dirContext = dirContext;
}

public List<String> getAdGroupsForUser(String userName) {
    List<String> adGroups = new ArrayList<>();

    try {
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        String searchFilter = "(&(objectClass=user)(sAMAccountName=" + userName + "))";

        javax.naming.NamingEnumeration<javax.naming.directory.SearchResult> results =
                dirContext.search("", searchFilter, searchControls);

        while (results.hasMoreElements()) {
            javax.naming.directory.SearchResult searchResult = results.nextElement();
            javax.naming.directory.Attribute memberOfAttribute = searchResult.getAttributes().get("memberOf");

            for (int i = 0; i < memberOfAttribute.size(); i++) {
                String groupDN = (String) memberOfAttribute.get(i);
                adGroups.add(groupDN.substring(0, groupDN.indexOf(",")));
            }
        }
    } catch (javax.naming.NamingException e) {
        e.printStackTrace();
    }

    return adGroups;
}

public List<String> getUsersForAdGroup(String adGroupName) {
    List<String> users = new ArrayList<>();

    try {
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        String searchFilter = "(&(objectClass=user)(memberOf=CN=" + adGroupName + ",OU=Groups,DC=example,DC=com))";

        javax.naming.NamingEnumeration<javax.naming.directory.SearchResult> results =
                dirContext.search("", searchFilter, searchControls);

        while (results.hasMoreElements()) {
            javax.naming.directory.SearchResult searchResult = results.nextElement();
            javax.naming.directory.Attribute sAMAccountNameAttribute = searchResult.getAttributes().get("sAMAccountName");
            users.add((String) sAMAccountNameAttribute.get());
        }
    } catch (javax.naming.NamingException e) {
        e.printStackTrace();
    }

    return users;
}

}


text:
Q: PowerMockito.whenNew not working on android's Intent class I am trying to use a mock Intent object but when using whenNew from PowerMockito, I am not able to mock the constructor. I have tried all possible combination of Arguments, but it just doesn't work.

A: I had a similar problem, and solution was found in this answer.
To be more specific: please try to add @PrepareForTest annotation at  test or at class level, and provide it with class that constructs your Intent.
public class SomeClassThatCreatesIntent {

    public void someMethodWithIntent() {
        Intent i = new Intent();
    }
}

And then test class should look like this:
@RunWith(PowerMockRunner.class)
@PrepareForTest({SomeClassThatCreatesIntent.class})
public class SomeClassThatCreatesIntentTest {

    @Test
    public void test() {
        // Some test that uses PowerMockito.whenNew(Intent.class)
    }
}

Hope this will help.


text:
Q: Row deletion animation issue with swipe to delete I am implementing swipe to delete feature on one of my table that uses custom table view cells. The issue I am facing is when I tap on "Delete" button, I see a weird transition while cell is being removed.
Below is my code in "commitEditingStyle" and also see the attached screenshot I captured while row is being removed.
PS: I have tried with all types of row removal animation styles but no luck.
- (void)tableView:(UITableView *)iTableView commitEditingStyle:(UITableViewCellEditingStyle)iEditingStyle forRowAtIndexPath:(NSIndexPath *)iIndexPath {
    if (iEditingStyle == UITableViewCellEditingStyleDelete && iTableView == self.temporaryCartTable) {
        if (self.temporaryCartTable.frame.size.height == kMyAppCartTableViewExpandedHeight) {

            [self.temporaryCartTable beginUpdates];
            [self.temporaryCartTable deleteRowsAtIndexPaths:[NSArray arrayWithObjects: iIndexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];

            MyAppCartInfo *aMyAppCartInfo = [self cart];

            if (([[aMyAppCartInfo.tempProducts allKeys] count] > iIndexPath.row) && [aMyAppCartInfo.tempProducts containsObjectForKey:[[aMyAppCartInfo.tempProducts allKeys] objectAtIndex:iIndexPath.row]]) {
                [aMyAppCartInfo.tempProducts removeObjectForKey:[[aMyAppCartInfo.tempProducts allKeys] objectAtIndex:iIndexPath.row]];
            }

            [self.temporaryCartTable endUpdates];
        }
    }
}

- (BOOL)tableView:(UITableView *)iTableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return (iTableView == self.temporaryCartTable) ? YES : NO;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)iTableView editingStyleForRowAtIndexPath:(NSIndexPath *)iIndexPath {
    return UITableViewCellEditingStyleDelete;
}

- (CGFloat)tableView:(UITableView *)iTableView heightForRowAtIndexPath:(NSIndexPath *)iIndexPath {

    if (iTableView == self.temporaryCartTable) {
        if (self.isTempCartCell)
            return 92.0;
        else
            return 58.0;
    } else {
        return 58.0;
    }
}

A: Add the following method implementation to your UITableViewDelegate
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView
          editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

A: Use [self.temporaryCartTable setRowHeight:xxx] instead of using the delegate rowHeightAtIndexPath. After the row is deleted and there is no other rows in the table, the delegate will not called and your table view's row height will be retrieved by its property (hence the default height). Plus, using this method from the delegate affects the performance.

A: If anyone else is having this, the problem in my case was heightForRowAtIndexPath: When cells have dynamic size delete animation behaves strange. In my case the solution was to use a different approach and not spend time investigating. But you can test it and see results. Assign a fixed height for cells:
self.tableView.rowHeight = Constant;

comment out heightForRowAtIndexPath:. And animations should be ok now.
I know this is not the solution but may still help someone.


text:
Q: UK BNG (Easting/Northing) to lat/long in R I am a new user of R and I have a project where some coordinates are provided in British National Grid coordinates. These are not recognised by our preferred mapping program, so I would prefer to convert to lat/long. I have found some resources on how to do this using the code below:
require("rgdal") || install.packages("rgdal")
require("sp") || install.packages("sp")

library(rgdal)
# prepare UTM coordinates matrix
utmcoor<-SpatialPoints(cbind(knime.in$"Easting",knime.in$"Northing"), proj4string=CRS("+proj=utm +zone=30"))
#utmdata$X and utmdata$Y are corresponding to UTM Easting and Northing, respectively.
#zone= UTM zone
# converting
longlatcoor<-spTransform(utmcoor,CRS("+proj=longlat"))

However, the results are not what I was expecting. I tried an Easting/Northing for somewhere in Greenwich as an example and the point eventually mapped was somewhere off the Ivory Coast!  I don't think UTM here is the correct system to specify, but I do not know how to specify BNG. I don't think I'm too far off solving the problem, but I could do with a bit of assistance. Thank you!
Example:
Tried the above code with East./North. 537869 , 178976. Was expecting 51.492927 , -0.015449524, but got the result -2.6595478348955846, 1.6192189249637292 instead.


text:
Q: Nginx Using KiB of shared memory for push module in I'm setup nginx with passenger on a ubuntu 14.04
and the nginx is throwing

403 Forbidden error

I checked the permissions and it is all ok.
I checked the nginx conf and it seems ok
user root;
worker_processes  1;
error_log  logs/error.log;

events {
    worker_connections  1024;
}

http {

    passenger_root /home/ubuntu/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/passenger-5.0.24;
    passenger_ruby /home/ubuntu/.rbenv/shims/ruby;
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    server {
        listen 80 default_server;
        server_name ;
        root /home/ubuntu/site/current/public;
        passenger_enabled on;
        rails_env production;
       index index.html;

        access_log  logs/access.log;

        location ~ ^/(assets)/  {
          gzip_static on;
          expires max;
          add_header Cache-Control public;
        }

       error_page 500 502 503 504 /500.html;
       client_max_body_size 4G;
       keepalive_timeout 10;

            }
}

but the nginx log keeps showing:

2016/02/18 03:28:57 [info] 13605#0: Using 32768KiB of shared memory
  for push module in /etc/nginx/nginx.conf:42 2016/02/18 03:31:11 [info]
  13642#0: Using 32768KiB of shared memory for push module in
  /etc/nginx/nginx.conf:42

Is someone having the same problem?


text:
Q: How to set subscript and superscript on QRadioButton of Qt How to set subscript, superscript and other special characters in QRadioButton of Qt

A: You can try overriding the paintEvent() of QRadioButton (you will have to subclass it though) and draw the text using QPainter. Here is an example that you can use. I have tried it out and it works relatively well except for the size problem:

The override paintEvent(QPaintEvent* event) of my radio button is:
QRadioButtonRichtTextSupport.h
void QRadioButtonRichtTextSupport::paintEvent(QPaintEvent* event)
{
  // First draw the original content of the radio button - the circle and the plain text
  QRadioButton::paintEvent(event);

  // Get the rectangle of the paint event
  QRect _rect = event->rect();
  QPainter painter(this);
  painter.setRenderHint(QPainter::Antialiasing, true);

  // Erase the text - I have used a translation of 16 along the X axis
  // from the top left corner of the paint rectangle but there might be
  // some less dirty way of doing this. Basically this is used to leave
  // the circle of the radio button intact while erasing the text part
  painter.eraseRect(_rect.topLeft().x()+16, _rect.topLeft().y(), _rect.width()-16, _rect.height());

  // Translate the painter along the X axis with 16
  painter.translate(QPointF(16, 0));
  // Create a text document which supports rich text formatting
  QTextDocument label;
  label.setHtml(this->text());
  // and finally draw the text over the radio button starting from +16 along the X axis
  label.drawContents(&painter);
  painter.end();
}

Widget.cpp
Widget::Widget(QWidget *parent)
  : QWidget(parent)
{
  setLayout(&this->layout);
  // Create the custom radio button. Notice that I've also added a string argument (not present in the default constructor of QRadioButton)
  // to add the ability to set the text upon initialization. This is completely optional
  QRadioButtonRichtTextSupport* rbrt = new QRadioButtonRichtTextSupport("Rich textabc123", this);
  this->layout.addWidget(rbrt);
}

The problem here is that I actually do set the text of the radio button (using setText(...)) and since the radio button doesn't support rich text formatting, you get a much wider radio button (the empty space after the text in the image above is actually where the raw text stood (in my case: Rich textabc123). You will have to look more into this to see how to adjust the size so that you cut the "extra" space. Should be possible by also overriding the resizeEvent(QResizeEvent* event) of the custom radio button. You can use label.documentLayout()->documentSize() to get the size of the QTextDocument that you are using and then add the extra space (in my case I use the +16 along the X axis which alters the width).
If that's not an option for you for some reason composite widget seems to be the easiest way to go - create a widget with a horizontal layout, place a QRadioButton without text first followed by a QLabel with the text for the radio button.
The problem with UTF-8 is that it supports only a subset of superscript Latin (and Greek) letters (for example the moment you want to write superscripted q you are screwed). There might be something more complete in UTF-16 (which Qt supports also) so you might want to look into that if creating your own QRadioButton or creating a composite widget is not optimal for you.

A: According to the documentation, the QRadioButton does not provide the rich text format for its label (like e.g. QLabel). Surprising!
So, this is what I tried:

*

*tgl1 ... radio button with rich text like QLabel but does not the expected

*tgl2 ... using Unicodes (limited success as long as the necessary characters exist)

*tgl3... compositing the radio button from multiple widgets

*subclass QRadioButton to override painting.

Option 3 and 4 are the most general approaches. (There should be done some additional effort to improve the layout of 3. option. 4. option I left as exercise...)
Sample code:
#include <QApplication>
#include <QRadioButton>
#include <QButtonGroup>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QLabel>
#include <QMainWindow>
#include <QVBoxLayout>

int main(int argc, char **argv)
{
  QApplication app(argc, argv);
  QMainWindow win;
  QGroupBox box;
  QVBoxLayout vBox;
  // radio button with mark-up
  QRadioButton qTgl1(QString::fromLatin1("Radio1"));
  vBox.addWidget(&qTgl1);
  // radio button exploiting Unicode extensively
  QRadioButton qTgl2(QString::fromUtf8("Radio\342\202\202"));
  // '2' as subscript ... U+2082 -> \342\202\202
  vBox.addWidget(&qTgl2);
  // fake a radio button with rich text by composition of widgets
  QHBoxLayout hBox3;
  QRadioButton qTgl3;
  hBox3.addWidget(&qTgl3);
  QLabel qLbl3(QString::fromLatin1("Radio3"));
  qLbl3.setTextFormat(Qt::RichText);
  hBox3.addWidget(&qLbl3);
  vBox.addLayout(&hBox3);
  box.setLayout(&vBox);
  win.setCentralWidget(&box);
  win.show();
  return app.exec();
}

And this is how it does look (in Windows 10):

Concerning the 2. option: there are some web pages which provide an overview about the available Unicode characters (and their code points).
Some sample Unicode code points:

*

*U+2070 ... U+2079: digits 0 ... 9 in superscript

*U+2080 ... U+2089: digits 0 ... 9 in subscript

*U+208A ... U+208E: characters "+-=()" in subscript

There might be others as well...


text:
Q: Images dont show in grid view, but do in list view In media library, images show in list view, but not in grid view.  This becomes an issue because adding a featured image is done by grid view only.
I had to edit the DB to make all jpg files lower case, and changed the actual picture files to match.  Everything shows correctly except grid view.  New images I upload through media manager show fine in grid view.

The corresponding URL is correct, as expected since the list view shows the image.  Plugins on or off do not make a difference.
Various forums have mentioned the same problem, but no solutions. What would be causing this and how to fix?


text:
Q: Using a Django template_tag on pages that extend from the view that loads the tag I've added a template tag to my app which I load in a view located in inc/base.html. This view contains my basic HTML layout. All my other views begin {% extends "inc/base.html" %}.
In one of my views I want to refer to my template tag, which is loaded in inc/base.html using this code: {% load spb_utils %}. If I try to use on of the template tags inside base.html it works fine, but if I try it any other view, it errors unless I manually add {% load spb_utils %} to the extended view as well.
Is this behaviour intentional? Eg, if I extend a template, does Django deliberately not load any of the template tags the 'parent' template loads? Is there a smart way to globally load my tags?
thanks.

A: that is the correct behaviour. extending a template does not load its template tags.
for always loading tags, see this answer, though you should carefully consider whether you really want this:
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
[...]


text:
Q: How can I get this in the title I am trying to get this link to go in the same block as the title. When I look at the page.php or index.php, I do not see the_title anywhere. All I see is the following:

    <?php the_content(); ?>
    <?php wp_link_pages(); ?>

If you view the page now you will see my share button above the content (Share icon with text "Share this event").

But I am trying to get it next to the title. Can someone tell me which php file contains this code so I can add it?
The page is http://isaevent.com/event/new-year-kick-off/

A: The site is using an events calendar plugin. You can create custom templates to make your changes. Here's how: http://tri.be/support/documentation/events-calendar-themers-guide/
It also tells you how to change the plugin files, but I wouldn't recommend that because you'll lose your changes if you update the plugin.


text:
Q: Simple regex - finding words including numbers but only on occasion I'm really bad at regex, I have:
    /(@[A-Za-z-]+)/

which finds words after the @ symbol in a textbox, however I need it to ignore email addresses, like:
    foo@things.com

however it finds @things
I also need it to include numbers, like:
    @He2foo

however it only finds the @He part.
Help is appreciated, and if you feel like explaining regex in simple terms, that'd be great :D

A: You can just add 0-9 to your regex, like so:
/(@[A-Za-z0-9-]+)/

Don't think any more explanation is needed since you've been able to come this far by yourself. 0-9 is just like a-z (though numeric ofcourse).
In order to ignore emailaddresses you will need to provide more specific requirements. You could try preceding @ with (^| ) which basically states that your value MUST be preceeded by either the start of the string (so nothing really, though at the start) or a space.
Extending this you can also use ($| ) on the end to require the value to be followed by the end of the string or a space (which means there's no period allowed, which is requirement for a valid emailaddress).
Update
$subject = "@a @b a@b a@ @b";
preg_match_all("/(^| )@[A-Za-z0-9-]+/", $subject, $matches);
print_r($matches[0]);

A: /(?:^|(?<=\s))@([A-Za-z0-9]+)(?=[.?]?\s)/

@This (matched) regex ignores@this but matches on @separate tokens as well as tokens at the end of a sentence like @this. or @this? (without picking the . or the ?) And yes email@addresses.com are ignored too.
The regex while matching on @ also lets you quickly access what's after it (like userid in @userid) by picking up the regex group(1). Check PHP documentation on how to work with regex groups.


text:
Q: winInColumn method should work but doesn't. Why? I have this method for a connect 4 game so that you can win in a column. However I get an Index Array out of bounds exception -1. The array it goes through is 8x8 in size (private int [][] values = new int [8][8];).
Where have i gone wrong?
public int winInAColumn(){
    int sum; //set sum as an integer
    for(int j=0;j<8;j++){ //loop through the rows
        for(int i=4;i>-1;i--){ //loop through columns. I must equal 4 as there must be three disks next to
            sum = 0; //set sum to 0
            for(int k=i;k>i-4;k--){ //loop backwards through k while k is bigger than i minus 4
                sum+=values[k][j]; //sum + sum = the value in  i and j
            }
            if(Math.abs(sum)==4){
                if(sum/4 == 1){
                    if(JOptionPane.showConfirmDialog(null, "Blue Has Won", "Game over", JOptionPane.OK_CANCEL_OPTION) == 0){
                        //
                    }
                    else
                    {
                        System.exit(0);
                    }
                }

                else if (sum/4 == -1){
                    if(JOptionPane.showConfirmDialog(null, "Blue Has Won", "Game over", JOptionPane.OK_CANCEL_OPTION) == 0)
                    {
                        //
                    }
                    else
                    {
                        System.exit(0);
                    }
                }
            }
        }
    }
                return 0;
        //JOptionPane.showMessageDialog(null, "No one won this time.");
}

A: In the second loop, i goes backward from 4 to 0, and in the third loop, k goes backward from i to i - 3, which can be as low as -3, hence the exception.
I did not really try to understand your algorithm in detail, but perhaps replace k>i-4 by k>i-4 && k>=0 would do the trick...


text:
Q: Shouldn't the key be capitalized in the json file? Shouldn't the key be capitalized in the json file? When fetch delete is performed, if uppercase letters are used, an error occurs that deletes all of them.
{
  "users": [
    {
      "name": "asas",
      "userId": "as",
      "password": "12341234",
      "email": "as@asas.kr",
      "id": 1
    }
  ]
}


text:
Q: Limit of $(n+n^{1/2}+\cdots+n^{1/n})/n$ I'm pretty sure this has been asked here before. But perhaps due to high flexibility in formulating this problem I couldn't find any useful resources.
Obviously a lower bound is $2$. And, numerically testing it in WolframAlpha, I'm quite convinced the limit should just be $2$.
My first thought was to see it as a Riemann partial sum but it failed, at least in the equi-partition case.
Could anybody help? Thanks.