text:
Q: How to change the Country value to a dropdown field This is something that has been terrible since day one in SF.
I want to replace the Country text field to a dropdown (without going into VF).
I have seen several solutions in the AppExchange - but am interested to know if anyone has experience, with a simple to implement solution.
The idea is to have a 3rd field that holds "Region" which is a collection of countries.

A: This may not be 100% what you need, but might at least provide some improvement...
In Spring'13, Salesforce announced the 'State and Country Picklist Beta'. It can be currently configured only via the Metadata API and only once the Salesforce Support team has enabled it for your org. Here is the IdeaExchange page for it, proof enough that at least sometimes our dreams come true! :-)

State and country picklists allow users to select states and countries from predefined, standardized lists, instead of entering state and country data into text fields. State and country picklists allow for faster and easier data entry and help to ensure cleaner data that can be leveraged for other uses—in reports and dashboards, for example—with more dependable results. The state and country names in the picklists are based on ISO-3166 standard values, making them compatible with other applications as well.

Video Demo: http://www.youtube.com/watch?v=osSN804ILlI&feature=youtu.be

A: In spring 13 they have announced "State and Country as picklist". but They are in Beta version right now.

A: I'm unsure how to solve your problem, but we use a free application called CountryComplete which works extremely well and I would greatly recommend.
https://appexchange.salesforce.com/listingDetail?listingId=a0N30000001SqRFEA0
The company that produces it also has a more advanced application called "AddressTools"
Hope this helps.


text:
Q: monitor system users on raspberry pi with akka actors I've a raspberry pi on my network with an LED strip attached to it.
My purpose is to create a jar file that will sit on the pi, monitor system events such as logins and load average, and drive the LED based on the those inputs.
To continuosly monitor the logged in users, I am trying to use akka actors. Using the examples provided here, this is what I've gotten so far :
import com.pi4j.io.gpio.GpioFactory
import com.pi4j.io.gpio.RaspiPin

import sys.process._

import akka.actor.{Actor, Props, ActorSystem}
import scala.concurrent.duration._

val who :String = "who".!!

class Blinker extends Actor {

  private def gpio = GpioFactory.getInstance
  private def led = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_08)

  def receive = {
    case x if who.contains("pi") => led.blink(250)
    case x if who.contains("moocow") => println("falalalala")
  }

  val blinker = system.actorOf(Props(classOf[Blinker], this))

  val cancellable =  system.scheduler.schedule(
    0 milliseconds,
    50 milliseconds,
    blinker,
    who)
}

However, system is not recognised by my IDE (IntelliJ) and it says, cannot resolve symbol
I also have a main object like this:
object ledStrip  {

  def main(args: Array[String]): Unit = {

    val blink = new Blinker
    // blink.receive

  }

}

In main, I'm not quite sure how to initialise the application.
Needless to say, this my first time writing a scala program
Help?
Edit::
Here is the updated program after incorporating what Michal has said
class Blinker extends Actor {

  val who: String = "who".!!

  private val gpio = GpioFactory.getInstance
  private val led = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_08)

  def receive = {
    case x if who.contains("pi") => led.blink(250)
    case x if who.contains("moocow") => println("falalalala")
  }

  val system = ActorSystem()

}

object ledStrip  extends  Blinker {

  def main(args: Array[String]): Unit = {

    val blinker = system.actorOf(Props(classOf[Blinker], this))
    import system.dispatcher

    val cancellable =
    system.scheduler.schedule(
      50 milliseconds,
      5000 milliseconds,
      blinker,
      who)

  }

}

This program compiles fine, but throws the following error upon execution:

Exception in thread "main" java.lang.ExceptionInInitializerError  at
  ledStrip.main(ledStrip.scala) Caused by:
  akka.actor.ActorInitializationException: You cannot create an instance
  of [ledStrip$] explicitly using the constructor (new). You have to use
  one of the 'actorOf' factory methods to create a new actor. See the
  documentation.    at
  akka.actor.ActorInitializationException$.apply(Actor.scala:194)   at
  akka.actor.Actor.$init$(Actor.scala:472)  at
  Blinker.(ledStrip.scala:15)     at
  ledStrip$.(ledStrip.scala:34)   at
  ledStrip$.(ledStrip.scala)    ... 1 more

Edit 2
Code that compiles and runs (behaviour is still not as desired)< blink(1500) is never executed when user: pi logs out from the shell>
object sysUser {
  val who: String = "who".!!
}

class Blinker extends Actor {

  private val gpio = GpioFactory.getInstance
  private val led = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_08)

  def receive = {
    case x if x.toString.contains("pi")  => led.blink(50)
    case x if x.toString.contains("moocow")  => println("falalalala")
    case _ => led.blink(1500)
  }
}

object ledStrip  {
  def main(args: Array[String]): Unit = {
    val system = ActorSystem()

    val blinker = system.actorOf(Props[Blinker], "blinker")
    import system.dispatcher

    val cancellable =
      system.scheduler.schedule(
        50 milliseconds,
        5000 milliseconds,
        blinker,
        sysUser.who)
  }
}

A: Well, it looks like you haven't defined "system" anywhere. See this example for instance:
https://doc.akka.io/docs/akka/current/actors.html#here-is-another-example-that-you-can-edit-and-run-in-the-browser-
you'll find this line there:
 val system = ActorSystem("pingpong")

That's what creates the ActorSystem and defines the val called "system", which you then call methods on.
In the main, I don't think you want to create another instance with "new Blinker", just use:
system.actorOf(Props[Blinker], "blinker")

(which you are already doing and putting it into the "blinker" val)

A: Seems it is just a akka usage issue. I don't know why you do something seems strange, so I change them for change1, change2, change3, FYI.
class Blinker extends Actor {
  val who: String = "who".!!

  private val gpio = GpioFactory.getInstance
  private val led = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_08)

  def receive = {
    case x if who.contains("pi") => led.blink(250)
    case x if who.contains("moocow") => println("falalalala")
  }
}

object ledStrip { // change1
  def main(args: Array[String]): Unit = {
    val system = ActorSystem() // change2

    val blinker = system.actorOf(Props(classOf[Blinker])) // change3
    import system.dispatcher

    val cancellable =
    system.scheduler.schedule(
      50 milliseconds,
      5000 milliseconds,
      blinker,
      who)
  }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: configuring postfix to catch all with a suffix using virtual alias map I'm having problems trying to configure a catch all email in postfix.
I have an email account messages@example.com. All emails sent to this address are piped to a php script.
What I would like to do is forward all emails in the format anything.messages@example.com, e.g. 3454534.messages@example.com and dsf843fdd.messages@example.com, to this email account.
After doing some research I've done the following but to no avail.
In /etc/postfix/main.cf I have added the line
virtual_alias_maps = hash:/etc/postfix/virtual

In /etc/postfix/virtual I have added
/.*messages@example.com   messages

Any help is appreciated! Thanks.

A: Nowhere is it documented that hash maps support this kind of wildcarding - you're probably thinking about regexp or PCRE tables:
http://www.postfix.org/PCRE_README.html
http://www.postfix.org/pcre_table.5.html
Something like this should work:
/etc/postfix/wildcard.pcre:
/^\d+\.message@example\.com$/ message
Note that PCRE maps are not compiled; don't run postmap on them.
However, I would strongly suggest you switch to using recipient delimiters instead; it makes all of this unnecessary.


text:
Q: Having Issue on Selecting Option From Hidden Box in FireFox With jQuery Can you please take a look at This Demo in Firefox browser(it is working fine in Chrome) and let me know why the Select option is not click-able in firefox?
the process is like after selecting international radio the #the-box hidden button which contains a select option will dropdown. It is how ever none select-able in firefox!
$('input:radio[name=map]').on('change', function () {
    var val = $('input:radio[name=map]:checked').val();
    switch (val) {
        case 'local':
             $('#the-box').hide().removeClass('hidden').slideUp();
            break;
        case 'international':
            $('#the-box').hide().removeClass('hidden').slideDown();
            break;

    }
});

A: You html is wrong because HTML5 doesn't allow interactive elements (such as select) within buttons., you cannot add a select inside a button. fixed it for you here:
Here is the working demo
HTML:
<input type="radio" name="map" value="local" />Local

<input type="radio" name="map" value="international" />International

    <button type="button" class="list-group-item"> Minimize Overlap Between Projects And:
    </button>
    <button type="button" class="list-group-item hidden" id="the-box"></button>

<select class="selectpicker">
            <option>Mustard</option>
            <option>Ketchup</option>
            <option>Relish</option>
        </select>

jQuery:
$('select').selectpicker();
$('input:radio[name=map]').on('change', function () {
    var val = $('input:radio[name=map]:checked').val();
    switch (val) {
        case 'local':
             $('#the-box').hide().removeClass('hidden').slideUp();
            break;
        case 'international':
            $('.wrapper').hide().removeClass('hidden').slideDown();
            break;

    }
});

Note that your <option> must contain a value otherwise it will save nothing so proper option: <option value="volvo">Volvo</option>


text:
Q: How to create a common code module for use with cloud functions or docker I have a typescript monorepo with front end, cloud functions, and back end (docker) packages in it. I'd like to add a "common" package that can be used by all of those.
Some production environments like Google Cloud Functions and Docker (at least in one common usage) package up the current app's directory and send it to a remote server, where it does "yarn install" to install all the dependencies.  This means the obvious ways of referencing the common package (import * as common from "../../common" and the like) don't work because the build server won't find common there.
Also, sadly, docker and GCF don't follow symlinks, so the yarn link: protocol isn't helpful.
And since I'm working on the common code just as much as the apps, I really don't want to publish it to a private NPM registry every time I make a change. I'd like that change process to be as seamless as possible.
The most seamless way is to just symlink common into each app's node_modules, but (a) yarn deletes those, and (b) the builders don't follow symlinks. So I assume I'll need some kind of build/push process when changing the common code.
It seems like a kind of common thing to want to abstract out common code into its own module that can be used anywhere in the monorepo, but I can't find a solution that works. (For extra points I'd like "jump to definition" in my IDE to go to the actual definition, not a local copy.) Any ideas? Can Yarn 2 help with this use case?


text:
Q: Cocoa way to represent data for iphone dev I come from heavy web application dev background, and having some problems representing my related data structures the right way in iPhone dev (the 'Model' part of MVC).
Lets say I have a data structure which is best represented via JSON like this:
{
    "Beethoven": {
        "description": "Another great composer",
        "pictures": [
            "pic1",
            "pic2",
            "pic3"
        ]
    },
    "Mozart": {
        "description": "Great Austrian composer",
        "pictures": [
            "pic1",
            "pic2",
            "pic3"
        ]
    }
}

This works great in Python/Django, but what would be the right approach for iPhone dev?
Eventually this would be stored in a property list (as the data won't too big/complex).
Should I create Composer class to represent top level objects?  or some other way?

A: You propably want to use CoreData. This framework allows you to create an abstract model of your data, just like for databases, and to use it in your app without writing a single line of code. It also provides independence of your persistent data storage, so you can switch between different types of storage (SQLite, XML...) easily. I quite liked this tutorial but you might also want to check out the official documentation.


text:
Q: Не получается настроить IPv6 в Ubuntu 16.04 Взял VPS, где для включения IPv6 необходимо убрать комментарии со строк конфигурации в /etc/network/interfaces. Получилось так:
iface ens3 inet6 static
address 2001:41d0:302:2200::f32
gateway 2001:41d0:302:2200::1
netmask 128
dns-nameservers 2001:4860:4860::8888 2001:4860:4860::8844
post-up /sbin/ip -6 route add 2001:41d0:302:2200::f32 dev eth0
post-up /sbin/ip -6 route add default via 2001:41d0:302:2200::f32 dev eth0
pre-down /sbin/ip -6 route del default via 2001:41d0:302:2200::f32 dev eth0
pre-down /sbin/ip -6 route del 2001:41d0:302:2200::f32 dev eth0

Но IPv6 так и не заработал.
При попытке пропинговать IPv6 сервер получаю ошибку:

connect: Network is unreachable

Что я сделал не так?


text:
Q: Kamon error with configuration 'requires-aspectj' I'm adding kamonto my standalone akka application and i'm getting this error:
com.typesafe.config.ConfigException$Missing: No configuration setting found for key 'requires-aspectj' error at Kamon.start().
This is the relative content of application.conf.
{
...
  modules {
    kamon-akka {
      auto-start = no
    }
    kamon-statsd {
      auto-start = no
    }
    kamon-system-metric {
      auto-start = no
      requires-aspectj = no
      extension-id = "kamon.system.SystemMetrics"
    }
  }
}

application.conf: 36: requires-aspectj has type STRING rather than OBJECT
However, when I include the asked property
{
  modules {
    requires-aspectj = no
  ...
  }
}

I get this error: application.conf: 36: requires-aspectj has type STRING rather than OBJECT
If i remove Kamon.start() my application starts as usual
This is an extract of the my build.sbt:
lazy val root = (project in file("."))
  .settings(name := "kamon-akka")
  .settings(Seq(scalaVersion := "2.11.8"))
  .settings(libraryDependencies ++= Seq(
    akka.Http,
    akka.slf4jApi,
    akka.akkaSlf4j,
    kamon.Core,
    kamon.Akka,
    kamon.LogReporter,
    kamon.SystemMetrics,
    aspectj.aspectjtools,
    aspectj.aspectjweaver,
    aspectj.aspectjrt
  ))
  .settings(aspectjSettings: _*)

PS:

*

*kamon = 0.6.7

*aspectj = 1.8.9

*sbt 0.13.13

*scala 2.12.3

*I'm also using this plugin addSbtPlugin("com.typesafe.sbt" % "sbt-aspectj" % "0.9.4")
any ideas?

A: First, your application.conf looks strange in that it doesn't appear to have a kamon namespace. It should look like the following (take note of the first line):
kamon {
  ...
  modules {
    kamon-akka {
      ...
    }
    kamon-statsd {
      ...
    }
    kamon-system-metrics {
      ...
    }
  }
}

Second, since you're using the sbt-aspectj plugin, add the following to your build.sbt (source: http://kamon.io/documentation/get-started/):
import com.typesafe.sbt.SbtAspectj._

// Bring the sbt-aspectj settings into this build
aspectjSettings

// Here we are effectively adding the `-javaagent` JVM startup
// option with the location of the AspectJ Weaver provided by
// the sbt-aspectj plugin.
javaOptions in run <++= AspectjKeys.weaverOptions in Aspectj

// We need to ensure that the JVM is forked for the
// AspectJ Weaver to kick in properly and do it's magic.
fork in run := true


text:
Q: How to use UISegmentControl to change detailViewController of CoreData I have implemented a UISegmentControl as the rightBarButton of my detailViewController.
This view controller displays that of the information passed through from a UITableView.
This UITableView's cells are populated with CoreData attribute values.
What I want to do is enable the user to go up and down in the list via the detailViewController. Instead of having to make the user have to go back to the rootViewController, they'll gain the ability to scroll through via the UISegmentControl.
I currently have this in my detailViewController.m
 - (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
 // Setting up UISegmentedControl

// Segmented Control - Custom right bar button with a view
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:
                                        [NSArray arrayWithObjects:
                                         [UIImage imageNamed:@"arrowdown.png"],
                                         [UIImage imageNamed:@"arrowup.png"],
                                         nil]];

[segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];

segmentedControl.frame = CGRectMake(0, 0, 75, 30);
segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
segmentedControl.momentary = YES;

UIBarButtonItem *segmentBarItem = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl];
[segmentedControl release];

self.navigationItem.rightBarButtonItem = segmentBarItem;
[segmentBarItem release];
  }

This is then attached to the following method, for detecting the tapped control.
 - (void)segmentAction:(id)sender
 {
UISegmentedControl* segCtl = sender;
// the segmented control was clicked, handle it here

if([segCtl selectedSegmentIndex]==0){
    NSLog(@"You clicked the down arrow - the segment clicked was %d", [segCtl selectedSegmentIndex]);
}else {

    NSLog(@"You clicked the up arrow - the segment clicked was %d", [segCtl selectedSegmentIndex]);

}

}

I am also curious as to whether or not anyone knows how to detect whether or not there is anymore to go to. So say, if the note loaded is in the first position, then the down arrow is disabled, and if the note loaded is in the last position, the up arrow is disabled. Is this even possible?
Any help would be greatly appreciated.

A: I'd suggest you to create a formal protocol MyDataSource which provides methods for accessing the data. As a minimum, there must be a method to get number of data objects and object for a specified index.
In your DetailViewController you should have a reference to an object which conforms to MyDataSource. I'd recommend you to use instance of RootViewController as a data source for DetailViewController.
You should also keep track of index of the object that is currently displayed in DetailViewController and update UI appropriately.


text:
Q: Got invalid expression error , while inserting JSON data into VARIANT column Trying to insert multiple rows into a snowflake table
insert into sample_table  (a, b, c) values ('foo','bar',parse_json($${"def": 1}$$)),('doo','bam',parse_json($${"def": 1}$$));

Have tried replacing '$$' with single quotes
Getting error:

SQL compilation error: Invalid expression [PARSE_JSON('{"def":1}')] in VALUES clause

What am I doing wrong?

A: You cannot use PARSE_JSON in the values section. But you can do a
create table sample_table(a text, b text, c variant);

insert into sample_table
  select column1, column2, parse_json(column3) from values
    ('foo', 'bar', '{"def": 1}'),
    ('doo', 'bam', '{"def": 1}');

number of rows inserted

2


text:
Q: Getting information about a current status of an Brodcast value without receiving a message I managed it to receive information about a status beeing changed, but how can I just checkt the current status?
For Example:
When the bluetoothadapter changes the connectivity information, I can update the UI but when I start the app and want to show the current state (which didn't changed, so I didn't received an msg) it dosen't work... Some ideas?
BroadcastReceiver cBT_receive = new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
          int iBT_adapter_state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, mBluetoothAdapter.ERROR);
          int iBT_connection_state = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE, mBluetoothAdapter.ERROR);
          ImageView Warning_image = findViewById(R.id.Status_Image);

          if(mBluetoothAdapter.ACTION_STATE_CHANGED.equals(intent.getAction()))
          {

              switch (iBT_adapter_state)
              {
                  case BluetoothAdapter.STATE_TURNING_ON:
                      Toast.makeText(context, "Bluetooth is turning on",Toast.LENGTH_SHORT).show();
                      Warning_image.setImageResource(R.mipmap.bt_foreground_yellow);
                      break;

                  case BluetoothAdapter.STATE_ON:
                       Toast.makeText(context, "Bluetooth is on",Toast.LENGTH_SHORT).show();

                      break;
              }
          }
          if (mBluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED.equals(intent.getAction()))

              switch (iBT_connection_state)
              {
                  case BluetoothAdapter.STATE_CONNECTED:
                      Toast.makeText(context, "Bluetooth is connected",Toast.LENGTH_SHORT).show();
                      Warning_image.setImageResource(R.mipmap.bt_foreground_green);
                      break;

                  case BluetoothAdapter.STATE_DISCONNECTED:
                      Toast.makeText(context, "Bluetooth is disconnected",Toast.LENGTH_SHORT).show();
                      Warning_image.setImageResource(R.mipmap.bt_foreground_red);
              }

      }
  };

The code above gives e Information when the status changed but not about the current status.

A: I got it:
if(mBluetoothAdapter.isEnabled())
{
    int icurrent_BT_state = mBluetoothAdapter.getState();

    switch (icurrent_BT_state)
    {
        case BluetoothAdapter.STATE_ON:
            Toast.makeText(context, "Bluetooth is already on", Toast.LENGTH_SHORT).show();
            break;

        case BluetoothAdapter.STATE_CONNECTED:
            Toast.makeText(context, "Bluetooth is already connected", Toast.LENGTH_SHORT).show();
            break;
    }
}

Solution: getState()


text:
Q: Is it possible to display a modal window in SCSF application at the center of the screen In SCSF application I would like to display a view as a modal window at the center of the screen. Is it possible to do that?
WindowSmartPartInfo doesn't have any option for setting screen postion.
Thanks.

A: Assuming you're talking about Winforms, not WPF since the WPF layer for CAB does expose this option. In winforms there is no option in the WindowSmartPartInfo to do this. However, you could extend it and extend WindowWorkspace to use your new SmartPartInfo (override the OnApplySmartPartInfo method).
Before you do this, you might want to check the contrib and community sites to see if anyone has already done it. I think I've seen one somewhere.


text:
Q: Can't create Google internet account I want Apple Mail to talk to a gmail account. In System Preferences, when I say I want a new Google account, I get a dialog that says

Google requires completing authentication in your web browser

So I click the button and immediately I see another dialog

Failed to authenticate with Google, please try again later

There is no evident communication with the browser, so I can't authenticate. I've also tried creating a normal manual mail account, but no better luck.
I have turned on Less Secure App Access for the account I want to use. I have no difficult logging into this account using the web (gmail.com), but I don't want to handle my mail that way; I need it to be part of my mail.
This has worked fine on other machines. This one is Catalina 10.15.7.

A: I was able to resolve the same issue by restarting the computer in safe mode and then adding the account as a Google account in the Internet Accounts prefpane. It opened the browser window and allowed me to authenticate.
Now that I've restarted out of safe mode the account is still working, and adding new accounts appears to be working again too. I have no idea why though!

A: This answer is likely not going to be useful, but the problem just mysteriously fixed itself. In Internet Accounts pref pane, I created a new account with Add Other Account (not Google), entered the information, and the account sprang to life successfully. I have no idea why.
All of this has something to do, I'm pretty sure, with the new use of OAuth by Google. Maybe it sometimes just doesn't work at the server end. I came into the process this time armed with the concept "OAuth" in my head, but unless the computer (or Google) was reading my mind, it was never actually used during setup.
It is interesting that, peeking into Keychain Access, on my Big Sur machine, my google accounts have OAuth entries, but my Catalina keychain has no such entries. This makes me think that Catalina just doesn't really understand OAuth, even when updated to the latest version.


text:
Q: Like, Reblog, and Follow functions I'm trying to create a really Like, Reblog, and Follow function in my PermalinksPagination section of my coding on Tumblr.
It seems that most Themes place these functions between the {block:Posts} and {/block:posts}, but I am trying to put these functions in between the {block:PermalinkPagination} and {/block:PermalinkPagination}
Can anyone help?

A: To insert a like- or reblog-button, simply input this code wherever you'd like it to be:
{ReblogButton size="21" color="black"}
{LikeButton size="20" color="black"}


text:
Q: What's the checksum algorithm for AnViz devices? I'm working on a way to directly connect to an AnViz biometric device(TC550, which uses TC400.dll methods) by TCP from Linux/PHP, however and thus I managed to get some strings for reading out of the device, I'm having a hard time to figure out the checksum which appears on the last 2 bytes of each code to send my own instructions to the device.
An example of a working code might be:
      function get_device_clock(){
      if(!$this->ip) return;
      if(!$this->open_socket()) return;
      $bytes = "A5";
      $bytes .= $this->fill_hex($this->id,8);
      $bytes .= "380000C4B8";

      $o = $this->comm($bytes);
      if(!trim($o)) return;
      $split = array();
      for($l = 0; $l < strlen($o); $l+=2){
          $split[] = substr($o,$l,2);
      }
      $year = hexdec($split[9]);
      if($year < 10) $year = "0" . $year;
      $year = "20$year";
      $month = hexdec($split[10]);
      if($month < 10) $month = "0$month";
      $day = hexdec($split[11]);
      if($day < 10) $day = "0$day";
      $hour = hexdec($split[12]);
      if($hour < 10) $hour = "0$hour";
      $min = hexdec($split[13]);
      if($min < 10) $min = "0$min";
      $sec = hexdec($split[14]);
      if($sec < 10) $sec = "0$sec";
      fclose($this->socket);
      return "$year-$month-$day $hour:$min:$sec\r\n";
  }

This will be sending A5 00 00 05 38 00 00 C4 B8 to the device at port 5010 causing it to reply with its time and date.
As this would enable realtime:
A5 00 00 00 05 33 00 0F FF FF FF FF 01 FF FF FF FF FF FF FF FF FF FF 4E 37
This would list the last entries:
A5 00 00 00 05 40 00 02 01 19 FA FA
A5 00 00 00 06 3C 00 00 68 FE
A5 00 00 00 05 3C 00 00 A5 DB
Now the issue is, the last 2 bytes, C4 B8 at the first example, 4E 37 at the second, FA FA at the third, 68 FE and A5 DB on that where the ID is changed from 5 to 6, seams to be some sort of checksum. I'd tried all variants of common algorithms, even used Fsum Frontend, with all variants of byte ordering without success so far.
Also appears to have some variance in longer instructions, like these:
a5 00 00 00 05 73 00 29  01 00 00 00 00 17 ff ff ff 00 12 d6 93 00 58 00  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00 40 6e 57
a5 00 00 00 05 73 00 29  01 00 00 00 00 01 10 00 01 3e eb 18 08 00 54 00  65 00 73 00 74 00 00 00 00 00 00 00 00 00 00 00  00 00 01 00 00 00 00 00 50 6f 54
Where in this case the checksum appears to be 40 6E 57 and 50 6F 54
Notes:
Requests seams to be composed of:
A5 + 4 bytes Serial# of the device + 1 byte Instruction code + variable length Content + 16/24 bits Checksum
You can get the SDK which generates this codes, tc400.dll, at SDK BIO-OFFICE
Any help to sort this out would be appreciated. TY in advance.
*UPDATE - Solved thanks to the Anviz Support Team *
Working code:
<?php
 $crc_table = [
      0x0000,0x1189,0x2312,0x329B,0x4624,0x57AD,0x6536,0x74BF,0x8C48,0x9DC1,0xAF5A,0xBED3,0xCA6C,0xDBE5,0xE97E,0xF8F7,
    0x1081,0x0108,0x3393,0x221A,0x56A5,0x472C,0x75B7,0x643E,0x9CC9,0x8D40,0xBFDB,0xAE52,0xDAED,0xCB64,0xF9FF,0xE876,
    0x2102,0x308B,0x0210,0x1399,0x6726,0x76AF,0x4434,0x55BD,0xAD4A,0xBCC3,0x8E58,0x9FD1,0xEB6E,0xFAE7,0xC87C,0xD9F5,
    0x3183,0x200A,0x1291,0x0318,0x77A7,0x662E,0x54B5,0x453C,0xBDCB,0xAC42,0x9ED9,0x8F50,0xFBEF,0xEA66,0xD8FD,0xC974,
    0x4204,0x538D,0x6116,0x709F,0x0420,0x15A9,0x2732,0x36BB,0xCE4C,0xDFC5,0xED5E,0xFCD7,0x8868,0x99E1,0xAB7A,0xBAF3,
    0x5285,0x430C,0x7197,0x601E,0x14A1,0x0528,0x37B3,0x263A,0xDECD,0xCF44,0xFDDF,0xEC56,0x98E9,0x8960,0xBBFB,0xAA72,
    0x6306,0x728F,0x4014,0x519D,0x2522,0x34AB,0x0630,0x17B9,0xEF4E,0xFEC7,0xCC5C,0xDDD5,0xA96A,0xB8E3,0x8A78,0x9BF1,
    0x7387,0x620E,0x5095,0x411C,0x35A3,0x242A,0x16B1,0x0738,0xFFCF,0xEE46,0xDCDD,0xCD54,0xB9EB,0xA862,0x9AF9,0x8B70,
    0x8408,0x9581,0xA71A,0xB693,0xC22C,0xD3A5,0xE13E,0xF0B7,0x0840,0x19C9,0x2B52,0x3ADB,0x4E64,0x5FED,0x6D76,0x7CFF,
    0x9489,0x8500,0xB79B,0xA612,0xD2AD,0xC324,0xF1BF,0xE036,0x18C1,0x0948,0x3BD3,0x2A5A,0x5EE5,0x4F6C,0x7DF7,0x6C7E,
    0xA50A,0xB483,0x8618,0x9791,0xE32E,0xF2A7,0xC03C,0xD1B5,0x2942,0x38CB,0x0A50,0x1BD9,0x6F66,0x7EEF,0x4C74,0x5DFD,
    0xB58B,0xA402,0x9699,0x8710,0xF3AF,0xE226,0xD0BD,0xC134,0x39C3,0x284A,0x1AD1,0x0B58,0x7FE7,0x6E6E,0x5CF5,0x4D7C,
    0xC60C,0xD785,0xE51E,0xF497,0x8028,0x91A1,0xA33A,0xB2B3,0x4A44,0x5BCD,0x6956,0x78DF,0x0C60,0x1DE9,0x2F72,0x3EFB,
    0xD68D,0xC704,0xF59F,0xE416,0x90A9,0x8120,0xB3BB,0xA232,0x5AC5,0x4B4C,0x79D7,0x685E,0x1CE1,0x0D68,0x3FF3,0x2E7A,
    0xE70E,0xF687,0xC41C,0xD595,0xA12A,0xB0A3,0x8238,0x93B1,0x6B46,0x7ACF,0x4854,0x59DD,0x2D62,0x3CEB,0x0E70,0x1FF9,
    0xF78F,0xE606,0xD49D,0xC514,0xB1AB,0xA022,0x92B9,0x8330,0x7BC7,0x6A4E,0x58D5,0x495C,0x3DE3,0x2C6A,0x1EF1,0x0F78
 ];
 /*************************************************
 * Calc CRC16 for Anviz TC-300,TC-400,TC-500,TC-550
 *
 * @param binary $b
 */
 function tc_crc16($b){
  global $crc_table;
  $crc = 0xFFFF;
  for($l = 0; $l < strlen($b); $l++){
      $crc ^= ord($b[$l]);
      $crc = ($crc >> 8) ^ $crc_table[$crc & 255];
  }
  $res = strtoupper( dechex($crc) );
  return($res[2].$res[3].$res[0].$res[1]);
}

/*****TEST AREA*****/
//$x = "A5000000033C0000"; //A5000000033C00003F90
 $x = "A5000000057300290100000000011000013EEB180800540065007300740000000000000000000000000001000000000050"; //A5000000057300290100000000011000013EEB1808005400650073007400000000000000000000000000010000000000506F54
echo tc_crc16(hex2bin($x));
?>

A: I consulted the R&D team and they informed me that the problem is with CRC16 checksum. Please download the CRC.rar file that contains CRC16Demo and let me know if that works better for you.
http://download.anviz.com/felix/CRC.rar
Kind Regards,
Anviz Support Team
http://anviz.com

A: I know this is an old question/answer, but it was the only useful thing I could find relating to Anviz that wasn't for Windows, so I though I would update it with some more info in case anyone else needs it in the future:
Command format

STXCH    (device code)    CMD(command)     LEN(data length)      DATA        CRC16
0xA5        4Bytes            1Byte              2Bytes         0-400Bytes    2Bytes

Response format

STX CH   (device code)    ACK(response)       RET(return value)     LEN(data length)        DATA       CRC16
0xA5        4Bytes      1Byte(command+0x80)      1Byte                  2Bytes            0-400Bytes    2Bytes

Description

*

*Order of four byte CH:IDHH,IDHL,IDLH,IDLL;

*CRC16 check means all data CRC16,order of two byte CRC16:CRCL CRCH;

*When CH is 0,all devices connected will response to this command.

*RET define as :

*

*define ACK_SUCCESS            0x00            // operation successful

*define ACK_FAIL                   0x01            // operation failed

*define ACK_FULL               0x04            // user full

*define ACK_EMPTY              0x05            // user empty

*define ACK_NO_USER            0x06            // user not exist

*define ACK_TIME_OUT           0x08            //capture timeout

*define ACK_USER_OCCUPIED      0x0A            //user already exists

*define ACK_FINGER_OCCUPIED    0x0B            //fingerprint already exists

*When the RET != ACK_SUCCESS, the DATA and LEN in the response data are always 0.

Commands
I've uploaded the communications protocol document from Anviz tech support to https://github.com/benperiton/anviz-protocol


text:
Q: setting a timeout for every new socket node.js As I'm building my own http module relying on net module, I want to set a timeout for every new socket.
I build the following:
server = net.createServer(function (socket) {
          if(server.timeout==null){
                server.timeout=120000;
                if(server.timeoutCallBack==null){
                    server.timeoutCallBack=function(){socket.destroy();};
                }
            }
          socket.setTimeout(server.timeout,server.timeoutCallBack());

so if the user of my server, set a new timeout duration , it will use it. if not, it has a default value of 2 minutes.
My problem is that my server doesn't serve the first connection, just the second. I mean, for the first http message it gets, it doesn't invoke my :
            socket.on("data", function (data) {
            });

A: The thing you passed to socket.setTimeout as your callback is the result of server.timeoutCallBack(), which is undefined. Instead of calling timeoutCallBack 2 minutes after that line, you called it on that line and setTimeout of nothing.
You should pass a reference to a function to setTimeout instead:
socket.setTimeout(server.timeout,server.timeoutCallBack);


text:
Q: Can't set custom font to the Button I have a Button, using like this <android.widget.Button, because of needs to set up custom background (read more about issue with DayNight theme and Buttons). Next I need set custom font, see my style below. In Studio designer panel custom font looks good, but running on device there is Roboto (default) font instead of my custom font (Nunito). Any suggestions? AS4.1.2/API30
<style name="ButtonGetStarted" parent="Widget.MaterialComponents.Button">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">60dp</item>
    <item name="android:textAllCaps">false</item>
    <item name="android:textSize">24sp</item>
    <item name="android:textStyle">bold</item>
    <item name="android:textColor">@color/text_invert</item>
    <item name="android:fontFamily">@font/app_font</item>
    <item name="android:background">@drawable/button_selector_get_started</item>
</style>

app_font.xml:
<font-family xmlns:app="http://schemas.android.com/apk/res-auto">
    <font
        app:fontStyle="normal"
        app:font="@font/nunito_regular" />

    <font
        app:fontStyle="italic"
        app:font="@font/nunito_regular_italic" />

</font-family>

A: Create a TextAppearance
here example
 <style name="TextAppearance.Robin.Button" parent="TextAppearance.MaterialComponents.Button">
            <item name="fontFamily">@font/dosis_medium</item>
                <item name="android:fontFamily">@font/dosis_medium</item>
                <item name="android:textSize">15sp</item>
</style>

Now Set the TextAppearance in Your Button Style
<style name="ButtonGetStarted" parent="Widget.MaterialComponents.Button">
 <item name="android:textAppearance">@style/TextAppearance.Robin.Button</item>
   .
   .
   .
   .
</style>

here reference to the MDC guide
Also you can use button itself
<Button
android:textAppearance:"android:textAppearance="@style/yourstYle
/>


text:
Q: Limit number of rows in Cursor query I need to get contacts from an android phone. so I am using this code:
Cursor phones = getActivity().getContentResolver().query(Phone.CONTENT_URI,
    new String[] { Phone.NUMBER, Phone.TYPE },
    " DISPLAY_NAME = ?", new String[] { displayName }, null);
while (phones.moveToNext()) {
   //do work here
}

I want to tell the cursor to limit the response to 50 with something like "LIMIT 50". Where do I pass that information to the cursor? Please copy and paste my code and make edit there.

A: There is no limit in Android API, but you can apply it in your code like this:
Cursor phones = getActivity().getContentResolver().query(Phone.CONTENT_URI,
    new String[] { Phone.NUMBER, Phone.TYPE },
    " DISPLAY_NAME = ?", new String[] { displayName }, null);
for (int i = 0; i < 50 && phones.moveToNext(); ++i) {
   // do work here
}
phones.close();

A: Order by id DESC Limit 1:
db.query("table", null, "column=?", new String[]{"value"}, null, null, "id DESC", "50");

A: If you have the DB and the table name you can use that, but Content providers don't have a limit argument in their query statement.
mDb = new DBHelper (this);

Cursor c = mDB.getReadableDatase().query(
       <Phone_Table_Name>,
       new String[] { Phone.NUMBER, Phone.TYPE },
       "DISPLAY_NAME = ?",
       new String[] { displayName }, null),
       null,
       null,
       null,
       "50");


text:
Q: Showing that $\frac{aA+bB+cC}{a+b+c}\geq\frac\pi3$ for $A$, $B$, $C$ the angles, and $a$, $b$, $c$ the sides, of a triangle
Let $A,B,C$ be the magnitude (in radians) of the three angles of a triangle, and let $a,b,c$ be the lengths of the sides opposite to these angles respectively. Prove that $$\frac{aA+bB+cC}{a+b+c}\geq\frac\pi3$$

Attempt:
WLOG, $A\geq B\geq C$.
As $A+B+C=\pi$, this implies $\frac{A+B+C}3=\frac\pi3$. We also note that by sine rule: $$\frac a{\sin A}=\frac b{\sin B}=\frac c{\sin C}=d$$
for some $d$. This implies $a=d\sin A$, $b=d\sin B$, $c=\sin C$. Using these substitutions:
$$\frac{Ad\sin A+Bd\sin B+Cd\sin C}{d\sin A+d\sin B+d\sin C}\geq\frac{A+B+C}3$$
$$A\sin A+B\sin B+C\sin C\geq\frac{A+B+C}3(\sin A+\sin B+\sin C)$$
$$\frac{A\sin A+B\sin B+C\sin C}3\geq\frac{A+B+C}3\frac{\sin A+\sin B+\sin C}3$$
If we assume $A,B,C\leq\frac\pi2$, then we note that in the interval $\left[0,\frac\pi2\right]$, $\sin x$ is monotonically increasing, hence $\sin A\geq\sin B\geq\sin C$. Then by Chebyshev's inequality, the above inequality is true.
But if $A>\frac\pi2$, it is not necessarily true that $\sin A\geq\sin B\geq\sin C$, and I cannot apply Chebyshev's inequality! What should I do in such a case?
I did wonder if I could apply Jensen's inequality, but the function $x\sin x$ has an inflection point in the interval $[0,\pi]$ so I could not use it.

A: Suppose $a \geqslant b \geqslant c,$ then $A \geqslant B \geqslant C.$ By the Rearrangement inequality, we have
$$3(aA+bB+cC) \geqslant (A+B+C)(a+b+c) = \pi(a+b+c),$$
or
$$\dfrac{aA+bB+cC}{a+b+c} \geqslant\frac{\pi}{3}.$$


text:
Q: Everyone turns their attention toward/Everyone's attention turns toward There's a party. Yelling can be heard from a bathroom.

Everyone turns their attention toward the bathroom. Just then, the door bursts open and Fred comes storming out, followed by Selma.

Everyone's attention turns toward the bathroom. Just then, the door bursts open and Fred comes storming out, followed by Selma.

Are either okay?

A: Both are acceptable, but there is a difference. The choice of subject in English can affect how intent and cause and effect are expressed.
In "everyone turns their attention toward ...," the subject is "everyone." With the following verb, this evokes the idea of intent: that the people in question (who are the subject of the sentence) are deliberately taking an action, shifting their attention to the bathroom. The cause of the action being described originates with the people ("everyone").
On the other hand, in "everyone's attention turns toward ...," the subject is no longer the people, but their attention. The idea of intent is gone, opening this up to the idea that some external factor caused the attention to shift. The cause of the action being described originates somewhere else: in this case, with the yelling described in the preceding sentence.

A: Both are grammatical and idiomatic in modern U.S. English.
There is an old-fashioned view that, because "everyone" is singular, "their" should be replaced by "his," with "his" implying nothing about sex, or by "his or her." Some writers might subscribe to such a view, but American idiom finds "their" to be perfectly acceptable when used in a singular sense without any implication as to sex.
To avoid all this, some might prefer your second version, which simply avoids the issue of what pronoun goes with "everyone" when no implication of sex is warranted, but that is an issue of style rather than grammar.


text:
Q: In an ASP.NET MVC 3 intranet app, how to modify a view depending on user's AD group membership? In our ASP.NET MVC 3 intranet application, configured with WindowsTokenRoleProvider for authentication, users must be members of a certain AD group in order to access administrative content. We have solved this by applying AuthorizeAttribute to the administrative MVC controller. However, we haven't integrated the administrative content with the GUI menu system yet.
To this end, we'd like to add links to the administrative sections to the app menu, but for authorized users only. This brings us to the question at hand, how can we in the view template (*.cshtml) render content depending on whether the user is part of the required AD group or not?

A: You can try something like below
                        @if (User.IsInRole("Manager"))
                    {
                          <li>@Html.ActionLink("Approvals", "TeamIndex", "Leave")</li>
                    }


text:
Q: MediaQueueItem And RemoteMediaItem, how can i make queue to cast? As you can see in the code below, I've come across a great Google Cast SDK feature, how to create a play queue?
Right now I have managed to transmit video and information to chrome cast (at the moment), I have ready the .css splash that they request for the start of the application, in fact it is almost ready! ... in Google Devlopers reading the documentation I came across the section "Queueing" which shows the following code:
MediaQueueItem queueItem = new MediaQueueItem.Builder(mediaInfo)
    .setAutoplay(true)
    .setPreloadTime(20)
    .build();

The million dollar questions are...

*

*Where should I put that code?

*How can I add lists to Google Cast?

*How do I update the lists, once finished?

A: Use this method on the Android sender to load a queueItem: https://developers.google.com/android/reference/com/google/android/gms/cast/framework/media/RemoteMediaClient.html#load(com.google.android.gms.cast.MediaLoadRequestData)
Example: https://developers.google.com/cast/docs/android_sender/integrate#load_media

*

*That will contain this request data: https://developers.google.com/android/reference/com/google/android/gms/cast/MediaLoadRequestData

*Inside that is the MediaQueueData: https://developers.google.com/android/reference/com/google/android/gms/cast/MediaQueueData
...which contains items and that should be set to the MediaQueueItem(s) from the guide: https://developers.google.com/cast/docs/android_sender/queueing#create_and_load_media_queue_items


text:
Q: fibonacci using fork() in the child process I wrote the code below for homework purposes. When I run it on XCode in OSX, after the sentence "Enter the number of a Fibonacci Sequence:", I enter the number 2 times. Why 2 and only 1 scanf.
The code :
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>

int main()

{

int a=0, b=1, n=a+b,i;

printf("Enter the number of a Fibonacci Sequence:\n");
scanf("%d ", &i);

pid_t pid = fork();
if (pid == 0)
{
    printf("Child is make the Fibonacci\n");
    printf("0 %d ",n);
    while (i>0) {
        n=a+b;
        printf("%d ", n);
        a=b;
        b=n;
        i--;
        if (i == 0) {
            printf("\nChild ends\n");
        }
    }
}
    else
    {
        printf("Parent is waiting for child to complete...\n");
        waitpid(pid, NULL, 0);
        printf("Parent ends\n");
    }
    return 0;
}

A: You have a space after %d in your scanf. Try scanf("%d", &i);.

A: When you call fork(), both processes get their own copies of stdout and the message in the buffer gets duplicated.
So in order to solve this problem you will have to flush stdout just before forking.
Solution:
Write fflush(stdout) just after printf("Enter the number of a Fibonacci Sequence:\n")


text:
Q: Determine expected lifetime of a TV purchased from 1 of 3 factories, using LIE. Problem Statement:
Consider a TV made in one of three factories, namely, A,B, and C. Note that the quality of work done at each factory is different. The pdf of time to failure, X, is given as $f_X^k(x)=\frac{1}{\lambda_k}e^{-\frac{x}{\lambda_k}}$ for $x\geq0$, zero otherwise, where $k=A,B,$ or $C$ and $\lambda_A=5,\lambda_B=6.5,$ and $\lambda_c=10.$ Here factory $A$ produces 3 times as many TVs as factory $B$ and factory $B$ produces twice as many TVs as factory $C$. The TVs are all sent to a central warehouse, mixed together, and then shipped to retail stores internationally. Determine the expected lifetime of a TV purchased at random from a store.
Attempted Solution:
Let $X$ denote the lifetime of a TV and $Y$ be the factory of manufacture. We must calculate $E[X].$
Let $N$ be the number of TVs produced in factory $C$. Then $2N$ is the number of TVs produced in factory $B$ and $6N$ for factory $A$. With this we have, $P(Y=A)=\frac{2}{3},P(Y=B)=\frac{2}{9},$ and $P(Y=C)=\frac{1}{9}$.
Using the LIE, we have $E[X]=E_Y[E_{X\mid Y}[X\mid Y]]$. Since the outcome space can be partitioned we can write
$$E[X]=E[X\mid Y=A]P(A)+E[X\mid Y=B]P(B)+E[X\mid Y=C]P(C)=\frac{2}{3}E[X\mid Y=A]+\frac{2}{9}E[X\mid Y=B]+\frac{1}{9}E[X\mid Y=C].$$
Now, for the first term we have,
$$E[X\mid Y=A]=\int_0^\infty xf_{X\mid Y}(x\mid Y=A)\,dx.$$
Using the wiki page for the Mixed case we have,
$$f_{X\mid Y}(x\mid Y=A)=\frac{P(Y=A\mid X=x)}{P(Y=A)}f_X^A(x).$$
Substituting this into the integral gives,
$$E[X\mid A]=\int_0^\infty x\frac{P(Y=A\mid X=x)}{P(Y=A)}f_X^A(x)\,dx.$$
This is as far as I can get. I'm unsure on how to compute $P(Y=A\mid X=x)$ for mixed random variables. I thought about grouping terms in the integrand to simplify the calculation, but couldn't come up with anything which helped.
I also found this question here, but it doesn't address my specific question. Moreover, I also looked at wiki page here, which provided an example to get me started.
Thanks for any help!

A: In the notation of the post, the probability $\Pr(A)$ that the TV comes from Factory A is $1/2$, and $\Pr(B)=1/3$, and $\Pr(C)=1/6$. We have, as in the post,
$$E(X)=E(X\mid A)\Pr(A)+E(X\mid B)\Pr(B)+E(X\mid C)\Pr(C).$$
A random variable that has density function $\frac{1}{d}e^{-x/d}$ for $x\gt 0$, and $0$ elsewhere, has mean $d$. This can be viewed as a standard fact about the exponential distribution. Or else we can show it by finding $\int_0^\infty \frac{x}{d}e^{-x/d}\,dx$ using integration by parts.
Thus $E(X\mid A)=5$. We also have been given the other two conditional expetations, so we have all the information required to finish.


text:
Q: Any Eclipse plugin to view Assembly Code (not bytecode) for java files? I need to view assembly code of a java file during debugging. Is there any plugin present for this? If yes, please let me know.
Thanks in advance!

A: You can't count on the code being compiled to machine instructions. The just-in-time (JIT) compiler might decide to interpreted your byte code instead. Or it might start out by interpritating it, and then later on compile some of it to machine instructions. It may even recompile it several times.

A: First of all java does not have assembly code, it has byteCode this is one of the requirement for Java to be machine independent. To know about byteCode check out this question
Is it possible to view bytecode of Class file?
Learning about Java bytecode and the JVM

A: I dont know about an eclipse plugin, but you can make the VM display the generated machine code in the console. It requires some extra dll, see here: http://classparser.blogspot.ch/2010/03/hsdis-i386dll.html

A: You can see assembly code using disassembly plugin.. search on Eclipse Marketplace.. this will give assembly code >>> http://andrei.gmxhome.de/bytecode/
And how about trying -XX:+PrintAssembly


text:
Q: Receive mails on openshift with custom domain I'm setting up a server on openshift. I'm on the Bronze Plan and have a pretty common setup, I assume. Tomcat 7 with a MySQL database, scalable cartridge, so nothing fancy. I've been able to setup the custom domain and I am aware of the missing SSL certificate. That stuff is pretty well documented.
But I could not figure out how to get mails working. I'm not talking about sending mails from the application itself, I've seen questions covering that topic. I mean mail in general, all mails from and to the domain (I'm more concerned with to the domain for now). I for example need a working info@speedapp.io mail address.
Sorry if that is bluntly obvious to anyone else. But I'm coming from a shared Tomcat hosting provider, where the web frontend for mails was already configure.

A: You need to sign up for email services at a third party host, you can not use OpenShift to host your email.


text:
Q: RealmProxy files are not being generated I have been using Parceler to serialize RealmObjects. After updating to version 1.2.0 of Realm, none of the RealmProxy classes are being generated.
I have cleaned and rebuilt the project several times unsuccessfully. Here is a snippet of the parceler.
@Parcel(implementations = {TrackRealmProxy.class},
        value = Parcel.Serialization.BEAN,
        analyze = {Track.class})

A: Update as on Realm 5.0.0
full package name is required with _ separator.
it will look like
import io.realm.com_example_test_SomeClassRealmProxy;

@Parcel(implementations = {com_example_test_SomeClassRealmProxy.class},
value = Parcel.Serialization.BEAN,
analyze = {SomeClass.class})

A: Have you tried including a default empty constructor that doesn't have any parameters? Parceler has some issues without that default constructor.
class A(){
    int attributeA;
    float attrubuteB;
}


text:
Q: How to divide a whole column by a single value and pivot horizontally I have the following table: The month column is each month of 2019. Assigned column represents the amount assigned to an account in their respective month. So for 01-2019, the account was assigned 35000.
cumulative_jan column shows how much of the assigned amount is collected in the given month. The 0-->11 columns represent how much time has passed since assignment. I need to check, for each passing month since the month of assignment, how much has been collected. For the 01-2019 values, I need to divide 100 by 35000 and replace the first NULL value under [0]. Next, I need to divide 250 by 35000 and replace the first NULL value under [1] etc. At the end, I have to divide 1500 by 35000 and replace the first NULL under [11].
Month    Assigned   cumulative_jan         0     1     2     3  ...   11
01-2019   35000           100             NULL  NULL  NULL  NULL     NULL
02-2019   16500           250             NULL  NULL  NULL  NULL     NULL
.           .              .
.           .              .
.           .              .
12-2019   87520          1500             NULL  NULL  NULL  NULL     NULL

A: This seems like an update:
update t
    set [0] = assigned / cumulative_jan ;


text:
Q: Put a class on every list item in the third row with jQuery filtering I have a media gallery. For some weird reason, the designer decided to put these media items in blocks of 12. Three rows, four items per row and then a gap.
Now I do not feel like putting a list of 12 items in a parent list per block.
I thought this could easily be handled by jQuery filtering, adding a class on every
item of every third row.
I know how to target every :nth(4) item, every fourth item in the list, but how do I do every item in the third row?
What filter can I use for something like that?
The markup is listed below. All items are just floating elements in a unordered list.

Floating, and four items fit per row.
So I would need to target item 9, 10, 11 and 12, but also three rows further, item 21, 22, 23, 24 and again...
I thought I could do it with some nifty calculation in the .filter(function(){});, but I'm not even close to the correct answer yet...
What I want to have is actually visible in this jsfiddle I just made: http://jsfiddle.net/DpMRc/5/**
I want to target the blue boxes with a .filter() function instead of having to write the whole for loop for it.

A: One option is:
$('tbody tr').filter(
    function(i){
        if ((i+1)%3 == 0){
            return this;
        }
    }).addClass('black');

JS Fiddle demo.
And then use the class of the tr element to style the children in some manner:
.black td {
    /* css for the td elements that are children of the tr with the class of 'black' */
}

Or you could use:
$('tbody tr').filter(
    function(i){
        if ((i+1)%3 == 0){
            return this;
        }
    }).children().addClass('black');

JS Fiddle demo.

A: You can use the *  in the selector? Or particular tag?
$('table tr:nth-child(3) > *')....

or
$('table tr:nth-child(3) > td')...

depends on whether you wan't to address direct child or all descendants, in that case remove the > character.

A: You can use eq(). for example
$('table tr:eq(3) td:nth-child(6)').each(function() {
    $(this).css('background-color', 'yellow')
});

selects the 6th 'td' of the third row. You can combine that with some logic to calculate the index for eq to choose every third row
fiddle: http://jsfiddle.net/u2Ru3/

A: I presume you're using jQuery because you want IE8 support, but in all other browsers (including IE9), you can do this with just CSS:
li:nth-child(12n+9), li:nth-child(12n+10), li:nth-child(12n+11), li:nth-child(12n+12) {
    border-bottom: 4px solid red;
}

Here's a working example, I've made a guess as to what a simplified version of the rest of your CSS would look like.  The same selectors will work in jQuery if you want to polyfill for IE, but I would suggest you do that in conditional comments so as to not waste time on other browsers.


text:
Q: Force python to ignore pyc files when dynamically loading modules from filepaths I need to import python modules by filepath (e.g., "/some/path/to/module.py") known only at runtime and ignore any .pyc files should they exist.
This previous question suggests the use of imp.load_module as a solution but this approach also appears to use a .pyc version if it exists.
importme.py
SOME_SETTING = 4

main.py:
import imp
if __name__ == '__main__':
    name = 'importme'
    openfile, pathname, description = imp.find_module(name)
    module = imp.load_module(name, openfile, pathname, description)
    openfile.close()
    print module

Executing twice, the .pyc file is used after first invocation:
$ python main.py
<module 'importme' from '/Users/dbryant/temp/pyc/importme.py'>

$ python main.py
<module 'importme' from '/Users/dbryant/temp/pyc/importme.pyc'>

Unfortunately, imp.load_source has the same behavior (from the docs):

Note that if a properly matching byte-compiled file (with suffix .pyc
  or .pyo) exists, it will be used instead of parsing the given source
  file.

Making every script-containing directory read-only is the only solution that I know of (prevents generation of .pyc files in the first place) but I would rather avoid it if possible.
(note: using python 2.7)

A: load_source does the right thing for me, i.e.
dir, name = os.path.split(path)
mod = imp.load_source(name, path)

uses the .py variant even if a pyc file is available - name ends in .py under python3. The obvious solution is obviously to delete all .pyc files before loading the file - the race condition may be a problem though if you run more than one instance of your program.
One other possibility: Iirc you can let python interpret files from memory - i.e. load the file with the normal file API and then compile the in-memory variant. Something like:
path = "some Filepath.py"
with open(path, "r", encoding="utf-8") as file:
    data = file.read()
exec(compile(data, "<string>", "exec")) # fair use of exec, that's a first!

A: How about using zip files containing python sources instead:
import sys
sys.path.insert("package.zip")

A: You could mark the directories containing the .py files as read-only.


text:
Q: Send large data to AWS Lambda function I am planning to invoke AWS Lambda function by modifying objects on AWS S3 bucket. I also need to send a large amount of data to the AWS Lambda function. How can I send the data to it in an efficient way?

A: I would use another S3 bucket to first send the data and then use it from the Lambda function

A: Your Lambda function should just read from the database your large data resides in.
Assuming your modified object on S3 contains - inside the object or as the object name - some type of foreign key to the data you need out of your database:

A) If your Lambda has access to the database directly: then you can just make your lambda function query your database directly to pull the data.

B) If your Lambda does not have direct access to the database: Then consider cloning the data as needed from the database to a secure S3 bucket for access by your lambda's when they are triggered/need it.  Clone the data to S3 as JSON or some other easy to read format as logical objects for your business case (orders, customers, whatever).  This method will be the fastest/most efficient for the Lambda if its possible for your use case.

A: I recently did this by gzipping the data before invoking the lambda function. This is super easy to do with most programming languages. Depending on your database content this will be a better or worse solution. The content of my database had a lot of data repetition and zipped very nicely.


text:
Q: Is the positive cone of $L^p(\Omega)$ weak-closed? Let $(\Omega,\mu)$ be a $\sigma$-finite measure space. Suppose $1 \leq p< \infty$. Consider the cone $L^p(\Omega)_+$ of positive functions of $L^p(\Omega)$.
Is $L^p(\Omega)_+$ weak-closed in $L^p(\Omega)$ ?

A: For $p>1$, $L_p$ is reflexive and this set is convex so it is weakly closed because it is norm-closed (Mazur's lemma).
In $L_1$, suppose that $(f_n)_{n=1}^\infty$ is a sequence of non-negative functions converging weakly to $f$. Suppose that $f$ is strictly negative on a set $A$ of positive measure. Let $g$ be the indicator function of $A$. We have
$$\int\limits_\Omega f_n g = \int\limits_A f_n \to \int\limits_\Omega f g= \int\limits_A f < 0.$$
This is impossible as $f_n$ are non-negative. This argument will work in $L_p$ too, so Mazur's lemma is not quite necessary.


text:
Q: Shared steps in vanilla Selenium Multithreaded Framework without Dependency Injection on TestNG I have a big Selenium framework, that has more than 300 tests and runs full suite in <1h on 15 threads. I use testNG and nothing else, no Spring. Methods from Page Objects are grouped in Steps classes to create reusable blocks of code.
Now, methods are run in parallel, and sometimes 1 class have up to 10 methods, like this:
public class CreateAccountTest extends BaseTest {

    @Test
    public void t1() throws InterruptedException, IOException {
        User user = User.of();
        new CreateAccountStep(getDriver())
            .registerAndVerifyAccount(user)
            .finishRegistrationAsCompany(user, Company.of());
        new ManageCompanyStep(getDriver()).verifyCompanyUniqueMenusVisibility();
        new ManageAccountStep(getDriver()).tryClosingAccount();

    }

    @Test
    public void t2() throws InterruptedException, IOException {
        User user = User.of();
        new CreateAccountStep(getDriver())
                .registerAndVerifyAccount(user)
                .finishRegistrationAsPrivatePerson(user);
        new ManageAccountStep(getDriver()).closeAccount();
    }

Now I can't write CreateAccountStep createAccountStep = new CreateAccountStep(getDriver()) in class field, because driver is not yet created at this point. (It is created in @BeforeMethod in BeforeTest and deleted after every test).
I could, however, write
private final ThreadLocal<CreateAccountStep> createAccountStep =
        ThreadLocal.withInitial(() -> new CreateAccountStep(getDriver()));

// and so on with every step

And then rewrite tests like this:
public class CreateAccountTest extends BaseTest {

    private final ThreadLocal<CreateAccountStep> createAccountStep =
        ThreadLocal.withInitial(() -> new
        CreateAccountStep(getDriver()));
    private final ThreadLocal<ManageCompanyStep> manageCompanyStep =
        ThreadLocal.withInitial(() -> new
        ManageCompanyStep(getDriver()));
    private final ThreadLocal<ManageAccountStep> manageAccountStep=
        ThreadLocal.withInitial(() -> new
        ManageAccountStep(getDriver()));

    @Test
    public void t1() throws InterruptedException, IOException {
        User user = User.of();
        createAccountStep.get()
            .registerAndVerifyAccount(user)
            .finishRegistrationAsCompany(user, Company.of());
        manageCompanyStep.get().verifyCompanyUniqueMenusVisibility();
        manageAccountStep.get().tryClosingAccount();

    }

    @Test
    public void t2() throws InterruptedException, IOException {
        User user = User.of();
        createAccountStep.get()
                .registerAndVerifyAccount(user)
                .finishRegistrationAsPrivatePerson(user);
        manageAccountStep.get().closeAccount();
    }

what is more, I could probably define one ThreadLocal for each of the steps I am using, and just define them in BaseTest class and probably never have to worry about writing new xxxStep() again.
Is such a solution viable? Is it pattern, does it have some hidden limits I havent think of, or can I happilly implement it across the framework?
Step classes have only 1 parameter that needs to be passed - WebDriver and they don't have any non final fields.


text:
Q: right-aligned textarea's cursor placement following whitespace I have a textarea with right-aligned text, and if the cursor is at the end of a line and whitespace is added, the whitespace shows up as expected, however the cursor remains adjacent to the previous non-whitespace character.
Is there anyway to make the cursor appear after newly entered whitespace in this context (like it does when the textarea is left-aligned)?

textarea {
  text-align: right;
}
<textarea></textarea>

A: you need to specify white-space inside an element. I.E

textarea {
  text-align: right;
  white-space: nowrap;
}
<textarea></textarea>

A: I think you're looking for the dir="rtl" attribute:

<textarea dir="rtl"></textarea>


text:
Q: Show the set is open by purely using definition of open in a metric space Show $S = \{(x,y)\in \mathbb R^{2}: y > x^2\}$ is open by using the definition of an open set.
Here is my attempt:
Choose a point $a \in S$, try to find a ball with radius $r$, such that $B(a,r) \subseteq S$.
Which means $\forall x \in \mathbb R ^{2}, |x - a| \lt r \implies x \in S$
My problem is I have no idea how to determine the radius $r$, can someone help me?
Thanks!

A: Hint: Draw a picture. Pick a point $(x_0,y_0)$ above the graph of $y=x^2$. Find that setting
$$
r=\frac{1}{2}\min \{ |x_0-\sqrt{y_0}|, |x_0+\sqrt{y_0}|, |y_0-x_0^2|\}
$$
does it.


text:
Q: How to read a single file web page / web archive excel file into R Is it possible to read this file into R without having to manually open the file myself and resave as an excel file. Below shows that this file is not actually an excel file.
https://www.sec.gov/Archives/edgar/data/320193/000119312511192493/Financial_Report.xls
url <- "https://www.sec.gov/Archives/edgar/data/320193/000119312511192493/Financial_Report.xls"
temp_xls <- tempfile(fileext = ".xls")
download.file(url, destfile = temp_xls, mode = "wb")

readxl::format_from_signature(temp_xls)
#> [1] NA

readr::read_lines(temp_xls, n_max = 5)
#> [1] "MIME-Version: 1.0"
#> [2] "X-Document-Type: Workbook"
#> [3] "Content-Type: multipart/related; boundary=\"----=_NextPart_e3144909_1d60_4840_908e_3419ae0a14d3\""
#> [4] ""
#> [5] "This document is a Single File Web Page, also known as a Web Archive file.  If you are seeing this message, your browser or editor doesn't support Web Archive files.  Please download a browser that supports Web Archive, such as Microsoft Internet Explorer."

unlink(temp_xls)

1) Is there any current solution to read this file into R
2) Is it possible to automate manually opening the file and saving it in a format that is readable in R

A: A possible solution is to use httr:
library(httr)
library(XML)
library(magrittr)
h <- GET("https://www.sec.gov/Archives/edgar/data/320193/000119312511192493/Financial_Report.xls") %>%
    content("text", encoding="UTF8") %>%
    readHTMLTable()

edit: add a version that uses worksheets' names as names for the tables
library(httr)
library(XML)
library(xml2)
library(magrittr)
ctnt <- GET("https://www.sec.gov/Archives/edgar/data/320193/000119312511192493/Financial_Report.xls") %>%
    content("text", encoding="UTF8")
tbls <- readHTMLTable(ctnt)
tbls <- tbls[names(tbls)!="NULL"]
names(tbls) <- read_html(gsub("<!--[if gte mso 9]>", "", ctnt, fixed=TRUE)) %>%
    xml_find_all(".//name") %>%
    xml_text()


text:
Q: Django Tutorial Shenanigans Aloha chaps,
Having a spot of bother with the Django tutorial
https://docs.djangoproject.com/en/1.8/intro/tutorial01/
As you can see below, it is saying 'Question' isn't defined.
c:\Python34\Scripts\mysite>python manage.py makemigrations polls
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "c:\Python34\lib\site-packages\django\core\management\__init__.py",        line
338, in execute_from_command_line
utility.execute()
File "c:\Python34\lib\site-packages\django\core\management\__init__.py",  line
312, in execute
django.setup()
File "c:\Python34\lib\site-packages\django\__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "c:\Python34\lib\site-packages\django\apps\registry.py", line 108, in populate
app_config.import_models(all_models)
File "c:\Python34\lib\site-packages\django\apps\config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "c:\Python34\lib\importlib\__init__.py", line 109, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked
File "<frozen importlib._bootstrap>", line 1129, in _exec
File "<frozen importlib._bootstrap>", line 1471, in exec_module
File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
File "c:\Python34\Scripts\mysite\polls\models.py", line 3, in <module>
class Question(models.Model):
File "c:\Python34\Scripts\mysite\polls\models.py", line 7, in Question
class Choice(models.Model):
File "c:\Python34\Scripts\mysite\polls\models.py", line 8, in Choice
question = models.ForeignKey(Question)
NameError: name 'Question' is not defined

Here is my models.py file
from django.db import models

class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')

class Choice(models.Model):
    question = models.ForeignKey(Question)
    choice_text = models.Charfield(max_length=200)
    votes = models.IntegerField(default=0)

Thanks in advance for any help

A: Don't nest the classes. Get your indentation levels right. Choice needs to be at the same level as Question, not inside Question. Your wrong indentation here and the stack trace give it away.

A: from django.db import models

class Question(models.Model):
     question_text = models.CharField(max_length=200)
     pub_date = models.DateTimeField('date published')

class Choice(models.Model):
    question = models.ForeignKey(Question)
    choice_text = models.Charfield(max_length=200)
    votes = models.IntegerField(default=0)

Identation is the problem


text:
Q: Codeigniter: Head & Title Tags with if/else I am newbie in CodeIgniter and in PHP as well. I am looking for an example to find out how it is worked before recode it to my project. And also you can explain basically if you want without any example. I have been looking for it on the internet but I couldnt find yet. I don't know how to search about this topic on Google I guess.
I have two header.php files that are renamed as header_post.php and header_main.php in "views" folder.
For header_post.php, the meta tags such as description, title and so on are changed based on the the title and the content of the post I published.
For header_main.php, the meta tags such as description, title and so on are stable based on the the title and the description of my blog.
But I want to create a header.php instead of header_post.php and header_main.php. When it is in homepage of the blog the codes I wrote for header_main.php should work and on the other hand when it is in a post's page the codes I wrote for header_post.php should work.
As an example,
Homepage:  <title>Bari's Blog</title>
In a Post: <title>Post's Title</title>

I need your help about how to write if/else statement?

A: You could check if the variables for setting the header etc. are set:
<?php if (isset($title) && $title) { ?>
<title><?php echo $title;?></title>
<?php } else { ?>
<title>Bari's Blog</title>
<?php } ?>


text:
Q: How to highlight code parts that are longer than 80 chars? In Emacs, I'd like to highlight the parts of long lines that exceed 80 characters.
The package highlight-80+ is great for that. But how can I automatically enable it when a C++ source file is loaded?
I tried to add highlight-80+ to the C++ mode, but it didn't work:
(require 'highlight-80+)
(defun my-c++-mode-common-hook ()
  (highlight-80+-mode 1))
(add-hook 'c++-mode-common-hook 'my-c++-mode-common-hook)

When I load a .cc file it goes in C++ mode but highlight-80+ is not enabled, so the long lines are not marked.

A: Note that the Highlight80Plus wiki says that it is built-in to emacs starting with 23.  I believe it's referring to whitespace-mode; it does this and is built in to emacs.
There is a function in emacs-starter-kit that does something like this already but you could easily duplicate it,
(defun esk-turn-on-whitespace ()
  (whitespace-mode t))

(add-hook 'prog-mode-hook 'esk-turn-on-whitespace)

A: Can you try this:
(autoload 'highlight-80+)
(add-to-list 'auto-mode-alist '("\\.cpp$" . highlight-80+-mode))

A: See the whitespace-mode, it does this kind of highlighting and more:
http://www.emacswiki.org/emacs/WhiteSpace


text:
Q: AWS Fargate cannot access application over Public DNS name This is a follow up to my previous question. I'm successfully able to access the public IP over fargate. However, after trying to attach Application load balancer, I cannot access application over public DNS. The registered target always show unhealthy status with 502 error.
Sharing my configuration settings-
VPC

Route Table Public Subnet

Route Table public subnet config

Route Table private subnet

Route Table private subnet config

ACL subnet associations

ACL inbound rules

ACL outbound rules

security inbound rules

security outbound rules

internet gateway

nat gateway

target group

target group health status

task details

service

ALB settings

ALB listeners

Target group with 8081 port

A: Based on the comments.
There were two issues identified:

*

*Incorrect port on the target group. It was 80 instead of 8081.

*Healthy threshold timeout was too short (5 seconds). Increasing it seemed to solved the issue.


text:
Q: Ideas on mass image conversion - why is this running out of memory? I am trying to:

*

*Loop through ~4000 folders.

*Get the images within each folder.

*Create several different sizes of images and save the new images to the same folder.

My code (below) for this is working, but after it has done only a few folders (maybe 50) it gives an "out of memory error". It takes about 5 minutes to get to this stage.
  I have tried increasing any max memory size I can  find in php.ini (to 1000MB), but I still get the same "out of memory error" and at the same value.
My server is showing as hardly doing anything (16 core/36gig ram) so I don't think it is a hardware limit.
Sorry if this is not the right place to ask this question, but does anyone have any ideas how I can re-size (and rename) all these images?
The code I am using is below:
ini_set('max_execution_time', 60000);

define('IMAGEWidth', 800);
define('IMAGEHeight', 800);
define('THUMBNAILWidth', 109);
define('THUMBNAILHeight', 164);
define('THUMBNAILWidthLARGE', 180);
define('THUMBNAILHeightLARGE', 270);

define('MAX_BYTE_IMAGE_SIZE', 83886080);                                    // max files size allowed = 10MB
//** ============ images sizes ===============
// small thumb
$imageSize_arr[] = array('image_resize' => true, 'image_x' => THUMBNAILWidth, 'image_ratio_y' => true, 'jpeg_quality' => 80, 'image_min_width' => 100, 'image_unsharp_amount' => 80, 'file_name_body_add' => '_thumb');
// normal thumb
$imageSize_arr[] = array('image_resize' => true, 'image_x' => THUMBNAILWidthLARGE, 'image_ratio_y' => true, 'jpeg_quality' => 80, 'image_min_width' => 100, 'image_unsharp_amount' => 80, 'file_name_body_add' => '_largethumb');
// full size image
$imageSize_arr[] = array('image_resize' => true, 'image_x' => IMAGEWidth, 'image_ratio_y' => true, 'jpeg_quality' => 80, 'image_min_width' => 100, 'image_unsharp_amount' => 80);
//origional file
$imageSize_arr[] = array('image_resize' => false, 'file_name_body_add' => '_origional');

require('upload.class.php');
$path = '/var/www/import/propertyimages/';
$results = scandir($path);
//echo '
';
//print_r($results);
//echo '
';

foreach ($results as $result) {
    if ($result === '.' || $result === '..') {continue;}

    if (is_dir($path.$result)) {
        $path2 = $path.$result;
        echo '
'.$path2.'

';
        $results2 = scandir($path2);
        //echo '
';
        //print_r($results2);
        //echo '
';

        foreach ($results2 as $image) {
            if ($image === '.' || $image === '..') {continue;}
            //echo 'image = '.$path2.'/'.$image.'
';
            $sourcePath = $path2.'/'.$image;

            //global $imageSize_arr;
            $handle = new  upload($sourcePath); // initiate upload class and provide file to be altered
            $fileName = $image;

            if ($handle->uploaded) {
                foreach ($imageSize_arr as $size_arr){                      // get image sizes from config.php
                    $handle->file_new_name_body   = $fileName;              // set the file name
                    $handle->file_overwrite       = true;
                    $handle->file_max_size        = MAX_BYTE_IMAGE_SIZE;    // get max image sizes from config.php
                    $handle->allowed              = array('image/*');       // set allowed file types
                    foreach($size_arr as $key=>$value){                     // get image convertion types from $imageSize_arr/$size_arr
                        $handle->$key = $value;
                    }
                    $handle->process($path2.'/'); // prosess the image and save to specified location
                }

                // check if all went well
                if ($handle->processed) {
                    $handle->clean();
                    $handle->error;
                    echo 'done
';
                }
                else {
                    echo $handle->error;
                    echo 'error
';
                }
            }
            else {echo 'ERROR'.$handle->error.'
';}
        }
    }
}

A: Might or might not be of some help: Clearing Memory
You can also add this to your script to increase your memory limit:
ini_set('memory_limit', '2048M');


text:
Q: eclipse: use files in different projects or use different toolchains in one project the code i develop for avr microcontrollers i write so that it runs on the PC and only differs in one or more files (the port). till now i do that using makefiles but now id like to move to eclipse CDT with the AVR plugin.
is there a way to

*

*use 2 different toolchains (x86 and avr compiler) in one project (and also tell these toolchains which port to include)

*or to create 2 project (one for x86 one for avr) that share the common files?
note that main() is in a shared file.
thanks for your help.

A: You may be able to set up multiple configurations to do this, with different toolchains. If this looks reasonable, you could have your source files change their behaviour based on what compile-time symbols are present.

A: Within Eclipse, only the x86 compiler will be used (so you can run the tests, etc). You will have to invoke the Makefile to build for AVR manually, so one project should be enough.
Eclipse will not use the output of the compiler but the C sources to build its project model. Therefore, you will see all files (even those for AVR) but they will never run in Eclipse. That means you can edit them including code completion.


text:
Q: Using sklearn StandardScaler on only select columns I have a numpy array X that has 3 columns and looks like the following:
array([[    3791,     2629,        0],
       [ 1198760,   113989,        0],
       [ 4120665,        0,        1],
       ...

The first 2 columns are continuous values and the last column is binary (0,1). I would like to apply the StandardScaler class only to the first 2 columns. I am currently doing this the following way:
scaler = StandardScaler()
X_subset = scaler.fit_transform(X[:,[0,1]])
X_last_column = X[:, 2]
X_std = np.concatenate((X_subset, X_last_column[:, np.newaxis]), axis=1)

The output of X_std is then:
array([[-0.34141308, -0.18316715,  0.        ],
       [-0.22171671, -0.17606473,  0.        ],
       [ 0.07096154, -0.18333483,  1.        ],
       ...,

Is there a way to perform this all in one step? I would like to include this as part of a pipeline where it will scale the first 2 columns and leave the last binary column as is.

A: I ended up using a class to select columns like this:
class ItemSelector(BaseEstimator, TransformerMixin):

    def __init__(self, columns):
        self.columns = columns

    def fit(self, x, y=None):
        return self

    def transform(self, data_array):
        return data_array[:, self.columns]

I then used FeatureUnion in my pipeline as follows to fit StandardScaler only to continuous variables:
FeatureUnion(
    transformer_list=[
        ('continous', Pipeline([  # Scale the first 2 numeric columns
            ('selector', ItemSelector(columns=[0, 1])),
            ('scaler', StandardScaler())
        ])),
        ('categorical', Pipeline([  # Leave the last binary column as is
            ('selector', ItemSelector(columns=[2]))
        ]))
    ]
)

This worked well for me.

A: Since scikit-learn version 0.20 you can use the function sklearn.compose.ColumnTransformer exactly for this purpose.

A: I can't think of another way to compact you code more, but you can definitely use your transformation in a Pipeline. You have to define a class extending StandardScaler that only performs the transformations on the columns passed as arguments, keeping the others intact. See the code in this example, you would have to program something similar to ItemSelector.

A: Inspired by skd's recommendation to extend StandardScaler, I came up with the below. It's not super efficient or robust (e.g., you'd need to update the inverse_transform function), but hopefully it's a helpful starting point:
class StandardScalerSelect(StandardScaler):

    def __init__(self, copy=True, with_mean=True, with_std=True, cols=None):
        self.cols = cols
        super().__init__(copy, with_mean, with_std)

    def transform(self, X):

        not_transformed_ix = np.isin(np.array(X.columns), np.array(self.cols), invert=True)

        # Still transforms all, just for convenience. For larger datasets
        # will want to modify self.mean_ and self.scale_ so the dimensions match,
        # and then just transform the subset
        trans = super().transform(X)

        trans[:,not_transformed_ix] = np.array(X.iloc[:,not_transformed_ix])

        return trans


text:
Q: IIS 7 Http Handler development issue I am using VSTS 2008 + C# + .Net 3.5 + IIS 7.0 to develop an ASP.Net web site. I want to develop an Http module, which could inspect whether incoming request has some specific http header (e.g. CustomerID) and if do not have such header, I will redirect user request to some other pages.
I think I should develop by using Http Modules in IIS 7.0 integrated mode? Please correct me if I am wrong or there is simplier solutions. Any reference samples or tutorials? I am new to Http Module development in IIS 7.0.

A: There are a number of articles that describe how to create standard HttpModules for ASP.NET. One such article can be found in the ASP.NET infrastructure MSDN Library titled "Walkthrough: Creating and Registering a Custom HTTP Module".
Make sure that you follow the steps to register your module with IIS 7 Integrated mode on that walkthrough or you will end up with an error similar to the following:
"HTTP Error 500.0 - Internal Server Error
Description: This application is running in an application pool that uses the Integrated .NET mode. This is the preferred mode for running ASP.NET applications on the current and future version of IIS.
In this mode, the application should not specify ASP.NET module components in the / configuration section. Instead, it should use the / configuration section to load ASP.NET module components."
You can find another article on the IIS.NET site which has detailed information on how to create both modules and handlers for IIS 7. This article is titled "Developing IIS 7.0 Modules and Handlers with the .NET Framework"


text:
Q: left join and non id join in agiletoolkit atk4 SELECT t1.field1, t1.field2, t1.field3, t2.field4, t2.field5,t2.field6
FROM table1 AS t1 LEFT JOIN table2 AS t2
ON t1.field1 = t2.field1 AND t1.field2 = t2.field2
WHERE t1.fieldstart <='2021-10-13' AND t1.fieldend >= '2021-10-31' OR t2.submitted_by='xyz';

I want convert the query above to agile toolkit akt4 code , any idea on how to do the left join in agiletoolkit, every time i use join it give me inner join , I want left join
$j_table = $m->join('table2.nameid');

I have tried this it looks fine
$j_table = $m->leftjoin('table2.nameid');

How ever when I try to join with none id I get this error
$j_table = $m->leftjoin('table2.name','name');

Fatal Error
atk4\data\Exception: You are trying to link tables on non-id fields. This is not implemented yet
looking for help please ?
Thanks

A: On Agile Toolkit v1.7.1 (legacy/v1 branch) only option how to do this is on underlying DSQL level.
To get DSQL instance from model use:
$model->table_alias = 't1';
$q = $model->dsql();

DSQL sample code below:
// You can use expression for more complex joins
$q->join('table2',
    $q->andExpr() // or orExpr()
        ->where('t1.field1=t2.field1')
        ->where('t1.field1=t2.field2'),
    'left',
    't2'
)

Bad thing about this approach is that as soon as you "move" from data model level to lower, DSQL level then you're kind of locked in there and can't use all nice features of data model because it's not aware of joins defined in dsql. At least that's how I remember that. A lot has changed in toolkit in last few years...

EDIT: Oh, actually looks like if found how it was possible to do with Model alone back then.
Try this:
$model->join('table2',
  [
    'foreign_alias' => 't2',
    'on' => $expr,
  ],
  'left'
);

where $expr can be simply a string like
$expr = 't1.field1=t2.field1 AND t1.field2=t2.field2';

but definitely preferred way is to use DSQL Expression object like
// which is functionally the same as above string approach
$expr = $model->expr('t1.field1=t2.field1 AND t1.field2=t2.field2');

// this is much better because takes care of escaping and table alias automatically
$expr = $model->expr('{}={} AND {}={}', [
    $model->getField('field1'),
    't2.field1',
    $model->getField('field2'),
    't2.field2',
]);

P.S. All code above is untested. If you find any error, then please let me know in comments and I'll fix.


text:
Q: Unable to get image in Canvas element to appear as DIV background image (HTML/Javascript)? I have a web page that displays an image in a CANVAS element that is a child to a DIV element.  I want to be able to grab the image from a CANVAS element and put it into a DIV that I will move around the screen.  I am using the code below to try and do this.  The Javascript code assigns the value of the canvas.toDataURL() method, wrapped in a "url()" method call, to the background image of the DIV using the JQuery CSS() method.  I checked in the Chrome debugger console and the backround-image property of the DIV is set to the value returned by the canvas.toDataURL() method.  I can see it in the backgroundImage field that is listed as a child of the DIV's Style property.  However if I set a Watch expression to $("#easter-egg-cat-1").css("backround-image") it returns "none" as the value.
In any case I don't see the background image in the DIV.  Why is this and how can I fix it?

        <canvas id="preview">
        </canvas>
        <canvas id="annotations">
        </canvas>

(none)

// This is the script that grabs the image from the CANVAS element and sets the
//  the desired DIVs background-image CSS property to the URL provided by the
//  CANVAS element.
var previewCanvasAsUrl = $("#preview").get(0).toDataURL();

$("#easter-egg-cat-1").css("backround-image", "url(" + previewCanvasAsUrl + ")");

A: You have a typo:
$("#easter-egg-cat-1").css("background-image", "url(" + previewCanvasAsUrl + ")");
                                ^


text:
Q: previous values get overwritten list i am trying to add items to cart which are stored in session but the session values are overwritten when i add a new product to the cart.
private List<int> newCart = new List<int>();
    protected void dlstCartItems_ItemCommand(object source, DataListCommandEventArgs e)
    {

        if (e.CommandName == "AddToCart")
        {
            var arg = e.CommandArgument;
            DropDownList ddlList = e.Item.FindControl("ddlAvailableSizes"+e.CommandArgument) as DropDownList;
            int currentItemID = int.Parse(this.dlstCartItems.DataKeys[e.Item.ItemIndex].ToString());
            if (ddlList.SelectedIndex == 0)
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('Please Select Size');", true);
            }
            else
            {

                newCart.Add(Convert.ToInt32(e.CommandArgument));
                Session["Cart"] = newCart;
                if (Session["Cart"] != null)
                {

                    int ct = ((List<int>)Session["Cart"]).Count;
                    lblCartMessage.Text = Convert.ToString(ct)+" "+"Product";

                }

            }

        }
    }

my problem is when ever i add a new product the old product is no more there in the list and the product count is always 1.

A: The list in which u are adding should be defined at a class level. Whenever you are adding new product , private List newCart = new List(); should not be executed otherwise it will make the count zero after addition you would only be left with the latest addition.

A: You're overriding the cart by Session["Cart"] = newCart;.
In order to do this write:
 newCart = Session["Cart"] as List<int>;
 if (newCart == null)
 {
    newCart = new List<int>();
    Session["Cart"] = newCart;
 }

// Rest of the code adding to newCart etc.

A: Perhaps newcart is always empty on the execution of dlstCartItems_ItemCommand and therefore
Session["Cart"] = newCart;

clears values

A: protected void dlstCartItems_ItemCommand(object source, DataListCommandEventArgs e)
    {
        List newCart;
    if (e.CommandName == "AddToCart")
    {
        var arg = e.CommandArgument;
        DropDownList ddlList = e.Item.FindControl("ddlAvailableSizes" + e.CommandArgument) as DropDownList;
        int currentItemID = int.Parse(this.dlstCartItems.DataKeys[e.Item.ItemIndex].ToString());
        if (ddlList.SelectedIndex == 0)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", "alert('Please Select Size');", true);
        }
        else
        {

            if (Session["Cart"] == null)
            {
                newCart = new List<int>();
                newCart.Add(Convert.ToInt32(e.CommandArgument));
                Session["Cart"] = newCart;
            }
            else
            {
                newCart = Session["Cart"] as List<int>;
                newCart.Add(Convert.ToInt32(e.CommandArgument));
                Session["Cart"] = newCart;
            }

            int ct = ((List<int>)Session["Cart"]).Count;
            lblCartMessage.Text = Convert.ToString(ct) + " " + "Product";

        }

    }
}


text:
Q: SQL Injection modify table I am doing an exercise in class to find web page vulnerabilities through a user/password form and we are suppouse to be able to modify columns of a table using SQL injection.
I know the tables of the database, for instance I am trying to modify the table users that has the colums id, password and email.
The problem is that for INSERT, UPDATE or DELETE the server code use the executeUpdate() method and for SELECT use the executeQuery() method which returns the ResultSet, so obviusly when I try someting like:
correctpassword'; UPDATE usuarios SET id='newname' WHERE id='oldname'; --
it returns an error because UPDATE does not return the ResultSet object.
I have also tried nested queries so the main consult would be a SELECT so it would actually return a ResultSet object but it doesnt work either. The query is:
correctpassword'; SELECT id FROM usuarios WHERE id = (SELECT id FROM usuarios WHERE id=?admin?; UPDATE usuarios SET id=?luciareina? WHERE id=?admin?); --
Do you know anyway to do this? Thank you very much in advance!

A: Depending on the database server you have, you can not have an update statement inside of a select statement.
you should close out the existing query and then do the update
Also, make sure the column you are updating is not an auto generated/key column that is not updatable.
SELECT id FROM usuarios WHERE id = 1; UPDATE usuarios SET id=1 WHERE id=2
You should test your injection directly on server to see if it is valid before testing it via the webpage.


text:
Q: Allow an app through Windows Defender Firewall I have moved the new Chromium Edge to a drive other than C:\ using the robocopy command and by creating a junction. The browser is working fine as of now.
But when I launched the app after copying it to another drive and typed a website in the URL bar, the Windows Firewall popped up asking me if I want to allow access via my network or not. Since I am at my home currently, I selected only the first option and clicked "Allow access" from the menu similar to this:

So, the question that I want to ask is - Will I be able to use the internet through Chromium Edge at my university since it is a public network (and I have allowed it to access internet only through my home network through the firewall menu)? Or will I have to change the permission for this Browser in Firewall Menu to make it work there?


text:
Q: Count number of alphabetic charcters in data i have string as '   #$rahul   ' and i have to calculate number of alpha bates without using inspect verb. Also not using by ord clause for ASCII value. My instructor told me to use empty array but how it is used?? I tried but it counts for symbols also.
DATA DIVISION.
   WORKING-STORAGE SECTION.
   01 WS-TABLE.
      05 WS-A OCCURS 3 TIMES INDEXED BY I.
         10 WS-B PIC A(2).
         10 WS-C OCCURS 2 TIMES INDEXED BY J.
            15 WS-D PIC X(3).

PROCEDURE DIVISION.
   MOVE '@#@#DEF34GHIJKL56MNOPQR' TO WS-TABLE.
   PERFORM A-PARA VARYING I FROM 1 BY 1 UNTIL I >3
   STOP RUN.

   A-PARA.
   PERFORM C-PARA VARYING J FROM 1 BY 1 UNTIL J>2.

   C-PARA.
    if ws-table(1) equals to spaces
    continue
    else
    add +1 to ws-count
    end-if
    DISPLAY WS-C(I,J).

A: Apart from your table-definition and actual use of the table, you have basically got the idea already, except you are not sure what, specifically, to test for.
What you need to do is find the section in your COBOL documentation on class condition and class tests.
I suspect this bit of code:
if ws-table(1) equals to spaces
continue
else
add +1 to ws-count
end-if

Has been added in haste. With your data, ws-table(1) will never be space, and ws-count is not defined.
Back to your definition. You are defining a structure with three parts (WS-A OCCURS 3) each of which consists of a two-byte alphabetic field followed by two three-byte alphanumeric fields. That definition is of no direct use to your task.
   01  the-data.
       05  FILLER OCCURS 24 TIMES
           INDEXED BY data-byte-index.
           10  the-data-byte               PIC X.

That will allow you to look at each byte individually. Note that you can always use good names, which will make your programs easier to understand, reduce the chance of careless errors, and make people's lives, including your own when you return to a program some time later, generally easier.
Note, you can also use reference-modification and lose out on the readability for the benefit of less typing.
Format of your program
Unless it is dictated to you (and although I've never seen it before in over 30 years, I have seen it a couple of time recently) there is absolutely no point in "indenting" things like the WORKKING-STORAGE section, or even paragraph/SECTION labels. They already have all the indentation they need, and further indentation adds nothing, which requiring more typing, and also causing experienced COBOL programmers to wonder why you are doing that.
Since the 1985 Standard for COBOL, the use of full-stops/periods in the PROCEDURE DIVISION is greatly relaxed. Since a full-stop/period in the wrong place can cause errors, this was a good thing. It will also be good if you take full advantage of it. Commas look far too much like full-stops/periods to be of any use in code. They never have to be there, so having them benefits nothing. Also noise-words like THEN can/should be avoided. Unlike commas, spacing can be a boon to the format of a program.
Here's your code above, reformatted:
       MOVE '@#@#DEF34GHIJKL56MNOPQR'
                                    TO WS-TABLE
       PERFORM                      A-PARA
         VARYING                    I
           FROM                     1
           BY                       1
           UNTIL                    I > 3
       STOP RUN
       .

   A-PARA.
       PERFORM                      C-PARA
         VARYING                    J
           FROM                     1
           BY                       1
             UNTIL                  J > 2
       .
   C-PARA.

       if ws-table ( 1 ) equal to space
           continue
       else
           add +1                   to ws-count
       end-if

       DISPLAY
               WS-C ( I  J )
       .

Use some proper names, and it's start to look like a real program.
Note, not all people agree on how a program should be formatted. Seriously.


text:
Q: Cannot deploy Spring, Struts 2, and Hibernate webapp due to startup errors I have to introduce some changes in an app I didn't develop originally.
It uses Maven. When I try to deploy after doing a mvn install, I get the following error:
Error creating bean with name 'org.springframework.transaction.interceptor.TransactionAttributeSourceAdvisor':
Cannot create inner bean '(inner bean)' of type [org.springframework.transaction.interceptor.TransactionInterceptor]
while setting bean property 'transactionInterceptor'; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name '(inner bean)': Cannot resolve reference to bean 'transactionManager'
while setting bean property 'transactionManager'; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'transactionManager' defined in class path resource [applicationContext.xml]:
Cannot resolve reference to bean 'entityManagerFactory' while setting bean property 'entityManagerFactory';
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory'
defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException:
org.hibernate.HibernateException: Errors in named queries:
dameTipoRelacion, consultaPerfil, consultaOrganizacionPorPadre, obtenerDepartamentos, consultaOrganizacionPorPadreYNivel,
consultaOrganizacionNivel, consultaGruposRelacion, consultaRelaciones, obtenerDepartamentosSC, dameGrupo, dameDepartamento

My persistence.xml is:
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
    version="1.0">
    <persistence-unit name="punit">
    </persistence-unit>
</persistence>

If you need more config or source tell me.

A: The error logs are clear in this case,
org.hibernate.HibernateException: Errors in named queries: dameTipoRelacion,.....

So, resolve this error, dig in to all the named queries and verify that all your named queries are proper.


text:
Q: Is it possible to force the typescript compiler check all possible branches when having a return type? I see that the typescript checker does not give a warning or an error when having a function like this:
function test(a: boolean): boolean {
    if (a) {
        return true;
    } else {
        // else branch not covered
    }
}

Is there a property that could be set in the tsconfig.json file to force the compiler to do the check? (I could not find any)

A: The noImplicitReturns flag should do exactly that:
https://www.typescriptlang.org/tsconfig#noImplicitReturns