text:
Q: mongodump no space on device error Ubuntu 14.04
MongoDB shell version: 2.4.9
doing backup of mongodb used for ceilometer in OpenStack Kilo. get no space error during back.  Where is partial back file? What file do I delete to get rid of the partial backup file. How do I recover the space
taken up by the failed backup?
stack@cloud:~$ mongodump --username ceilometer --password mypassword --host 3.2.0.10 --port 27017 --db ceilometer
...

Thu Apr 13 18:33:33.033         Collection File Writing Progress: 39821000/94803354 42% (objects)
Thu Apr 13 18:33:43.960         Collection File Writing Progress: 39824300/94803354 42% (objects)
Thu Apr 13 18:33:48.731         Collection File Writing Progress: 39827600/94803354 42% (objects)
**assertion: 14035 couldn't write to file: errno:28 **No space left on device****

stack@cloud:/$ df
Filesystem                 1K-blocks      Used Available Use% Mounted on
udev                        49474116         4  49474112   1% /dev
tmpfs                        9897052      1552   9895500   1% /run
/dev/mapper/cloud--vg-root 381244660 361897752         0 100% /
none                               4         0         4   0% /sys/fs/cgroup
none                            5120         0      5120   0% /run/lock
none                        49485248         0  49485248   0% /run/shm
none                          102400         4    102396   1% /run/user
/dev/sda1                     240972    237343         0 100% /boot

A: Since you didn't specify --out or -o on the command line to mongodump, the output would default to the current directory.
I would suggest you verify by running ls -la ~/dump. You can remove the dump by running rm -rf ~/dump.


text:
Q: Parsing nested JSON with NODE Second question for the day :)
Still working on my first ever app, and I've hit a bit of a snag using an API that returns currency exchange values. I need to extract the current AUD value from this JSON :
{"base":"USD","date":"2016-05-30","rates":{"AUD":1.3919,"BGN":1.7558,"BRL":3.6043,"CAD":1.3039,"CHF":0.99273,"CNY":6.5817,"CZK":24.258,"DKK":6.6765,"GBP":0.68341,"HKD":7.7688,"HRK":6.7195,"HUF":281.72,"IDR":13645.0,"ILS":3.8466,"INR":67.139,"JPY":111.19,"KRW":1190.9,"MXN":18.473,"MYR":4.1175,"NOK":8.3513,"NZD":1.4924,"PHP":46.73,"PLN":3.9447,"RON":4.0428,"RUB":65.89,"SEK":8.3338,"SGD":1.3811,"THB":35.73,"TRY":2.9565,"ZAR":15.771,"EUR":0.89775}}

Here is the code I am using:
var http = require('http');
var options = {
  host: 'api.fixer.io',
  port: 80,
  path: '/latest?base=USD',
  method: 'GET'
};

http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    const json = JSON.parse(chunk);
    rate = json.AUD;
    console.log(rate);
  });
}).end();

Unfortunately this doesn't work, and I assume that is because the JSON is nested? How do I go about querying this nested string correctly?
I also know I need to tighten up my handling of chunks, but it's baby steps for me right now :)
Thank you!

A: not json.AUD, it is
json.rates.AUD

A: You should wait for whole data first, or use one of the streaming parsers instead (for example: https://github.com/dominictarr/JSONStream).
That is because "chunk" is not all data at once - it may be just part of it, which means it's not a valid JSON itself.
http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  var data = '';
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    data += chunk;
  });
  res.on('end', function () {
    const json = JSON.parse(data);
    // As @huaoguo mentioned, it should be `json.rates.AUD`, not `json.AUD`
    rate = json.rates.AUD;
    console.log(rate);
  });
}).end();

Also, as @huaoguo mentioned, there should be json.rates.AUD instead of json.AUD.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to mock ActionExecutingContext with Moq? I am trying to test the following filter:
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Filters;

namespace Hello
{
    public class ValidationFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!filterContext.ModelState.IsValid) {
                filterContext.Result = new BadRequestObjectResult(filterContext.ModelState);
            }
        }
    }
}

I am trying to mock the ActionFilterAttribute using Moq.
I am using Mvc 6.0.0-rc1
My first try:
var context = new ActionExecutingContext(
                    new ActionContext(Mock.Of<HttpContext>(), new RouteData(), new ActionDescriptor()),
                    new IFilterMetadata[] { filter, },
                    new Dictionary<string, object>(),
                    controller: new object());

But I could not override the ModelState. It looks to be readonly: https://github.com/aspnet/Mvc/blob/6.0.0-rc1/src/Microsoft.AspNet.Mvc.Abstractions/ActionContext.cs#L25
Then I tried:
var contextMock = new Mock<ActionExecutingContext>(
                    new ActionContext(Mock.Of<HttpContext>(), new RouteData(), new ActionDescriptor()),
                    new IFilterMetadata[] { filter, },
                    new Dictionary<string, object>());

But when I call filter.OnActionExecuting(contextMock.Object) I get the following error:
Castle.DynamicProxy.InvalidProxyConstructorArgumentsException : Can not instantiate proxy of class: Microsoft.AspNet.Mvc.Filters.ActionExecutingContext.
      Could not find a constructor that would match given arguments:
      Microsoft.AspNet.Mvc.ActionContext
      Microsoft.AspNet.Mvc.Filters.IFilterMetadata[]
      System.Collections.Generic.Dictionary`2[System.String,System.Object]

How to test a filter that uses ModelState?

A: I just stumbled on the same problem and solved it in this way.
[Fact]
public void ValidateModelAttributes_SetsResultToBadRequest_IfModelIsInvalid()
{
    var validationFilter = new ValidationFilter();
    var modelState = new ModelStateDictionary();
    modelState.AddModelError("name", "invalid");

    var actionContext = new ActionContext(
        Mock.Of<HttpContext>(),
        Mock.Of<RouteData>(),
        Mock.Of<ActionDescriptor>(),
        modelState
    );

    var actionExecutingContext = new ActionExecutingContext(
        actionContext,
        new List<IFilterMetadata>(),
        new Dictionary<string, object>(),
        Mock.Of<Controller>()
    );

    validationFilter.OnActionExecuting(actionExecutingContext);

    Assert.IsType<BadRequestObjectResult>(actionExecutingContext.Result);
}

A: If someone was wondering how to do this when you inherit from IAsyncActionFilter
[Fact]
public async Task MyTest()
{
    var modelState = new ModelStateDictionary();

    var httpContextMock = new DefaultHttpContext();

    httpContextMock.Request.Query = new QueryCollection(new Dictionary<string, StringValues> {}); // if you are reading any properties from the query parameters

    var actionContext = new ActionContext(
        httpContextMock,
        Mock.Of<RouteData>(),
        Mock.Of<ActionDescriptor>(),
        modelState
    );

    var actionExecutingContext = new ActionExecutingContext(
        actionContext,
        new List<IFilterMetadata>(),
        new Dictionary<string, object>(),
        Mock.Of<Controller>()
    )
    {
        Result = new OkResult() // It will return ok unless during code execution you change this when by condition
    };

    Mymock1.SetupGet(x => x.SomeProperty).Returns("MySomething");
    Mymock2.Setup(x => x.GetSomething(It.IsAny<string>(), It.IsAny<string>())).ReturnsAsync(true);

    var context = new ActionExecutedContext(actionContext, new List<IFilterMetadata>(), Mock.Of<Controller>());

    await _classUnderTest.OnActionExecutionAsync(actionExecutingContext, async () => { return context; });

    actionExecutingContext.Result.Should().BeOfType<OkResult>();
}


text:
Q: What's wrong with this class? I'm trying to create a simple static C++ library that I can link it into a MonoTouch app and invoke the functions via MonoTouch. I'm trying to compile the static library in XCode and have this (edited since ildjarn fixes):
class MyClass
{
public:
    static int Get5() { return 5; }
    static int Get10() { return 10; }
};

I get the following error on the first line:

Expected '=', ',', ';', 'asm' or
  'attribute' before 'MyClass'

Any ideas why?
As an aside can I compile a static library in Visual Studio and link it into a MonoTouch app or is that impossible?

A: Member accessibility decorators are followed by a colon in C++, like labels or switch cases --
class MyClass
{
public:
    static int Get5() { return 5; }
    static int Get10() { return 10; }
};

Also, accessibility decorators have no effect on namespace-scoped types in C++, so public class MyClass is nonsensical.

A: You are mixing Java with C++. Obmit the "public" before the class and change the other "public" to "public:"

A: class MyClass
{
    public:
    int Get5()
    {
        return 5;
    }
    int Get10()
    {
       return 10;
    }
};

Or probably you need to compile it with /clr compiler flag (with your original code).


text:
Q: How to use Coroutine in singleton properly I want to create a singleton with Coroutine to load image from network. I have done implement the singleton and can load network image into imageView. Here is my singleton class.
class Singleton(context: Context) {

    private val TAG = "Singleton"

    private val scope =
        CoroutineScope(SupervisorJob() + Dispatchers.Main + CoroutineExceptionHandler { _, exception ->
            Log.e(TAG, "Caught $exception")
        })

    private var job:Job? = null

    companion object {

        private var INSTANCE: Singleton? = null

        @Synchronized
        fun with(context: Context): Singleton {

            require(context != null) {
                "ImageLoader:with - Context should not be null."
            }

            return INSTANCE ?: Singleton(context).also {
                INSTANCE = it
                Log.d("ImageLoader", "First Init")
            }

        }
    }

    private fun onAttachStateChange(imageView: ImageView, job: Job) {
        imageView.addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener {
            override fun onViewAttachedToWindow(v: View?) {
            }

            override fun onViewDetachedFromWindow(v: View?) {
                job.cancel()
            }

        })
    }

    fun loadImage(url: String, imageView: ImageView) {
        job = scope.launch {
            try {
                updateData(URL(url), imageView)
            } catch (e: CancellationException) {
                Log.d(TAG, "work cancelled!")
            }
        }.also {
            onAttachStateChange(imageView, it)
        }
    }

    suspend fun updateData(url: URL, imageView: ImageView) = run {
        fetchImage(url)?.apply { imageView.setImageBitmap(this) }
            ?: imageView.setImageResource(R.drawable.ic_launcher_background)
    }

    fun stopUpdate() {
        scope.cancel()
    }

    private suspend fun fetchImage(url: URL): Bitmap? {
        return withContext(Dispatchers.IO) {
            try {
                val connection = url.openConnection() as HttpURLConnection
                val bufferedInputStream = BufferedInputStream(connection.inputStream)
                BitmapFactory.decodeStream(bufferedInputStream)
            } catch (e: Exception) {
                Log.e("TAG", e.toString())
                null
            }
        }
    }
}

My problem is when I cancel my coroutine scope in onDestroy() at ActivityB and than use my singleton again in ActivityA it won't do anything cause the scope have been cancel(). So is there any way to use Coroutine in singleton properly with scope.cancel() when activity is onDestroy(). Here is a demo:
class MainActivityA : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main_activity)

        Singleton.with(this).updateData(url, imageView)
    }
}

class MainActivityB : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main_activity)
    }

    override fun onDestroy() {
        super.onDestroy()
        // Do not need to call scope.cancel(). Cause when the view is
        // detached it will cancel the job.
        // Singleton.with(this).stopUpdate()
    }
}

Edited
I have come up with an idea and have added into Singleton class. Using view.onAttachStateChange to detect whether the view is still attached to the window. If is detached then we can cancel the job. Is this a good way to doing so?

A: Singleton by definition lives forever, so I'm not really sure it makes sense to cancel its scope. What if you would need to use your singleton from multiple components at the same time? They would cancel jobs of other components.
To make sure you don't leak jobs of destroyed components, you can either create a child job per component and put all tasks under it or just do not define a custom scope at all and reuse the coroutine context of the caller.


text:
Q: Is it possible to control horizontal letter spacing in Vim? Is it possible to control horizontal letter spacing in Vim (Ubuntu)?

A: Vim is a text editor, not a word processor or publishing package so there isn't such a feature.

A: Not directly, but if you change the font for your terminal window your font in vim will change as well. So what you need is a widely-spaced monospace font. Try OCR B (the spacing between letters is very wide):
http://new.myfonts.com/fonts/tilde/ocr-b-10/
You may already have it installed, and/or it may be available from other sources.


text:
Q: Creating an Ad-hoc iOS build to test on other devices using an existing CSR / organization account Okay, I have put a day in this and am super - confused ( hail Android, it's super easy ). A client of mine has an organization developer account on apple, and uses his public-private Key Pair to look after development and deployment of an app on test devices. I am developing another app for him , and can request for his credentials (to generate the public-private Key Pair to sign and create ad - hoc provisioning profile and builds / invite me as a developer of the team on apple , and proceed) . The problem is : I need to issue a CSR ( Xcode -> Preferences -> Accounts -> Add Apple ID and request for public - private key ), BUT if I add his account , and generate CSR request to create key-value pair, would that not invalidate the CSR on his Mac and hamper his development? Is there a way out to generate a separate CSR for me using his organization account so that I can create provisioning profiles for an ad - hoc build ? Dang .. this is confusing..

A: you can do that by created a new APP ID specifically for you or your fellow developers and link with the developer profile you create.
Else you can also ask for .p12 file that can be exported from machine keychain from which your client first created CSR certificate from. Just you would require to add to it your mac and download the same profile and certificate from apple's developer portal, finally you can install it on your device.


text:
Q: Get In That DB! Parsing CSV Using Ruby I have a CSV file formatted just like this:
name,color,tasty,qty
apple,red,true,3
orange,orange,false,4
pear,greenish-yellowish,true,1

As you can see, each column in the Ruby OO world represents a mix of types -- string, string, boolean, int.
Now, ultimately, I want to parse each line in the file, determine the appropriate type, and insert that row into a database via a Rails migration.  For ex:
Fruit.create(:name => 'apple', :color => 'red', :tasty => true, :qty => 3)

Help!

A: For Ruby 1.8:
require 'fastercsv'

FasterCSV.parse(my_string, :headers => true) do |row|
  Fruit.create!(
    :name => row['name'],
    :color => row['color'],
    :tasty => row['tasty'] == 'true',
    :qty => row['qty].to_i
  )
end

For Ruby 1.9, just rename FasterCSV to CSV and fastercsv to csv:
require 'csv'

CSV.parse(my_string, :headers => true) do |row|
  # same as ruby-1.8
end


text:
Q: Right Click for New Text File on Mac OS I am looking for the way to create a new text file When I right click.
When I right click on an empty area in the Finder, I want an option called "Create New Text File" in the menu. But When I right click on a file in Finder, I want two options called "Create New Text File"  and "Create Text File as the Same Name of the file" in the menu.
Is it possible?


text:
Q: Delay MathJax with jQuery function With jQuery I run a function on-the-go which causes MathJax on the page to render. In this style:
function renderMath() {
  MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
}

I would like to delay it a bit, though, since the page jumps a lot if several function calls are made quickly after one another. How can the function be delayed in its responds? The setTimeout function in jQuery has no effect:
function renderMath() {
  setTimeout(function(){
    MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
  }, 2000);
}

Here it is set with 2 seconds delay for exaggeration, but it has no effect.
What other option do I have for delaying the function?


text:
Q: JDK is not present on the system but the system says it needs to be removed So I tried to build the .rpm file that Oracle gives. The installation was not 100% successful so i want to uninstall it and do it the easy way this openjdk, but now i cant install nothing cause linux tells me jdk is on the system when its not. Linux tries tries to remove it and fails blocking me from installing anything:
For example if i tried
sudo apt install openjdk-7-jdk

It gives me this:
0 upgraded, 38 newly installed, 1 to remove and 0 not upgraded.
1 not fully installed or removed.
Need to get 0 B/62,5 MB of archives.
After this operation, 162 MB disk space will be freed.

Do you want to continue? [Y/n] y
Extracting templates from packages: 100%
(Reading database ... 183637 files and directories currently installed.)
Removing jdk1.8.0-101 (1.8.0101-fcs-1) ...
find: `/usr/java/*': No such file or directory
/var/lib/dpkg/info/jdk1.8.0-101.postrm: line 586: /usr/sbin/alternatives: No such file or directory
/var/lib/dpkg/info/jdk1.8.0-101.postrm: line 598: /usr/sbin/alternatives: No such file or directory
dpkg: error processing package jdk1.8.0-101 (--remove):
subprocess installed post-removal script returned error exit status 127
Errors were encountered while processing:
jdk1.8.0-101
E: Sub-process /usr/bin/dpkg returned an error code (1)

A: Issue solved.
Analysed the file where it was getting an error and figured out what i did wrong.
I uninstalled java while the jdk was broken. As a result when i tried to uninstall jdk it would run the function present on lines 586 and 598, that referred to alternative versions of java that i had remove.
As i had already uninstalled java with no problems, those function where useless so i just edited the content of the functions,in case the rest of the script needed them to a simple:
echo "Hello World"

And as expected when i uninstalled jdk it gave me two times "Hello World". Now is fully uninstalled.
Thx for all the help anyway.


text:
Q: Evaluation metrics for algoritthms to calculate topic-hotness How do you evaluate algorithms for calculation of hotness of a post? As in how would you know, which performs better an exponential-decay or the redddit's algo? I understand the question may be a bit naive, but I am looking into performance metrics, or cost functions to help with this?

A: As with evaluation of any piece of software, you have to first set out problems for it solve and from those derive goals you want to achieve.  After you have those, then you can start to determine what metrics will provide a useful approximation of progress towards the goals.
Perhaps you want your site to be great at breaking news.  You probably will derive goals from that like "given sufficient votes, a new post should be able to make it to the top 30 listings in the first 10 minutes after it's posted".  Then you can build out some test cases and see if you meet them.
Or perhaps you want to be the place with the "best" stuff from across the web.  Your goals will weight more heavily towards user approval than newness.
You have to evaluate your own situation to come up with reasonable performance metrics.


text:
Q: How to get python-decouple to work on a live server? I can't seem to get python-decouple to work on a live server. I have a Django project in which python-decouple is used to separate my important variables such as secret key, debug, database vars, and so on in a .env file. When the project is run locally, python-decouple works well and I have no problems.
After confirming that it works well locally, I then added the .env file to my .gitignore file, pushed the code to my GitHub repository, then pulled the code to the AWS live server.
However, when trying to make migrations while configuring the project on an AWS EC2 Ubuntu server, I get the error below. It seems as though the variables in the .env file are not being applied on the AWS Ubuntu server which would make sense because of the .gitignore file. But I thought the whole point of python-decouple was to not have the important variables on the live server. Does anyone know why this error is occurring? and how I can fix it? or do not fully understand the use cases of python-decouple?
$ python manage.py makemigrations
Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "/home/theo/aggtrends/aggenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "/home/theo/aggtrends/aggenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 345, in execute
    settings.INSTALLED_APPS
  File "/home/theo/aggtrends/aggenv/lib/python3.6/site-packages/django/conf/__init__.py", line 76, in __getattr__
    self._setup(name)
  File "/home/theo/aggtrends/aggenv/lib/python3.6/site-packages/django/conf/__init__.py", line 63, in _setup
    self._wrapped = Settings(settings_module)
  File "/home/theo/aggtrends/aggenv/lib/python3.6/site-packages/django/conf/__init__.py", line 142, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678,
in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/theo/aggtrends/aggregatetrends/settings.py",
line 26, in <module>
    SECRET_KEY = config('SECRET_KEY')
  File "/home/theo/aggtrends/aggenv/lib/python3.6/site-packages/decouple.py", line 199, in __call__
    return self.config(*args, **kwargs)
  File "/home/theo/aggtrends/aggenv/lib/python3.6/site-packages/decouple.py", line 83, in __call__
    return self.get(*args, **kwargs)
  File "/home/theo/aggtrends/aggenv/lib/python3.6/site-packages/decouple.py", line 68, in get
    raise UndefinedValueError('{} not found. Declare it as
envvar or define a default value.'.format(option))
decouple.UndefinedValueError: SECRET_KEY not found. Declare it as envvar or define a default value.

A: Yes, you should not store vulnerable data such as .env files in public repositories.
But, you should create it again on the server-side.

*

*Connect to the server

*Go to the project folder

*Create .env file and fulfill it with all necessary variables you use.

A: From my findings I think there is just one way using every environment, either local and live server.
First you need to install python-decouple library in conjunction with .env file as follows:

*

*Install Python-Decouple:
pip install python-decouple

*Create a .env file in the root directorate of your project  and follow this format to define your Environment Variables inside the file.
SECRET_KEY = secret_key_for_app_you_may_use_code_to_it_unique
DATABASE_NAME = name_of_your_database
DATABASE_USER = your_database_username
DATABASE_PASSWORD = your_database_password
Notice there are no quotation marks in the values for the variables.
3. Import the config method in settings.py and use it to call these variables as follows:
from decouple import config

Now Call the variables in the appropriate places using the config method
DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.postgresql',
    'NAME': config('DATABASE_NAME'),
    'USER': config('DATABASE_USER'),
    'PASSWORD': config('DATABASE_PASS'),
    'HOST': 'localhost'
}
}

With this method, if you are hosting on server that is using CLI or Cpanel they will work fine in either ways, either by uploading the .env file to your web server (Cpanel) and doing just as I have done here or adding Environment Variable under the Python Application with Key Value pairs, install Python-Decouple, import config from decouple in settings.py and then call them as shown above.
I think this should help you. thanks


text:
Q: CoreData: fetching instance with second degree condition My CoreData structure is like this:
A.setWithBs ->> B
B.setWithCs ->> C

Now, knowing only A, I need to fetch the only B in setWithBs that links to a specific C. Can this be done elegantly with single fetch?
Thanks

A: You can try it with the "self in" and "Subquery" request. Haven't tested this special case, but this should be the way you have to go
NSFetchRequest* fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setEntity:[NSEntityDescription entityForName:@"B" inManagedObjectContext:context]];

NSPredicate* predicate = [NSPredicate predicateWithFormat:@"self in %@ AND SUBQUERY(setWithCs, $sc, $sc == %@).@count > 0", A.setWithBs, C];

A: Assuming that you have also defined the inverse relationship (which you should)
B.inA --> A, C.inB --> B

then you can execute the following fetch request:
A *theAObject = ...;
C *theCObject = ...;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"B"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(inA = %@) AND (ANY setWithCs = %@)",
         theAObject, theCObject];
[request setPredicate:predicate];

It fetches all "B" objects that are related to the given "A" object (via the inverse relationship "inA") and also related to the given "C" object (via the to-many relationship
"setWithCs").


text:
Q: how to switch between two background color of the same button on button click i'm am very new to android programming.
i am trying to switch button color on button click.
i tried to get the button color in the if statement but im getting an error.
thank you in advance for anyone who will answer..
//ONCLICK INFORMATION BUTTON
bt_more_info.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
      String more_info   = getResources().getString(R.string.more_info);
      String less_info   = getResources().getString(R.string.less_info);

      if(bt_more_info.getResources().getColor(R.color.material_yellow)){
         //bt_more_info.setText(less_info);
         bt_more_info.setBackgroundResource(R.color.button_white);
         bt_more_info.setTextColor(getResources().getColor(R.color.text_grey));

      }else if(bt_more_info.getResources().getColor(R.color.button_white)){
         //bt_more_info.setText(more_info);
         bt_more_info.setBackgroundResource(R.color.material_yellow);
       bt_more_info.setTextColor(getResources().getColor(R.color.material_button));
      }else{
         bt_more_info.setText("logic error");
      }
   }
});

here is the image of the app

A: there are many way for what you want.
one of easy way is add a boolean value for checked.
for example,
public class MainActivity extends AppCompatActivity {

    private TextView bt_more_info;
    private Boolean isClicked = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bt_more_info = (TextView) findViewById(R.id.text);

        bt_more_info.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isClicked) {
                    bt_more_info.setText(getResources().getString(R.string.more_info));
                    bt_more_info.setBackgroundResource(R.color.colorAccent);
                    bt_more_info.setTextColor(Color.parseColor("#000000"));
                    isClicked = false;
                } else {
                    bt_more_info.setText(getResources().getString(R.string.less_info));
                    bt_more_info.setBackgroundResource(R.color.colorPrimary);
                    bt_more_info.setTextColor(Color.parseColor("#FFFFFF"));
                    isClicked = true;
                }
            }
        });

    }

}


text:
Q: How to remove thin, black line which forms border in pgfgantt How do I remove the box around the tasks in the gantt chart shown in the following code.  How can I then make the bar and group descriptions nice and snug with the tasks?
\NeedsTeXFormat{LaTeX2e}
\documentclass[12pt]{standalone}
\usepackage{pgfgantt}
\usepackage{times}

\definecolor{teal}{rgb}{0,0.57,0.81}%
\definecolor{aqua}{rgb}{0.51,0.81,0.79}%
\definecolor{blue_gray}{rgb}{0.36,0.52,0.63}%

% create a new command for a ganttbar entry
\newcommand{\ganttbarentryprogresscustom}[5]{%
\ganttbar[progress=#1,%
bar/.append style={pattern color = #2},%
bar progress label anchor=south,%
bar inline label node/.style={above=3pt}]%
{#3}{#4}{#5}%
}%

\begin{document}
\begin{ganttchart}[%
x unit=1.4cm,%
y unit chart=1.1cm,%
time slot unit=day,%
bar/.append style={pattern=north west lines, pattern color = cyan},%
inline%
]{0}{11}%
\ganttgroup[inline=false]{Task 1}{1}{10}\\%
\ganttbarentryprogresscustom{100}{blue_gray}{Subtask 1}{1}{6}
\ganttbarentryprogresscustom{90}{teal}{Subtask 2}{7}{8}%
\ganttbarentryprogresscustom{75}{aqua}{Subtask 3}{9}{10}%
\end{ganttchart}%
\end{document}%

A: The frame around the entire diagram is drawn by the canvas node, and to remove it you add
canvas/.append style={draw=none}

to the ganttchart environment options.
For the second part, the reason there is so much space between the task 1 label and task bar itself, is that the diagram spans the region 0 to 11, while your task spans 1 to 10. Hence, there is one unit of empty space on the left side. If you add group label node/.append style={draw}, and you don't remove the canvas frame, you'll see that there is no space between that node and the canvas node.
There is a little bit of space between the text and the node border, which you can remove with group label node/.append style={inner sep=0}. But I'm wondering whether you actually want \begin{ganttchart}[...]{1}{11} instead of \begin{ganttchart}[...]{0}{11}.


text:
Q: How do you add the toolbar back to the viewer after you enterEditMode()? So, my current problem is that when I enter edit mode with MarkupsCore, the toolbar disappears. I have tried numerous ways of adding it back. My latest attempt was this:
 var button1 = new Autodesk.Viewing.UI.Button('toolbar-markup');
  button1.setToolTip('Markup');
  button1.addClass('markuptool');
  var toolbar = viewer.toolbar;
  button1.onClick = function(){
      var markups = viewer.getExtension('Autodesk.Viewing.MarkupsCore');
      markups.enterEditMode();
      var text = new Autodesk.Viewing.Extensions.Markups.Core.EditModeText(markups);
      markups.changeEditMode(text);
      markups.allowNavigation(true);
      viewer.toolbar = new Autodesk.Viewing.UI.ToolBar('toolbar');
      viewer.toolbar.addControl(toolbar._controls[0]);
      console.log(toolbar);
  };

However, this does not provide me with any errors, and it does not create a UI. I have also tried checking if the toolbar is visible after edit mode is entered, and also if it is collapsed, both of which said, it's visible and not collapsed.
At this point, I am wondering, how do you add the toolbar back to the viewer?


text:
Q: how to find how many days each item stayed in each category My dataset looks something like this:
Item | Date        | Category
1    | 01/01/2019  | A
1    | 02/01/2019  | A
1    | 03/01/2019  | B
2    | 10/02/2019  | A
2    | 11/02/2019  | B
2    | 12/02/2019  | B
2    | 13/01/2019  | C
3    | 07/02/2019  | A
3    | 10/02/2019  | A

So, this is basically a panel dataset, because for each item there are many dates, but they are not necessarily continued (see item 3). When an item dissapears it means it was sold. Also items' codes will not be repeated, so item 1 only references that item. The "date" is in string format.
This is just a sample but the dataset has millions of rows.
My goal is to find descriptive statistics, and I'm specially interested in getting the average days an item spends in each category.
Tried using
df.groupby(category).mean()

but i find it's not really giving me what I'm looking for. Any ideas?

A: IIUC, you can try groupby withnunique to get the number of unique date per item and category
print (df.groupby(['Item', 'Category'])['Date'].nunique()
Item  Category
1     A           2
      B           1
2     A           1
      B           2
      C           1
3     A           2
Name: Date, dtype: int64

followed by unstack to make it with a different shape.
print (df.groupby(['Item', 'Category'])['Date'].nunique().unstack(fill_value=0))
Category  A  B  C
Item
1         2  1  0
2         1  2  1
3         2  0  0

which is then equivalent to a pivot_table:
df.pivot_table(index='Item', columns='Category', values='Date',
               aggfunc='nunique', fill_value=0)


text:
Q: typescript error that property does not exist when it should I don't understand how this message is occuring.
Property 'message' does not exist on type '{ username: string; } | { message: string; }'.
The relevant code (cut down):
// types.ts
type LoginMessage = {
  type: 'login';
  payload: { username: string };
};

type SendChatMessage = {
  type: 'send_chat_message';
  payload: { message: string };
};

export type ClientToServerMessage = LoginMessage | SendChatMessage;

// reducer.js

const { message } = action.payload; // this is the line that causes the error
// action has type ClientToServerMessage

A: The answer was elsewhere... a missing break; in a switch case

A: You'll need to use a user-defined type guard to narrow the ClientToServerMessage union type.
The example from the documentation illustrates how these can be useful by narrowing a union type.
function isFish(pet: Fish | Bird): pet is Fish {
    return (pet as Fish).swim !== undefined;
}

Any conditional branches of your code will narrow the type to Fish if swim is defined.
if (isFish(pet)) {
    pet.swim(); // compiler knows that `pet` is of the `Fish` type
}


text:
Q: Open a new page in Chrome extension windows using  tag I have an extension which there is a link on the default HTML page. When I click my extension and I click on hyperlink nothing happens.
Log In

I searched the stackoverflow but many suggested using target="_blank". The problem is I don't want to open it in a new tab or window. I want to see it in my extension popup. Am I making a mistake somewhere?


text:
Q: Removing .html extension from URL on GitHub Pages I have a static website hosted on GitHub Pages and I am trying to remove the .html extension from the URL.
I understand that when using Jekyll, there is something called Permalink to do so. The thing is that I am not using Jekyll but only pure HTML & CSS.
I've also tried to create an .htaccess file at the root of my folder, but it doesn't seem to work on GitHub Pages.
I only have three html pages: index.html, projects.html and about-me.html.
When redirecting to the index.html, I can write  and then it'll remove the .html from the URL, but that's only specific to the index.
Any other way to do it for the other html pages?

A: It already works and you don't have to do anything
I'm not sure if you are already aware of that or not but to remove .html extension from GitHub Pages all you have to do is remove .html extension from your links.
In other words it already works and you don't have to do anything. You don't have to use subdirectories, CNAME, redirects, Jekyll _config.yml, YAML front-matter or any other hack.
For example you can use:
https://rsp.github.io/gh-pages-no-extension/test1
instead of:
https://rsp.github.io/gh-pages-no-extension/test1.html
and it displays the same file. Just change the links in your links and that's it.


text:
Q: Из fragment1 перейти fragment2, по нажатию на ListView из fragment1 перейти fragment2, по нажатию на ListView, вот пробую делать. он выдает ошибку, java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0... в общем правильно ли я делаю? можно еще ссылку на пример какой нибудь?

public class Fragment1 extends Fragment {
ImageView ivIcon;
TextView tvItemName;
ListView lvMain;;
final String LOG_TAG = "myLogs";

public static final String IMAGE_RESOURCE_ID = "iconResourceID";
public static final String ITEM_NAME = "itemName";

List<DrawerItem> dataList;

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

    View view = inflater.inflate(R.layout.fragment_layout_two, container,
            false);
    lvMain = (ListView) view.findViewById(R.id.listView1);

    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
            getActivity(), R.array.myTask,
            android.R.layout.simple_list_item_1);
    lvMain.setAdapter(adapter);

    lvMain.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {

            dataList = new ArrayList<DrawerItem>();
            Fragment fragment = null;
            Bundle args = new Bundle();
            switch (position) {
            case 0:
                toastMtethod("1");
                fragment = new Fragment2();
                args.putString(Fragment2.ITEM_NAME, dataList.get(position)
                        .getItemName());
                args.putInt(FragmentOne.IMAGE_RESOURCE_ID, dataList.get(position)
                        .getImgResID());
                break;
            case 1:
                toastMtethod("2");
                break;

            case 2:
                toastMtethod("3");
                break;
            }}
    });
    return view;
}

void toastMtethod(String text) {
    Toast toast = Toast.makeText(getActivity(), text, Toast.LENGTH_LONG);
    toast.show();
}}

A: у вас инициализируется
dataList = new ArrayList<DrawerItem>();

а затем берётся по индексу
dataList.get(position)

при этом список пустой...поэтому и ошибка


text:
Q: Reading all values from certain tags in XML with Python 3 I have an XML structure like this
<city>
   <house>
       <color>red</color>
       <residents>3</residents>
   </house>
   <house>
       <color>yellow</color>
       <residents>5</residents>
   </house>
   <apartment>
       <color>blue</color>
       <residents>4</residents>
   </apartment>
</city>

What I am looking to do, is get the total population in this city that lives in houses - basically fetch all residents tags' values under the house tag.
Every solution I can find will get me all te residents and a sum of 12 instead of 8: which is the correct number.
I am also restricted to use minidom only ://
Thank you in advance!

A: See below. './/house/residents' is the XPATH expression that does the magic.
Note that the solution is based on ElementTree (core python) and not minidom
import xml.etree.ElementTree as ET

xml = '''<city>
   <house>
       <color>red</color>
       <residents>3</residents>
   </house>
   <house>
       <color>yellow</color>
       <residents>5</residents>
   </house>
   <apartment>
       <color>blue</color>
       <residents>4</residents>
   </apartment>
</city>'''
root = ET.fromstring(xml)
print(sum(int(r.text) for r in root.findall('.//house/residents')))

output
8

minidom based solution
from xml.dom.minidom import parseString

xml = '''<city>
   <house>
       <color>red</color>
       <residents>3</residents>
   </house>
   <house>
       <color>yellow</color>
       <residents>5</residents>
   </house>
   <apartment>
       <color>blue</color>
       <residents>4</residents>
   </apartment>
</city>'''

residents = 0
dom = parseString(xml)
houses = dom.getElementsByTagName('house')
for h in houses:
    resident = h.getElementsByTagName('residents')
    residents += int(resident[0].firstChild.data)
print(residents)

output
8

A: Let me also say: Being restricted to minidom only is a really strange requirement:)
Give you another solution for your reference.
from simplified_scrapy import SimplifiedDoc

xml = '''
<city>
   <house>
       <color>red</color>
       <residents>3</residents>
   </house>
   <house>
       <color>yellow</color>
       <residents>5</residents>
   </house>
   <apartment>
       <color>blue</color>
       <residents>4</residents>
   </apartment>
</city>
'''
doc = SimplifiedDoc(xml)
residents = doc.selects('city>residents>text()')
print (sum(int(r) for r in residents))

Result:
12


text:
Q: Double Click Event on the items of the ListBox of a Userform VBA I am trying to do a small "save as" interface on excel using vba, so that I can save some of the information that i have putted in my sheet in another sheet. I am almost done with it and it looks like this: click here to see my Save As interface
My problem is that I want to put an event on double clicking on one of the elements of my list, let's say SoCs2. On double click, I want the string "SoCs2" to appear in the textbox below.
I tried something like that:
Private Sub Listbox1_BeforeDoubleClick(ByVal Cancel As MSForms.ReturnBoolean)

With Me.ListBox1
     For i = 0 To .ListCount - 1
       If .Selected(i) Then
         Me.TextBox1.Value = .List(i, 0)
         Exit For
       End If
     Next
End With

End Sub

My ListBox is called ListBox1 and my TextBox is called TextBox1.
Unfortunately, this code doesn't work: when I double click on one of the items of my ListBox, it does absolutely nothing.
Can somebody help me with this issue ?

A: The name of the Event Handler you are looking for is Listbox1_DblClick.  Try this:
Private Sub Listbox1_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
  With Me.ListBox1
    For i = 0 To .ListCount - 1
      If .Selected(i) Then
        Me.TextBox1.Value = .List(i, 0)
        Exit For
      End If
    Next
  End With

End Sub


text:
Q: Asp.net Response.Write inside an ascx/aspx file <%if (CanRemove) Response.Write(""+ProductName+""); %>

This code strikes me as ugly.  More specifically, any time I see a call to Response.Write inside an ascx or aspx file, I get suspicious that I'm doing something wrong.  Perhaps this is due to previously working with XSLT and noticing that when done right, there is rarely a need for <xsl:text> element in order to generate html.  I feel like it interferes with my ability to read the code when my html code is hidden inside a <% %> block.
Is this just something I need to get used to with Asp.Net or is there a better way to do it?

A: <% if (CanRemove) { %><%= ProductName %><% } %>

<%= is equivalent to Response.Write.
And as nicely formatted code:
<% if (CanRemove) { %>
    <%= ProductName %>
<% } %>

Also, this is the ASP.NET MVC method.

A: An alternative approach is to use a <asp:Literal> control and bind (or manually set) its Visible property to CanRemove and its contents to the specific text.
Whether this approach is better or worse depends on the style the application is developed in. In ASP.NET MVC style apps (or those that heavily modify HTML directly), I think the current method makes more sense. In ASP.NET Web form and server control based apps, the <asp:Literal> solution is more consistent.

A: It looks like you are just doing some conditional formatting here. You could do some of this in the codebehind if you wanted to. Try using a Label and doing some logic against it.
<asp:Label id="lblProductName" runat="server" />

And in your codebehind you could do something like this:
lblProductName.Text = ProductName;
lblProductName.Visible = CanRemove;
lblProductName.CssClass = "productLabel";

It is not a terrible thing to do stuff using server side includes, but you can utilize the codebehind to make for a cleaner seperation of view logic if you choose.

A: I think that is better to use Literal control and set his Text property in Page_Load or OnLoad methods in the code behind class.
protected void Page_Load(object sender, EventArgs e)
{
  if (CanRemove)
  {
    myLiteral.Text = "ProductName"
  }
}

Additionally System.Web.UI.WebControls.Literal control has an property named Mode that gives control of the rendering:

*

*PassThrough - The contents of the control are not modified;

*Encode - The contents of the control are converted to an HTML-encoded string (can give you some defense against cross-site scripting).

*Transform - Unsupported markup-language elements are removed from the contents of the control. If the Literal control is rendered on a browser that supports HTML or XHTML, the control's contents are not modified.

Check MSDN online documentation for literal class link


text:
Q: Dimension of subspace in the space of polynomials Let $W$ be the linear space of polynomials in two variables $x$, $y$ of degree at most $N$, i. e.
$$
W=\{f\in\mathbb{R}[x,y]:\deg(f)\leq N\}
$$
Consider subspace
$$
V=\left\{f\in W: \oint\limits_{x^2+y^2=R^2} f(x,y)ds=0\quad\mbox{for all $R>0$} \right\}
$$
Question: How can I find $\dim(V)$?
Attempt: I reduced this problem to the computation of the rank of certain matrix but this looks like wrong way.

A: If we denote the homogeneous part of $f$ of degree $k$ by $f_k$, we see that
$$\begin{align}
I(R) &:= \int\limits_{x^2+y^2 = R^2} f(x,y)\,ds\\
&= \int\limits_{x^2+y^2=R^2} \sum_{k=0}^N f_k(x,y)\,ds\\
&= \sum_{k=0}^N \int\limits_{x^2+y^2=R^2} f_k(x,y)\,ds\\
&= \sum_{k=0}^N \int\limits_{x^2+y^2=1}f_k(x,y)\,ds\cdot R^{k+1},
\end{align}$$
so the integral of each homogeneous part must vanish.
By symmetry, the integral of each monomial $x^\alpha y^\beta$ vanishes when $\alpha$ or $\beta$ is odd, and is strictly positive when $\alpha$ and $\beta$ are both even.
So for odd $k$, the integral vanishes for all monomials of degree $k$, and for even $k = 2m$, we have $m$ monomials where the exponent of $x$ and $y$ is odd, so their integral vanishes, and for $\mu = 0,\dotsc,m-1$, we have a homogeneous polynomial $x^{2\mu}y^{2(m-\mu)} - c_\mu\cdot x^{2m}$ of degree $k$ whose integral vanishes, and these $k$ homogeneous polynomials are linearly independent.
So overall, we lose one dimension for every even $0 \leqslant k \leqslant N$, whence
$$\dim V = \sum_{k=0}^N (k+1) - \left(\left\lfloor \frac{N}{2}\right\rfloor + 1\right) = \frac{(N+1)(N+2)}{2} - \left\lfloor \frac{N+2}{2}\right\rfloor.$$


text:
Q: using a variable in css class names, and dynamically giving it attributes I have a set of classes named class1 up to classN, and I want each class classK to get the color rgb(k%256, 0, 0).
N in this case is dynamic and has no theoretical upper limit, as the elements with these class names are generated based on user input and some js code.
I was thinking of having CSS kind of like this:
class[k]{
    color: rgb(k%256, 0, 0);
}

However, I have found no way of making CSS rules that vary based on a variable in the class name.
I briefly explored trying to use CSS variables, but those are more like constants and can't accommodate all classes 1 to N simultaneously.
Alternatively I could use javascript for the styling and have something like:
for(let i = 0; i < N; i++){
    document.getElementByClassName(`class${k}`).forEach(e => e.style = `color: rgb(${k}, 0, 0)`);
}

However, this is not very scaleable if I want to add more complex CSS (which I most likely will, the rgb value I'm using now is proof of concept), it is very inefficient and I much prefer having CSS handle as much of my styling as possible.
Looking around on the internet I did find this post on stackoverflow that asks pretty much the same question, and received an answer of "this is impossible". However, that post was barely viewed and from 2015, so there might be a new feature since then that could help me.


text:
Q: Tasks and WaitAll/WhenAll Could you help me to speed up/optimize this code:
var keys = xRoot.Elements("key").Select(key => new { ID = int.Parse(key.Attribute("id").Value), VerificationCode = key.Attribute("verificationCode").Value });

var tasks = keys.Select(key => EveOnlineClient.GetAccountStatusAsync(key.ID, key.VerificationCode));

var tasks2 = keys.Select(key => EveOnlineClient.GetAPIKeyInfoAsync(key.ID, key.VerificationCode).ContinueWith(x =>
    {
        var characters = x.Result.Characters;

        var tasks3 = characters.Select(character => EveOnlineClient.GetCharacterSheetAsync(key.ID, key.VerificationCode, character.ID));
        var tasks4 = characters.Select(character => EveOnlineClient.GetSkillInTrainingAsync(key.ID, key.VerificationCode, character.ID));

        Task.WaitAll(tasks3.ToArray());
        Task.WaitAll(tasks4.ToArray());
    }));

await Task.WhenAll(tasks.Concat(tasks2));

A: If I may offer one suggestion. I've found that WHEN APPLICABLE, using a list offers insignificantly, however more nevertheless processing speed and less allocated memory. .ToList(), while it does essentially boil down to the same format since it stores its information dynamically, tends to offer less allocated memory in the long run on the heap. When viewing other questions about Lists vs Arrays, I've learned that the goal and essentially the necessity for saving what could be insignificant time and memory[though possibly Significant time and memory, is to profile your code and see which would be more demonstrable in the long run.


text:
Q: Loop through XPath element positions in Python using Selenium How can I loop through element positions in Python using Selenium?
I've tried this and it's not working:
for i in range(2,21):
    un = browser.find_element_by_xpath("(//div[@class='cname'])[i]").text
    print(un)

A: You have to format your string to put inside i value:
for i in range(2,21):
    un = browser.find_element_by_xpath("(//div[@class='cname'])[{0}]".format(i)).text
    print(un)

A: As per your code block an alternative would be to to use find_elements_by_xpath along with the index [i] as follows :
for i in range(2,21):
    un = browser.find_elements_by_xpath("//div[@class='cname']")[i].text
    print(un)


text:
Q: Inheritance in Objective-c and Functions I have class X, an abstract class, and classes A and B that inherit from it.  Classes A and B each have their own 'return_something' function.  I have another method elsewhere that calls 'return_something' on a series of objects, all of type X.  'return_something' returns something different depending on whether it is an A or a B, so I can just call id *result = [x return_something).
I can design this all fine, but when I come to implementing it I don't know what to put in class X, the parent.  It needs to have a 'return_something' function in order for it to be callable, but the function itself is defined in the child classes.  I can declare it in the parent and both children, but I don't have anything to return from the X implementation - the returned object is dependent on the child's re-definition.
This would be fine for a non-returning method, but how am I meant to use inheritance and polymorphism with a function?

A: The simplest thing to do is throw an exception from the "base" function. That way you'll know if it gets called by mistake.
Other languages which provide explicit "abstractness" don't require method bodies for abstract methods.

A: Use an objective-C protocol instead of an abstract base class:
@protocol ProtocolX
-(int)return_something;
@end

@interface ClassA : NSObject <ProtocolX> {
}
-init;
-(int)return_something;
@end

@interface ClassB : NSObject <ProtocolX> {
}
-init;
-(int)return_something;
@end

@implementation ClassA : NSObject <ProtocolX>
-(int)return_something { return 1; }
-init { retur [super init]; }
@end

@implementation ClassB : NSObject <ProtocolX>
-(int)return_something { return 3; }
-init { retur [super init]; }
@end

References of type id<ProtocolX> can then be passed around and used:
id<ProtocolX> ref = [[ClassA alloc] init];
int myIntForA = [ref return_something];
[ref release];
ref = [[ClassB alloc] init];
int myIntForB = [ref return_something];
[ref release];


text:
Q: How can I change an option menu's sub-item selection color programmatically? I know how to change the selection color of android option menu but how can I change the selection color of an option menu's sub-item?

A: I know that you're talking about submenus, but this question might help you (about changing the color of option menus).


text:
Q: How to format timevalue to HH:MM:SS in datalabel So i have a bar graph in crystal reports. On this graph i have a data label attached to each of the graphs that displays the value of the graph in seconds, which appears like so:

 What i would like to do is format this data-label into a time formatting. So for each bar in the graph it would have the data-label appear in the following format:
HH:MM:SS.
i am able to get the time formatting to appear using the following formula:
local NumberVar Sec;
local NumberVar ss;
local NumberVar mm;
local NumberVar hh;
local StringVar SSS;
local StringVar MMM;

Sec := Sum ({GetAlarmSummaryDataSet2Response/GetAlarmSummaryDataSet2Result/Items/AlarmSummaryItem2.StopTime}, {GetAlarmSummaryDataSet2Response/GetAlarmSummaryDataSet2Result/Items/AlarmSummaryItem2.Section}) ;
hh := Int (Sec/3600);
mm :=Int ((Sec/60)- (60* Int(Sec/3600 )));
If mm<10 then MMM := "0" & ToText (mm,0);
If mm>9 Then MMM := ToText(mm,0) ;

ss :=Sec-(3600 * hh ) - (60 * mm ) ;
If ss<10 then SSS := "0" & ToText (ss,0);
If ss>9 Then SSS := ToText(ss,0) ;

ToText ( hh,0) & ":" & MMM & ":" & SSS

But what i am unsure of is how to implement this formula onto a data label.
Any help or suggestions are greatly appreciated.
Thank you

A: You can choose to display the group name, and you can display and format the summarized value calculated by the chart, but you can't provide a custom formula. It just isn't possible using the chart library in CR XI.
My eventual workaround for this problem:

*

*Modify the value formula to eliminate the aggregate function. (This is necessary because Crystal won't allow an aggregate function in a group name field -- see #2.)

*For the group name, specify a formula with the text you want to display in the riser. Include both the label and the formatted value, separated by Chr(13) & Chr(10) to place them on separate lines.

*Configure the riser to display the label, not the value.

To apply this to your problem you'd need to make these changes:

*

*Eliminate the aggregate function. Of course I don't know if this will be possible using your setup. Perhaps if you're using a DBMS you could use a SQL command or a stored procedure to calculate the sum before the data reaches Crystal.

*Print the label and value together, either on the riser or the X-axis.

If that's not good enough for your application, you might consider CRChart, a commercial replacement which tries to address the sometimes-crippling limitations of Crystal's chart library. (I thought it was too pricey.) I think the @APPEND_DATATEXT macro would let you place a custom value on a riser, but you'd still need to move the summary to the server.


text:
Q: Spark ML API to convert a vector to a probability for multilabel classification I'm a bit new to Spark ML API. I'm trying to do multi-label classification for 160 labels by training 160 classifiers(logistic or random forest etc). Once I train on Dataset[LabeledPoint], I'm finding it hard to get an API where I get the probability for each class for a single example. I've read on SO that you can use the pipeline API and get the probabilities, but for my use case this is going to be hard because I'll have to repicate 160 RDDs for my evaluation features, get probability for each class and then do a join to rank the classes by their probabilities. Instead, I want to just have one copy of evaluation features, broadcast the 160 models and then do the predictions inside the map function. I find myself having to implement this but wonder if there's another convenience API in Spark to do the same for different classifiers like Logistic/RF which converts a Vector representing features to the probability for it belonging to a class. Please let me know if there's a better way to approach multi-label classification in Spark.
EDIT: I tried to  create a function to transform a vector to a label for random forest, but it's super annoying because I now have to clone large pieces of tree traversal in Spark, and almost everywhere I encountered dead ends because some function or variable was private or protected. Correct me if wrong, but if this use case is not already implemented, I think it atleast is well-justified because Scikit-learn already has such APIs in place to do this.
Thanks

A: Found the culprit line in Spark MLLib code: https://github.com/apache/spark/blob/5ad644a4cefc20e4f198d614c59b8b0f75a228ba/mllib/src/main/scala/org/apache/spark/ml/Predictor.scala#L224
The predict method is marked as protected but it should actually be public for such use cases to be supported.
This has been fixed in version 2.4 as seen here:
https://github.com/apache/spark/blob/branch-2.4/mllib/src/main/scala/org/apache/spark/ml/Predictor.scala
So upgrading to version 2.4 should do the trick ... although I don't think 2.4 is out yet, so it's a matter of waiting.
EDIT: for people that are interested, apparently not only is this beneficial for multi-label prediction, it's been observed that there's 3-4x improvement in latency as well for regular classification/regression for single instance/small batch predictions (see https://issues.apache.org/jira/browse/SPARK-16198 for details).


text:
Q: Sending a `Null` value for parameter with Alamofire I have updated to Swift3 and the latest Alamofire '~> 4.0'
When I try and make my parameters I now get <null> instead of null for settings that I do not have set. Which conflicts with my backend.
Is there a way to send null?
When I set the value to nil it is not included in the put the dictionary strips it out. But I need all values to be sent back.
My code
func saveOfficeHours(days: [OfficeHours]) {
  guard let URL = LocationInfo.shared.url else {
    assertionFailure("location URL is nil")
    return
    }

  let formatter = DateFormatter()
  formatter.dateFormat = "HH:mm:ss"

  func formatTime(time: Date?) -> Any {
      guard let time = time else { return NSNull() }
      return formatter.string(from: time)
  }

  var parameters: [String: Any] = [:]
  for week in days {
    parameters["\(week.day)_hours_start"] = formatTime(time: week.hoursStart)
    parameters["\(week.day)_hours_stop"] =  formatTime(time: week.hoursEnd)
    parameters["\(week.day)_lunch_hours_start"] =  formatTime(time: week.lunchStart)
    parameters["\(week.day)_lunch_hours_stop"] =  formatTime(time: week.lunchEnd)
    parameters["\(week.day)_break_hours_start"] =  formatTime(time: week.breakStart)
    parameters["\(week.day)_break_hours_stop"] =  formatTime(time: week.breakEnd)
  }

  Alamofire.request(URL, method: .put, parameters: parameters, encoding: URLEncoding.httpBody, headers: API.workstationTokenAuthHeaders()).validate().responseJSON {
    response in
    switch response.result {
    case .success:
        print("Success setting office hours")
    case .failure(let error):
        print("Failure setting office hours: \n \n -------==========-------- \n \n\(error)\n \n -------==========-------- \n")
    }
  }
}

Thanks for your help in advance.

A: Rather than relying on NSNull mapping correctly through various abstractions between Alamofire and the data being sent over HTTP with your parameters, I would do the following:
func formatTime(time: Date?) -> String? {
  guard let time = time else { return nil }
  return formatter.string(from: time)
}

var parameters: [String: Any] = [:]
  for week in days {
    if let hoursStart = formatTime(time: week.hoursStart) { parameters["\(week.day)_hours_start"] = hoursStart }
    if let hoursEnd = formatTime(time: week.hoursEnd) { parameters["\(week.day)_hours_stop"] = hoursEnd }
    if let lunchStart = formatTime(time: week.lunchStart) { parameters["\(week.day)_lunch_hours_start"] =  lunchStart }
    if let lunchStop = formatTime(time: week.lunchEnd) { parameters["\(week.day)_lunch_hours_stop"] = lunchStop }
    if let breakStart = formatTime(time: week.breakStart) { parameters["\(week.day)_break_hours_start"] = breakHoursStart }
    if let breakEnd = formatTime(time: week.breakEnd) { parameters["\(week.day)_break_hours_stop"] = breakEnd }
  }

As an aside, your question should state where exactly you are seeing <null> as opposed to null? In some logging call in Cocoa, or at your server end? Again though, safer (and arguably Swiftier, as formatTime has a meaningful return type in above example) option would be above IMO.


text:
Q: How to create a function in excel for sum of cubes or higher powers? I'm trying to implement p-means, as laid out in this question
If p=2, I can do SQRT(SUMSQ(data)).
If p=3, I need to do CBRT(**SUM OF CUBES**(data))
And so on. The first part is easy to scale, I can just raise the whole thing to 1/N. But how would I implement sum of cubes, fourth powers, etc. ?

A:
"But how would I implement sum of cubes, fourth powers, etc."?

With SUMPRODUCT:
If your data is in A1:A3 for example:
=SUMPRODUCT(A1:A3^3)

=SUMPRODUCT(A1:A3^4)

etc.

I'd ditch the use of SUMSQ here and just use SUMPRODUCT all around.

A: Scott's answer to another question of mine is what I ended up using:
=(SUM(IF(ISNUMBER(E2:E99),E2:E99^3))/COUNT(E2:E99))^(1/3)

This is an array formula (ctrl + shift + enter or it won't work).


text:
Q: Elastic Search Query to get ( count of something = other field ) Disclaimer: I am very new to ES! Sorry if this is an obvious question!
I have the following user example index
{"user":{
"id":"ID-1",
"documents":3,
"docs":[
  {"status":"approved"},
        {"status":"approved"},
        {"status":"approved"}
]
}
}

how do I get users that number of approved docs match the number of documents?

A: In this post explains why it is not possible to iterate over the nested type field.
It also shows an example of how to solve it with the help of copy_to and include_in_root.
However, as the status is the same within the array, the copy_to and include_in_root functions will only count once (elastic behavior).
What I mean is, for docs it has status [approved, approved], when using copy_to the new variable will only have 1 approved.
If docs has status [approved, disapproved], the new variable will only have 2 elements.
I have a suggestion but you would need to process the data before indexing, if you want to hear it I can post it.
From the information I used this mapping:
PUT my-index
{
  "mappings": {
    "properties": {
      "user": {
        "properties": {
          "id": {
            "type": "keyword"
          },
          "documents": {
            "type": "long"
          },
          "docs": {
            "type": "nested",
            "include_in_root": true,
            "properties": {
              "status": {
                "type": "keyword"
              }
            }
          }
        }
      }
    }
  }
}

Note that I added the include_in_root property.
Indexing Data:
POST my-index/_doc
{
  "user": {
    "id": "ID-1",
    "documents": 3,
    "docs": [
      {
        "status": "approved_1"
      },
      {
        "status": "approved_2"
      },
      {
        "status": "approved_3"
      }
    ]
  }
}

At this point you will need to make some changes before indexing. I figured the "documents" field is a count of the "docs" array so each document has its status. To solve the problem I mentioned above it will be necessary to add a character to the end of the status.
What I thought is to add at the end of each status the doc number, for example, "approved_1", "approved_2", "disapproved_3".
This way it will be possible to iterate the array and make a status comparison, if all are approved and the total is equal to the value in the "documents" property, the document is returned.
GET my-index/_search
{
  "query": {
    "bool": {
      "filter": [
        {
          "script": {
            "script": {
              "inline": """
                  def count = 0;
                  def status = doc['user.docs.status'];
                  for(int i = 0; i < status.size(); i++) {
                    def real_status = status[i].splitOnToken('_')[0];
                    if(real_status == 'approved') {
                      count++;
                    }
                  }
                  if(count == doc['user.documents'].value){
                    return true;
                  }
                  """
            }
          }
        }
      ]
    }
  }
}


text:
Q: How to implement a basic Datalog interpreter? I am looking for a good tutorial on how to implement a basic Datalog interpreter for learning purposes. I have found a lot of papers which discuss how to make them faster or add some features but none that describes how to implement a basic one.

A: Here is a sample implimentation, Java source code included:
http://abcdatalog.seas.harvard.edu/
The developers explicitly cite facilitation of research and pedagogy among their objectives.
There are also many links to open source projects here:
https://en.wikipedia.org/wiki/Datalog#Systems_implementing_Datalog
Best of luck!


text:
Q: restore AWS RDS Postgres snapshot in google cloud SQL Postgres I have a Postgres DB (size is 1TB) that i want to duplicate into google cloud SQL Postgres.
How do I achieve this ?
I have taken a snapshot of the DB but I don't know how to transfer it to google cloud and create a Postgres DB from it

A: Most of the market Cloud Services also offer transfer services. Since you are looking for migration into GCP
you can use google's storage transfer service for transferring data in TBs.
I suggest compress the data if possible
below links will help you to transfer files.
https://cloud.google.com/solutions/transferring-big-data-sets-to-gcp
https://cloud.google.com/storage-transfer/docs/

A: I suggest you check this official documentation where is explained how to migrate your database to Cloud SQL service[1]
Also, on this document you can find how to import data using CSV files too [2], I strongly recommend you take a look on the best practices for importing and exporting data too [3].
And here you can take a look on a very good example[4].
[1] https://cloud.google.com/solutions/migrating-postgresql-to-gcp
[2] https://cloud.google.com/sql/docs/postgres/import-export/importing
[3] https://cloud.google.com/sql/docs/postgres/import-export/
[4] https://medium.com/faun/how-to-migrate-postgresql-databases-to-google-cloud- sql-81ae448dc086


text:
Q: Chart.js color change of the data points I want to make the dots solid color instead of a border of the line color. How do I remove the border color from the data points and make it a solid color?
Current Output:

What I want:

A: You can set point and point border to same color.
datasets: [
    {
      label: 'Dataset 1',
      data: Utils.numbers(NUMBER_CFG),
      fill: false,
      borderColor: Utils.CHART_COLORS.red,
      backgroundColor: '#1F363D', # Here
      borderWidth: 1,
      pointRadius: 5,
      pointBorderColor: '#1F363D' #Here
    },

A: You can set the color value for each data point an array.
data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(54, 162, 235, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(54, 162, 235, 1)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(54, 162, 235, 1)',
            ],
            borderWidth: 1
        }]

codepen - https://codepen.io/non_tech_guy/pen/VwzwRrL
The only catch I can see is the first borderColor value controls the color of the line but it is a step closer.


text:
Q: Extending MongoDB's "save" method in nodejs In our app, we have a large document that is the source of most of our data for our REST api.
In order to properly invalidate our client-side cache for the REST api, i want to keep track of any modifications made to teh document. The best we came up with is to extend the mongo save command for the document to send off the notification (and then save as usual).
The question is, how does one actually do this in practice? Is there a direct way to extend mongo's "save" method, or should we create a custom method (i.e. "saveAndNotify") on the model that we use instead (which i would avoid if i can)?
[edit]
So in principle, i am looking to do this, but am having an issue not clobbering the parent save function();
mySchema.methods.save = function() {
  // notify some stuff
  ...
  //call mongo save function
  return this.super.save();
};

A: Monkey patching the core mongo object is a bad idea, however it turns out mogoose has a middleware concept that will handle this just fine:
var schema = new Schema(..);
schema.pre('save', function (next) {
  // do stuff
  next();
});


text:
Q: How can I download, compile and execute a simple ImageMagick (++) on Windows For no particular reason other than to learn a graphic library API I decided to give ImageMagick a try. I thought I'd be downloading a DLL along with a header file (*.h) and then create a c++ program that uses this header file and links against the DLL.
Now, the problem is: I didn't find such a header file.
I found ftp://ftp.imagemagick.org/pub/ImageMagick/binaries/ImageMagick-6.6.7-Q16-windows.zip that contains a few DLLs and EXEs, but no header file.
On the other hand, at http://image_magick.veidrodis.com/image_magick/windows/ I found a few zip files that are full of header files, but without any DLL. I could probably create such a DLL if I compiled the the tree contained in such a zip file, but since I don't know if I am going to like ImageMagick, I'd rather not do that, especially since I am on windows and the entire build process seems to be made for a Unix variant.
In short, my question probably boils down to: is there a possibility to create a simple ImageMagick "application" in c++ or c, and what are the minimal requirments for it, and where would I get them.
Edit: As per a comment, I have tried the MagicWand C API http://www.imagemagick.org/script/magick-wand.php
I can compile the c source file, but I cannot link it because of undefined references to MagickWandGenesis, NewMagickWand, MagickReadImage, MagickGetException, MagickRelinquishMemory, MagickResetIterator, MagickResizeImage, MagickNextImage, MagickWriteImages, MagickGetException, MagickRelinquishMemory, DestroyMagickWand and MagickWandTerminus. And it's these symbols that I thought I'd find in a DLL.
Edit: maybe ImageMagick is just too big for my purposes and it is not as simple as I'd like it to be. In this case, I'd be happy for any pointer towards other graphic libraries that can do a bit more than just straight lines and circles.

A: we need to know your requirements to advise any image processing library. there're many with different capabilities: OpenCV, libpng, libjpeg, GIL and so on.
also probably what you need is just a native Windows library like GDI, GDI+ or DirectX (Direct3D or Direct2D)


text:
Q: value too long for type character varying(100)----recently switched database, didn't do anything in db I recently switched to postgresql, I thought everything worked fine until I realized when I make post I get value too long for type character varying(100). Now I googled it, and saw some similar questions but when I tried some solutions there none of them worked. I will explain why my question is different in my opinion. I have this code in models.py
class Post(models.Model):
    url = models.URLField(max_length=250, blank=True, null=True)

    slug = models.CharField(max_length=255, unique=True)
    objects = models.Manager()

@property

def save(self, *args, **kwargs):
    self.slug = uuslug(self.title, instance=self, max_length=255)
    super(Post, self).save(*args, **kwargs)

As I saw some recommended solutions, I did try changing my max_length to 100. I have no idea why this is happening, I don't have anything in db. I recently switched to postgresql. Can you help me why this error is occurring and how I can fix it? should I move away from uuslug?
Full model
.
class Category(models.Model):

    name = models.CharField(max_length=128, unique=True)
    description = models.TextField(verbose_name=('describe'))
    author = models.ForeignKey(settings.AUTH_USER_MODEL)

    def __unicode__(self):
        return self.name

    def get_absolute_url(self):
        return "/category/%s/" %self.name

def my_handler(sender, instance, created, **kwargs):
    action.send(instance.author, verb='following', target=Category)
post_save.connect(my_handler, sender=Category)

class Post(models.Model):
    category = models.ForeignKey(Category, verbose_name=('community'))
    pub_date = models.DateTimeField(auto_now_add = True)
    url = models.URLField(max_length=250, blank=True, null=True)
    video = EmbedVideoField(verbose_name='link',help_text="Youtube", blank=True, null=True)

    title = models.CharField(max_length = 50)
    moderator = models.ForeignKey(User)
    views = models.IntegerField(default=0)
    slug = models.CharField(max_length=255, unique=True)
    objects = models.Manager()            # default manager
    content = RichTextUploadingField(config_name='default')
    rank_score = models.FloatField(default= 1)
    image = models.ImageField(upload_to='images',blank=True, null=True)
    thumbnail = models.ImageField(upload_to='images', blank=True, null=True)

    @property
    def domain(self):
        long_url = urlparse(self.url).netloc if self.url else "be kind to one another"
        return long_url.split('.', 1)[1] if long_url.split('.', 1)[0] == 'www' else long_url
    def save(self, *args, **kwargs):
        self.slug = uuslug(self.title, instance=self, max_length=255)
        super(Post, self).save(*args, **kwargs)
    def __unicode__(self):
        return self.title

Here's full Traceback
T
raceback:
File "env/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "env/local/lib/python2.7/site-packages/django/views/generic/base.py" in view
  71.             return self.dispatch(request, *args, **kwargs)
File "env/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper
  34.             return bound_func(*args, **kwargs)
File "env/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  22.                 return view_func(request, *args, **kwargs)
File "env/local/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func
  30.                 return func.__get__(self, type(self))(*args2, **kwargs2)
File "ebagu/main/views.py" in dispatch
  191.      return super(PostCreateView, self).dispatch(request, *args, **kwargs)
File "env/local/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch
  89.         return handler(request, *args, **kwargs)
File "env/local/lib/python2.7/site-packages/django/views/generic/edit.py" in post
  249.         return super(BaseCreateView, self).post(request, *args, **kwargs)
File "env/local/lib/python2.7/site-packages/django/views/generic/edit.py" in post
  215.             return self.form_valid(form)
File "ebagu/main/views.py" in form_valid
  186.          self.object.save()
File "ebagu/main/models.py" in save
  66.       super(Post, self).save(*args, **kwargs)
File "env/local/lib/python2.7/site-packages/django/db/models/base.py" in save
  734.                        force_update=force_update, update_fields=update_fields)
File "env/local/lib/python2.7/site-packages/django/db/models/base.py" in save_base
  762.             updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "env/local/lib/python2.7/site-packages/django/db/models/base.py" in _save_table
  846.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "env/local/lib/python2.7/site-packages/django/db/models/base.py" in _do_insert
  885.                                using=using, raw=raw)
File "env/local/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method
  127.                 return getattr(self.get_queryset(), name)(*args, **kwargs)
File "env/local/lib/python2.7/site-packages/django/db/models/query.py" in _insert
  920.         return query.get_compiler(using=using).execute_sql(return_id)
File "env/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
  974.                 cursor.execute(sql, params)
File "env/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
  79.             return super(CursorDebugWrapper, self).execute(sql, params)
File "env/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
  64.                 return self.cursor.execute(sql, params)
File "env/local/lib/python2.7/site-packages/django/db/utils.py" in __exit__
  97.                 six.reraise(dj_exc_type, dj_exc_value, traceback)
File "env/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
  64.                 return self.cursor.execute(sql, params)

Exception Type: DataError at /add_post/
Exception Value: value too long for type character varying(100)

A: Look into database.

Quick psql tutorial
Start postgres client shell, eg. with python manage.py dbshell. Something like this shows:
ebagu=>

The lines
File "ebagu/main/models.py" in save
  66.       super(Post, self).save(*args, **kwargs)

show you are trying to save model Post in what I assume is app main. If you didn't change table in Post's Meta, the table should be something like main_post.
You want to display all tables in postgres shell with command:
\d

It will list tables in a similar fashion:
                          List of relations
 Schema |               Name                |     Type      | Owner
--------+-----------------------------------+---------------+--------
 public | django_migrations                 | table         | hruske
 public | django_migrations_id_seq          | sequence      | hruske
 public | django_session                    | table         | hruske

If you want to check the details of the table django_session you can do:
\d django_session

And you get something like this:
             Table "public.django_session"
    Column    |           Type           | Modifiers
--------------+--------------------------+-----------
 session_key  | character varying(40)    | not null
 session_data | text                     | not null
 expire_date  | timestamp with time zone | not null
Indexes:
    "django_session_pkey" PRIMARY KEY, btree (session_key)
    "django_session_de54fa62" btree (expire_date)
    "django_session_session_key_461cfeaa630ca218_like" btree (session_key varchar_pattern_ops)

Here you can see which fields are defined as varchar(100).
If you want to know more psql commands, type \?

A: I don't think you need help fixing this problem, so much as you need help debugging it. Once the problem is clear, the solution seems clear as well. The Traceback is perhaps a bit unclear because it's going through so much Django source code and it's not telling you which of your fields is having an issue.
Background To This Issue
To start with, we're having problems saving a Post instance. Well, look at all of these fields you have in your model definition:
 ...
  url = models.URLField(max_length=250, blank=True, null=True)
  video = EmbedVideoField(verbose_name='link',help_text="Youtube", blank=True, null=True)
  content = RichTextUploadingField(config_name='default')
  image = models.ImageField(upload_to='images',blank=True, null=True)
  thumbnail = models.ImageField(upload_to='images', blank=True, null=True)

These may not look like text fields, but a lot of them are variations on text fields because, if you think about it, you're probably not going to store whole files in your database. What you will do instead (and what Django does by default) is store the file somewhere on some disk and then in the database you would store the path to that file so you can retrieve it when you need to.
Further, it's probably a waste to store file-paths in the db as LongText or whatever, so every FileField we have means we've got a field with a max_length whether we specify it or not. Thus, all of the above fields have an implicit max_length. You can actually find this out by reading the Django source code.
Source Examples
I've never used EmbedVideoField, for example, but it turns out to be a subclass of models.URLField, which means it has a max_length by default set to 200 if you do not specify one.
Moreover, your various ImageFields are just subclasses of FileField, which has a max_length default of 100.
How to Debug Problems Like This In the Future?
Now, this doesn't help us to know which of your fields is throwing an error in this case. For that, I would probably set a breakpoint somewhere in the code, probably here:
File "ebagu/main/models.py" in save
   66.       super(Post, self).save(*args, **kwargs)

By "set a breakpoint", I mean the following:
Go to line 65 in the module mentioned above, ebagu/main/models.py and enter the following and save the module: import pdb; pdb.set_trace()
(I actually have a strong preference for ipdb myself, but that requires Ipython, which I also have a strong preference for...)
Run your local server, and run through the steps that produced this issue. You will end up submitting your form and if you look at the console where you started your server, you'll eventually be dumped into a shell right at line 65. This shell is a pdb shell, which has different rules from a normal shell, but you can evaluate your about-to-be-saved Post instance, by looking at the various fields on the instance itself, self, and running Python code in the context of that method call:
(pdb) len(self.image.path)

Using that, I would manually evaluate the various fields and look at which one has this really long entry that is choking the save (probably one of your ImageFields).
Solution with Warnings
Alternately, you can just add a max_length to all of these, but be forewarned that you will most likely need to perform database migrations for any limited text field you change because your database is still going to verify the length of the input against how the column is defined. Here's a good StackOverflow answer looking at exactly this problem.
Footnote
Why didn't this come up before you switched to Postgresql? There are a variety of potential reasons, but it probably has to do with how the previous database was setup vs how the Postgresql database was set up (manually vs Django migrations?).
It may also have to do with whether or not you changed where these things are being stored. Did you change your MEDIA settings so the paths where files are stored got a lot longer?
What you really should be doing is looking directly at your database. Open up a psql instance and ask it to describe your tables for you. It'll tell you which fields are limited to 100 characters and those are the fields giving you problems.

A: Removing the migration files from previous database should solve your problem.

A: The error is due to already saved data in your database being longer than the given characters. You may want to look at the data and consider fixing it or whether the given characters are really the limit you want.
If you are maintaining history for model than you also need to delete data in history table.


text: Q: reading off invariants of a scheme $X$ from $D^b_c(X, \bar{\mathbf{Q}}_\ell)$ Which invariants of a scheme $X$ can be read off from $D^b_c(X, \bar{\mathbf{Q}}_\ell)$ (the bounded derived category of $\bar{\mathbf{Q}}_\ell$-sheaves on $X$, see e.g. [Kiehl-Weissauer])?


text:
Q: Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause     SELECT t0.testid,
 t0.pt500,
 t0.pt600,
 t1.id,
 t1.pt100,
 t1.pt200,
 t1.pt300  ,
     ( SELECT AVG(testid) FROM ab_Test ) AS testid_AVERAGE,
 ( SELECT MIN(testid) FROM ab_Test ) AS testid_MINIMUM,
 ( SELECT MAX(testid) FROM ab_Test ) AS testid_MAXIMUM,
 ( SELECT STDEV(testid) FROM ab_Test ) AS testid_STANDARDDEVIATION,
 ( SELECT SUM(testid) FROM ab_Test ) AS testid_TOTAL,
      ( SELECT COUNT(testid) FROM ab_Test ) AS testid_COUNT FROM sampletest t0
    Join ab_Test t1 ON (t0.testid=t1.id)

This is giving me error. my table structure is like below:
id pt100 pt200 pt300 inverter1 voltage1
1   1   0   2   1   5   20  2   20  0   2016-02-23 16:33:10.080
2   0   0   2   1   5   20  2   20  0   2016-02-23 16:35:40.320
3   0   0   2   1   5   20  2   20  0   2016-02-23 16:39:26.860
4   0   0   2   1   5   20  2   20  0   2016-02-23 16:39:40.133
5   0   0   2   1   5   20  2   20  0   2016-02-23 16:42:20.407
testid pt500 pt600 cdt
1   3   5   2016-02-23 16:33:10.080

when i declare a join i am getting the error as in my question. why it is giving me error and if you can briefly explain me it will be very helpful. when i add group by like below:
group by t0.testid, t0.pt500, t0.pt600, t1.id, t1.pt100, t1.pt200, t1.pt300

I am getting following error.

Subquery returned more than 1 value. This is not permitted when the
  subquery follows =, !=, <, <= , >, >= or when the subquery is used as
  an expression.

I know its a duplicate question but i couldn't understand what the others had explained.

A: Rather hard to figure out what you are doing but it is not correct the way you are doing it. I am guessing as to what you really want but I think this should be pretty close.
with TestValues as
(
    SELECT testid
        , AVG(testid) AS testid_AVERAGE
        , MIN(testid) FROM ab_Test AS testid_MINIMUM
        , MAX(testid) FROM ab_Test AS testid_MAXIMUM
        , STDEV(testid) FROM ab_Test AS testid_STANDARDDEVIATION
        , SUM(testid) AS testid_TOTAL
        , COUNT(testid) AS testid_COUNT
    FROM ab_Test
    group by testid
)

SELECT t0.testid
    , t0.pt500
    , t0.pt600
    , t1.id
    , t1.pt100
    , t1.pt200
    , t1.pt300
FROM sampletest t0
Join ab_Test t1 ON t0.testid = t1.id
join TestValues tv on tv.testid = t0.testid

A: Hope this help.. This code is not tested ..
SELECT t0.testid,
     t0.pt500,
     t0.pt600,
     t1.id,
     t1.pt100,
     t1.pt200,
     t1.pt300  ,
    AVG(testid)  AS testid_AVERAGE,
    MIN(testid)  AS testid_MINIMUM,
    MAX(testid)  AS testid_MAXIMUM,
    STDEV(testid) AS testid_STANDARDDEVIATION,
    SUM(testid)  AS testid_TOTAL,
    COUNT(testid AS testid_COUNT
        FROM sampletest t0
        Join ab_Test t1
        ON t0.testid=t1.id

        group by t0.testid, t0.pt500, t0.pt600, t1.id, t1.pt100, t1.pt200, t1.pt300


text:
Q: Comunicación entre componentes hijos Angular Me gustaría poder llamar a los métodos que tiene un componente hijo desde otro componente que es hijo del mismo padre pero a un nivel mas bajo. Visto esquematicamente:
           |--Hijo B
 Padre A---|
           |--Hijo C---|--Hijo D

A es el padre de todos y tiene dos hijos B y C. C es a la vez el padre de D.
En mi aplicación de Angular el componente B posee una instancia de un mapa y funciones para manejar dicho mapa. C es un componente router que va cambiando el componente D según la aplicación lo requiera.
Componente A
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {

}

HTML componente A
<ng-container>
   <mat-sidenav-container>
      <mat-sidenav>

          <router-outlet></router-outlet>
      </mat-sidenav>
      <mat-sidenav-content >

        <app-map></app-map>
      </mat-sidenav-content>
   </mat-sidenav-container>
</ng-container>

Componente B
@Component({
  selector: 'app-map',
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.css']
})

    export class MapComponent implements OnInit {
      ngOnInit(){...}
      dibujarCapaWMS(nombreCapa:string){...}
      borrarCapaWMS(){...}
      dibujarCoordenadas(coordenadas:any){...}
      obtenerMapaDeIDENA(){...}
      //......//
    }

HTML componente B

Componente C
const routes: Routes = [
  { path: '', redirectTo: '/inicio', pathMatch: 'full' },
  { path: 'inicio', component: PaginaInicioComponent },
  { path: 'edificios', component: EdificiosComponent },
  { path: 'parkings', component: ParkingsComponent },
  //..........//
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

El componente D es cambiado por el router (uno de ellos)
@Component({
  selector: 'app-edificios',
  templateUrl: './edificios.component.html',
  styleUrls: ['./edificios.component.css']
})
export class EdificiosComponent implements OnInit {
  //........//
 /* Quiero llamar a las funciones de MapComponent desde aqui */
}

El componente B siempre es el mismo, y solamente modifica los valores de sus atributos mediante sus funciones. Se trata de una aplicación "tipo Google Maps" en la que el mapa es el mismo y va cambiando según que le mande que haga el componente D.

A: Yo usaría un servicio para comunicar los elementos, porque no tienen una relación directa entre sí y sobrecargar la lógica de sus respectivos padres complicaría mucho el código. Te pongo un ejemplo básico:
@Injectable()
export class MessageService {

    private subject = new Subject<any>();

    sendMessage(message: string) {
        this.subject.next({ text: message });
    }

    clearMessage() {
        this.subject.next();
    }

    getMessage(): Observable<any> {
        return this.subject.asObservable();
    }
}

En tu caso, si quieres evitar un switch para ver qué tipo de mensaje es, podrías crear varios Subjects (para cada tipo de evento), y tus componentes podrían enviar/escuchar diferentes tipos de mensajes en diferentes métodos:
@Injectable()
export class MessageService {

    private subjectAccion1 = new Subject<any>();

    private subjectAccion2 = new Subject<any>();

    hazAccion1(message: string) {
        this.subjectAccion1.next({ text: message });
    }

    hazAccion2(message: string) {
        this.subjectAccion2.next({ text: message });
    }

    escucharAccion1(): Observable<any> {
        return this.subjectAccion1.asObservable();
    }

    escucharAccion2(): Observable<any> {
        return this.subjectAccion2.asObservable();
    }

    ...

}

Entonces el componente que espera órdenes se suscribiría al servicio:
constructor(private msgService: MessageService) { }

ngOnInit() {
  this.observer1 = msgSer.escucharAccion1().subscribe(mensaje => this.cambiarAlgo1(mensaje));
  this.observer2 = msgSer.escucharAccion2().subscribe(mensaje => this.cambiarAlgo2(mensaje));
  //...
}

ngOnDestroy() {
  this.observer1.unsubscribe();
  this.observer2.unsubscribe();
}

¡No te olvides cancelar la subscripción o tendrás memory-leaks!


text:
Q: R custom ordering of character vector by matching the first character I'm trying to sort a vector in R.
This is an example of how the vector looks like:
test = c("Xpsomethingelse", "3qsometext", "22qsomeothertext")

Simple sorting results in:
> sort(test)
[1] "22qsomeothertext" "3qsometext"       "Xpsomethingelse"

However I want to sort in a custom order, based on the first/second character of each string. I have created another vector that represents the order that should be followed
order_custom = c("21","18","13","X","Y","1","2","3","4","5","6","7","8","9","10","11","12","14","15","16","17","19","20","22")

I thought of
test[order(match(test, order_custom))]

But this only matches the complete string, while I'm looking for a match with the start of the string. Everything before the 'p' or 'q' character should be taken into account. The match in regex terms should be this [0-9,X,Y]{1,2} I think. But I don't see how I can sort based on this type of match.
The final result should look like this
[1] "Xpsomethingelse", "3qsometext", "22qsomeothertext"

A: You can use sub to remove p or q and everything afterwards and then use match and order.
test[order(match(sub("[pq].*", "", test), order_custom))]
#[1] "Xpsomethingelse"  "3qsometext"       "22qsomeothertext"

A: You can use your original code providing a regular expressions to match whatever comes before a "p" or a "q":
library(stringi)

test = c("Xpsomethingelse", "3qsometext", "22qsomeothertext")

order_custom = c("21","18","13","X","Y","1","2","3","4","5","6","7","8","9","10","11","12","14","15","16","17","19","20","22")

test[order(match(stri_extract(test, regex=".+(?=[p|q])"), order_custom))]
#> [1] "Xpsomethingelse"  "3qsometext"       "22qsomeothertext"

Created on 2021-07-15 by the reprex package (v2.0.0)

A: Here is a intutional solution to sort by the rank of h3.
library(data.table)
test = c("22qsomeothertext", "3qsometext", "Xpsomethingelse")
order_custom = c("21","18","13","X","Y","1","2","3","4","5","6","7","8","9","10","11","12","14","15","16","17","19","20","22")

dt <- data.table(test)
dt[,`:=`(h1 = substr(test,1,1),
         h2 = substr(test,1,2)) ]

dt[,h3 := fcase(h1 %in% order_custom & !(h2 %in% order_custom), h1,
                h1 %in% order_custom & (h1 %in% order_custom), h2,
                default = NA)]

dt[,rank := match(h3, order_custom)][]
#>                test h1 h2 h3 rank
#> 1: 22qsomeothertext  2 22 22   24
#> 2:       3qsometext  3 3q  3    8
#> 3:  Xpsomethingelse  X Xp  X    4

desired_string <-  dt[order(rank),test]

Created on 2021-07-15 by the reprex package (v2.0.0)