text:
Q: Design my database I've to do my whole project from scratch, and I'm ok with it, just don't want to do the same mistake ..
I've two tables, on is ( Jobs ) and ( Categories ) , I need to link the categories to the jobs, is it one-to-one relationship ? I want to link them together
so I Can do edit and delete and add jobs from my web-site using PHP
[Jobs Table]
+--------------+-------------+------+-----+-----------------+
| JobID        | Name        | description| numberOfJob     |
+--------------+-------------+------+-----+-----------------+
| 0            |    xxxx     | xxxx       |     xxxx        |
| 1            |    xxxx     | xxxx       |     xxxx        |
+--------------+-------------+------+-----+-----------------+

[Categories Table]
+--------------+-------------+
| JobID        | Name        |
+--------------+-------------+
| 0            |    xxxx     |
| 1            |    xxxx     |
+--------------+-------------+

these are my tables, I would appreciate your help guys

A: Assuming Categories is a lookup table, and every job belongs to one category:
Jobs
----
JobID
CategoryID
JobName
JobDescription
JobNumber

Categories
---------
CategoryID
CategoryDescription

To display all data from Jobs table, your SQL would be:
SELECT * FROM Jobs

You could also sort the results by any column, such as:
SELECT * FROM Jobs ORDER BY JobDescription

...or show just certain data like so:
SELECT J.JobDescription, C.CategoryDescription
FROM Jobs J
LEFT JOIN Categories ON J.CategoryID = C.CategoryID
ORDER BY J.JobDescription


text:
Q: Forward port other than 80 for HTTP Server I would like to host a web server on my computer for at most a day. My ISP has blocked port 80 and the only port open is 22. My question is if I could forward this port so that the server is accessible via WAN ip on port 22, eg xx.xxx.x.xx:22 when accessed should forward the request to my computer ip address 192.168.0.10 on internal port 80(Apache)? I am aware port 22 is meant for SSH server but I have no SSH server on my Windows Pc. I am running the web server on WAMP64. I am using Tenda F9 Router

A: You can set up Apache to listen directly on 22 in its config and then access your server as http(s)://your-public-ip:22. Your router certainly has to do the forwarding from your-public-ip:22 to 192.168.0.10:22. If you choose to keep 80 for Apache at 192.168.0.10, then sure forward :22 to :80. The services really don't care which ports they really listen to.
I strongly recommend having HTTPS though, I am assuming this is plan despite the port 80 usage, as some browsers now trust less plain HTTP connections. EDIT: may not be worthwhile if one just one day as per comments.
EDIT2: given OPs finding that their router IP is not a public IP provided by the ISP, one way to have your WAMP be available temporarily publicly is to use the ngrok HTTP proxy.

A: Well I figured out the problem. The problem is ROUTER AND WHAT IS MY IP SHOWING DIFFERENT IP . My Router shows WAN my Ip as 192.xxx.x.xxx while What is my Ip gives 102.xx.xx.xxx. Thank you all for your contribution

redpajama_set_name: RedPajamaStackExchange


text:
Q: Interaction picture field operators, and the on-shell condition In the explicit expression of the interaction picture field operator in terms of ladder operators given in Peskin and Schroeder (4.15), the time-dependence is specified via an instruction to evaluate the expression at $x_0 = t-t_0$,
\begin{align}
\phi_I(x) = \int\frac{d^3p}{(2\pi)^3} \frac{1}{\sqrt{2E_{p}}} \left( a_{\vec{p}}e^{-ip\cdot x} + a_{\vec{p}}^\dagger e^{ip\cdot x}\right)\bigg|_{x_0 = t-t_0}. \tag{4.15}
\end{align}
In this expression, the value of $p_0$ is always equal to $E_\vec{p}$, but this fact is left implicit within the four-vector $p$ appearing in each exponent. Is that right? I could make it explicit by writing,
\begin{align}
\phi_I(x) = \int\frac{d^3p}{(2\pi)^3} \frac{1}{\sqrt{2E_{p}}} \left( a_{\vec{p}}e^{-ip\cdot x} + a_{\vec{p}}^\dagger e^{ip\cdot x}\right)\bigg|_{x_0 = t-t_0; p_0 = E_{\vec{p}}},
\end{align}
correct? It's an operator defined by an integration over all three-momenta, or equivalently, an integration over all on-shell four momenta.


text:
Q: separate values from a string using SQL I have this requirement where we need to separate values from a string the format of the  is like
{Feature1=Value1} | {Feature2=Value2} | .. | {FeatureN=ValueN}

{12345=Gold}|{12346=Silver}

so need to separate features and values from the given srting..
To separate PIPE separated values i am using..
select *
  from xmltable('r/c' passing xmltype('<r><c>' || replace('{12345=Gold}|{12346=Silver}','|','</c><c>') || '</c></r>')
columns new_str varchar2(30) path '.');

NEW_STR
------------------------------
{12345=Gold}
{12346=Silver}

I am writing a PLSQL block which iterate through each pipe separate values using above query.
I can store these values in PLSQL variable.
Now another task here  is to get features and values from two above strings for this i write below SQL
select substr ('{12345=Gold}',2, instr('{12345=Gold}', '=')-2) features from dual;

FEATURES
----------------------
12345

SELECT SUBSTR('{12345=Gold}', instr('{12345=Gold}', '=')+1, LENGTH(substr ('{12345=Gold}', instr('{12345=Gold}', '=')+1, INSTR('{12345=Gold}', '}', 2)))-1) value FROM DUAL;

VALUE
--------------
Gold

So here i am able to get the features and values from a string......
I am looking for another or alternate SQL for my SQL's specially for the last one i find it complex function use so if you have any better idea for the above scenario then please  Post !
Please ask if the scenario is not clear
MY DB is --
Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production

A: with line as (
      select '{12345=Gold}|{12346=Silver}|{12399=Copper}' str from dual)

select substr (parse, 2, instr(parse,'=')-2) as feature
      ,substr (parse, instr(parse,'=')+1, length(parse)-instr(parse,'=')-1 ) as value
from
   (select distinct regexp_substr(str, '[^|]+', 1, level) as parse
    from line
    connect by regexp_substr(str, '[^|]+', 1, level) is not null)

A: Here is a way using types and a handy built-in package called apex_util:
create type keyval_t is object (key varchar2(10), value varchar2(100));
/

create type keyval_tab_t is table of keyval_t;
/

create or replace package test_pkg is
   function keyval_tab (p_keyval_string varchar2) return keyval_tab_t;
end;
/

create or replace package body test_pkg is
   function keyval_tab (p_keyval_string varchar2) return keyval_tab_t
   is
      l_tab apex_application_global.vc_arr2;
      l_tab2 apex_application_global.vc_arr2;
      l_keyval_tab keyval_tab_t := keyval_tab_t();
      l_str long;
   begin
      -- Split string at pipe delimiters
      l_tab := apex_util.string_to_table (p_keyval_string, '|');
      -- For each {key=value} pair
      for i in 1..l_tab.count loop
         l_str := l_tab(i);

         -- Remove the {}
         l_str := ltrim (l_str, '{ ');
         l_str := rtrim (l_str, '} ');

         -- Split string into key and value
         l_tab2 := apex_util.string_to_table (l_str, '=');
         if l_tab2.count = 2 then
            l_keyval_tab.extend;
            l_keyval_tab(i) := keyval_t (l_tab2(1), l_tab2(2));
         else
            -- ?? invalid string
            null;
         end if;
      end loop;
      return l_keyval_tab;
   end;

end;
/

Now you can query:
SQL> select value from table(test_pkg.keyval_tab ('{12345=Gold}|{12346=Silver}'))
  2* where key='12346';

VALUE
--------------------------------------------------------------------------------
Silver

SQL> select key from table(test_pkg.keyval_tab ('{12345=Gold}|{12346=Silver}'))
  2  where value='Gold';

KEY
----------
12345

A: Use this query to get your expected output. Sorry if there are too many replace functions. But this is quite easier.
select EXTRACTVALUE (COLUMN_VALUE, '/row/Code') code,
        EXTRACTVALUE (COLUMN_VALUE, '/row/Value') Value
from TABLE(XMLSEQUENCE(EXTRACT(XMLTYPE('<rowset><row>'||replace(replace(replace(replace('{12345=Gold}|{12346=Silver}','}|{','</Value></row><row><Code>'),'{','<Code>'),'=','</Code><Value>'),'}','</Value>')||'</row></rowset>'),'/rowset/row')));

A: If you already have separated columns into rows the work to do is fairly simple with REGEXP_REPLACE function.
Considering that your cols now is:
NEW_STR
--------------
{12345=Gold}
{12346=Silver}

You can do this sql to transform it into two different columns:
select regexp_replace( col, '\{(\d+)=\w+\}', '\1' ) as feature,
       regexp_replace( col, '\{\d+=(\w+)\}', '\1' ) as value
  from testTable

Transform that into a view and then just select with columns as you like:
create or replace view testView as
   select regexp_replace( col, '\{(\d+)=\w+\}', '\1' ) as feature,
          regexp_replace( col, '\{\d+=(\w+)\}', '\1' ) as value
     from testTable

Then just do:
select * from testView where feature = '12345'

Or
Select * from testView where value = 'Gold'

If you like to transform the feature value as a number just use the to_number function on that column as:
to_number(regexp_replace( col, '\{(\d+)=\w+\}', '\1' ))

Remember that in order to do this you must be absolute sure that it is only numbers on that, otherwise you will have conversion errors

A: You can also use a pivot table and REGEXP_SUBSTR
with MyStrings as
 (select '{Feature1=Value1}|{Feature2=Value2}|{FeatureN=ValueN}' Str from dual
  union all
  select '{12345=Gold}|{12346=Silver}' from dual
  )
,pivot as (
  Select Rownum Pnum
  From dual
  Connect By Rownum <= 100
  )
SELECT rownum rn
      ,REGEXP_SUBSTR (ms.Str,'[^|]+',1,pv.pnum) TXT
  FROM MyStrings ms
      ,pivot pv
where REGEXP_SUBSTR (ms.Str,'[^|]+',1,pv.pnum) is not null


text:
Q: I'm trying to create a code that asks the user to choose from one of the products and add the quantity that he needs but I'm stuck? This is the code. I'm really struggling with it little help will be much appreciated thanks in advance!
package online.market;

import java.util.HashMap;
import java.util.Scanner;

public class OnlineMarket {

public static void main(String[] args) {
    System.out.print("Products\n");

    HashMap<String, Double> products = new HashMap<>();

    Scanner product = new Scanner(System.in);

    products.put("Computer", 999.99);
    products.put("Airpods", 129.30);
    products.put("TV", 129.30);
    products.put("Playstation 5", 569.70);
    System.out.println(products);

    String name = product.nextLine();
    System.out.println("Which product would you like to choose?");
}

A: try this :
public static void main(String[] args) {
    System.out.print("Products\n");

    HashMap<String, Double> products = new HashMap<>();

    Scanner product = new Scanner(System.in);

    products.put("Computer", 999.99);
    products.put("Airpods", 129.30);
    products.put("TV", 129.30);
    products.put("Playstation 5", 569.70);
    System.out.println(products);

    System.out.println("Which product would you like to choose?");
    String name = product.nextLine();

    Double price = products.get(name);
    if (price != null) {
        System.out.println("enter quantity :");
        int n = product.nextInt();
        System.out.println("you order " + n + " x " + name + "   , Total : "+n*price);
    } else {
        System.out.println("sorry this product not exist");
    }
}

A: Nice continue your code with this:
Scanner s = new Scanner(System.in);
String option = s.next();
System.out.println("How much"+option+"you want?");
int q = s.nextInt();

Of course the String "option" is the input of the user which you expecting you can also use a loop to make sure that user will input one of your options like this:
Scanner s = new Scanner(System.in);
String option = s.next();
while (!(option.equals("option1") || option.equals("option2"))){
        System.out.println("Wrong input please try again");
        option = s.next();
 }
System.out.println("How much"+option+"you want?");
    int q = s.nextInt();
    while (q<0){
        System.out.println("Wrong input please try again");
        q=s.nextInt();
    }

A: Something like this would finish off your code. Its hard to tell exactly what you want it to do.
 public static void main(String[] args) {
    System.out.print("Products\n");
    HashMap<String, Double> products = new HashMap<>();
    Scanner product = new Scanner(System.in);

    products.put("Computer", 999.99);
    products.put("Airpods", 129.30);
    products.put("TV", 129.30);
    products.put("Playstation 5", 569.70);
    System.out.println(products);

    System.out.println("Which product would you like to choose?");
    String name = product.nextLine();

    System.out.println("How much would you like?");
    int count = product.nextInt();

    System.out.println("Total Cost: "+products.get(name) * count);
}


text:
Q: ffmpeg error: Too large number of skipped frames xxxxx > 60000 I try to record on RasperryPI from usb Cam (/dev/video0) using segments to obtain sliced video.
The command I'm using is:
ffmpeg -input_format mjpeg -video_size 640x480 -i /dev/video0 -y -y -f v4l2 -an -pix_fmt yuv420p -codec copy -f segment -segment_time 60 -segment_wrap 10 -t 180 stream/looper%02d.avi

I got an error after 2 minutes about skipped frames (see later for detail).
Is I run the same command without segmentation is working.
I tested on different HW, with different segment parameters, with different usb cam but the situation still the same.
Here there is the output:
   ffmpeg version 4.1.4-1+rpt1~deb10u1 Copyright (c) 2000-2019 the FFmpeg developers
  built with gcc 8 (Raspbian 8.3.0-6+rpi1)
  configuration: --prefix=/usr --extra-version='1+rpt1~deb10u1' --toolchain=hardened --libdir=/usr/lib/arm-linux-gnueabihf --incdir=/usr/include/arm-linux-gnueabihf --arch=arm --enable-gpl --disable-stripping --enable-avresample --disable-filter=resample --enable-avisynth --enable-gnutls --enable-ladspa --enable-libaom --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libcdio --enable-libcodec2 --enable-libflite --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-libgme --enable-libgsm --enable-libjack --enable-libmp3lame --enable-libmysofa --enable-libopenjpeg --enable-libopenmpt --enable-libopus --enable-libpulse --enable-librsvg --enable-librubberband --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libssh --enable-libtheora --enable-libtwolame --enable-libvidstab --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx265 --enable-libxml2 --enable-libxvid --enable-libzmq --enable-libzvbi --enable-lv2 --enable-omx --enable-openal --enable-opengl --enable-sdl2 --enable-omx-rpi --enable-mmal --enable-libdc1394 --enable-libdrm --enable-libiec61883 --enable-chromaprint --enable-frei0r --enable-libx264 --enable-shared
  libavutil      56. 22.100 / 56. 22.100
  libavcodec     58. 35.100 / 58. 35.100
  libavformat    58. 20.100 / 58. 20.100
  libavdevice    58.  5.100 / 58.  5.100
  libavfilter     7. 40.101 /  7. 40.101
  libavresample   4.  0.  0 /  4.  0.  0
  libswscale      5.  3.100 /  5.  3.100
  libswresample   3.  3.100 /  3.  3.100
  libpostproc    55.  3.100 / 55.  3.100
Input #0, video4linux2,v4l2, from '/dev/video0':
  Duration: N/A, start: 40185.241073, bitrate: N/A
    Stream #0:0: Video: mjpeg, yuvj422p(pc, bt470bg/unknown/unknown), 640x480, 25 fps, 25 tbr, 1000k tbn, 1000k tbc
[segment @ 0x9800b0] Opening 'stream/looper00.avi' for writing
Output #0, segment, to 'stream/looper%02d.avi':
  Metadata:
    encoder         : Lavf58.20.100
    Stream #0:0: Video: mjpeg, yuvj422p(pc, bt470bg/unknown/unknown), 640x480, q=2-31, 25 fps, 25 tbr, 600 tbn, 1000k tbc
Stream mapping:
  Stream #0:0 -> #0:0 (copy)
Press [q] to stop, [?] for help
[segment @ 0x9800b0] Opening 'stream/looper01.avi' for writing/A speed=1.01x
[segment @ 0x9800b0] Opening 'stream/looper02.avi' for writing/A speed=1.01x
[avi @ 0x9822a0] Too large number of skipped frames 72034 > 60000speed=1.01x
av_interleaved_write_frame(): Invalid argument
[avi @ 0x9822a0] Too large number of skipped frames 72034 > 60000
frame= 3011 fps= 25 q=-1.0 Lsize=N/A time=00:02:00.06 bitrate=N/A speed=1.01x

I did not find any suggestion to solve it.
Could you help me?
Thanks
Dario


text:
Q: Filtering a list based on a condition - c#? I have a list of items with the following pattern of results in a variable named dataList
{PH:8,PDate:3/22/2021,
PH:8,PDate:3/23/2021,
PH:4,PDate:3/24/2021,
PH:8,PDate:3/29/2021,
PH:8,PDate:3/30/2021,
PH:4,PDate:3/31/2021,
PH:8,PDate:4/5/2021,
PH:8,PDate:4/6/2021}
The list may have more items like this and I just put a few to understand the pattern. And the list has a type which can hold an <int,DateTime> object.
The week of the day starts on Monday. So from the above list the first 3 items belongs to the same week. Second 3 items belongs to another week and the last 2 items belongs to a different week.
I want to filter this like below
{PH:20,PDate:3/22/2021,
PH:20,PDate:3/29/2021,
PH:16,PDate:4/05/2021}
which is like the sum of PH for each week. Any helps appreciated Thanks.

A: given you don't really have any code, you want to do something like the following where we group by week number starting on monday, then select  the first items date and sum all the ints.   Then when printing out we need to adjust the first items date to be the start of the week by subtracting off the first day of week.
 var list = new List<(int, DateTime)>();
        list.Add((8, new DateTime(2021,3,22)));
        list.Add((8, new DateTime(2021,3,22)));
        list.Add((4, new DateTime(2021,3,24)));
        var r = list.GroupBy(l =>
                CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(l.Item2, CalendarWeekRule.FirstFullWeek,
                    DayOfWeek.Monday))
            .Select(g => (g.Sum(x => x.Item1), g.First().Item2))
            .ToList();

        r.ForEach(i => Console.WriteLine($"{i.Item1} {i.Item2 - new TimeSpan(i.Item2.DayOfWeek - DayOfWeek.Monday, 0,0,0)}"));


text:
Q: Symfony CMF Nested Embedded Forms I have the following issue:
Article Page contains -> Multiple ArticleUnit Blocks contains -> Multiple Media Blocks
(Edit: See in the comments below for a summary of what I indented to do.)
I built the forms separately using buttom-up approach and what I currently have in a working state is:

*

*Individually each of the 3 Documents works correctly

*ArticleUnit Block embeds Media Block works correctly

*Article Page embeds standlone ArticleUnit Block (without embedding Media Block) works correctly

*But when Article Page embeds ArticleUnit Block which embeds Media Block it is NOT working correctly. After clicking on 'Add New' Button in Article Page the ajax response that I get is a hyperlink 'Add New' that is not displayed on the Article Page form.

Ajax response

        Add new

My code:
Article Page/News Admin (Admin of a StaticContent)
/**
 * Service name of the sonata_type_collection service to embed
 * @var string
 */
protected $embeddedArticleUnit;

/**
 * Configure the service name (admin_code) of the admin service for the embedded units
 *
 * @param string $adminCode
 */
public function setEmbeddedArticleUnitAdmin($adminCode)
{
    $this->embeddedArticleUnit = $adminCode;
}

protected function configureFormFields(FormMapper $formMapper)
{
    parent::configureFormFields($formMapper);

    $formMapper
        ->with('form.group_general', ['name' => 'Details'])
        ->add('body', 'hidden', ['data' => 'default'])
        ->add('colour', 'choice', [
            'choices' => [
                'red' => 'Red',
                'blue' => 'Blue',
                'yellow' => 'Yellow',
            ],
        ])
        ->end()
        ->with('Items')
        ->add('children', 'sonata_type_collection',
            ['label' => 'Text'],
            [
                'edit' => 'inline',
                'inline' => 'standard',
                'admin_code' => $this->embeddedArticleUnit,
            ])
        ->end();
}

Article News service
xx.article.admin.article.news:
    class: xx\ArticleBundle\Admin\NewsAdmin
    arguments:
        - ''
        - xx\ArticleBundle\Document\News
        - 'SonataAdminBundle:CRUD'
    tags:
        - { name: sonata.admin, manager_type: doctrine_phpcr, group: 'xx Dashboard', label: 'News' }
    calls:
        - [setRouteBuilder, ['@sonata.admin.route.path_info_slashes']]
        - [setRootPath, ['%cmf_base_page_article_news%']]
        - [setContainer,[@service_container]]
        - [setEmbeddedArticleUnitAdmin, ['xx.block.admin.article_unit_block_admin']]
        - [setEmbeddedMediaBlockAdmin, ['xx.block.admin.media_block_admin_header_image']]

ArticleUnit Block Admin (Admin of a Container Block)
/**
 * {@inheritdoc}
 */
protected function configureFormFields(FormMapper $formMapper)
{
    $formMapper
        ->with('form.group_general', ['name' => 'General'])
            ->add('body', 'textarea', ['required' => false])
            ->add('mediaPosition', 'choice', [
                'choices' => [
                    'bottom' => 'Bottom',
                    'right' => 'Right',
                    'left' => 'Left',
                ],
            ])
            ->add('parentDocument', 'doctrine_phpcr_odm_tree', ['root_node' => $this->getRootPath(), 'choice_list' => [], 'select_root_node' => true])
            ->add('position', 'hidden', array('mapped' => false))
        ->end()
        ->with('Items')
            ->add('children', 'sonata_type_collection',
                ['label' => 'Image(s)'],
                [
                    'edit' => 'inline',
                    'inline' => 'table',
                    'admin_code' => $this->embeddedAdminCode,
                    'sortable' => 'position',
                ])
        ->end()
    ;
}

ArticleUnit Block service
xx.block.admin.article_unit_block_admin:
    class: xx\BlockBundle\Admin\ArticleUnitBlockAdmin
    arguments:
        - ''
        - xx\BlockBundle\Document\ArticleUnitBlock
        - 'SonataAdminBundle:CRUD'
    tags:
        - { name: sonata.admin, manager_type: doctrine_phpcr, group: 'xx Dashboard', label: 'Article Unit Block' }
    calls:
        - [setRouteBuilder, ['@sonata.admin.route.path_info_slashes']]
        - [setEmbeddedMediaAdmin, ['xx.block.admin.media_block_admin']]
        - [setRootPath, ['%cmf_base_block%']]

Media Block Admin (Admin of an Imagine block)
/**
 * {@inheritdoc}
 */
protected function configureFormFields(FormMapper $formMapper)
{
    parent::configureFormFields($formMapper);

    $formMapper
        ->with('form.group_general')
        ->remove('filter')
        ->remove('name')
        ->remove('position')
        ->add('imageMobile', 'cmf_media_image', ['required' => false])
        ->add('imageTablet', 'cmf_media_image', ['required' => false])
        ->add('label', 'text', ['label' => 'Label (Alt)'])
        ->add('position', 'hidden', array('mapped' => false))
        ->end();
}

Media Block service
xx.block.admin.media_block_admin:
    class: xx\BlockBundle\Admin\MediaBlockAdmin
    arguments:
        - ''
        - xx\BlockBundle\Document\MediaBlock
        - 'SonataAdminBundle:CRUD'
    tags:
        - { name: sonata.admin, manager_type: doctrine_phpcr, group: 'xx Dashboard', label: 'Media Block' }
    calls:
        - [setRouteBuilder, ['@sonata.admin.route.path_info_slashes']]
        - [setRootPath, ['%cmf_base_block%']]

Thanks for reading. Any ideas/suggestions? :)


text:
Q: Laravel Can't disable Maintenance mode I've put my Laravel into the maintenance mode with php artisan down.
No I try to disable the mode with the command from the docs (php artisan up) but nothing happends.
I've cleared all Laravel caches and my browser cache. What is wrong?

A: Seems weird, But you can up it again by deleting a file named down in storage/framework.
It will do the trick.
Note:
You can create the file manually inside storage/framework. It will down your project. When you want live your project again, just remove the file.


text:
Q: MySQL query SELECT inside IN I'm new in SQL, have a comlpex query for me which choose only one cheapest line from each cityId to each cityId:
SELECT cityIdFrom, cityIdTo, MIN(fromToPrice) fromToPrice_min
FROM pricing
WHERE cityIdFrom IN (91, 94, 95, 99)
AND cityIdTo IN (91, 94, 95, 99)
GROUP BY cityIdFrom, cityIdTo

So we take cheapest from 91 to 94, cheapest from 91 to 95 etc. How can I fix this query to SELECT lines for cityIdFrom 91 only when column Bull IS 1.
For example, if we have:
cityIdFrom - cityIdTo - fromToPrice - Bull
91, 94, 3000, 0
91, 94, 5000, 1
91, 95, 1000, 0
91, 99, 1500, 1
99, 95, 2000, 0

Our query will give us:
91, 94, 5000, 1
91, 99, 1500, 1
99, 95, 2000, 0

Thank for help!

A: I was all about one line in my Query:
AND (CityIdFrom = 91 AND Bull = 1) OR CityIdFrom <> 91

Many thanks to @ADyson, he helped me so much!


text:
Q: javax.net.ssl.SSLHandshakeException: sinch voice call I'm making an app where i want to add voice call function using SINCH . First 2 days it works fine  but now it is not working , when i run the code android studio show the following error :
javax.net.ssl.SSLHandshakeException: SSL handshake aborted: ssl=0x74a32b4c88: I/O error during system call, Connection reset by peer
I'm using this code  https://github.com/agusibrahim/SinchVoiceCall-Example
Please help me to solve it


text:
Q: How do I get a key from a single object in the array? I have a FirebaseListObservable which is looped through and a single object in the list is passed through, how do I get the key value of the object passed through?
A single instance of the object is passed through to the function when selected and I need to get the key but if I use value.key or value.uid it is undefined.
This is the loop which does through the firebase array
<sebm-google-map-marker
*ngFor="let m of markers | async"
(markerClick)="test(m)"
[latitude]="m.lat"
[longitude]="m.lng"

>
When clicked on this is the function
 test(m){
var things=m;
console.log(m.val());}

I want to get the key of the item being passed through
this is the data being passed and want to get the key for the object

A: You will need to get the keys and then use the keys to loop through the collection:
First make an array of your keys (probably do this in a subscribe block since it looks like an observable in your code):
markerKeys = Object.keys(markers);

Then use the keys to loop:
<sebm-google-map-marker
  *ngFor="let mKey of markerKeys"
  (markerClick)="test(markers[mKey])"
  [latitude]="markers[mKey].lat"
  [longitude]="markers[mKey].lng"

A: I believe Eeks33 is right, but since markers is not an collection but instead an Observable of an collection you canot treat it as collection.
try
const addKeys = (collection => Object.keys(collection)
                                     .map(key => collection[key] = key));
const markersWithKeys = markers.map(addKeys);

then you should be able to iterate in your template over markersWithKeys where every item now has also a key property.
<sebm-google-map-marker
*ngFor="let m of markersWithKeys | async"
(markerClick)="test(m)"
[latitude]="m.lat"
[longitude]="m.lng"

Within your clickhandler you should be able to access the key like so:
test(m) {
    console.log(m.key);
}


text:
Q: How can i parse from SQL datetime to JSON and finally to java.util.Date? i have a remote sql satabase, and i connect him by php with JSON.
I can get string and int data OK, but now i have a problem.... i have a datetime field on my SQL database, and i dont know how to get it with JSON into java.util.Date
this is the code i tryed, but it fails getting the Date correctly, it gives me an exception (java.lang.ClassCastException: java.lang.String)
code:
JSONArray jArray = new JSONArray(result);

                for(int i=0;i<jArray.length();i++)
                {
                        JSONObject json_data = jArray.getJSONObject(i);
                        positions.add(new Position(json_data.getString("latitude"), json_data.getString("longitude"), (Date)json_data.get("timestamp")));
                 }

A: You will have to fetch the string sent in the JSON data and parse that string with something like SimpleDateFormat.

A: In my projects I have used two different solutions.

*

*Storing the Date not as Date but as long(milisecs since 1.1.1980). In Java you can get this with date.getTime(). There should also a methode in PHP. The get the Date Object in Java just pass the long value to the constructor(date= new Date(long_value)).
With this Method you may have problems when dates comes from different time zones.

*Write the Date as a formatted Date String in the JSON. How you encode the Date is up to you. A short sample give below. see[1] for further infos.
To get the Date you need a SimpleDateFormater.
DateFormat df = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");
try
{
  Date today = df.parse("2001.07.04 AD at 12:08:56 PDT");
  System.out.println("Today = " + df.format(today));
}
catch (ParseException e)
{
  e.printStackTrace();
}

[1]http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html


text:
Q: Proof of $C\left(n, k\right) = \frac{C\left(n, k-1\right) \cdot C(n - (k - 1), 1)}k$ I was wondering if anyone could explain to me why this holds true?
$$C\left(n, k\right) = \frac{C\left(n, k-1\right) \cdot C(n - (k - 1), 1)}k$$
or
$$C\left(3, 2\right) = \frac{C\left(3, 1\right) \cdot C(2, 1)}2$$
I was playing around with combinatorics, and realized that this holds true for all values that I put into it.

A: Here is a combinatorical explanation:
You can choose $k$ from $n$ items by

*

*choosing $k-1$ from $n$: $\color{blue}{\binom{n}{k-1}}$ and then

*choosing $1$ from the remaining $n-(k-1)$: $\color{blue}{\binom{n-(k-1)}{1}}$
But using this selection method the same selection can result in $\color{blue}{k}$ ways, since the $1$ you choose "last" can be one of the $k$. So,
$$\color{blue}{\binom{n}{k-1}\cdot\binom{n-(k-1)}{1}} = \color{blue}{k}\cdot \binom{n}{k}$$

A: LHS is number of ways to choose $k$ objects from $n$ objects.
RHS is nothing but,
now from $n$ objects first choose $k-1$ objects and then from remaining $n-(k-1)$ objects choose $1$ obajects. But in this counting we are repeating same object for $k$ times so devide by $k$.
So LHS and RHS count same things. So are equal.

A: Expanded with factorials,
$$\frac{n!}{k!(n-k)!}=\frac1k\frac{n!}{(k-1)!(n-k+1)!}\frac{(n-k+1)!}{1!(n-k)!}.$$
The simplifications are obvious.

A: LHS is the number of ways to choose $k$ objects from $n$ objects.
RHS is nothing but, now from $n$ objects first choose $k - 1$ and then from remaining $n-(k-1)$ objects choose 1 obeject.
but in this counting, we are repeating the same objects to objects K, so divided by Y
enter image description here
$\frac { n ! } { k ! ( n - k ) ! } \simeq \frac { 1 } { k } \frac { n ! } { ( n - 1 ) ( n - k + 1 ) ! } \frac { ( n - k + 1 ) ! } { 1 ! ( n - k ) ! }$


text:
Q: Build 3 distinct sections in HTML body tag I've been trying to set up the body of my website so that it's composed of three sections - a main section (for a slideshow/image), a mid-section (white background), and a footer (gray background). How would I go about doing this? So far, I have tried extending a tutorial for making a simple footer to allow me to add a third section. My HTML and CSS snippets are below:
index.html

text

Mid

Footer

styles.css

html, body {
    margin: 0px;
    padding: 0px;
    min-height: 100%;
    height: 100%;
}

  #wrapper {
    background-color: #212121;
    min-height: 100%;
    height: auto !important;
    margin-bottom: -300px; /* the bottom margin is the negative value of the footer's total height */
  }

  #wrapper:after {
    content: "";
    display: block;
    height: 300px; /* the footer's total height */
  }

  #content {
    height: 100%;
  }

  #midsection {
    height: 300px; /* the footer's total height */
    margin-bottom: -100px;
  }

  #midsection:after {
    content: "";
    display: block;
    height: 100px;
  }

#mid-content {
    background-color: #f9f9f9;
    height: 284px; /* height + top/bottom paddding + top/bottom border must add up to footer height */
    padding: 8px;
  }

/* main image section (wrapper) + mid section */

#footer {
    height: 100px;
}

#footer-content {
    background-color: #808080;
}

Ideally, I'd like the midsection to be 300px, and the footer to be 100px.

A: How about this:
there were a bit of errors in the html. Remember to close html tags correctly. Hope this helps.
html:

text

Mid

Footer

css:
html, body {
    margin: 0px;
    padding: 0px;
    min-height: 100%;
    height: 100%;
    background-color: #212121;
}

  #wrapper {

    min-height: 100%;
    height: auto !important;
    margin-bottom: -300px; /* the bottom margin is the negative value of the footer's total height */
  }

  #wrapper:after {
    content: "";
    display: block;
    height: 300px; /* the footer's total height */
  }

  #content {
    height: 100%;
  }

  #midsection {
    background-color: white;
    height: 300px; /* the footer's total height */
    margin-bottom: -100px;
  }

  #midsection:after {
    content: "";
    display: block;
    height: 100px;
  }

#footer {
  background-color: #212121;
  height: 200px;
}


text:
Q: Player Keeps Sticking On The Platform Collision Pygame I am trying to get a good collision with my rectangles but I feel like my method is bad because when ever I job and collide  with my other platform my player keeps getting stuck on it, is there  a way I could make it collide good without it getting stuck I am just looking for a good collision Thank You!
VIDEO < as you can see my player keeps getting stuck on the platform its the same thing for left and right when I collide with the platform it will just make my player stuck without proper collision
        # collisions
        for platform in platforms:
            if playerman.rect.colliderect(platform.rect):
                collide = True
                playerman.isJump = False
                if (platform.rect.collidepoint(playerman.rect.right, playerman.rect.bottom) or
                    platform.rect.collidepoint(playerman.rect.left, playerman.rect.bottom)):
                    playerman.y = platform.rect.top - playerman.height + 1
                    playerman.moveright = True
                    playerman.moveleft = True

                if (platform.rect.collidepoint(playerman.rect.right, playerman.rect.top) or
                    platform.rect.collidepoint(playerman.rect.right, playerman.rect.bottom - 10)):
                    playerman.moveright = False
                elif (platform.rect.collidepoint(playerman.rect.left, playerman.rect.top) or
                      platform.rect.collidepoint(playerman.rect.left, playerman.rect.bottom - 10)):
                    playerman.moveleft = False
            else:
                playerman.moveright = True
                playerman.moveleft = True

my full code:  script
I been searching everywhere for proper collision and I cant manage to find any good working ones

A: From your video it looks like the collision detection does not work if you come up from below a block.
In general (see below for an example): I encountered the same "puzzle" with my game and as far as I could see there are two possible ways.

*

*Pre-Checking
You check how far away the player is from the closest "block" and let the player move only so far. This includes:

*

*checking which blocks are the closest to the player

*checking the distance to each close block and calculating the remaining possible x pixels  the player can move in direction z.

*move player exactly x pixels in direction z.

*Post-Checking (I used this as it was easier to figure out on my own back then)

You move the player according to his current speed and then check for collisions. If you get a collision, you move the player back for the amount of pixels which is the intersection between player-border and block-border.

*

*move player according to his speed to the full extent

*check collisions for all close blocks (or all blocks on the map for starters and you can improve the performance from there)

*if you get a collision, calculate by how much the player intersects with the colliding block. This is easy if your player's hitbox is a rectangle and you work with a tilemap made up of rectangular blocks, you can simply subtract player.x  and block.x coordinates

*move the player back (before updating the screen) by that amount of pixels.

If you want to learn more about it and have in-depth code examples (if you don't want to try and error by yourself until you figure it out) I suggest searching on youtube for pygame-2D collision detections, there are great teachers on there.
Here is an excerpt of my collisiondetection_x_axis() method (self references the player!)
# move player etc ...
for tile in map_tiles: # for all tiles on the map
    if pygame.sprite.collide_rect(self.hitboxBody, tile):
        if self.SpeedX < 0 and tile.rect.right > self.hitboxBody.rect.left:  # moving left and collision
             # move char back to "in front of the wall"
             self.rect.x += tile.rect.right - self.hitboxBody.rect.left
             self.SpeedX = 0  # set speedX to zero, as we cannot move in that direction anymore

        elif self.SpeedX > 0 and self.hitboxBody.rect.right > tile.rect.left:  # moving right and collision
             # move char back to "in front of the wall"
             self.rect.x -= self.hitboxBody.rect.right - tile.rect.left
             self.SpeedX = 0  # set speedX to zero, as we cannot move in that direction anymore

collision_detection_y_axis:
for tile in map_tiles: # for all tiles on the map
    if pygame.sprite.collide_rect(self.hitboxBody, tile):
        if self.SpeedY < 0 and tile.rect.bottom > self.hitboxBody.rect.top:  # moving up
            self.rect.y += tile.rect.bottom - self.hitboxBody.rect.top # move char back to "below the wall"
            self.SpeedY = 0
        elif self.SpeedY > 0 and self.hitboxBody.rect.bottom > tile.rect.top:  # moving downwards
            self.rect.y -= self.hitboxBody.rect.bottom - tile.rect.top # move back to "on top of the wall"
            self.SpeedY = 0
            self.jumping = False  # on ground

Edit: this requires your movement between collision-checks to be less than the width of a block, otherwise your character can 'glitch' through blocks if he has enough speed.
Note: you should take into the account the direction your player is moving before you do collision-tests, it makes it easier to determine which side of the player will possibly collide first with a block. For instance if you are moving to the right, then the right side of the player will collide with the left side of a block. Then write a collision detection for those two points as well as consequent action (e.g. reset to a position in front of the block and speed_x = 0)
PS: Try and use the function pygame.Rect.colliderect, it tests if two rects overlap (=collision), I have a feeling the way you set up your collidepoint-functions don't return collisions for all possible scenarios.


text:
Q: How can I iterate multiple key from a dictionary in Django template I have given data from views to template in django. I want to iterate these multiple keys to build a html table.
views.py
data={'pacientes':p,'inicios':i,'finales':f,'enfermedad':enf} # p, i and f are lists
return render(request,'verEnf.html',data)

I want to do something like
index.html

     {% for p, i, f in pacientes, inicios, finales %} # I know that this code is not work

            {{ p.nombre }}
            {{ i }}
            {{ f }}

     {% endfor %}

p is an object from Pacientes
class Usuario(models.Model):
    dni=models.CharField(max_length=9,primary_key=True)
    clave=models.CharField(max_length=16)
    nombre=models.CharField(max_length=30)
    ...

and i is a string's list as
('20-2-2014', '12-2-2014', ..., '11-5-2014')

A: I suppose that each index of paciente, inicio and finales are related between them.
Just as Ignacio says, you can write some code in the view, before passing it to the template in order to solve your problem.
A possible solution could be packing the values in a list of tuples like this:
[
  (pacientes[0], inicios[0], finales[0]),
  (pacientes[1], inicios[1], finales[1]),
  ...
]

You can achieve this easily by using the zip function in your view:
pacientes_data = zip(p, i, f)
data={'pacientes_data':pacientes_data,'enfermedad':enf} # p, i and f are lists
return render(request,'verEnf.html',data)

And in your template:

     {% for p,i,f in pacientes_data %}

            {{ p.nombre }}
            {{ i }}
            {{ f }}

     {% endfor %}

A: Here is a working solution for similar task:

                    #
                    Model Name
                    Device Count

                  {% for all_model in all_models %}

                    {{ forloop.counter }}
                    {{ all_model.0 }}
                    {{ all_model.1 }}

                  {% endfor %}

In view.py
    all_models = []
    all_models_names = [1,2,3,4]
    all_models_names_values = [1,2,3,4]
    all_models = zip(all_models_names,all_models_names_values)
return render(request, "sample.html",{'all_models':all_models})


text:
Q: django customization of save method for change the default db I want to customize the save method to change my db and also
I have connected my django project to a mysql db .
I have tried to create a user in the shell which is from my models.py :
>>> from adabazi_test.models import Users
>>> user = Users(user_name = 'mamad' , password= 'bikbik')
>>> user.save()

and here is my models.py:
from django.db import models
class Users(models.Model):
    user_name = models.CharField(blank=False , max_length = 40)
    password = models.CharField(blank = False , max_length = 40)

in mysql db i have adabazi_test schema and Users schema and save method automatically put new instances of my models.Users in adabazi_test and i whould put them in Users schema.
 How can i customize save method for making this change?


text:
Q: Unable to add an icon at left of an input box in twitter bootstrap I am designing a login page here and I want to add the icon glyphicon-eye-open inside the password input field on the right, but I am unable to do so.
I tried putting it inside .has-feedback but it didn't work.
I tried the solution to  Add Bootstrap Glyphicon to Input Box, but that didn't work as well.
There might be an external style-sheet causing the problem, but I'm unable to fix it.

A: Using bootstrap's native validation states is definitely preferable to writing custom CSS here.
When using .has-feedback, make sure you also add the class .form-control-feedback to the glyphicon.  It should look like this:

    Username
    <input type="password" class="form-control" placeholder="Password" />

Demo in jsFiddle

For more info, see my answer to adding a Bootstrap Glyphicon to Input Box

A: Insert the icon inside of #password:

    <input placeholder="Password" name="password" class="form-control input-field" type="password">

Then use the following CSS:
#password {
    position: relative;
}

#password input[type="password"] {
    padding-right: 30px;
}

#password .glyphicon {
    right: 65px;
    position: absolute;
    top: 12px;
}


text:
Q: Error : Document not defined , On build angular universal app Error :
factory(require("jquery"), document, window, navigator);
                               ^ReferenceError: document is not defined

Facing issue angular universal rendering server side, I have googled this and go through many posts but didn't get any helpful resource.

A: Jquery works on the browser side and browser functions is not supported on server side.
for example if you want to use jquery in angular universal you will have to make sure you are using it on browser side only.
For example you can do the following.
In your component.ts file import the following.
import { isPlatformServer } from '@angular/common';
import * as $ from 'jquery';

and then in your ngOnInit function do the following
constructor(@Inject(PLATFORM_ID) private platformId: any) {}
  ngOnInit() {
    if (isPlatformBrowser(this.platformId)) {
     /* jQuery here */
     $("#test-button").click(function () {
       alert('WOOOW');
       $(this).css("background","#000");
    });
  }
}

A: I was having same issue, searched. Found this answer on https://github.com/angular/universal-starter/issues/623
Put this code in your server.ts file
const domino = require("domino");
const fs = require("fs");
const path = require("path");
const templateA = fs
  .readFileSync(path.join("dist/browser", "index.html"))
  .toString();
const win = domino.createWindow(templateA);
win.Object = Object;
win.Math = Math;

global["window"] = win;
global["document"] = win.document;
global["branch"] = null;
global["object"] = win.object;

A: To avoid your errors you can create mock for document and window objects in NodeJS server implementation server.ts:
// ssr DOM
const domino = require('domino');
const fs = require('fs');
const path = require('path');
// index from browser build!
const template = fs.readFileSync(path.join(DIST_FOLDER, 'index.html')).toString();
// for mock global window by domino
const win = domino.createWindow(template);
// mock
global['window'] = win;
// not implemented property and functions
Object.defineProperty(win.document.body.style, 'transform', {
  value: () => {
    return {
      enumerable: true,
      configurable: true,
    };
  },
});

// mock documnet
global['document'] = win.document;
// othres mock
global['CSS'] = null;
// global['XMLHttpRequest'] = require('xmlhttprequest').XMLHttpRequest;
global['Prism'] = null;

Here you can find working example
After modifications rebuild your server sources again.

A: If you are using server-side than you must have to add check whether the platform is browser or server because keywords like Document, Window are not available in Server side support
you can use isPlatformBrowser from angular.


text:
Q: Why don't the following two functions produce identical output? I would expect identical output to be produced but instead I get the following
string1,string2
WrappedArray(string1, string2)

.
  def appendcsv(fileName: String, args: Any*) {
    val fw = new FileWriter(fileName, true)
    val line = args.mkString(",")
    fw.write(line + "\r\n")
    fw.close()
  }
  def printcsv(fileName: String, args: Any*) {
    appendcsv(fileName, args)
  }
  appendcsv("test.csv", "string1", "string2")
  printcsv("test.csv", "string1", "string2")

A: Because when you do appendcsv(fileName, args), you are passing a WrapedArray instead of multiple arguments as you will expected. So in facts appendcsv only received only one argument of WrappedArray, not two strings.
You could use appendcsv(fileName, args: _*) to expend array to multiple arguments, and it will be what you would expected.


text:
Q: How to create [key:value,key:value] type json in java I try to  create [key:value,key:value] type json in java but I got only [{key:value},{key:value}] type.
How to create the above type?

A: [key:value,key:value] is not a valid json format (http://jsonlint.com/).
You can only have an array of the same elements.
It looks like you are trying to serialize/deserialize a map. In that case, the json would look like:
{
  "key1":"value1",
  "key2":"value2"
}


text:
Q: LightDM won't start after Grub - Cannot Access TTY unless closing and re-opening lid I am running Ubuntu 14.04 on an hp envy 17 3D. New installation + ATI Drivers
I would appreciate some help troubleshooting what I think is a LightDM issue which I have not been able to solve.
When I boot the computer after selecting Ubuntu at grub - the laptop seems to go through the regular boot process. The screen will flicker a second and I will hear the login screen prompt, but the login screen will not appear.
Attempting to switch to TTY mode will make the screen flicker again. I am able to run commands - but i cannot see the terminal. I have successfully rebooted, and attempted to start lightdm this way, but after running:
sudo service lightDM restart

It shows me the desktop background and cursor and just hangs.
I am able to still use the computer, if when I hear the login prompt, I close the lid to tell it to go to sleep, and then turn it back on. LightDM login shows up and I can use the computer normally.
Does this correctly seem like a lightdm issue? or is this xorg?
What logs should I be looking at to troubleshoot if I can only do so after putting the computer to sleep before logging in? What should I be looking for in those logs based on the issue above?
Thanks!
[Update]
If I attempt to logout, the same issue happens. I hear the Ubuntu login screen chime, but cannot see the login screen or switch to a TTY or login by typing. I can though shutdown by pressing the power button then enter.
I followed this bug to see if it applied, adding a sleep to start of lightdm and telling it to wait for udev, while this has prolonged the time it takes to hear the chime, it has not made the login screen appear.
https://bugs.launchpad.net/ubuntu/+source/lightdm/+bug/1066410

A: Instead of installing the beta, I followed the instructions here for installing via command line.
I also followed the instructions here for some troubleshooting to remove all errors
https://help.ubuntu.com/community/BinaryDriverHowto/AMD
Then I looked through some x.org logs to find any errors.
Following these two posts helped clear those errors up
https://askubuntu.com/questions/46524...ossfirex-in-ub
https://askubuntu.com/questions/94272.../175677#175677
As of this morning with a hard reboot, it is back to normal


text:
Q: Google Places API - Submitting reviews I am researching whether the following is possible and if so how I could go about achieving it.
We collect reviews for businesses from their customers and we'd like to post these reviews to Google places as part of the reviews they have on their.
I was wondering how I would go about getting our website to "push" this data to the Google places website, I've done lots of searching on the APIs but have found nothing that says it's possible or not.

A: Currently the Google Places API does not have write capability. It only has read capability. Right now only ratings are available, but I suspect reviews might come someday too.
Although you can send check-in signals and fix Places through the API. Hopefully Google will add the ability to send reviews and receive them.
If you're looking to get your content added to Google, you may want to talk to their content partnerships teams http://www.google.com/support/mapcontentpartners/
Since Google's local and maps initiatives are under the same people that would be the place to go.

A: I too looked into this as it would be of huge value to companies if possible.
My research led me to believe that it is not possible and could possibly violate Google's TOA with negative results for the company's Places page.
Instead, I built a workaround that makes it really easy for companies to collect feedback and get their own customers to submit the reviews: http://dallasmarketingservices.com/survey-local-unveiled-how-online-reviews-affect-your-local-business/
Maybe we will see this in the future though.


text:
Q: How to fix ' FCMPlugin Ready ERROR' in Phonegap? I'm new to Phonegap.I have no prior experience with Cordova projects. I'm trying to send push notifications from Firebase Cloud Messaging(FCM) to app. I'm using cordova-plugin-fcm. I added google-services.json to the cordova project root. I also modified build.gradle to use the plugin. When I run the project I get the following message
[phonegap] [console.log] adding proxy for Device
[phonegap] [console.log] Error: exec proxy not found for :: FCMPlugin :: ready
[phonegap] [console.log] FCMPlugin Ready ERROR
[phonegap] [console.log] FCMPlugin.js: is created
[phonegap] [console.log] adding proxy for File
[phonegap] [console.log] adding proxy for Globalization
[phonegap] [console.log] adding proxy for InAppBrowser
[phonegap] [console.log] adding proxy for Capture
[phonegap] [console.log] adding proxy for NetworkStatus
[phonegap] [console.log] Persistent fs quota granted
[phonegap] [console.log] Received Event: deviceready

How to fix this issue? Did I miss something? Any help would be appreciated.
Thanks in advance : )

A: I am using ionic cordova and had the same issue. After a 5 hrs of RnD come to know that this issue was because of the ionic version installation.
Steps to solve:

*

*Uninstall the ionic using below command
npm uninstall -g ionic

*Then install the below ionic version :
npm install -g ionic@5.4.13. (This version worked after trying many latest versions)

*Remove the android version
ionic cordova platform rm android --save

*Add new paltform
cordova platform add android@8.0.0
// After new android installation need to accept all license with below command
Go to cd. /Users/anand/Library/Android/sdk
Cd tools/bin.
Then type below command
yes | ./sdkmanager --licenses && ./sdkmanager --update


text:
Q: ASP.NET MVC Display HTML Based on User Role Following best practices, is there a better way to show/hide controls based on the user's role, or is it perfectly acceptable to use User.IsInRole() inside of a view? An answer on this post says it violates separation of concerns. What are the alternatives?

@if(User.IsInRole("Admin"))
{
    @Html.ActionLink("Create", "Create", "Games")
}

            Date
            Home
            Away
            Field
            Result
            @if (User.IsInRole("Admin"))
            {

            }

        @foreach (var g in Model)
        {

            @g.GameDate
            @g.HomeTeam.TeamName
            @g.AwayTeam.TeamName
            @g.Ballpark.Name
            (@g.HomeTeamRuns-@g.AwayTeamRuns) @g.Result
            @if (User.IsInRole("Admin"))
            {
                 @Html.ActionLink("Edit", "Edit", new { id = g.GameId })
            }

        }

A: Personally, I would add a bool property to the model IsAdmin and set the value in the controller. That way your View is only working with the Model.
@if (Model.IsAdmin)
{
    // render admin elements
}


text:
Q: Wrap a DataGrid in XAML I have a DataGrid that is being populated by a DataTable. Problem is that the DataTable has 12 columns but only 9 will show in the DataGrid as thats all that will fit on the page.
Anyone know how to wrap a DataGrid so the rest of the columns show further down the page? or any other ideas of how I could solve this?
Thanks

A: I don't think there is a way to wrap a data grid object instead you could put the DataGrid inside a ScrollViewer and enable the HorizontalScroll.
ScrollViewer Class http://msdn.microsoft.com/en-us/library/system.windows.controls.scrollviewer%28v=vs.110%29.aspx

A: Not sure how to wrap it easily.  I guess you would have to manage which columns are displayed by monitoring the width of your controls (not to mention having multiple data tables).  Yuck!  I'd suggest going with inserting your DataGrid inside of a ScrollViewer  This will be consistent with many other user interfaces as well, allowing your application to be more easily understood.
Just make sure to set the HorizontalScrollBarVisibility property to Auto or Visible
See XAML below:
<ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
    <DataGrid AutoGenerateColumns="False" Name="dataGrid1">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Column 1" />
            <DataGridTextColumn Header="Column 2" />
            <DataGridTextColumn Header="Column 3" />
            <DataGridTextColumn Header="Column 4" />
            <DataGridTextColumn Header="Column 5" />
            <DataGridTextColumn Header="Column 6" />
            <DataGridTextColumn Header="Column 7" />
            <DataGridTextColumn Header="Column 8" />
            <DataGridTextColumn Header="Column 9" />
            <DataGridTextColumn Header="Column 10" />
        </DataGrid.Columns>
    </DataGrid>
</ScrollViewer>

This creates the DataGrid below:

EDIT:
Since you need to print the DataGrid, I'll post a snippet on how to print it.  This will print the entire DataGrid; however, if your DataGrid is indeed too large, then you may need to look at modifying the output image.
PrintDialog dialog = new PrintDialog();
if (dialog.ShowDialog() == true)
{
    dialog.PrintVisual(dataGrid1, "The Entire DataGrid");
}

You can find PrintDialog in the namespace: System.Windows.Controls
The PrintDialog.PrintVisual function can be used to print your WPF controls, simply pass the control as the first argument.


text:
Q: JCEPolicy:38 - Exception caught while trying to open JCE via reflection java.lang.NoSuchFieldException: modifier? I am migrating my application from open JDK 11 to open JDK 15. Maven build was successful, but when I try to run the springboot application, I get this JCE policy exception. Could you please help.
I am using spring-data-mongodb-encrypt 1.3.0
The exception occurs in the below method as soon as the return statement is invoked (which is line no. 196 - MongoConfig.java in the stacktrace attached below)
public CryptVault cryptVault() {
   return new CryptVault()
         .with256BitAesCbcPkcs5PaddingAnd128BitSaltKey(0, oldKey)
         .with256BitAesCbcPkcs5PaddingAnd128BitSaltKey(1, secretKey)
         // can be omitted if it's the highest version
         .withDefaultKeyVersion(1);
}

The stack trace is
    JCEPolicy:38 - Exception caught while trying to open JCE via reflection
java.lang.NoSuchFieldException: modifiers
    at java.base/java.lang.Class.getDeclaredField(Class.java:2569)
    at com.bol.util.JCEPolicy.allowUnlimitedStrength(JCEPolicy.java:32)
    at com.bol.crypt.CryptVault.<clinit>(CryptVault.java:170)
    at MongoConfig.cryptVault(MongoConfig.java:196)
    at MongoConfig$$EnhancerBySpringCGLIB$$83ef758.CGLIB$cryptVault$3(<generated>)
    at MongoConfig$$EnhancerBySpringCGLIB$$83ef758$$FastClassBySpringCGLIB$$f9adb058.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:356)
    at MongoConfig$$EnhancerBySpringCGLIB$$83ef758.cryptVault(<generated>)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1128)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1022)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:512)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:381)
    at MongoConfig$$EnhancerBySpringCGLIB$$83ef758.cryptVault(<generated>)
    at MongoConfig.mongo(MongoConfig.java:232)
    at org.springframework.data.mongodb.config.AbstractMongoConfiguration.mongoDbFactory(AbstractMongoConfiguration.java:114)
    at MongoConfig$$EnhancerBySpringCGLIB$$83ef758.CGLIB$mongoDbFactory$32(<generated>)
    at MongoConfig$$EnhancerBySpringCGLIB$$83ef758$$FastClassBySpringCGLIB$$f9adb058.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:356)
    at MongoConfig$$EnhancerBySpringCGLIB$$83ef758.mongoDbFactory(<generated>)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1128)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1022)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:512)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:381)
    at MongoConfig$$EnhancerBySpringCGLIB$$83ef758.mongoDbFactory(<generated>)
    at org.springframework.data.mongodb.config.AbstractMongoConfiguration.mongoTemplate(AbstractMongoConfiguration.java:100)
    at MongoConfig$$EnhancerBySpringCGLIB$$83ef758.CGLIB$mongoTemplate$22(<generated>)
    at MongoConfig$$EnhancerBySpringCGLIB$$83ef758$$FastClassBySpringCGLIB$$f9adb058.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:356)
    at MongoConfig$$EnhancerBySpringCGLIB$$83ef758.mongoTemplate(<generated>)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1128)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1022)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:512)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1486)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1231)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:551)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:207)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1131)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1059)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:589)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:370)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1219)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:551)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:207)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1131)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1059)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:589)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:370)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1219)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:551)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.boot.web.servlet.ServletContextInitializerBeans.getOrderedBeansOfType(ServletContextInitializerBeans.java:234)
    at org.springframework.boot.web.servlet.ServletContextInitializerBeans.addAsRegistrationBean(ServletContextInitializerBeans.java:182)
    at org.springframework.boot.web.servlet.ServletContextInitializerBeans.addAsRegistrationBean(ServletContextInitializerBeans.java:177)
    at org.springframework.boot.web.servlet.ServletContextInitializerBeans.addAdaptableBeans(ServletContextInitializerBeans.java:159)
    at org.springframework.boot.web.servlet.ServletContextInitializerBeans.<init>(ServletContextInitializerBeans.java:80)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getServletContextInitializerBeans(EmbeddedWebApplicationContext.java:241)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.selfInitialize(EmbeddedWebApplicationContext.java:228)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.access$000(EmbeddedWebApplicationContext.java:89)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext$1.onStartup(EmbeddedWebApplicationContext.java:213)
    at org.springframework.boot.context.embedded.jetty.ServletContextInitializerConfiguration$Initializer.callInitializers(ServletContextInitializerConfiguration.java:83)
    at org.springframework.boot.context.embedded.jetty.ServletContextInitializerConfiguration$Initializer.doStart(ServletContextInitializerConfiguration.java:72)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:131)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:105)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61)
    at org.eclipse.jetty.server.handler.ScopedHandler.doStart(ScopedHandler.java:120)
    at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:809)
    at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:345)
    at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1404)
    at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1366)
    at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:778)
    at org.eclipse.jetty.servlet.ServletContextHandler.doStart(ServletContextHandler.java:262)
    at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:520)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:131)
    at org.eclipse.jetty.server.Server.start(Server.java:422)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:105)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:61)
    at org.eclipse.jetty.server.Server.doStart(Server.java:389)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainer.initialize(JettyEmbeddedServletContainer.java:91)
    at org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainer.<init>(JettyEmbeddedServletContainer.java:79)
    at org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainerFactory.getJettyEmbeddedServletContainer(JettyEmbeddedServletContainerFactory.java:540)
    at org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainerFactory.getEmbeddedServletContainer(JettyEmbeddedServletContainerFactory.java:185)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:164)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:134)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:536)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
    at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:134)

A: Installing the unlimited strengt crypto policy is useless nowadays. Java 11 never required this and recent versions of Java 8 also already use the unlimited strength policy. Looks like you are using an outdated and defect library of com.bol:spring-data-mongodb-encrypt.
Therefore you have to upgrade this library. You should need at least version  2.3.1 according to this issue.


text:
Q: Modelado de tablas con esquema de MSSQL en ASP.NET CORE 3.1 Estoy creando modelos en una aplicación MVC con ASP.NET Core 3.1, el problema es con las tablas que tienen esquema, hice un modelo con dbo y funciona normal, pero al momento de tomar una tabla con Esquema diferente a dbo la compilación dice que el nombre es inválido.
El modelo empieza así:
[Table("Esquema1.Tabla1")]
 public class Tabla1
    {
        [Key]
        public int id { get; set; }
    }

Lo anterior me funcionaba en ASP.NET con Framework 4.7 pero en CORE 3.1 no.
Al compilar el error es el siguiente:

Gracias

A: Después de investigar, supe que tuve un error al no llamar al esquema aparte, la solución fue:
[Table("Tabla1", Schema ="Esquema1")]
public class Tabla1
    {
        [Key]
        public int id { get; set; }
    }


text:
Q: Do an HTTP Post in .NET (Vb) with compressed data using deflatestream The data that I am posting from a VB.Net client is large and I want to compress.
I want to do a "POST" and the apache server supports mod_deflate.
I am trying to integrate DeflateStream into my post code, however does not seem to be working.
I can send the data without compression using the standard code.
    request.ContentType = "application/x-www-form-urlencoded"

    Dim dataStream As Stream = request.GetRequestStream()
    Dim byteArray As Byte() = Encoding.UTF8.GetBytes(strEncodedXML)
    request.ContentType = "application/x-www-form-urlencoded"
    request.ContentLength = byteArray.Length
    dataStream.Write(byteArray, 0, byteArray.Length)
    dataStream.Close()
    Dim response As WebResponse = request.GetResponse()

However I am not sure how to add the compression using the Deflate Stream.
My best guess is the following, however I do not think it is working.
    request.Headers.Add("Content-Encoding", "deflate")
    request.ContentType = "application/x-www-form-urlencoded"

    Dim dataStream As Stream = request.GetRequestStream()
    Dim byteArray As Byte() = Encoding.UTF8.GetBytes(strEncodedXML)
    Dim compress As New DeflateStream(dataStream, CompressionMode.Compress, True)
    request.ContentType = "application/x-www-form-urlencoded"
    request.ContentLength = byteArray.Length
    dataStream.Write(byteArray, 0, byteArray.Length)
    dataStream.Close()
    Dim response As WebResponse = request.GetResponse()

Questions.

*

*Should I be sending the
ContentLength of the Compressed
Stream, if so, how do I get that.

*Should I be writing to the datastream
or compress?

*Is this how you use
DataStream and DeflateStram
together?

*On the server side, considering that apache is automatically supposed to be handling the inflating, how do I
know that it is working (so far, I
know there is no times savings on my
posts between the two methods used
above).

A: This question contains code that zips the request (which implicitely answers your Q1,Q2 and Q3).
Q4: Use a sniffer to check the data sent on the wire. Fiddler2 is free and super easy to install and use.
Answers to the linked question explain why mod_deflate is not going to be your friend regarding compression of the request.


text:
Q: Is it possible to change the background color for item in a wx.ListBox? I'd like to alternate the background color in my listbox so that it is a little easier to read. Something like this:

However, I can't figure out how to do so. From the docs, I see that the wx.listbox has a method called SetItemBackgroundColor(self, item, colour), but I'm unsure if (a) the item parameter is an index or a wx.ID of some kind, or (b) if that method is actual applicable to the listbox (maybe it was for something higher up in the inheritance tree?)
I've tried passing in an index, along with a color to the method, but it doesn't do anything. So I'm not sure whether it doesn't work because I'm passing in the wrong type of identifier, or if it doesn't work because the method doesn't apply to the object.
If it is a wx.ID that I'm supposed to pass in for the item parameter, how to do get the such information for the listbox instance?

A: Setting the background color is not possible with a ListBox.  ListCtrl can do this though.
In general, ListBox is for small simple lists (and is therefore quick and easy), and ListCtrl provides much more flexibility (but is also a bit more involved).
For an example of how to make striped backgrounds, see the demo under CoreWindows\ListCtrl_virtual.
Update on the difference between the wx docs (which don't have the SetItemBackgroundColor method), and wxpython docs (which do):  It seems that when the native API can be used, and when it supports some functionality beyond the wx library, access to it is sometime added to the wrapper.  That is, use of SetItemBackgroundColor is platform dependent, based on the native API.  See this thread for some discussion (particularly, Robin Dunn's entry).  When it's not available in the native platform, the command is ignored.


text:
Q: Flutter proxy object - how to delegate method call I'm trying to achieve some kind of Proxy pattern using noSuchMethod method. But I have no idea how to pass the method call and its arguments to the underlying object in some generic way.
Is it even possible in flutter?
class MyClass {
  void Method(String s, int d) {
    print('Method called: ' + s + ', ' + d.toString());
  }
}

class Proxy {
  MyClass myclass = MyClass();
  noSuchMethod(Invocation invocation) {
    print(invocation);
    //invocation.invokeOn(myclass);
  }
}

void main() {
  dynamic proxy = Proxy();
  proxy.Method('Hello World!', 17);
}


text:
Q: Why can I ssh logon without key or password? How do I stop this? I have just discovered I can log into my server as long as I provide a missing file to the ssh client!
What can I check to find out why and what can I change to stop this from happening?
Logging in with missing file
$ ssh -i ~/.ssh/x user@server.com
Warning: Identity file /c/Users/G/.ssh/x not accessible: No such file or
directory.
Last login: Wed Aug  9 20:20:49 2017 from 192.168.15.250
user@server:~$

Failing to log in with invalid cert
$ ssh -i ~/.ssh/invalid.pem user@server
Permission denied (publickey).

Successfully logging in
$ ssh -i ~/.ssh/valid.pem user@server
Last login: Wed Aug  9 20:21:07 2017 from 192.168.15.250
user@server:~$

These are the only non-commented lines in my /etc/ssh/sshd_config
Host *
    SendEnv LANG LC_*
    HashKnownHosts yes
    GSSAPIAuthentication yes
    GSSAPIDelegateCredentials no

A: In answer to "What can I check to find out why"
ssh -vv. The -vv parameter gives verbose debugging showing what is happening between pressing return on the local client and seeing the prompt on the remote server
In answer to "Why can I ssh logon without key or password?"
That wasn't what was happening. In this specific case, the appropriate key, valid.pem was duplicated in the id_rsa file. The duplicate key was being used

The following occurs on this client:

*

*Warning is shown that the specified key file is not accessible

*the client tries looking for any suitable key

as shown here:
debug2: key: /c/Users/G/.ssh/id_rsa (0x0)
debug2: key: /c/Users/G/.ssh/id_dsa (0x0)
debug2: key: /c/Users/G/.ssh/id_ecdsa (0x0)
debug2: key: /c/Users/G/.ssh/id_ed25519 (0x0)

*It then tries the id_rsa key. As shown here debug1: Trying private key: /c/Users/G/.ssh/id_rsa

*The server sees that this key is valid and allows logon to continue debug1: Authentication succeeded (publickey).


text:
Q: Linq-to-SQL - Grouping and joins I have this schema:
Products (**ProductId**, OwnerId, Name)
Categories (**CategoryId**, Name)
ProductsInCategories( **ProductId**, CategoryId )

When I wish to return the list of categories the Linq is simple enough:
from c in db.Categories
orderby c.Name
select c;

However, I want to return only the set of categories that contain products with a specific OwnerId.
If this were normal T-SQL then I can do that easily enough:
SELECT ProductsInCategories.CategoryId
FROM ProductsInCategories
INNER JOIN Categories ON ProductsInCategories.CategoryId = ProductsInCategories.CategoryId
INNER JOIN Products   ON ProductsInCategories.ProductId  = Products.ProductId
WHERE Products.OwnerId = 3
GROUP BY ProductsInCategories.CategoryId

(But I note this SQL only returns Category IDs but not Category names as well, ideally I'd like to return both)
However when I convert this to Linq it doesn't work anymore:
from pic in db.ProductsInCategories
join p in db.Products   on pic.ProductId  equals p.ProductId
join c in db.Categories on pic.CategoryId equals c.CategoryId
orderby c.Name
where p.OwnerId == ownerId
select c;

LinqPad reports this returns a large result set that contains numerous duplicate entries (category names are repeated for each product-in-category mapping).
What's the solution here?
Thanks!

A: var q =
    from c in db.Categorie
    where (from pic in db.ProductsInCategories
          join p in db.Products on pic.ProductId equals p.ProductId
          where p.OwnerId == ownerId && pic.CategoryId == c.CategoryId
          select pic).Any()
    select c;

A: Please run this SQL Statement.If you get true result,we can convert it to Linq 2 sql together
SELECT CategoryId, Name
FROM Categories
WHERE CategoryId IN (SELECT CategoryId FROM ProductsInCategories PIC
                     INNER JOIN Products P ON PIC.ProductId = P.ProductId
                     WHERE P.OwnerID = @OwnerID)


text:
Q: Liquibase: check if a property was set I could not find a way to check in a precondition element if a custom property is set.
What I found out about this issue so far is here.
As the ticket comment indicates, extending CustomPrecondition will not help without modifying the API. Is there another way?

A: The documentation describes a changeLogPropertyDefined precondition.
The following example worked fine for me:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-2.0.xsd">

    <changeSet author="mark (generated)" id="mark-1">
        <preConditions onFail="HALT">
            <changeLogPropertyDefined property="testing" value="1"/>
        </preConditions>

        <createTable tableName="TEST001">
            <column name="ID" type="VARCHAR(10)">
                <constraints nullable="false"/>
            </column>
            <column name="X" type="VARCHAR(9)">
                <constraints nullable="false"/>
            </column>
            <column name="Y" type="DECIMAL(7,2)"/>
            <column name="Z" type="DECIMAL(7,2)"/>
        </createTable>
    </changeSet>

</databaseChangeLog>

I run liquibase from Maven. The testing property can be set from the command line as follows:
mvn -Dtesting=1 compile


text:
Q: How to remove small camera preview box in artoolkit? I'm using unity3d and ARToolkit to create an AR app. My question is when opening the application, a small camera preview box always shows in the upper left of the screen. Is there a way to remove this by editing UnityARPlayer.jar via android studio or the unity package itself?

A: To solve this issue (just to hide the small camera, not to remove it completely!), you have to regenerate the UnityARPlayer.jar file after making a small correction in the UnityARPlayerActivity.java file available in the AndroidStudio project of ARToolkit 5.3.2 which is available here.
In the project, in the UnityARPlayer\src\main\java\org\artoolkit\ar\unity\UnityARPlayerActivity.java file, in the onResume() method, change the code
decorView.addView(previewView, new LayoutParams(128, 128));

to
decorView.addView(previewView, new LayoutParams(1, 1));

Here, we are just changing the camera preview size, to make it nearly invisible.


text:
Q: render a variable foreach in react On React (Next.js), I am trying to make a counter for adding records to the PostgreSQL database (>30,000 records) (for import from EXELL). The addition procedure works quite quickly, but I still want to make a counter that would be displayed when this procedure is launched and output the current record. In my code, the counter is output to console.log , but not rendered on the screen. And it is not displayed in  either when insertRows.current > 0 or when setIsInsert(true). What is wrong, and whether it can be implemented somehow. I wanted to use useEffect() , but I think it's only used when getting data before the initial rendering. I guess I still don't know much about Refct? Please help implement this, or suggest something else to
import { useEffect, useState, useRef } from "react"

  export default function insertCounter() {
  const insertRows = useRef(0) //number of inserted records
  const [insRows, setInsRows] = useState(0) //number of inserted records
  //const [isInsert, setIsInsert] = useState(true) // Visual ProgressBar

  const data = [
    { id: 1, name: "Roman" },
    { id: 2, name: "Misha" },
    { id: 3, name: "Vova" },
  ]

  const addRows = (data) => {
     try {
      data.forEach((row) => {
        // const cInsert = insertToPSQL(row) //Insert record to PostgreSQL (async function)

        insertRows.current = insertRows.current + 1
        setInsRows(insRows+1)
        console.log("insertRows.current=", insertRows.current)
        console.log("insRows=", insRows)
      })
    } finally {
      console.log("insertCounter.js/addRows/finally/insertRows.current=", insertRows.current)
      alert(`finally:Added ${insertRows.current}`)
      insertRows.current = 0
      setInsRows(0)
    }
  }
  const handleInsert = () => {
    insertRows.current = 0
    // setIsInsert(true)
    addRows(data)
  }

  useEffect(() => {
    //?????????????????? /
  }, [])

  return (

insertCounter

      <button onClick={handleInsert} style={{ color: "yellow", backgroundColor: "blue" }}>
        Insert
      </button>
      {
Added records:{insertRows.current}
}
      {
Added records:{insRows}
}

  )
}

A: Don't forget that ref in React doesn't trigger a render. If you want to trigger a rerender you should use state instead.
Also you're setting your variable to 0 in the finnaly so at the end of your function, it will always be 0


text:
Q: Java logging and throwing exception I know this is an Anti-Pattern, but in my RESTful application I want to log and throw.
I have this Code
log.warn("Cannot determine provider from name: " + name);
throw X.bad("Cannot determine provider from name: " + name);

This is a situation that shouldn't happen - it is just the last else in a series of if/else if.  However in case it does happen it might indicate a front-end bug/error.

*

*My restful stack can deal with exceptions and map them to HTTP responses.

*I also want a log entry with a good stacktrace.

*I would like the log entry to pertain to the place it was thrown from (I.e. logger category (class name) and stacktrace.

I did think of putting a log.warn(...) inside X.bad() but then the logging class is X and the stacktrace is bigger than it was when the exception was needed to be thrown.
Does anyone have a more integrated solution?
(I think to stop the repetition of the text component more then anything)
Thanks
Rob

A: there's a 2007 article from Barry Ruzek covering this problem.
http://www.oracle.com/technetwork/articles/entarch/effective-exceptions-092345.html
The overall solution is to have a Fault Barrier at the upper layer of your call stack. This Fault Barrier replaces your step 1. It will catch ALL exceptions, and log it accordingly.
I think the thing you didn't check is to create a Custom Exception extending RuntimeException (i.e. MyAppRuntimeException), and add in it the level of log you need to log it, and any other field you would like to transmit to your fault barrier.
Your fault barrier will need also to catch all other exception (Exception, Runtime, etc) an manage them with a default behavior.
You do not need to log before you throw the exception, you only need to log at one place: when you catch the exception with your fault barrier.
If you log the stacktrace, and not only the message, you will still be able to see the root of the problem in your log.
After that, you continue as you do here. Send back the ReST message.


text:
Q: Grails' respond method outputs HTML content with charset=ISO-8859-1 I just noticed that the respond method in controllers is returning HTML responses in the ISO-8859-1 charset (which garbles my unicode characters). It uses UTF-8 if I set the format to JSON. The render method also uses UTF-8.
I'm using Grails 2.4.4 and the Tomcat plugin v. 7.0.55 in development mode without overriding web.xml. Both grails.converters.encoding and grails.views.gsp.encoding are set to UTF-8. I have <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> in my template if that influences anything.
I've also tried forcing the charset by using respond myInstance, [encoding: "UTF-8"] but it didn't change anything.
Is there something I am not seeing or have I hit a bug?
EDIT: my config.groovy contains the following mime type definitions:
grails.mime.types = [ // the first one is the default format
    all:           '*/*', // 'all' maps to '*' or the first available format in withFormat
    atom:          'application/atom+xml',
    css:           'text/css',
    csv:           'text/csv',
    form:          'application/x-www-form-urlencoded',
    html:          ['text/html','application/xhtml+xml'],
    js:            'text/javascript',
    json:          ['application/json', 'text/json'],
    multipartForm: 'multipart/form-data',
    rss:           'application/rss+xml',
    text:          'text/plain',
    hal:           ['application/hal+json','application/hal+xml'],
    xml:           ['text/xml', 'application/xml']
]

A: It would seem this is a Grails bug, I've narrowed down the specific case when it happens: you need to have a static responseFormats = ['html', ...] limitation on the controller to trigger it. The fact that Grails' generate-restful-controller includes the responseFormats block automatically makes developers even more likely to encounter this issue.
I've filed a bug report.
EDIT: to keep the responseFormats block but still have UTF-8 responses, it's possible to set the encoding manually, perhaps like this:
def beforeInterceptor = {
    response.characterEncoding = 'UTF-8' //workaround for https://jira.grails.org/browse/GRAILS-11830
}


text:
Q: Buffered string mangled I am making an XML formatter in C. It's going really well, but my previous approach (direct printf at each character) wouldn't print the right amount of spaces for each line. Therefore, I made a string buffer and realloced it each time to print a new character. (I know it's not the best, but I don't care.) The new code won't clear the buffer or detect newlines correctly.
void bufprint(char **line, char *poo) {
    /*SNIP old code without realloc*/
    *line=realloc(*line,strlen(*(line))+1+strlen(poo));
    strcpy(*line+strlen(*line),poo);
}

And buf is declared like char *buf=malloc(1);.
bufprint is called: bufprint(&buf,"<");.
Code for clearing buffer:
    if (new) {
        new=False;
        int i;
        for (i=0; i < level; i++) {
            printf(" ");
        }
        printf("%s",buf);
        free(buf);
        buf=malloc(1);
        printf("\n");
        //printf("BUFFER CLEARED! --------------");
        //printf("New buffer: %s %d",buf,strlen(buf));
    }

Sample output:
<
 <root>
  <root><element num="1">
  This is element 1

 </element>
  </element><element num="2">
  This is element 2

   <subelement>
   <subelement>This is a sub-element

  </subelement>
  </subelement>Self-closing tag:

</element>
</root>

A: The malloc(1) call will not zero out the byte that was just allocated. You must do this yourself, otherwise your newly allocated memory might contain some random nonzero byte.
buf = malloc(1);
buf[0] = '\0';

If this does not solve your problem, then the bug may lie somewhere else that you haven't shown us.


text:
Q: Send to Messenger does not show up on my page I have logged in fb account to have session.
I have whitelisted my domain.
I followed below as listed in Send to Messenger Plugin
(function(d, s, id){
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) {return;}
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.com/en_US/messenger.Extensions.js";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'Messenger'));

Then I have,
<div class="fb-send-to-messenger"
 messenger_app_id="xxx" #another question, is this same as the FB.init({appId: xxx})
 page_id="fb_page_id"
 data-ref="<PASS_THROUGH_PARAM>"
 color="blue"
 size="xlarge">
</div>

I already set up configurations in Facebook Developer page (see attached).


text:
Q: opencv_world linking issue I have an issue linking the provided opencv_world340.lib file to my application:
I downloaded the windows prebuilt version of Opencv 3.4.0 from here. I linked the opencv_world340.lib to my application with headers and runtime dll from the build\x64\vc14 folder to my Visual Studio 2015 C++ console application.
I am able to create a cv::Mat from file, it is well created in runtime, but when I try to convert it with .convertTo() (or use any further functionality of OpenCV) I got a LNK2019 linking issue that the function is not resolved. I though the opencv_world340.lib is a all_in_one file containing every module.
Am I missing something?


text:
Q: Node .fs Working with a HUGE Directory Picture a directory with a ton of files. As a rough gauge of magnitude I think the most that we've seen so far is a couple of million but it could technically go another order higher. Using node, I would like to read files from this directory, process them (upload them, basically), and then move them out of the directory. Pretty simple. New files are constantly being added while the application is running, and my job (like a man on a sinking ship holding a bucket) is to empty this directory as fast as it's being filled.
So what are my options? fs.readdir is not ideal, it loads all of the filenames into memory which becomes a problem at this kind of scale. Especially as new files are being added all the time and so it would require repeated calls. (As an aside for anybody referring to this in the future, there is something being proposed to address this whole issue which may or may not have been realised within your timeline.)
I've looked at the myriad of fs drop-ins (graceful-fs, chokadir, readdirp, etc), none of which have this particular use-case within their remit.
I've also come across a couple of people suggesting that this can be handled with child_process, and there's a wrapper called inotifywait which tasks itself with exactly what I am asking but I really don't understand how this addresses the underlying problem, especially at this scale.
I'm wondering if what I really need to do is find a way to just get the first file (or, realistically, batch of files) from the directory without having the overhead of reading the entire directory structure into memory. Some sort of stream that could be terminated after a certain number of files had been read? I know Go has a parameter for reading the first n files from a directory but I can't find a node equivalent, has anybody here come across one or have any interesting ideas? Left-field solutions more than welcome at this point!

A: You can use your operation system listing file command, and stream the result into NodeJS.
For example in Linux:
var cp=require('child_process')
var stdout=cp.exec('ls').stdout

stdout.on('data',function(a){
         console.log(a)
});0

RunKit: https://runkit.com/aminanadav/57da243180f3bb140059a31d