text:
Q: Runs locally with SQLite, but on Heroku: PGError: ERROR:  syntax error at or near "NULL" My code runs fine for sqllite locally, but when I push to heroku I get:
ActiveRecord::StatementInvalid (PGError: ERROR:  syntax error at or near "NULL"
LINE 1: ...LECT  "beeps".* FROM "beeps" WHERE ((widget_id NOT NULL) AND ...
                                                             ^
: SELECT  "beeps".* FROM "beeps" WHERE ((widget_id NOT NULL) AND (updated_at > '2011-02-06 02:27:59.867809') AND (userphone = '0000000xxxx') AND (beeper
= '0000000zzzz') AND (inbound = 't')) ORDER BY beeps.id DESC LIMIT 1):

the ruby code is :
Beep.last(:conditions => [ "(widget_id NOT NULL) AND (updated_at > ?) AND (userphone = ?) AND (beeper = ?) AND (inbound = ?)", 5.minutes.ago, aphone, beeper, inboundflag ])

By the way, is there any way to structure this query using pure active record, so we can (hopefully) avoid database-specific query strings?

A: Are you sure you are using SQLLite on Heroku and not MySQL? Either way the query syntax seems a little incorrect. I would modify your query to this:

Beep.last(:conditions => [ "(widget_id IS NOT NULL) AND (updated_at > ?) AND (userphone = ?) AND (beeper = ?) AND (inbound = ?)", 5.minutes.ago, aphone, beeper, inboundflag ])

If you are using Rails3 you can chain your conditions together like this:

Beep.where('widget_id IS NOT NULL)
  .where('updated_at > ?', 5.minutes.ago)
  .where(userphone: aphone)
  .where(beeper: beeper)
  .where(inbound: inboundflag)
  .last


text:
Q: How composer `extra.symfony.require` restriction is enforced? Let's say I have a Symfony v4.4 (Flex) project with the following block in the composer.json:
"extra": {
    "symfony": {
        "allow-contrib": false,
        "require": "4.4.*"
    }
}

As expected, it restricts the Symfony core packages to stick to the v4.4 version.
symfony/monolog-bridge package respects it, so you cannot install symfony/monolog-bridge ~4.3.0 or ^5.0.
Yet you can install symfony/monolog-bundle ~3.5.0, which is also expected, given it's just a bundle that is not part of the core Symfony framework and which has its own independent release and versioning cycle.
What I cannot understand is what helps composer to distinguish, which of those packages a Symfony core package so that extra.symfony.require restriction was applied, and which is not?
I originally thought it's the composer's type property that makes it possible, but I cannot find any traces of symfony-bridge type being any unique. If it is - a link to source code or documentation would be extremely helpful.
UPD:
The default Symfony (with Flex) v4.4 composer.json:
{
    "name": "symfony/website-skeleton",
    "type": "project",
    "license": "MIT",
    "description": "A skeleton to start a new Symfony website",
    "require": {
        "php": "^7.1.3",
        "ext-ctype": "*",
        "ext-iconv": "*",
        "sensio/framework-extra-bundle": "^5.1",
        "symfony/asset": "*",
        "symfony/console": "*",
        "symfony/dotenv": "*",
        "symfony/expression-language": "*",
        "symfony/flex": "^1.3.1",
        "symfony/form": "*",
        "symfony/framework-bundle": "*",
        "symfony/http-client": "*",
        "symfony/intl": "*",
        "symfony/mailer": "*",
        "symfony/monolog-bundle": "^3.1",
        "symfony/orm-pack": "*",
        "symfony/process": "*",
        "symfony/security-bundle": "*",
        "symfony/serializer-pack": "*",
        "symfony/translation": "*",
        "symfony/twig-pack": "*",
        "symfony/validator": "*",
        "symfony/web-link": "*",
        "symfony/yaml": "*"
    },
    "require-dev": {
        "symfony/debug-pack": "*",
        "symfony/maker-bundle": "^1.0",
        "symfony/profiler-pack": "*",
        "symfony/test-pack": "*"
    },
    "config": {
        "preferred-install": {
            "*": "dist"
        },
        "sort-packages": true
    },
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "App\\Tests\\": "tests/"
        }
    },
    "replace": {
        "paragonie/random_compat": "2.*",
        "symfony/polyfill-ctype": "*",
        "symfony/polyfill-iconv": "*",
        "symfony/polyfill-php71": "*",
        "symfony/polyfill-php70": "*",
        "symfony/polyfill-php56": "*"
    },
    "scripts": {
        "auto-scripts": {
            "cache:clear": "symfony-cmd",
            "assets:install %PUBLIC_DIR%": "symfony-cmd"
        },
        "post-install-cmd": [
            "@auto-scripts"
        ],
        "post-update-cmd": [
            "@auto-scripts"
        ]
    },
    "conflict": {
        "symfony/symfony": "*"
    },
    "extra": {
        "symfony": {
            "allow-contrib": false,
            "require": "4.4.*"
        }
    }
}

now if you add "symfony/monolog-bridge": "^5.0" dependency and composer update you'd get
$ composer update
Loading composer repositories with package information
Updating dependencies (including require-dev)
Restricting packages listed in "symfony/symfony" to "4.4.*"
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested package symfony/monolog-bridge ^5.0 exists as symfony/monolog-bridge[4.4.x-dev, v4.4.0, v4.4.0-BETA1, v4.4.0-BETA2, v4.4.0-RC1, v4.4.1] but these are rejected by your constraint.
  Problem 2
    - symfony/monolog-bundle v3.5.0 requires symfony/monolog-bridge ~3.4 || ~4.0 || ^5.0 -> satisfiable by symfony/monolog-bridge[4.4.x-dev, v4.4.0, v4.4.0-BETA1, v4.4.0-BETA2, v4.4.0-RC1, v4.4.1] but these conflict with your requirements or minimum-stability.
    - symfony/monolog-bundle v3.5.0 requires symfony/monolog-bridge ~3.4 || ~4.0 || ^5.0 -> satisfiable by symfony/monolog-bridge[4.4.x-dev, v4.4.0, v4.4.0-BETA1, v4.4.0-BETA2, v4.4.0-RC1, v4.4.1] but these conflict with your requirements or minimum-stability.
    - symfony/monolog-bundle v3.4.0 requires symfony/monolog-bridge ~3.4|~4.0 -> satisfiable by symfony/monolog-bridge[4.4.x-dev, v4.4.0, v4.4.0-BETA1, v4.4.0-BETA2, v4.4.0-RC1, v4.4.1] but these conflict with your requirements or minimum-stability.
    - symfony/monolog-bundle v3.3.1 requires symfony/monolog-bridge ~2.7|~3.3|~4.0 -> satisfiable by symfony/monolog-bridge[4.4.x-dev, v4.4.0, v4.4.0-BETA1, v4.4.0-BETA2, v4.4.0-RC1, v4.4.1] but these conflict with your requirements or minimum-stability.
    - symfony/monolog-bundle v3.3.0 requires symfony/monolog-bridge ~2.7|~3.3|~4.0 -> satisfiable by symfony/monolog-bridge[4.4.x-dev, v4.4.0, v4.4.0-BETA1, v4.4.0-BETA2, v4.4.0-RC1, v4.4.1] but these conflict with your requirements or minimum-stability.
    - symfony/monolog-bundle v3.2.0 requires symfony/monolog-bridge ~2.7|~3.0|~4.0 -> satisfiable by symfony/monolog-bridge[4.4.x-dev, v4.4.0, v4.4.0-BETA1, v4.4.0-BETA2, v4.4.0-RC1, v4.4.1] but these conflict with your requirements or minimum-stability.
    - symfony/monolog-bundle v3.1.2 requires symfony/monolog-bridge ~2.7|~3.0|~4.0 -> satisfiable by symfony/monolog-bridge[4.4.x-dev, v4.4.0, v4.4.0-BETA1, v4.4.0-BETA2, v4.4.0-RC1, v4.4.1] but these conflict with your requirements or minimum-stability.
    - symfony/monolog-bundle v3.1.1 requires symfony/monolog-bridge ~2.7|~3.0|~4.0 -> satisfiable by symfony/monolog-bridge[4.4.x-dev, v4.4.0, v4.4.0-BETA1, v4.4.0-BETA2, v4.4.0-RC1, v4.4.1] but these conflict with your requirements or minimum-stability.
    - symfony/monolog-bundle v3.1.0 requires symfony/monolog-bridge ~2.7|~3.0 -> no matching package found.
    - Installation request for symfony/monolog-bundle ^3.1 -> satisfiable by symfony/monolog-bundle[v3.1.0, v3.1.1, v3.1.2, v3.2.0, v3.3.0, v3.3.1, v3.4.0, v3.5.0].

Potential causes:
 - A typo in the package name
 - The package is not available in a stable-enough version according to your minimum-stability setting
   see <https://getcomposer.org/doc/04-schema.md#minimum-stability> for more details.
 - It's a private package and you forgot to add a custom repository to find it

Read <https://getcomposer.org/doc/articles/troubleshooting.md> for further common problems.

The question remains - how symfony knows that package should be restricted by v4.4

A: As far as I know Flex uses the list of components from the symfony/symfony metapackage, according to the message in your output:

Restricting packages listed in "symfony/symfony" to "4.4.*"

You can find the list of packages in the corresponding composer.json or on packagist:

*

*https://packagist.org/packages/symfony/symfony

*https://github.com/symfony/symfony/blob/master/composer.json#L38-L100
This is the current list for 4.4.1:
symfony/asset: v4.4.1
symfony/amazon-mailer: v4.4.1
symfony/browser-kit: v4.4.1
symfony/cache: v4.4.1
symfony/config: v4.4.1
symfony/console: v4.4.1
symfony/css-selector: v4.4.1
symfony/dependency-injection: v4.4.1
symfony/debug: v4.4.1
symfony/debug-bundle: v4.4.1
symfony/doctrine-bridge: v4.4.1
symfony/dom-crawler: v4.4.1
symfony/dotenv: v4.4.1
symfony/error-handler: v4.4.1
symfony/event-dispatcher: v4.4.1
symfony/expression-language: v4.4.1
symfony/filesystem: v4.4.1
symfony/finder: v4.4.1
symfony/form: v4.4.1
symfony/framework-bundle: v4.4.1
symfony/google-mailer: v4.4.1
symfony/http-client: v4.4.1
symfony/http-foundation: v4.4.1
symfony/http-kernel: v4.4.1
symfony/inflector: v4.4.1
symfony/intl: v4.4.1
symfony/ldap: v4.4.1
symfony/lock: v4.4.1
symfony/mailchimp-mailer: v4.4.1
symfony/mailer: v4.4.1
symfony/mailgun-mailer: v4.4.1
symfony/messenger: v4.4.1
symfony/mime: v4.4.1
symfony/monolog-bridge: v4.4.1
symfony/options-resolver: v4.4.1
symfony/postmark-mailer: v4.4.1
symfony/process: v4.4.1
symfony/property-access: v4.4.1
symfony/property-info: v4.4.1
symfony/proxy-manager-bridge: v4.4.1
symfony/routing: v4.4.1
symfony/security: v4.4.1
symfony/security-core: v4.4.1
symfony/security-csrf: v4.4.1
symfony/security-guard: v4.4.1
symfony/security-http: v4.4.1
symfony/security-bundle: v4.4.1
symfony/sendgrid-mailer: v4.4.1
symfony/serializer: v4.4.1
symfony/stopwatch: v4.4.1
symfony/templating: v4.4.1
symfony/translation: v4.4.1
symfony/twig-bridge: v4.4.1
symfony/twig-bundle: v4.4.1
symfony/validator: v4.4.1
symfony/var-dumper: v4.4.1
symfony/var-exporter: v4.4.1
symfony/web-link: v4.4.1
symfony/web-profiler-bundle: v4.4.1
symfony/web-server-bundle: v4.4.1
symfony/workflow: v4.4.1
symfony/yaml: v4.4.1

As for symfony/monolog-bundle, which is not in the list, it will be installed in a version which does not conflict with other packages. In other words it will be installed in whatever version fits best for Symfony 4.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python(Spyder) problems with speed when I import (Spyder; scipy loadmat) 3 vectors with 250.000 elements it is impossible to continure working (if i want to write something into Ipython Console - it takes minutes). If i import the same vectors in Matlab, I have no problems.
Is that a Python or a Spyder Problem? Are there any tipps/tricks?


text:
Q: ASP.Net Core MVC - List multiselect not showing select = true items

I'm making a strongly typed update/create view for "Medical Supplies" in which users can select multiple options ("Kits") from a dropdown list that received a List<SelectListItem>. The list is a <select multiple="multiple">. It was originally working perfectly, but I must have accidentally changed something.
Now the dropdown does not display SelectListItems passed to it as selected = true as selected (as verified by VS debugger), so I can select new items but not deselect previously selected ones. I need this to compare the list of IDs from the new selection to the old one in order to determine what must be removed from the Db.
This is my view model:
 public class MedicalSupplyViewModel
    {
        public MedicalSupplyViewModel()
        {
            Supply = new MedicalSupply();
            KitList = new List<SelectListItem>();
            KitIds = new List<int>();
        }

        public MedicalSupply Supply { get; set; }
        public List<SelectListItem> KitList { get; set; }
        public string StringKits { get; set; }
        public List<int> KitIds { get; set; }

        public void KitStringSet()
        {
            IEnumerable<string> KitNames = Supply.KitSupplies.Select(ks => ks.Kit.Name);

            StringKits = Supply.KitSupplies.Count() == 0 ? "N/A" : string.Join(", " , KitNames);
        }
    }

This is the relevant cshtml in my view:
<select multiple="multiple" class="form-control" id="kit_select" asp-for="KitIds" asp-items="Model.KitList"></select>

This is the part of the controller method for this page that creates the SelectListItems:
DetailsModel.KitList = _db.Kits.ToList().ConvertAll(k =>
{
     return new SelectListItem()
     {
          Value = k.Id.ToString(),
          Text = k.Name,
          Selected = SelectedKits.Contains(k)
      };
});

Even setting the item to selected = true will not display them as such. I've set breakpoint everywhere, including in the view, and I cannot find a discrepancy between the selected property and what it should be anywhere except for the rendered html. I've also used different browsers and spent hours searching the internet and this website.
What could be the cause of this issue?

A: You should set the selected items' value to the KitIds. Below is my test example:
Model:
public class MedicalSupplyViewModel
{
    public MedicalSupplyViewModel()
    {
        KitList = new List<SelectListItem>();
        KitIds = new List<int>();
    }

    public List<SelectListItem> KitList { get; set; }
    public string StringKits { get; set; }
    public List<int> KitIds { get; set; }

}
public class Kit
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Controller:
public IActionResult Index()
    {
        List<Kit> kits = new List<Kit>
        {
            new Kit{ Id = 1, Name = "AA"},
            new Kit{ Id = 2, Name = "BB"},
            new Kit{ Id = 3, Name = "CC"},
        };

        List<Kit> SelectedKits = new List<Kit>
        {
            new Kit{ Id = 1, Name = "AA"},
            new Kit{ Id = 2, Name = "BB"}
        };

        var DetailsModel = new MedicalSupplyViewModel();
        DetailsModel.KitIds = SelectedKits.Select(x => x.Id).ToList();
        DetailsModel.KitList = kits.ToList().ConvertAll(k =>
        {
            return new SelectListItem()
            {
                Value = k.Id.ToString(),
                Text = k.Name
            };
        });
        return View(DetailsModel);
    }

View:
<select multiple="multiple" class="form-control" id="kit_select" asp-for="KitIds" asp-items="Model.KitList"></select>

Result:


text:
Q: Electron - renderer.js across html pages Good evening.
I am experimenting with electron and I really like it. However, I'm becoming stuck on some fundamentals that seem to slip between the net in terms of documentation. It's definitely an understanding thing on my part, so I thought I'd ask the good people for some guidance.
I have an electron app with a main.js that loads in index.html.
In index.html I have some markup and also a script tag linking to renderer.js at the bottom of the page.
Everything works great with the ipc allowing main.js and renderer.js to communicate, so I am able to do client side js and also use node functionality on index.html, as node integration is set to true.
I also have another page (about.html). This also has renderer.js in a script tag at the bottom of the page. However, when I click a button in the electron app and land on about.html, the renderer.js script does nothing at all when any functions are called, and logs nothing to the console.
In fact, renderer.js only seems to work on index.html in electron.
Why is this?
Thanks in advance.


text:
Q: How to create an API endpoint without a model in Loopback? I understand we can create remote methods on models which will expose an endpoint. However, is there a way to expose an endpoint without a model?
For example, if I want to create an endpoint checks the version of a native app. I don't need a model to back this endpoint. The endpoint would simply check the passed in version and respond.
Does this construct exist within Loopback?  Or does it need to be done within the context of Express?

A: You can use express routes as shown in Loopback's Getting Started example.


text:
Q: Slow page Loads When Using Dynamic Coding I have written code to get certain tags, and then show the products that have those tags.
This is the code:
$tag_string = '';

for ($i = 0; $i < 8; $i++) {
    for ($j = 0; $j < 8; $j++) {

        $tag_to_use = get_post_meta($post->ID, '_tag_to_use_'.$i.'_'.$j, true);
        $tag_string = $tag_to_use ? $tag_string .= $tag_to_use . ',' : $tag_string .= '';

    }
}

if ( substr( $tag_string, -1) == ',' ) {
    $tag_string = rtrim( $tag_string, ',' );
}

echo do_shortcode( '[products tag="' . $tag_string . '"]' );

}

When I run th code, I get slow page loads.
When I change this:
echo do_shortcode( '[products tag="' . $tag_string . '"]' );

To this:
echo do_shortcode( '[products tag="test,test1"]' );

The page loads fast.
Why is that happening, and how can I fix it? If any more information is needed, tell me and I'll update the question.
Thanks!

A: I'm not sure, if it is the root of the problem, but the thing that I noticed is that your code ends up calling get_post_meta quite many times (64? 8 loops within 8 loops, yes?) for the same post.
Perhaps you could get all of the post meta just once, before the for loop. Then within your loop use isset() or ! empty() to check if the data exists.
Something along these lines,
$post_meta = get_post_meta($post->ID); // This returns an array with all the data in position 0, if I remember correctly
for ($i = 0; $i < 8; $i++) {
  for ($j = 0; $j < 8; $j++) {
    if ( isset( $post_meta[0]['_tag_to_use_'.$i.'_'.$j] ) ) {
      $tag_to_use = $post_meta[0]['_tag_to_use_'.$i.'_'.$j];
      // The meta value might be in a array with the position 0, var_dump $tag_to_use to see if this is the case
      // $tag_to_use = $post_meta[0]['_tag_to_use_'.$i.'_'.$j][0];
      $tag_string = $tag_to_use ? $tag_string .= $tag_to_use . ',' : $tag_string .= '';
    }
  }
}

Use var_dump to check that you get the array indexes correct and maybe_unserialize() the meta data, if needed.
I don't know if this is just broscience and wishful thinking, but maybe it's worth the try. You can of course use microtime to get a rough idea, if the loop above is faster than the original.


text:
Q: How can I get the last 10 records of each day? I have a DataFrame with 96 records each day, for 5 consecutive days.
Data:  {'value': {Timestamp ('2018-05-03 00:07:30'): 13.02657778, Timestamp ('2018-05-03 00:22:30'): 10.89890556, Timestamp ('2018-05-03 00:37:30'): 11.04877222,... (more days and times)
Datatypes: DatetimeIndex (index column) and float64 ('flow' column).
I want to save 10 records before an indicated hour (H), of each day.
I only managed to do that for one day:
df.loc[df['time'] < '09:07:30'].tail(10)

A: You can group your data by day (or by month or by other ranges) using pandas.Grouper (see also this discussion).
In your case, use something like:
df.groupby(pd.Grouper(freq='D')).tail(10)

EDIT:
For getting all rows before a given hour, use df.loc[df.index.hour < H] (as already proposed in simpleApp's answer) where H is the hour as an integer value.
So in one line:
df.loc[df.index.hour < H].groupby(pd.Grouper(freq='D')).tail(10)

A: I would suggest filter the record by an hour and then group by date.
Data setup:
import pandas as pd
start, end = '2020-10-01 01:00:00', '2021-04-30 23:30:00'
rng = pd.date_range(start, end, freq='5min')
df=pd.DataFrame(rng,columns=['DateTS'])

set the hour
noon_hour=12 # fill the hour , for filteration

Result, if head or tail does not work on your data, you would need to sort it.
df_before_noon=df.loc[df['DateTS'].dt.hour < noon_hour] # records before noon
df_result=df_before_noon.groupby([df_before_noon['DateTS'].dt.date]).tail(10) # group by date


text:
Q: How to display dynamic text Hello I am new to react native and I am trying to build an app that simulates a basic dialer. What I am having trouble with is displaying the numbers that I click.
For example, this is my function to add '1' to the display
var number = '';
const tlac1 = function(){
  var add_one = '1';
  number = number + add_one;
  console.log(number);
};

and this is how I am trying to display it:
<View style={styles.display}>
  <Text>{number}</Text>
</View>

Can anyone please explain to me why is the showing text not updated? When I am pressing 1 it does update and shows correct numbers in consoler, however it does not do the same with displaying it in Text element.
My whole component:
<View style={styles.container}>
        <View style={styles.display}>
          <Text>{number}</Text>
        </View>
        <View style={styles.keys}>
            <View style={styles.inner}>
              <Pressable onPress={tlac1}>
                <Text style={{fontSize: 40, fontWeight: '200'}}>1</Text>
              </Pressable>
            </View>
        </View>
</View>

A: Here's how a similar component would be described in HTML-based react code:

class TodoApp extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
        number: 1
    }

    this.increment = this.increment.bind(this);
  }

  increment() {
    this.setState({number: this.state.number + 1})
  }

  render() {
    return (

        <input type="text" value={this.state.number} />
        <button onClick={this.increment}>increment</button>

    )
  }
}

ReactDOM.render(<TodoApp />, document.querySelector("#app"))

As you can see, you set the state initially in the constructor and then use the increment function to modify the state, by using this.setState
The exact same principles will apply in react-native.
Not sure what your setup is like, but make sure your handling the this.<function>.bind(this) situation somehow


text:
Q: Is it possible to resize mounted partition over ssh? Background: I was given SSH access to a Ubuntu 20.04 VPS that has root partition of 5G (sda total 25G). VPS provider says Linux admin can resize the /dev/sda1 partition.
$ sudo fdisk -l && df -h
Disk /dev/sda: 25 GiB, 26843545600 bytes, 52428800 sectors
Disk model: Virtual disk
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xe1f10bb0

Device     Boot Start      End  Sectors Size Id Type
/dev/sda1  *     2048 10483711 10481664   5G 83 Linux
Filesystem      Size  Used Avail Use% Mounted on
udev            1.9G     0  1.9G   0% /dev
tmpfs           394M  788K  393M   1% /run
/dev/sda1       4.9G  3.0G  1.7G  64% /
tmpfs           2.0G     0  2.0G   0% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           2.0G     0  2.0G   0% /sys/fs/cgroup
tmpfs           394M     0  394M   0% /run/user/1002

I need to resize /dev/sda1 partition mounted to / over SSH. As far as I know, it is not possible.
Is it impossible, is it possible or has there been some miscommunications with the VPS provider? I am in contact with them through a third party.

A: You can use the growpart utility to resize the partition to fill the available space. growpart expects the disk device and partition number as separate arguments. So you can resize the partition /dev/sda1 by: growpart /dev/sda 1. Note that the space is required. After that is done, you can resize the filesystem.

A: I do this all the time on VMs, using parted and resize2fs:
$ sudo parted /dev/sda
(parted) resizepart 1 100%
(parted) quit
$ sudo partprobe /dev/xvda
$ sudo resize2fs -p /dev/xvda1

Obviously you need free space on the sda disk after the first partition.
partprobe (comes with parted) is necessary to get kernel to reread partition table.
resize2fs to resize an ext* filesystem can normally be done online, but it can only grow filesystems. Other Linux filesystems will have other resizing commands; most can only grow online, not shrink.
Use print command in parted before and after resizepart if unsure.


text:
Q: How to access/change the content of a button from ViewModel I want a certain function to execute from a command depending on the content of the button. As of now I have two buttons. DesignImg When connect is clicked I need to change it to "Disconnect". How do I access the content of the button from my view model.
Here is my viewModel where I will connect/disconnect:
namespace firstApp
{
    public class ViewModel
    {
        public TcpClient client = null;
        public ICommand MyCommand { get; set; }

        public ViewModel()
        {
            MyCommand = new Command(ExecuteMethod, canExecuteMethod);
        }

        private bool canExecuteMethod(object parameter)
        {
            return true;
        }

        public void ExecuteMethod(object parameter)
        {
            //if client is not connected do this... id client is connected then close client.
            try
            {
                // Create a TcpClient.
                // Note, for this client to work you need to have a TcpServer
                // connected to the same address as specified by the server, port
                // combination.
                Int32 port = 8000;
                TcpClient client = new TcpClient("127.0.0.1", port);

            }
            catch (ArgumentNullException ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
            catch (SocketException ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

And here is the view model of my send:
namespace firstApp
{
    public class SendViewModel: ViewModel
    {
        public ICommand MySendCommand { get; set; }

        public SendViewModel()
        {
            MyCommand = new Command(ExecuteMethod, canExecuteMethod);
        }

        private bool canExecuteMethod(object parameter)
        {
            return true;
        }

        public void ExecuteSendMethod(object parameter)
        {
            if (client.Connected)
            {
                Byte[] data = System.Text.Encoding.ASCII.GetBytes("hello");

                // Get a client stream for reading and writing.
                //  Stream stream = client.GetStream();

                NetworkStream stream = client.GetStream();

                // Send the message to the connected TcpServer.
                stream.Write(data, 0, data.Length);
                //ChatScreentextBox.AppendText(TextToSend);//probably done need it here
                                                           //worker1.RunWorkerAsync();///gets to here
            }
            else
            {
                //ChatScreentextBox.AppendText("There is no connection");
            }
        }

A: C#
//This variable needs to be usable in XAML fyi
private bool IsConnected = false;

// Your command method
private void ChangeConnectionStatus()
{
  if (IsConnected)
  {
    IsConnected = false;
    //call method for connecting bellow
  }
  else
  {
    IsConnected = true;
    //call method for disconnecting bellow
  }
}

XAML
                     <Button Command="{Binding ChangeConnectionStatus}">
                        <Button.Style>
                            <Style TargetType="Button">
                                <Style.Triggers>
                                    <DataTrigger Binding="{Binding IsConnected}" Value="true">
                                        <Setter Property="Content" Value="Conected" />
                                    </DataTrigger>
                                  <DataTrigger Binding="{Binding IsConnected}" Value="false">
                                        <Setter Property="Content" Value="Disconected" />
                                    </DataTrigger>
                                </Style.Triggers>
                            </Style>
                        </Button.Style>
                    </Button>

Not copy and pasteable code but should give you an idea of how to do it.
Also in the ViewModel usually people try to avoid editing the view that's why the DataTrigger is generally a better way because it keeps them separated.

A: Add a ViewModel property and bind it to the button text. Then you can change the button text to something else easily. Note that your ViewModel will need to implement INotifyPropertyChanged and add the appropriate event and event-raising method.
In ViewModel (assumes INotifyPropertyChanged is implemented):
private string _connectButtonText = "Connect"; // set initial value here or in the constructor
public string ConnectButtonText { get => _connectButtonText; set => { _connectButtonText = value; RaisePropertyChanged(nameof(ConnectButtonText)); }

In XAML (assumes your page's DataContext is set to your ViewModel):
<Button Text={Binding ConnectButtonText} ... />

To change the button text, in your ViewModel:
public void ExecuteSendMethod(object parameter)
{
    ...

    ConnectButtonText = "Disconnect";

    ...
}


text:
Q: Scaling elements like an image When I for example have an image in  :

Its height automatically gets scaled according to width the image gets (you can see that when you resize the browser window for example). Is there any way to do the same with other elements in html ?

A: Solution #1
You could use the new css viewport units vw, vh etc to pull this off.
FIDDLE
div
{
    width: 40vw;
    height: 20vw;
    background: pink;
}

CSS3 has some new values for sizing things relative to the current
  viewport size: vw, vh, and vmin.
  One unit on any of the three values is 1% of the viewport axis.
  "Viewport" == browser window size == window object. If the viewport is
  40cm wide, 1vw == 0.4cm.
1vw = 1% of viewport width 1vh = 1% of viewport height 1vmin = 1vw or
  1vh, whichever is smaller 1vmax = 1vw or 1vh, whichever is larger (css-tricks post)

Support: IE 9+, Firefox 19+, Chrome 20+, Safari 6+
Reference: w3c, mozilla

Solution #2
FIDDLE
Markup

CSS
/* container defines margins and width */
.container {
    margin: 60px 120px 0;
}

/* outer container will define aspect ratio */
.outer {
    position: relative;
    width: 100%;
}

.outer.r4x3 {
    padding-top: 75%; /* "height" will be 3/4 of width */
}
/* inner container positioned absolutely and holds content */
.outer .inner {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    outline: 1px solid grey;
    background: pink;
}

A: here is a trick which is actually for responsive video and Iframes to maintain aspect ratio but it work on other things as well... http://webdesignerwall.com/tutorials/css-elastic-videos


text:
Q: How to use ntheorem and beamer together? I want to create a presentation with beamer. In it I want to include the package ntheorem.
When I do it, I get the following error message:
 ! LaTeX Error: \begin{altenv} on input line 40 ended by \end{itemize}.

It seems to be a known problem since I found some related questions (here and here). However, I tried to include some solution in my MWE, but it is not working.
It also seems that this issue was not present in TeXLive 2019 (whithout any warranty), because I get a problem with ntheorem when I recompiled a presentation using it that I made last year.
Here is a MWE:
\documentclass{beamer}

    \usepackage[utf8]{inputenc}
    \usepackage[T1]{fontenc}

    \usepackage{amsmath}
    \usepackage{amssymb, amscd, amsxtra}

        \makeatletter   % Releash command of ntheorem already defined by beamer to avoid conflict
            \let\th@plain\relax
            \let\openbox\relax
            \let\proofname\relax
            \let\proof\relax
            \let\endproof\relax
        \makeatother
    \usepackage[amsthm, amsmath, thmmarks, hyperref]{ntheorem}
%       \newtheorem{proposition}{Proposition}
        \newtheorem{defs}{Definition}
    \usepackage[ntheorem]{empheq}

    \title{Test}
    \date{\today}
    \author{John Doe}
    \institute{My Institut}

\begin{document}

        \begin{frame}
            \titlepage
        \end{frame}

        \begin{frame}{Animation}
            \begin{itemize}[<+- | alert@+>]
                \item \alert<4>{This is\only<4>{ really} important}
                \item Now this
                \item And now this
            \end{itemize}
        \end{frame}

        \begin{frame}{Math}
            \begin{equation}
                e = \lim_{n\to \infty} \left(1 + \frac{1}{n}\right)^n
            \end{equation}

            \begin{theorem}[test]
                something
            \end{theorem}
        \end{frame}

\end{document}

So how to solve this problem and use ntheorem with beamer ?

A: You want to turn off the theorem definitions of beamer, or else use those instead of ntheorem.
\documentclass[notheorems,noamsthm]{beamer}
    \usepackage[utf8]{inputenc} % The default since 2018
    \usepackage[T1]{fontenc}

    \usepackage{amsmath}
    \usepackage{amssymb, amscd, amsxtra}

    \usepackage[amsthm, amsmath, thmmarks, hyperref]{ntheorem}
      \newtheorem{theorem}{Theorem}
      \newtheorem{proposition}{Proposition}
      \newtheorem{defs}{Definition}
    \usepackage[ntheorem]{empheq}

    \title{Test}
    \date{\today}
    \author{John Doe}
    \institute{My Institut}

\begin{document}

        \begin{frame}
            \titlepage
        \end{frame}

        \begin{frame}{Animation}
            \begin{itemize}
                \item \alert<4>{This is\only<4>{ really} important}
                \item Now this
                \item And now this
            \end{itemize}
        \end{frame}

        \begin{frame}{Math}
            \begin{equation}
                e = \lim_{n\to \infty} \left(1 + \frac{1}{n}\right)^n
            \end{equation}

            \begin{theorem}[test]
                something
            \end{theorem}
        \end{frame}

\end{document}

I slightly edited the itemize command you used to avoid a clash with the option you gave it and the default inner theme.  You'd want to fix that quick-and-dirty kludge, but it's not germane to your question.


text:
Q: How can I get query of MYSQL table with string column value, where it is "01" to a certain 1? This doesn't look working
Mytable.where("property::int = ? ",
               params[:property].to_i)

I need a query to find 002 or 02 for 2 for example

A: You can use MySQL's LIKE operator.
property = params[:property].to_i
Mytable.where("property LIKE ?", "%#{property}")

A: First of all don't forget to index the property column in your table.
Also you are not much clear in the question. The column will have the data in form of "002" / "02" / "2" OR it can be "123"/"213" format as well?
If its just "002" / "02" / "2" format, then you can do it as below:
Mytable.where("property LIKE ?", "%#{params[:property].to_i}")

Or if you assume all the formats including "123"/"213", then:
Mytable.where("property LIKE ?", "%#{params[:property].to_i}%")

Also you may want to check the params[:property] parameter value to be present, numericality etc.


text:
Q: Graph-like info-graphics The Sunday, January 27, 2019 New York Times has a superb info-graphic describing the path from citizen to Member of the House of Representatives for the current members, including steps such as college, ivy-league college, law school, business, and so on.

Each path (red for Republican, blue for Democrat) starts at the starting node and then passes through an appropriate sequence of circular regions ("milestone disks") associated with each of these milestones.
The simplest approximation would be to create a traditional multi-graph (Graph), but that would miss several key features of this info-graphic:

*

*Each path must remain continuous and visible through each circular "milestone disk"

*Each path stays separate from the others and none cross needlessly, particularly within each "milestone disk"

Of course this info-graphic structure can be used for many applications, but as an illustration consider the input data of the following form:
{{"Jay Smith", "Democrat", "College", "Law School", "Military", "Congress"},
 {"Mary Jones", "Republican", "Ivy-league college", "Graduate school", "Business", Congress"}}

Presumably the designer can place the centers of the "milestone disks" which would be automatically scaled in size (based on the number of paths through it) and the paths would conform appropriately.
Special credit would be to be able to mouseover or click-highlight a single path and have the representative's name, college and so on appear, and to force all blue paths to pass through the top of a milestone disk and red paths to pass through the bottom of a milestone disk (to enable better comparison between Democrats and Republicans.

A: Version 2
Get some node data to work with...:
BlockRandom[
  people = RandomEntity["Person", 1000];
  names = DeleteMissing@EntityValue[people, "FullName"];
  numPeeps = Length@names;
  mainCategory = RandomWord[2];
  wordChoices = TakeList[RandomWord[25], RandomInteger[{2, 5}, 5]];
  nodes =
   Join[
    List /@ names,
    List /@ RandomChoice[mainCategory, numPeeps],
    Transpose[RandomChoice[#, numPeeps] & /@ wordChoices],
    ConstantArray["End", {Length@names, 1}] ,
    2
    ]
  ];

And here's an updated single function to generate the graphics:
regroupArrows[arrowGroups_, graphPaths_] :=
  Module[
   {
    shrinkingArrows = arrowGroups,
    paths = graphPaths,
    arrow,
    arrows,
    arrowGroup
    },
   arrows =
    Table[
     Table[
      arrowGroup = shrinkingArrows[pair[[1]], pair[[2]]];
      If[MissingQ[arrowGroup],
       pair = Reverse[pair];
       arrowGroup = shrinkingArrows[pair[[1]], pair[[2]]]
       ];
      Which[
       MissingQ[arrowGroup],
       {arrowGroup, pair},
       Length@arrowGroup > 0,
       arrow = arrowGroup[[1]];
       shrinkingArrows[pair[[1]], pair[[2]] ] = Rest[arrowGroup];
       arrow,
       True,
       {$Failed, pair}
       ],
      {pair, path}
      ],
     {path, Values@paths}
     ];
   AssociationThread[
    Keys[paths],
    arrows
    ]
   ];
joinBezier[arrows_] :=
  With[
   {
    bezzz = Cases[arrows, _BezierCurve, \[Infinity]],
    setBacks = arrows[[{1, -1}, -1]]
    },
   If[Length[bezzz] == Length[arrows],
    ReplacePart[
     arrows[[-1]],
     {
      1 ->
       BezierCurve[
        Join @@ bezzz[[All, 1]]
        ],
      If[AllTrue[setBacks, NumericQ],
       -1 -> 0(*setBacks*),
       Nothing
       ]
      }
     ],
    arrows
    ]
   ];
makeStreamGraph // Clear
makeStreamGraph[
   nodes : {_, _, _, __} ..,
   embedding : _String : "LayeredDigraphEmbedding",
   colorFunction : _Function : (If[EvenQ[#2[[1]]], Hue[.666, .6, .6],
       Hue[0, 1, .8]] &),
   diskStyles :
    Except[_?OptionQ | {__String}, _Directive | _List] : {GrayLevel[
      1, .5], EdgeForm[Black]},
   useDynamics : True | False : False,
   labeledNodes : {___String} : {},
   ops : OptionsPattern[]
   ] :=
  Module[
   {
    mainCategory,
    mainCategoryColors,
    namedNodes,
    baseGraphs,
    baseWeights,
    choiceWeights,
    coreGraph,
    choicePositions,
    coreGraphics,
    arrows,
    disks,
    gComplexPositions,
    arrowGroups,
    graphPaths,
    arrowGroupings,
    endNodes
    },
   mainCategory = DeleteDuplicates@nodes[[All, 2]];
   endNodes = DeleteDuplicates@nodes[[All, -1]];
   mainCategoryColors =
    AssociationThread[mainCategory,
     MapIndexed[colorFunction, mainCategory]
     ];
   namedNodes = Association@Map[#[[1 ;; 2]] -> #[[3 ;;]] &, nodes];
   baseGraphs =
    MapThread[DirectedEdge, {Most[#], Rest[#]}] & /@ namedNodes;
   baseGraphs =
    KeySortBy[baseGraphs, #[[2]] &];
   baseWeights =
    Counts /@
     Transpose[Values[namedNodes]];
   If[Length@endNodes == 1,
    baseWeights[[-1]] =
     AssociationThread[
      Keys[baseWeights[[-1]]],
      {Mean@Flatten@Values@baseWeights}/2
      ]
    ];
   choiceWeights =
    Join @@ (N@baseWeights/Max[baseWeights]);
   choiceWeights =
    Thread[
     Keys[choiceWeights] ->
      Rescale[Rescale[Values@choiceWeights], {0, 1}, {.2, 1}]
     ];
   coreGraph =
    Graph[
     Flatten@Values[baseGraphs],
     GraphLayout -> embedding,
     VertexSize -> choiceWeights,
     VertexStyle -> White
     ];
   choicePositions =
    AssociationThread[
     VertexList[coreGraph],
     GraphEmbedding[coreGraph, embedding]
     ];
   coreGraphics = Show@coreGraph;
   If[Head@coreGraphics[[1]] =!= GraphicsComplex,
    Return[
     Failure["NotImplemented", <|
       "MessageTemplate" ->
        "Not gonna work for this embedding for whatever reason"
       |>], Module]
    ];
   arrows =
    Cases[coreGraphics,
     a_Arrow :> (Cases[a, _Integer, \[Infinity]][[{1, -1}]] ->
        a), \[Infinity]];
   disks = Cases[coreGraphics, _Disk, \[Infinity]];
   gComplexPositions =
    KeySelect[! MissingQ[#] &]@
       AssociationThread[# -> Range[Length[#]]] &@
     Lookup[
      AssociationMap[Reverse, choicePositions],
      Key /@ coreGraphics[[1, 1]]
      ];
   arrowGroups =
    GroupBy[arrows, #[[1, 1]] & -> (#[[1, 2]] -> #[[2]] &),
     GroupBy[First -> Last]];
   graphPaths =
    Lookup[gComplexPositions, List @@ #] & /@ # & /@ baseGraphs;
   arrowGroupings = regroupArrows[arrowGroups, graphPaths];
   DynamicModule[
    {
     colors = mainCategoryColors,
     blends = Blend[{#, White}] & /@ mainCategoryColors
     },
    Graphics[
     GraphicsComplex[
      coreGraphics[[1, 1]],
      {
       {
        Arrowheads[0.],
        KeyValueMap[
         Which[useDynamics,
          {
            Tooltip[
             Dynamic[
              {
               If[CurrentValue["MouseOver"],
                Sequence @@
                 {
                  colors[#[[2]]],
                  AbsoluteThickness[8]
                  },
                Sequence @@ {
                  blends[#[[2]]],
                  AbsoluteThickness[1]
                  }
                ],
               #2
               }
              ],
              #[[1]]
             ]
            } &,
          Length@labeledNodes > 0,
          Tooltip[
            {

             Sequence @@

              If[MemberQ[labeledNodes, #[[1]]],
               {colors[#[[2]]], AbsoluteThickness[8]},
               {blends[#[[2]]], AbsoluteThickness[1]}
               ],
             #2
             },
            #[[1]]
            ] &,
          True,
          Tooltip[
            {
             colors[#[[2]]], AbsoluteThickness[1], #2
             },
            #[[1]]
            ] &
          ],
         (*joinBezier/@*)
         KeySortBy[
          arrowGroupings,
          { MemberQ[labeledNodes, #[[1]]] &}
          ]
         ]
        },
       {
        Sequence @@ Flatten@{diskStyles},
        MapThread[Tooltip, { disks, VertexList[coreGraph]}]
        }
       }
      ],
     ops
     ]
    ]
   ];

Now we can use it like normal:
makeStreamGraph[nodes, ImageSize -> {200, Automatic}]

Or try a different embedding:
makeStreamGraph[nodes, "SpringEmbedding",
 ImageSize -> {Automatic, 250}]

Label some specific nodes:
makeStreamGraph[nodes, "SpringEmbedding", nodes[[;; 5, 1]],
 ImageSize -> {Automatic, 250}]

Or have a Dynamic implementation where we can mouse over a path and see it (note that this is preliminary and slow):
makeStreamGraph[nodes, "SpringEmbedding", True,
 ImageSize -> {Automatic, 250}]

Version 1
Implementation
Here's a place to start, although I don't have time to do the final annoying bits to get it to actually work.
We'll start with some core data of the form you provided:
BlockRandom[
  people = RandomEntity["Person", 1000];
  names = DeleteMissing@EntityValue[people, "FullName"];
  numPeeps = Length@names;
  mainCategory = RandomWord[2];
  wordChoices = Partition[RandomWord[15], 5];
  nodes =
   Join[
    List /@ names,
    List /@ RandomChoice[mainCategory, numPeeps],
    Transpose[RandomChoice[#, numPeeps] & /@ wordChoices],
    2
    ]
  ];

Then we'll extract each subgraph we want to build off of these:
namedNodes =
  Association@
   Map[#[[1 ;; 2]] -> #[[3 ;;]] &, nodes];
baseGraphs =
  MapThread[UndirectedEdge, {Most[#], Rest[#]}] & /@ namedNodes;

Then we sort this so everything looks nice in the end:
baseGraphs = KeySortBy[baseGraphs, #[[2]] &];

Next we assign weights for each node:
choiceWeights =
  Join @@
    With[
     {
      base =
       Counts /@
        Transpose[nodes[[All, 3 ;;]]]
      },
     N@base/Max[base]
     ] // Thread[Keys[#] ->
      Rescale[Rescale[Values@#], {0, 1}, {.2, 1}]
     ] &;

And we extract the vertex coordinates of the best looking multigraph I could find:
coreGraph =
  Graph[
   Flatten@Values[baseGraphs]
   ];
choicePositions =
  AssociationThread[
   VertexList[coreGraph],
   GraphEmbedding[coreGraph, "LayeredDigraphEmbedding"]
   ];

Now here comes the hard part. We can't disambiguate each multigraph edge, so we really need to build this code ourselves. First we extract all the arrows and group them by their coordinates:
coreGraphics = Show@coreGraph;
postProcessArrow[a_Arrow] :=
  Cases[a, _Integer, \[Infinity]][[{1, -1}]] -> a;
arrows = Cases[coreGraphics,
   a_Arrow :> postProcessArrow[a], \[Infinity]];
disks = Cases[coreGraphics, _Disk, \[Infinity]];

Then we try to rebuild our arrow paths:
arrowGroups =
  GroupBy[arrows, #[[1, 1]] & -> (#[[1, 2]] -> #[[2]] &),
   GroupBy[First -> Last]];

graphPaths =
  Lookup[gComplexPositions, List @@ #] & /@ # & /@ baseGraphs;

arrowGroupings =
  Module[
   {
    shrinkingArrows = arrowGroups,
    paths = graphPaths,
    arrow,
    arrows,
    arrowGroup
    },
   arrows =
    Table[
     Table[
      arrowGroup = shrinkingArrows[pair[[1]], pair[[2]]];
      If[MissingQ[arrowGroup],
       pair = Reverse[pair];
       arrowGroup = shrinkingArrows[pair[[1]], pair[[2]]]
       ];
      Which[
       MissingQ[arrowGroup],
       {arrowGroup, pair},
       Length@arrowGroup > 0,
       arrow = arrowGroup[[1]];
       shrinkingArrows[pair[[1]], pair[[2]] ] = Rest[arrowGroup];
       arrow,
       True,
       {$Failed, pair}
       ],
      {pair, path}
      ],
     {path, Values@paths}
     ];
   AssociationThread[
    Keys[paths],
    arrows
    ]
   ];

And finally remake our info graphic:
GraphicsComplex[
  coreGraphics[[1, 1]],
  {
   Arrowheads[0.],
   KeyValueMap[
    {If[#[[2]] === mainCategory[[2]], Hue[0, 1, .8],
       Hue[.666, .6, .6]], Tooltip[#2, #[[1]]]} &,
    arrowGroupings
    ],
   {
    White, EdgeForm[Black],
    MapThread[Tooltip, { disks, VertexList[coreGraph]}]
    }
   }
  ] // Graphics[#, ImageSize -> 1000] &

Now I haven't made sure all the paths are clean, but for non-random data we might get that more-or-less for free. Oh yeah and I have tooltips on there.
One nice thing about this approach is we can really get everything directly from coreGraph so we don't need to rebuild all the Graphics architecture ourselves.


text:
Q: Not able to install editor add-on for whole domain I have published a Sheets Editor Add-on on Chrome Web Store and my colleagues on the same G Suite domain can install it just fine, via the Web Store link.
However, the G Suite account admin doesn't have the option to install it for the whole domain. Anyone have a clue on where to start investigating this?
Edit: I have read in other places that it sometimes takes 3-4 days from publishing in Chrome Web Store until it shows up in the Marketplace. However this doesnt seem to be the case for us since we now have waited for about a week.

A: The app has to be published on the G Suite Marketplace in order to enable a domain-wide installation.
If it is only published on the Chrome Web Store it has to be installed manually by each user.
Choosing where to publish: GSuite Marketplace or Chrome WebStore
If it is published on the G Suite Marketplace it can be installed for the whole domain by admin account following this steps:

*

*Sign in to Google Admin console.

*On the dashboard, click on the Apps icon:

*Once there, go to 'Marketplace apps'

*Add services to your domain

*Search your App and choose to install it for the whole domain

And you are done, the app is installed for the whole domain.
Install Marketplace apps

A: So I have found a way to publish the app even if it's not discoverable in the Marketplace.

*

*Go to https://console.cloud.google.com/

*Go to G Suite Marketplace SDK

*Under Publish in the left pane, Publish the add-on and get the App URL.

*From the app URL, the domain admin can install the add-on for the whole domain.


text:
Q: value map is not a member of models Hi I'm trying to fetch a object from a class and displaying it and I'm getting error "value map is not a member of models.TimeSheetDataStore"
Here is my model class files
TimeSheetDataStore.java
package models;
public class TimeSheetDataStore {
    String ID;
    String EmployeeID;
    String RoleID;
    String Task;
    String TimeSheetDate;
    String CreateDate;
    String UpdateDate;
    String TaskHour;
    String IsBilled;
    String ClientID;
    String ProjectID;
    String atHome;
    String atClientSite;
}

TimeSheet.java
package models;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import models.TimeSheetDataStore;

public class Timesheet {
    public static  List<TimeSheetDataStore> PopulateProject() {
        List<TimeSheetDataStore> TimeSheetList = new ArrayList<TimeSheetDataStore>();
        try {

            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
            Connection conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433","SUMEET","sumeet");
            Statement sta = conn.createStatement();
            String Sql = "select * from Project";
            ResultSet rs = sta.executeQuery(Sql);
            while (rs.next()) {
                TimeSheetDataStore TSDS= new TimeSheetDataStore();
                TSDS.ID=rs.getString("ID");
                TSDS.EmployeeID=rs.getString("EmployeeID");
                TSDS.RoleID=rs.getString("RoleID");
                TSDS.Task=rs.getString("Task");
                TSDS.TimeSheetDate=rs.getString("TimeSheetDate");
                TSDS.CreateDate=rs.getString("CreateDate");
                TSDS.UpdateDate=rs.getString("UpdateDate");
                TSDS.TaskHour=rs.getString("TaskHour");
                TSDS.IsBilled=rs.getString("IsBilled");
                TSDS.ProjectID=rs.getString("ProjectID");
                TSDS.ClientID=rs.getString("ClientID");
                TSDS.atHome=rs.getString("atHome");
                TSDS.atClientSite=rs.getString("atClientSite");
                TimeSheetList.add(TSDS);
               }

        } catch (InstantiationException | IllegalAccessException
                | ClassNotFoundException |SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return(TimeSheetList);

    }

}

Controller file
Application.java
public static Result myAction(String ClientFilter,String ConsultantFilter) {
       DynamicForm requestData = Form.form().bindFromRequest();

        if (requestData.get("Submit")!=null) {
            return ok(index.render(Client.PopulateClient(),Consultant.PopulateConsultant(),Project.PopulateProject(ClientFilter)));
        } else if (requestData.get("Generate Timesheet")!=null) {
            //return ok(list.render(Client.PopulateClient(),Consultant.PopulateConsultant(),Project.PopulateProject()));
            return ok(DisplayTimeSheet.render(Timesheet.PopulateProject()));
        } else {
            return badRequest("This action is not allowed");
        }

     }

View file DisplayTimeSheet.scala.html
@(currentPage:List[TimeSheetDataStore])

     <form>

                    ID
                    EmployeeID
                    RoleID
                    Task
                    TimeSheetDate
                    CreateDate
                    UpdateDate
                    TaskHour
                    IsBilled
                    ProjectID
                    ClientID
                    atHome
                    atClientSite

              @for(i <- currentPage.indices) {
               @for(element <- currentPage.get(i)) {

                        @element.ID
                        @element.EmployeeID
                        @element.RoleID
                        @element.Task
                        @element.TimeSheetDate
                        @element.CreateDate
                        @element.UpdateDate
                        @element.TaskHour
                        @element.IsBilled
                        @element.ProjectID
                        @element.ClientID
                        @element.atHome
                        @element.atClientSite

                }
                }

        </form>

Can some one tell me what I'm doing wrong?

A: try instead of
@for(i <- currentPage.indices) {
           @for(element <- currentPage.get(i)) {

                    @element.ID
                    @element.EmployeeID
                    @element.RoleID
                    .
                    .
                    .

            }
            }

use only one for loop because you have list of currentPage: List[TimeSheetDataStore] so when you do @for(element <- currentPage) it will return you one object assigned to the element variable so now you have TimeSheetDataStore object in element variable so you can directly access it's fields
Do it like this:

@for(element <- currentPage) {

                    @element.ID
                    @element.EmployeeID
                    @element.RoleID
                    @element.Task
                    @element.TimeSheetDate
                    @element.CreateDate
                    @element.UpdateDate
                    @element.TaskHour
                    @element.IsBilled
                    @element.ProjectID
                    @element.ClientID
                    @element.atHome
                    @element.atClientSite

            }


text:
Q: Prawn gem - Undefined Method 'position' Using ruby 2.0.0, I am receiving the following error:
undefined method 'position=' for #<Prawn::Table:0x007fa85cb72850> (NoMethodError)
I've read several posts and 100% of them have pointed to adding this to your gem file and running bundle update:
gem 'prawn', :git => "https://github.com/prawnpdf/prawn.git", :ref => '8028ca0cd2'
However, I still get the same error when I do this versus just using gem 'prawn'.
It's worth noting that my script worked perfectly fine on another machine in another environment, using the same gem file that only had gem prawn in it. I don't recall altering the other environment in any way to make it work, but it's possible that I did.
Any thoughts as to how I can get rid of this error?


text:
Q: Laravel: how to access record by id in view In my controller I return a view with a ?collection $programs? from an eloquent query to the view.
Controller
    $programs = ScheduledProgram::where('registration_start_date', '<=', $today)

    return View::make('admin/register_users/show', compact(programs));

I wan to do something like this without it running a new query from the view...
VIEW
{{$program->find(id)}}

I know that $programs is a dataset that already has the record, but I don't know the way to access the element by ID this way.
How do I do this?
(sorry, seems like an obviously searchable question but my search terms aren't comming up with the answer)

A: in that case you need to make a @foreach in $programs to access the data. Like this:
 @foreach($programs as $key => $value)
    {{$value->id}}
 @endforeach

If the return is only one line you can do this:
{{$programs[0]->id}}

A: 1.You have to add the method get (converts the "dataset " in a Laravel collection) to iterate the collection.
$programs = ScheduledProgram::where('registration_start_date', '<=', $today)
             ->get()

2.If you want to get a single record:
ScheduledProgram::where('registration_start_date', '<=', $today)->where('id', 5)->get();


text:
Q: How to cancel CountdownTImer in Android kotlin? I want to cancel the timer when user presses the back button or minimizes the app.
I have tried using cancel() on 'override fun onDestroy()' but still the timer is running.
Below is my countdown timer code
countDownTimer = object : CountDownTimer(Constants.timerDuration, 1000) {
        override fun onTick(millisecondFinished: Long) {
            binding?.tvTimer?.text = (millisecondFinished / 1000).toString()

            Log.i("millis", "onTick: $millisecondFinished")
        }

        override fun onFinish() {
            val action = GameplayDirections.actionGameplayToGameover()

            findNavController().navigate(action)

        }
    }.start()`

This is how I have initialized the countdown variable
private var countDownTimer: CountDownTimer? = null

And below is the code for cancelling the timer
override fun onDestroy() {
    super.onDestroy()
    countDownTimer.cancel()
    countDownTimer = null
    Log.i("destroy", "onDestroyView: destroyed")
    binding = null
}

I have referred to many links, still I wasn't able to resolve this issue. I can see the timer running in the logcat even when I press the back button or minimize the app.
I have implemented countdown timer in fragment and after the timer is finished I am traversing to other fragment. And because the timer is not cancelling I am getting an error as shown below.
2022-07-24 12:25:15.643 32685-32685/io.ronli.protypist E/AndroidRuntime: FATAL EXCEPTION: main
Process: io.ronli.protypist, PID: 32685
java.lang.IllegalStateException: Fragment Gameplay{735bc2f} (915d1b65-13a2-40f3-b94a-4519fde2252d) not associated with a fragment manager.
    at androidx.fragment.app.Fragment.getParentFragmentManager(Fragment.java:1059)
    at androidx.navigation.fragment.NavHostFragment$Companion.findNavController(NavHostFragment.kt:375)
    at androidx.navigation.fragment.FragmentKt.findNavController(Fragment.kt:29)
    at io.ronli.protypist.ui.Gameplay$startTimer$1.onFinish(Gameplay.kt:325)
    at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:142)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loopOnce(Looper.java:210)
    at android.os.Looper.loop(Looper.java:299)
    at android.app.ActivityThread.main(ActivityThread.java:8105)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:556)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1045)

A: If you want to stop the timer when user press the back button or minimize the app you should call cancel method in onPause like this:
override fun onPause() {
        super.onPause()
        countDownTimer.cancel()
}

And the error is not related to the timer. It's about navigation. You can see similar situation in below :
Fragment XXX {} not associated with a fragment manager


text:
Q: SSLSocket not found; Spring Roo 1.2.5, STS 3.6, SQLServer driver, cannot convert from Class to Class extends Serializable> I started working with Spring Tool Suite 6.0 M1, Spring Roo 1.2.5, JDK 8.0, Windows 7 Home; I created a Spring Roo project but I'm having troubles to complete the project configuration.
Here the steps:

*

*The Roo project is created: File > New > Other > Spring > Spring
Roo Project

*jpa setup is completed

*JTDS is being used by default as follow..
database.driverClassName=net.sourceforge.jtds.jdbc.Driver
database.url=jdbc\:jtds\:sqlserver\://localhost\:1433/mydb

*osgi start --url file:///D:/RooThings/jtds-1.2.4.jar  (it worked fine)

*database reverse engineering complete with success.

*There are warnings for a couple of classes within the project:
@RooJpaEntity(identifierType = SeriePK.class, versionField = "", table = "Serie", schema = "dbo")
public class Serie {}

** SeriePK.class : Type mismatch: cannot convert from Class<'SeriePK> to Class<'? extends Serializable>

At SeriePK.class:
@RooIdentifier(dbManaged = true)
public final class SeriePK {}
I extended it with Seriealizable, but the warning is still there.
I tried to fix this changing the SQLServer driver as follow:

*

*I followed this support:
Setup SqlServer Driver in Roo project

*
database.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
database.url=jdbc\:sqlserver\://localhost\:1433;database=mydb

*osgi start --url file:///D:/RooThings/sqljdbc4-4.0.jar  (it worked fine)

roo> database introspect --schema dbo
  javax.net.ssl.SSLSocket not found by [84]

so, I can't to continue working with Roo anymore..
Any help I'd really appreciate.

A: I had same problem. After add "osgi start --url file:c:/sqljdbc4-4.0.jar" and before running "database introspect --schema dbo", you should write:
jpa setup --database MSSQL --provider HIBERNATE --hostName LOCALHOST --userName USERDB --password PSSWDB --databaseName DB

A: I have the same problem after updating my sts.
I think that implements Serializable in the .aj file is not detected.
So you have to rewrite implements Serializable in your .java file.
Roo will delete automatically the concerning .aj file.
Try to implement Serializable in SeriePK.java


text:
Q: How to paginate Laravel collection
Hi, I am trying to paginate all these elements, but whatever I tried it shows all on one page, it doesnt split this on more pages.
public function referralTransactions($id){
        $user_id=$id;
        $refs=User::where('sponsor_id', '=', $user_id)->pluck('id');
        $alltxns=[];
        $i=0;
        //$m=0;
        if(count($refs)>0) {
            foreach ($refs as $key =>$referral) {

                $alltxn = $this->buyselltransactionlist($referral);
                //$paginate = $this->getpaginateforbuysell($referral, 5);
                //$m=$m+count($alltxn);
                $alltxns[$i]=$alltxn;

                $i++;

            }
        }
        dd($alltxns);
        return view('adminpartials.referral_transactions',
            ['user_id'=>$user_id,
               // 'lists'=>$lists
                'alltxns'=>$alltxns,
                //'referrals'=>$referrals,
                'refs'=>$refs,
            ]
        );```

A: public function paginate($items, $perPage = 15, $page = null, $options = [])
{
    $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
    $items = $items instanceof Collection ? $items : Collection::make($items);
    return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
}

$items = $this->paginate($collection);

A: This can be achieved by using a Collection macro.
<?php

namespace App\Providers;

use Illuminate\Support\Collection;
use Illuminate\Pagination\LengthAwarePaginator;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        /**
         * Paginate a standard Laravel Collection.
         *
         * @param int $perPage
         * @param int $total
         * @param int $page
         * @param string $pageName
         * @return array
         */
        Collection::macro('paginate', function($perPage, $total = null, $page = null, $pageName = 'page') {
            $page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);

            return new LengthAwarePaginator(
                $this->forPage($page, $perPage),
                $total ?: $this->count(),
                $perPage,
                $page,
                [
                    'path' => LengthAwarePaginator::resolveCurrentPath(),
                    'pageName' => $pageName,
                ]
            );
        });
    }
}

Then you use like any other collection helper.
collect([...])->paginate(15);

Ref:
https://gist.github.com/simonhamp/549e8821946e2c40a617c85d2cf5af5e

A: in controller use paginate(number you want perPage),
example :
#Controller
$posts=Post::latest()->paginate(number you want)
return view('index')->with('posts', $posts);

in View
#loop items
{{ $posts->links() }}


text:
Q: how to execute Google API Url in Android I want to access googlePlaces API and i have the url but i dont know how to execute the API and get json result can anyone help me with the code ? provide me a simple method bu which i can execute the API
here is my code:
package com.astro.famouspandit.Activities.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.astro.famouspandit.R;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.places.Place;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Location extends AppCompatActivity  {

    private EditText mEdttxtCity;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location);
        final String API_KEY = "AgAjkAkAk-hsdwdweohdohwedhooooo";
        mEdttxtCity = (EditText)findViewById(R.id.edttxtCity);
        mEdttxtCity.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
               String Edttxtcity =  mEdttxtCity.getText().toString();
                if (Edttxtcity.length() >3) {

                    String url = " https://maps.googleapis.com/maps/api/place/autocomplete/json?input=ban&key=" + API_KEY;
                    Log.d("data", "onTextChanged: " + url);

                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }

        });

    }

}

A: Code in onTextChange -
  input = s.toString();
  SearchPlacesTask   searchplacesTask = new SearchPlacesTask();
  searchplacesTask.execute();

Code to Search Places
    private class SearchPlacesTask extends AsyncTask<String, Void, String> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                System.out.println("SearchPlacesTask Called");

            }

            @Override
            protected String doInBackground(String... place) {
                // For storing data from web service
                String data = "";

                // Obtain browser key from https://code.google.com/apis/console

                String key = "key=YOUR_API_KEY";

                try {
                    input = "input=" + URLEncoder.encode(input, "utf-8");
                    System.out.println("input String : " + input);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }

                // place type to be searched
                String types = "types=geocode";

                // Sensor enabled
                String sensor = "language=en";

                /*// Building the parameters to the web service
                String parameters = input + "&" + types + "&" + sensor + "&" + key;*/

                // Building the parameters to the web service

                String parameters = input + "&" + sensor + "&" + key;

                // Output format
                String output = "json";

                // Building the url to the web service

                String url = "https://maps.googleapis.com/maps/api/place/autocomplete/"
                        + output + "?" + parameters;

                System.out.println("Final URL Google API : " + url);
    //            String url = "https://maps.googleapis.com/maps/api/place/autocomplete/location=13.758662,100.496443" + output + "?" + parameters;

                try {
                    // Fetching the data from we service
                    data = downloadUrlsearch(url);
                } catch (Exception e) {
                    Log.d("Background Task", e.toString());

                }

                return data;
            }

            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);

//YOUR JSON DATA HERE.
//NOW YOU CAN PARSE.

            }
        }

Code to Download Data from URL -
 /** AUTO SEARCH CODE  */
    /**
     * A method to download json data from url
     */
    private String downloadUrlsearch(String strUrl) throws IOException {
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try {

            URL url = new URL(strUrl);

            // Creating an http connection to communicate with url
            urlConnection = (HttpURLConnection) url.openConnection();

            // Connecting to url
            urlConnection.connect();

            // Reading data from url
            iStream = urlConnection.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

            StringBuffer sb = new StringBuffer();

            String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

            data = sb.toString();

            System.out.println("data: " + data);

            br.close();

        } catch (Exception e) {

            e.printStackTrace();
//            Log.d("Exception while downloading url", e.toString());
        } finally {

            iStream.close();
            urlConnection.disconnect();
        }
        return data;
    }

A: volley is best; try this:
 StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_TO_QUERY,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Toast.makeText(MainActivity.this,response,Toast.LENGTH_LONG).show();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
                }
            });
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);

A: Android Samples Using Google Places API
Please refer the sample code which uses Google Places APIs. Its Recommended way for using the APIs.


text:
Q: How can I use @Scripts.Render with .Net Core 2.0 MVC application? How can I use @Scripts.Render with a .NET Core 2.0 MVC application?
I am converting code from .NET Framework 4.6.1 to .NET Core 2.0. I have read from here how to bundle with .NET Core 2.0. How can I fix the error, and replace the code with the new version?
Code:
@Scripts.Render("~/bundles/login")

It says

The name 'Scripts' does not exist in the current context

Existing BundleConfig.cs:
public static void RegisterBundles(BundleCollection bundles)
{
    bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
        "~/Scripts/jquery-{version}.js"));
    bundles.Add(new ScriptBundle("~/bundles/jqueryvalidate").Include(
    BundleTable.EnableOptimizations = true;
}

A: As stated in the other answer, the BundleConfig.cs is gone. However, the @Scripts.Render() had some good use cases and it's not a good idea to replace it with static <script src="..."></script>. In some cases where you only want to link libraries on some pages, not all, you don't want to repeat the same code over and over especially when you link to the libraries in CDNs with fallbacks. So here is a good approach that I use to replace the old good @Scripts.Render():
First create a partial view for your libraries. You can combine the ones that you use together in the same view if you like. Think about it like you're creating bundles in BundleConfig.cs. For example, you can create a view for the jQuery validation like this:
<environment include="Development">
    <script src="~/lib/jquery-validate/jquery.validate.js"></script>
    <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
</environment>
<environment exclude="Development">
    <script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.19.0/jquery.validate.min.js"
            asp-fallback-src="~/lib/jquery-validate/jquery.validate.min.js"
            asp-fallback-test="window.jQuery && window.jQuery.validator"
            crossorigin="anonymous"
            integrity="sha384-jR1IKAba71QSQwPRf3TY+RAEovSBBqf4Hyp7Txom+SfpO0RCZPgXbINV+5ncw+Ph">
    </script>
    <script src="https://ajax.aspnetcdn.com/ajax/jquery.validation.unobtrusive/3.2.10/jquery.validate.unobtrusive.min.js"
            asp-fallback-src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"
            asp-fallback-test="window.jQuery && window.jQuery.validator && window.jQuery.validator.unobtrusive"
            crossorigin="anonymous"
            integrity="sha384-y9k3BO+hbWD6gTgtfMyg1egwFmd2oEgQ0fALVtFnCl9F6j6mCh+oCa0P0h+aj7Ii">
    </script>
</environment>

You can call it something like _ValidationScriptsPartial.cshtml.
Now, on the pages where you need the validation, you can inject the partial view like this:
@section Scripts {
    @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
}

Of course, for those libraries that are required on all pages (like jQuery and Bootstrap), you can inject them directly in _Layout.cshtml like this:
<!DOCTYPE html>
<html>
<head>
    ...
    @await Html.PartialAsync("_LayoutHeadScriptsPartial")
</head>
<body>
    ...
    @RenderBody()
    ...
    @await Html.PartialAsync("_LayoutFooterScriptsPartial")
    @RenderSection("scripts", required: false)
</body>
</html>

A: In ASP.Net MVC Core they removed BundleConfig.cs and replaced with bundleconfig.json file. you need to specify your bundle and minification logic in bundleconfig.json. If you don't have this file in your project add  json file with this name.
bundleconfig.json
Content of this file should like below.
  // Configure bundling and minification for the project.
// More info at https://go.microsoft.com/fwlink/?LinkId=808241
[
  {
    "outputFileName": "wwwroot/css/site.min.css",
    // An array of relative input file paths. Globbing patterns supported
    "inputFiles": [
      "wwwroot/css/site.css"
    ]
  },
  {
    "outputFileName": "wwwroot/js/bundles.min.js",
    "inputFiles": [
      "wwwroot/js/site.js",
      "wwwroot/lib/jquery/dist/jquery.js",
      "wwwroot/lib/jquery/dist/jqueryvalidate.js"
    ],
    // Optionally specify minification options
    "minify": {
      "enabled": true,
      "renameLocals": true
    },
    // Optionally generate .map file
    "sourceMap": false
  }
]

_Layout.cshtml
 <script src="~/js/bundles.min.js"></script>

Read Microsoft docs related to Bundling and minification to get more understanding about Bundling and minification in asp.net core mvc


text:
Q: Get attachment by slug I would like to get an image by specifying a certain slug and then echoing that address in the image src code.
The slug for the image would be "book-site-header"
I've looked through the get_wp_attachment and get_wp_attachment_metadata in the wordpress codex but neither makes mention of the slug. Slugs have to be unique and are saved in the DB so it must be possible to find it based on the slug and then get the related file url.

A: An attachment is just a post with the post_status = inherit and the post_type = attachment, so can be queried with WP_Query or get_posts.
Note that slug (post_name) is unique per post type.
$_header = get_posts('post_type=attachment&name=book-site-header&posts_per_page=1&post_status=inherit');
$header = $_header ? array_pop($_header) : null;
$header_url = $header ? wp_get_attachment_url($header->ID) : '';

you can also use the code above to built your own custom fucntion
function get_attachment_url_by_slug( $slug ) {
  $args = array(
    'post_type' => 'attachment',
    'name' => sanitize_title($slug),
    'posts_per_page' => 1,
    'post_status' => 'inherit',
  );
  $_header = get_posts( $args );
  $header = $_header ? array_pop($_header) : null;
  return $header ? wp_get_attachment_url($header->ID) : '';
}

and then
$header_url = get_attachment_url_by_slug('book-site-header');


text:
Q: Is this valid argument in jquery I have ajax code. Here is part of it.
Is it valid to do something like this:
$('#addCommentForm'+refID '#files')

?
$(function() {
    $("#submit").click(function() {

        var refID = $("#refID").val();
        var file_data = $('#addCommentForm'+refID '#files').prop('files')[0];

A: If you are trying to target multiple elements you can do so by separating them with commas (note the additional +):
$('#addCommentForm'+refID+',#files').each(function(){
    $(this).prop('files')[0];
});

Example here.


text:
Q: Performance boost long MySQL query I'm coming from finance side not programming but with some personal readings.
I've 2 tables, one includes data about the clients such as their balance on daily basis, total number of rows is 1.7 million, and another table includes the commissions paid by each client and it's a bit smaller table,
I want to see the data for the last day of the first big table with a sum of total profits for each client for the whole history registered in the table, plus the total commissions paid from the other table.
I used the following query:
SELECT
DATE_FORMAT(day, '%e %b %Y') AS 'Date',
m.account_number,
equity,
@total:=(SELECT
        ROUND(SUM(profits), 2)
    FROM
        gbp
    WHERE
        account_number = m.account_number) AS Absolute_return,
commissions.Total AS Commissions FROM
gbp m
    JOIN
(SELECT
    MAX(id) max_msg_id
FROM
    gbp
GROUP BY account_number) mc ON m.id = mc.max_msg_id
    INNER JOIN
commissions ON  commissions.account_number = m.account_number GROUP BY account_number

The code is working and generating the desired results, it's just takes too much time to get the results, I was thinking if there's a better way to make the query, I'm also using indexes for all tables based on account_number column.


text:
Q: How to make a php a href post value use ajax? I want to post a value using a href with target_self, but I do not want to refresh the page when it posts. How to add a ajax function?
<form name="info" id="info" method="post" action="index.php" >
<input name="name" type="hidden" value="test" />

test
<form>

A: With ajax the page is never refreshed, you will just POST data to your webserver, if you want to stop page refresh after ajax just add this at the end of ajax function
return false;

assuming you use JQuery:
   $("form").submit(function(){

      $.ajax(); // Which needs some other stuff for making it useful
return false; //This will stop the page from refresh !
});

And please show some code so we can batter understand what you want.


text:
Q: all css classes in page using js i want to be able to get all the class names of all css files on the page.
Is there any existing possibility or do i have to read it and parse it by myself. Isn´t there any api of the browser?

A: is maybe a dulplicate request of this? How do you read CSS rule values with JavaScript?
function getStyle(className) {
    var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules
    for(var x=0;x<classes.length;x++) {
        if(classes[x].selectorText==className) {
                (classes[x].cssText) ? alert(classes[x].cssText) : alert(classes[x].style.cssText);
        }
    }
}
getStyle('.test')


text:
Q: The quotient of homogeneous polynomial on a smooth projective curve is meromorphic if the denominator is not identically zero. Suppose $X \subset \mathbb{CP}^n$ is a smooth projective curve.
Why is $G/H$ a meromorphic function on $X$ if $G$ and $H$ are homogeneous polynomials of degree $d$ and $H$ does not vanish identically on $X$.
It's been a while since I did Riemann surfaces, so I forgot what kind of approach should be used. I was initially thinking that perhaps Bezout would be useful, but now I'm doubting that.
Should one explicitly do something with the homogenous function $F(x,y,z)$ which defines $X$ (and then embeds it into $\mathbb{CP}^n$.  Or perhaps I should do something with affine patches or charts and show that $G/H$ has no essential singularities. But then again, I'm not sure how to show that all singularities are either poles or removable.
I was also thinking about the fact that $G/H$ being meromorphic, means that it's holomorphic when extended to the Riemann sphere $C_{\infty}$ and not the constant $\infty$ function. The latter is clear, as $H$ is not identically zero on $X$, but then again I'd have no idea how to show that the map to $C_{\infty}$ would be holomorphic.
I used the search function here as well, but I didn't really find posts tackling the same problem, so I hope it's not a duplicate.


text:
Q: how to write unit test cases for App_Initializer using Karma/Jasmine in angular 7 I have imported APP_INITIALIZER in my app.module.ts file and calling a initializer function.
How to write unit test case for this initializer method using jasmine/karma?
Code:
initializer.ts
import { CookieService } from 'ngx-cookie-service';
import { KeycloakOptions, KeycloakConfig } from 'keycloak-angular';
import { EnlivenKeycloakAuthService } from './services/enliven-keycloak-auth.service';
export function initializer(keycloakService: EnlivenKeycloakAuthService, cookieService: CookieService): () => Promise<any> {

cookieService.set('test','test');

 const config: KeycloakConfig = {
        url: serverUrl,
        realm: realmName,
        clientId: clientId,
        credentials: {
            secret: secret
        }
    };
    const options: KeycloakOptions = {
        config: config,
        initOptions: {
            onLoad: 'login-required',
            checkLoginIframe: false
        },
        enableBearerInterceptor: true,
        bearerExcludedUrls: ['/assets']
    };
    keycloakService.setIsClientSecretKeyFetech(true);
    return (): Promise<any> => keycloakService.init(options);

}

app.module.ts
{
    provide: APP_INITIALIZER,
    useFactory: initializer,
    deps: [ EnlivenKeycloakAuthService, CookieService],
    multi: true
}

A: The code in your question is not clear to me and I couldn't help you with the test case for it, but I'm sure this example will help you.
app-initializer.ts
import { ConfigService } from './services';

export const appInitializer: (ConfigService) => (() => Promise<boolean>) = function (config: ConfigService) {
    return (): Promise<boolean> => {
        return new Promise<boolean>((resolve: (boolean) => void, reject: (boolean) => void) => {
            config.load().subscribe(
                (data: any) => {
                    // do something with data and resolve the promise
                    resolve(true);
                },
                (error) => reject(error)
            );
        });
    };
};

app-initializer.spec.ts
import { async, TestBed } from "@angular/core/testing";
import { of } from "rxjs";
import { tap } from "rxjs/operators";
import { ConfigService } from "./services";
import { appInitializer } from "./app-initializer";

describe('appInitializer', () => {
    const mockedConfigService: any = jasmine.createSpyObj('ConfigService', ['load']);

    let configService: ConfigService;

    beforeEach(() => {
        TestBed.configureTestingModule({
            providers: [
                { provide: ConfigService, useValue: mockedConfigService }
            ]
        });
        configService = TestBed.get(ConfigService);
    });

    it('should resolve the promise', async(() => {
        mockedConfigService.load.and.returnValue(of({}));
        appInitializer(configService)()
            .then((status) => {
                expect(status).toBe(true);
            })
    }));

    it('should reject the promise', async(() => {
        mockedConfigService.load.and.returnValue(
            of({})
                .pipe(tap(() => {
                    throw Error('failure');
                }))
        );
        appInitializer(configService)()
            .then(() => { }, (error) => {
                expect(error.message).toEqual('failure');
            })
    }));
});


text:
Q: Xpath select multiple classes

 stuff....

I have this silly HTML which I am parsing, as you can see there is one main class called one and another one nested called two.
I am trying to parse all the images in class one, but apparently the XPath I have is only catching one image, which is the image from class one
I tried this:
//div[@class="one"]/img | //a[@class="two"]/img

But apparently I am not catching from class two, but only from class one is there anyway to do this?
I am using lxml.html's xpath feature.

A: Try this Xpath expression :
//div[@class="one"]//img

Test :
xmllint --html --xpath '//div[@class="one"]//img' \
    'http://sputnick-area.net/ftp/downloads/testSO.html'

OUTPUT


text:
Q: How to learn whether a user password is expired or not in Active Directory? In my ASP.NET MVC (C#) project I must learn whether a user password is expired or not? I found some answers about that on the internet but they didn't be useful for me.
The first way to do using maxpwdage +pwdlastset= password expired date, and the second solution is that using useraccountcontrol attribute to learn whether it is expired or not. If this attribute's value is 8389120, user password is expired.
Altough user password is expired in AD, useraccountcontrolvalue is still 512. I tried to do with maxpwdage+pwdlastset but I couldn't see an attribute like maxpwdage (I got users as an administrator)
Active Directory user password expiration date .NET/OU Group Policy (first way)
https://support.microsoft.com/en-us/kb/305144 (second way)
Both of them aren't working because of reasons that I mentioned above.
Are there any other ways to do this or how can i see value of the maxpwdage attribute?
EDIT: I am getting the user who i want from here
            DirectoryEntry dEntry = new DirectoryEntry
                        ( "LDAP://a.b.c:123/OU=d, DC=e, DC=f", this.GetAdUserName(),
                        this.GetAdUserPassword() );
            DirectorySearcher directorySearcher = new DirectorySearcher( dEntry );
            directorySearcher.Asynchronous = true;
            directorySearcher.CacheResults = true;
            directorySearcher.Filter = "(&(sAMaccountName=" + identificationNumber + "))";
            SearchResult user = directorySearcher.FindOne();
            return user;

I am checking user's properties but I couldn't find maxpwdage property.

A: You can use TimeSpan which represent time interval. And then all you need is check today's date and expired date.
DateTime expireDate = passwordLastChanged.AddDays(iMaxPwdAge);
TimeSpan ts = expireDate - DateTime.Now;
int iDaysTilExpired = ts.Days;
WriteLogMessage("Days til password expires:" + iDaysTilExpired);

And also there is a good example, I changed someparts for my project and it works for me.
Edit :
You can use attribute msDS-UserPasswordExpiryTimeComputed for getting user password expiration date.
and also
The 'maxPwdAge' attribute is held on the domainDNS class (the root of the directory) as it is part of policy.  It is not held on the user object.  If you are using .NET 2.0, you can get this easily:
using (DirectoryEntry domain = Domain.GetCurrentDomain())
{
    DirectorySearcher ds = new DirectorySearcher(
        domain,
        "(objectClass=*)",
        null,
        SearchScope.Base
        );

        SearchResult sr = ds.FindOne();

        TimeSpan maxPwdAge = TimeSpan.MinValue;

        if (sr.Properties.Contains("maxPwdAge"))
            maxPwdAge = TimeSpan.FromTicks((long)sr.Properties["maxPwdAge"][0]);
}

Edit 2 :
Here is full example you can use:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;

namespace LDAP
{
    class Program
    {
        static void Main(string[] args)
        {
            string domainAndUsername = string.Empty;
            string domain = string.Empty;
            string userName = string.Empty;
            string passWord = string.Empty;
            AuthenticationTypes at = AuthenticationTypes.Anonymous;
            StringBuilder sb = new StringBuilder();

            domain = @"LDAP://w.x.y.z";
            domainAndUsername = @"LDAP://w.x.y.z/cn=Lawrence E."+
                        " Smithmier\, Jr.,cn=Users,dc=corp,"+
                        "dc=productiveedge,dc=com";
            userName = "Administrator";
            passWord = "xxxpasswordxxx";
            at = AuthenticationTypes.Secure;

            DirectoryEntry entry = new DirectoryEntry(
                        domain, userName, passWord, at);

            DirectorySearcher mySearcher = new DirectorySearcher(entry);

            SearchResultCollection results;
            string filter = "maxPwdAge=*";
            mySearcher.Filter = filter;

            results = mySearcher.FindAll();
            long maxDays = 0;
            if(results.Count>=1)
            {
                Int64 maxPwdAge=(Int64)results[0].Properties["maxPwdAge"][0];
                maxDays = maxPwdAge/-864000000000;
            }

            DirectoryEntry entryUser = new DirectoryEntry(
                        domainAndUsername, userName, passWord, at);
            mySearcher = new DirectorySearcher(entryUser);

            results = mySearcher.FindAll();
            long daysLeft=0;
            if (results.Count >= 1)
            {
                var lastChanged = results[0].Properties["pwdLastSet"][0];
                daysLeft = maxDays - DateTime.Today.Subtract(
                        DateTime.FromFileTime((long)lastChanged)).Days;
            }
            Console.WriteLine(
                        String.Format("You must change your password within"+
                                      " {0} days"
                                     , daysLeft));
            Console.ReadLine();
        }
    }
}


text:
Q: jsPDF not support a Thai language I am using JsPDF for my Vuejs project and facing some issues while saving pdf for Thai version but it is working fine with English version.
Issues it is printing random special chracters
Any help would be appreciated.
Here is my code
    exportTable () {
      const pdf = jsPDF({
        encoding: 'UTF-8',
        defaultStyle: {
          font: 'THSarabunNew'
        }
      });
      pdf.addFileToVFS('THSarabunNew.ttf', THSarabunNew);
      pdf.addFont('THSarabunNew.ttf', 'THSarabunNew');
      pdf.setFont('THSarabunNew');
      pdf.text('รายการสมรรถภาพทั้งหมด:', 14, 22);

      this.data.forEach((item, index) => {
        pdf.text(`Capacity Name : ${item.CapacityName}`, 14, 28 + (index * 10));
      });

here is my problem


text:
Q: Unable To Submit iOS 9 Apps (Invalid Swift Support) We were able to submit builds to iTunes Connect for internal beta testing just fine with Xcode 6.X. Now that we have upgraded our Swift project to Xcode 7 and Swift 2, we have been getting the "Invalid Swift Support" error:
Invalid Swift Support - The files libswiftCoreAudio.dylib,
libswiftCoreMedia.dylib, libswiftCoreData.dylib, libswiftAVFoundation.dylib
don't match /Payload/AppName.app/Frameworks/libswiftCoreAudio.dylib,
/Payload/AppName.app/Frameworks/libswiftCoreMedia.dylib,
/Payload/AppName.app/Frameworks/libswiftCoreData.dylib,
/Payload/AppName.app/Frameworks/libswiftAVFoundation.dylib. Make sure the
files are correct, rebuild your app, and resubmit it. Don't apply
post processing to /Payload/AppName.app/Frameworks/libswiftCoreAudio.dylib,
/Payload/AppName.app/Frameworks/libswiftCoreMedia.dylib,
/Payload/AppName.app/Frameworks/libswiftCoreData.dylib,
/Payload/AppName.app/Frameworks/libswiftAVFoundation.dylib

A: Xcode 7 is currently in Beta, and Apple do not allow apps built with beta tools to be submitted.
Expect an announcement in the next few days as to when you can submit iOS 9 versions of your app to the App Store.

A: There is currently a post on twitter going around, but i cant find the original post:

Apple confirmed TestFlight external test doesn't support iOS 9 GM and
  it seems they think it is OK and won't fix it.

https://twitter.com/an0/status/642015637678723072


text:
Q: DJango Querysets Filter     clients = Client.objects.filter(user_id=request.user)
    quotes = Quote.objects.filter(customer_act_id=clients)

I have the above code and I am trying to display the users clients and quotes to the user. The clients display fine but the quotes only show the quotes for the FIRST client and not all of them. Any help is appreciated.
Relationships:
User has_many clients(user_id FK) has_many quotes(client_id FK)

A: Ben is right. Using customer_act_id__in=clients should do the trick. Could you double check if the clients are associated with the same user, then?


text:
Q: Populating campaign id field in IndividualEmailResult (during an email send from MC) When sending emails from MC (via journeys, email studio etc...) we would like to populate the campaign id field in IndividualEmailResult object in SF. An idea suggested was to use the UpdateSingleSalesforceObject AMPScript function within the emails' code and update the campaign id field this way. However, we can only achieve that if the id of the IndividualEmailResult record created for the email send is retrievable.
Is there a way to retrieve the IndividualEmailResult id of the record created for each email? Can this code be implemented in the email itself and be executed during the email send? If not, are there any alternatives which can be suggested to populate the campaign id field?
Many thanks,
Barak

A: that sounds like a bit of a bold undertaking and I would discourage the approach you lay out.
Here is my reasoning:

*

*Are you aware of the potential performance drops when using the sales cloud AMPscript functions? Be sure to test "updateSingleSalesforceObject" at scale if you want to use this in larger sendouts to ensure this doesn't slow your sendout.

*I doubt that the IER data is created in real time but have not tested.

*Even if the creation of the IER record were realtime, the retrieve performance is pretty slow. Example from my own dabbles: in a non-sending context, in order to create a Personaccount, and retrieve a field value from it directly after creation  requires around a second of waiting. Totally inadequate for bulk sendouts.
so - avoid this pattern. Don't try to build performant, scalable, real-time sendout processes involving your Sales Cloud via AMPscript.
alternative
I have not tried the following (and there are unsolved questions), but the alternative that I could see would probably be largely custom and it would involve the following patterns:
Logging the relevant information for your sendout into a send logging DE (e.g. campaign ID alongside the features that define a sendout event (jobid, subscriberkey, listId, batchid).
In an asynchronous process, try to retrieve the IER id by your logged data in the sendlog.
Here is the problem: When checking the schema generator in Sales Cloud for the IER object, unfortunately, none of these things that define a sendout event uniquely are present on IER. (Except subscriberkey). So you would have a hard time matching your sendout event to an IER record.
You would have to make "proxy" lookups to things like Email ID, subject line etc. which are represented on IER to find the right IER record for your recipient / sendout, but this is highly error prone.
assuming you find that this matching can be done somehow - then asynchronously push data into the sales cloud object, in small numbers via Journey Builder, in large numbers via the Bulk API, see here:
Account Activity or Object Activity in Journey Builder has limits to update like Data Loader?
You would have to test such an operation in conjunction with the existing API calls that populate IER by default (which is managed by MC Connect), be aware there could be conflicts by trying to update something while the connector is busy with it. This is a bit of a blackbox, so I would also steer clear.
final thoughts
With all that effort in mind, I would first consider a cost-benefit analysis of the underlying requirement. If it stands that test -
Second, fallback to maybe a custom object that basically mirrors your Send Log. This can clear the roadblocks in terms of "finding the right IER record" and avoids conflicts with the standard MC connect API. Consider that data storage could be a problem here, which btw is true also for IER.
I understand a custom object might not have all the bells and whistles of standard IER, but again, cost / benefit.
Third, fallback to a BI tool where you can tie your data together in a meaningful way.