text:
Q: nginx 502 bad gateway in ubuntu Ubuntu and nginx in my server. I have multiple subdomain for this server, which port 3000 it is alraedy be use by other website. Whole of this node app will be serve from pm2.
I guess cause the 502 gateway error, is the port is not be serve from my server.
// /etc/nginx/sites-available/projectB

server {
    root /var/www/projectB;
    server_name projectB.domain.com www.projectB.domain.com;

    location / {
      proxy_pass http://localhost:3001; // this will be fine if it is localhost:3000;
      proxy_http_version: 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection 'upgrade';
      proxy_set_header Host $host;
      proxy_cache_bypass $http_upgrade;
    }
}

This is my backend service port. It's not exist port 3001 inside there. I'll porvide the nginx error.log at below too.
// sudo netstat -plant

Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 127.0.0.53:53           0.0.0.0:*               LISTEN      494/systemd-resolve
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      787/sshd: /usr/sbin
tcp        0      0 0.0.0.0:443             0.0.0.0:*               LISTEN      80730/nginx: master
tcp        0      0 127.0.0.1:27017         0.0.0.0:*               LISTEN      32831/mongod
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      80730/nginx: master
tcp        0      0 127.0.0.1:27017         127.0.0.1:39994         ESTABLISHED 32831/mongod
tcp        0      0 127.0.0.1:39994         127.0.0.1:27017         ESTABLISHED 81007/node
tcp        0    364 139.59.107.31:22        124.13.195.75:50855     ESTABLISHED 82341/sshd: root@pt
tcp        0      0 127.0.0.1:27017         127.0.0.1:39984         ESTABLISHED 32831/mongod
tcp        0      0 127.0.0.1:27017         127.0.0.1:39986         ESTABLISHED 32831/mongod
tcp        0      0 127.0.0.1:39986         127.0.0.1:27017         ESTABLISHED 81007/node
tcp        0      0 127.0.0.1:39984         127.0.0.1:27017         ESTABLISHED 81007/node
tcp6       0      0 :::22                   :::*                    LISTEN      787/sshd: /usr/sbin
tcp6       0      0 :::3000                 :::*                    LISTEN      81007/node
tcp6       0      0 :::443                  :::*                    LISTEN      80730/nginx: master
tcp6       0      0 :::80                   :::*                    LISTEN      80730/nginx: master

nginx/error.log
[error] 80731#80731: *434 connect() failed (111: Connection refused) while connecting to upstream, client: clientPort, server: projectB.domain.com, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:3001/", host: "projectB.domain.com"

A: It looks like your application itself isn't listening on port 3001, which is where nginx is trying to forward your requests to.
Check your application is configured to listen on that port and that it is running. You can check if it's working by trying to connect without nginx in the way, by running this command on your server.
curl http://localhost:3001/
If you get a response, then your application is working. See if Nginx is able to serve the page. It looks like it should based on your config.


text:
Q: How to remove carriage returns and line feeds from a column? I'm trying to remove carriage returns and line feeds from a column I imported from a csv file.
I'm using the code:
SELECT replace(replace(column,CHAR(13),''),CHAR(10),'')
FROM table

It correctly finds all the CR and LF, but it doesn't update the database.

A: Your query retrieve from your table named TABLE all rows with the column replaced.
About UPDATE your database you must use UPDATE command in this way:
UPDATE table SET column = replace(replace(column,CHAR(13),''),CHAR(10),'')

If you want condition the UPDATE about the satisfaction of some conditions, so you must add the WHERE clause.
For example
UPDATE table SET column = replace(replace(column,CHAR(13),''),CHAR(10),'')
WHERE column_2 = 'XXX'

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does Ant offer a way to bypass dependency? The build.xml has a test and a build target. The test target obviously depends on the build target.
How can I run the test target only, temporarily skipping the compilation, without modifying the build.xml file ?
I'm asking because the compilation is too long, and kept up-to-date by a continuous integration server ; and I'm chasing after an issue with the unit tests.

A: Personally I've found the dependency stuff in Ant to get in the way more than helping. I usually set up two sets of targets - ones which actually do stuff (with no dependencies) and then targets which just have dependencies. That way you can easily run a single target, and you can also easily run the whole suite etc. This fits in with practical (rather than ideological) uses in my view.

A: Use the unless attribute.
<target name="test" unless="dont.run.tests">

If you don't want "test" to run, just

ant -Ddont.run.tests=true

It should be undefined if you want the tests to run. Ant just checks for whether it's defined at all. Also, there's an if attribute that does the converse.
Here's an article on the both.

A: No, you can't skip it without modifying the build file.
Here is what I do in my projects to solve this issue.
For every public target I will create a private target with "do-" in front of it.
The private target has no dependency, and the public target has the "do-" target as a dependency.
For example:
<target name="compile" depends="init, do-compile" description="Compiles all of the source code" />

<target name="do-compile">
        <javac destdir="${classes.dir}" debug="true" encoding="ISO-8859-1">
            <src refid="src.path" />
            <include name="*.java" />
            <classpath refid="external.libraries.classpath" />
        </javac>
</target>

A: A well written build target will not need to rebuild anything if the code hasn't changed.  So the fact that the test target depends on it should be largely irrelevant.  If you run the build target twice in a row and it tries to rebuild something the second time, you might want to investigate why it is doing that.
The simple way to avoid executing the target is to set the "unless" attribute of the target to the name of some property.  If you then set this property on the command line when running Ant, it will bypass that target.

A: Just "remove" the dependency temporarily?`If the code is built already all your files should be available, no? - oops, just saw that you cannot alter the file, hmm, why don´t you run the same job locally first?


text:
Q: Helo All, need input I have 3 objects, A,B,C.
B is a child of A(Lookup)
C is a child of A(lookup)
Now I want to write a trigger on object B, that whenever a B record is created all the C records linked with A object should be linked to B records also.
I am able to get the C records details in a list once B record is created, but I am not sure how to map those records. Could some one pls help me out with the trigger.
===============
trigger PitchElement on Pitch__c (after insert) {
    List<ID> marketingIdea = new List<ID>();
    //Marketing_Package__c MarektingIdeaList = new Marketing_Package__c();
    List<Marketing_Element__c> MarketingElements = new List<Marketing_Element__c>();
    for(Pitch__c pitch :Trigger.new)
    {
        marketingIdea.add(pitch.Marketing_Package__c);
        System.debug('!!!!' +marketingIdea);
    }
    Marketing_Package__c m = [select ID,Name from Marketing_Package__c where ID IN:marketingIdea];
    System.debug('@@@@@Marketing Package@@@@@@@' +m);

    MarketingElements = [select ID,Name from Marketing_Element__c where Marketing_Package__c =: m.Id];
    System.debug('Marketing elements' +MarketingElements);

}

Marketing_Package__c , Pitch__c,Marketing_Element__c
A, B, C

A: As per your comment, you would create a junction object between Pitch__c and Marketing_Element__c. Let that be Junction__c which will have two lookup relationship fields Pitch__c and Marketing_Element__c objects.
The following trigger will insert Junction object records with Pitch and Marketing Element lookups.
trigger PitchElement on Pitch__c (after insert) {
    List<ID> marketingIdea = new List<ID>();
    //Marketing_Package__c MarektingIdeaList = new Marketing_Package__c();
    List<Marketing_Element__c> MarketingElements = new List<Marketing_Element__c>();
    Map<Id,Id> mapMarketingPitch = new Map<Id,Id>();
    List<Junction__c> lstJunction = new List<Junction__c>();

    for(Pitch__c pitch :Trigger.new)
    {
        marketingIdea.add(pitch.Marketing_Package__c);
        mapMarketingPitch.put(pitch.Marketing_Package__c,pitch.Id);
        System.debug('!!!!' +marketingIdea);
    }
    //List<Marketing_Package__c> m = [select ID,Name from Marketing_Package__c where ID IN:marketingIdea]; // This query is not required
    //System.debug('@@@@@Marketing Package@@@@@@@' +m);

    for(Marketing_Element__c me : [select ID,Name,Marketing_Package__c from Marketing_Element__c where Marketing_Package__c =: marketingIdea]) {
        lstJunction.add(new Junction__c(Pitch__c = mapMarketingPitch.get(me.Marketing_Package__c),Marketing_Element__c = me.Id);
    }
    insert lstJunction;
}

Change the API names according to your actual API names.
Hope it helps.


text:
Q: How to close session with a Jquery UI tab click in Asp.Net I would like to know how to close session with a Jquery UI tab click in asp.net.
Actually I am working with upload Images and when user upload I am saving them under a folder with genrated random string value.
So I need to close the session with a tab click as I am having problem when the user refreshes and tries to upload  I'm getting error as the session is not clearing.
Here is my Javascript code:

Here is the Jquery UI tab code:

A: you should have an ajax call to an ASHX file with *IRequiresSessionState  * Interface
and there you should use the session abandon.


text:
Q: CentOS 6.7: 'No address associated with name' as 'hostname --fqdn' output I have CentOS 6.7 x64 (Final) Desktop standard installation, on a dedicated pc (not on a VM), Linux version 2.6.32-573.el6.x86_64 (gcc version 4.4.7 20120313 (Red Hat 4.4.7-16) (GCC) ).
I've configured my /etc/sysconfig/network-scripts/ifcfg-eth0 file as follow:
DEVICE=eth0
HWADDR=A4:5D:36:66:39:82
TYPE=Ethernet
UUID=36d492f3-cf76-4472-b8f1-b855d4af724d
ONBOOT=yes
NM_CONTROLLED=no
BOOTPROTO=none
IPADDR=192.168.1.2
NETMASK=255.255.255.0
GATEWAY=192.168.1.1
DNS1=8.8.8.8
DNS2=8.8.4.4 ,

then:
chkconfig network on
service network start

After, I've modified my /etc/hosts and /etc/sysconfig/network as:
192.168.1.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.1.2 srvr1.cloud.priv ,

then:
service network restart .

As result, I've got that I can go on the web (I'm on with this configuration by now), but when I run:
hostname --fqdn ,

it returns:
hostname: No address associated with name

instead of a correct FQDN response.
I would need to know how to solve this situation and get the right output.
PS: I don't know if it has something to do with this problem, but my modem-router has the DHCP activated and the provider does not allow to disable it (or better, it can not be disabled by the user with official versions of the firmware).

A: You can set the hostname using hostname command hostname man page
From the man page, "Hostname is the program that is used to either set or display the current host, domain or node name of the system. These names are used by many of the networking programs to identify the machine. The domain name is also used by NIS/YP.
You can't change the FQDN (as returned by hostname --fqdn) or the DNS domain name (as returned by dnsdomainname) with this command. The FQDN of the system is the name that the resolver(3) returns for the host name.
Technically: The FQDN is the name gethostbyname(2) returns for the host name returned by gethostname(2). The DNS domain name is the part after the first dot.
Therefore it depends on the configuration (usually in /etc/host.conf) how you can change it. Usually (if the hosts file is parsed before DNS or NIS) you can change it in /etc/hosts.
If a machine has multiple network interfaces/addresses or is used in a mobile environment, then it may either have multiple FQDNs/domain names or none at all. Therefore avoid using hostname --fqdn, hostname --domain and dnsdomainname. hostname --ip-address is subject to the same limitations so it should be avoided as well."
Add to your /etc/hosts a reference to 127.0.0.1 with the fqdn as first row, and it should work.
EDIT: I noticed you changed the 127.0.0.1 with the IP of the machine. You always must have 127.0.0.1 in your /etc/hosts, as this indicates the loopback interface which is used by different applications and services.

A: Try setting your hostname:
# hostame srvr1.cloud.priv

Then edit your /etc/hostname file to have it stick on reboot.
/etc/hostname:
srvr1.cloud.priv


text:
Q: Change value of label in Xcode I'm new in Xcode. I want to make a Progress View and below is a label. This label can change value from 1 to 100 just the same when the progress run. For example: when i tap the "Start" button then the progress run from 1 to 100, so does the label run from 1 to 100. Absolutely, i want to see to value change 1,2,3,4... of the label. Can anyone help me?
Code details attached is good. Thanks!

A: You can use this logic to get your answer.


text:
Q: MMX Invalid floating point operation Using C++ Builder 6 and trying to run this code
  __int64 m64_1 = 1424115525456;
  __int64 m64_2 = 2222222222222;
  __int64 m64_3 = 1111111111111;

    __asm movq mm1, m64_1
    __asm paddd mm1, m64_2
    __asm movq m64_3, mm1

but I don't execute division by zero.
What about this error

A: just type __asm emms after your mmx commands
like that:
__asm movq mm1, m64_1;
__asm paddd mm1, m64_2;
__asm movq m64_3, mm1;
__asm emms


text:
Q: He remained cool as a cucumber Why do we use cucumber to describe the attitude of a person who is able to control his/her temper  in front of a difficult event?

A: This entry in the Encyclopedia of Word and Phrase Origins (p133) has the answer:

It took scientists with thermometers until 1970 to find out what has
  been folk knowledge for centuries - that cucumbers are indeed cool, so
  much so that the inside of a field cucumber on a warm day registers
  about 20 degrees cooler than the outside air. The belief is ancient,
  but was first put on record by Francis Beaumont and John Fletcher in
  their play Cupid's Revenge (1610), when they referred to certain women
  as "as cold as cucumber".

A: In addition to Shoe's answer, cucumber slices over the eyes are a long-standing folk remedy, rejuvenated into a modern luxury spa treatment. If you've never tried it, they really do have a soothing, cooling effect even if they weren't previously refrigerated.


text:
Q: How to crop image after upload and get image url? I am using codeigniter 3.1 .
I want to crop image after upload but the crop not working.
After crop how to get the image url ?
if ($_FILES['upload']['size'] > 0) {
       $this->upload->initialize(array(
                   "upload_path" => $this->upload_path,
                   "encrypt_name" => TRUE,
                   "remove_spaces" => TRUE,
                ));

                $data = $this->upload->data();
                $image = $data['file_name'];

        $this->load->library('image_lib');
        $this->image_lib->initialize(array(
             "source_image" => $data,
             "new_image" => $this->upload_path. $image,
             "x_axis" => 300,
             "y_axis" => 300
                ));

        $data = $this->upload->data();
        $image = $data['file_name'];

  //Get full path of image

  }

A: Use these functions in your model
<?php
 class Image_model extends CI_Model {
public function __construct()   {
    parent::__construct();
    $this->load->helper('url');
    $this->load->library('upload');
    $this->load->library('image_lib');
}

public function do_resize($filename)
{

    $source_path =  'uploads/' . $filename;
    $target_path =  'uploads/thumb/'.$filename;

    $config_manip = array(

        'image_library' => 'gd2',
        'source_image' => $source_path,
        'new_image' => $target_path,
        'maintain_ratio' => TRUE,
        'width' => 300,
        'height' => 300
    );
    $this->image_lib->initialize($config_manip);
    $this->load->library('image_lib', $config_manip);

    if (!$this->image_lib->resize()) {
        echo $this->image_lib->display_errors();
        die();
    }
}

public function img_upload()
{
    $config = array(
        'upload_path' => "uploads",
        'allowed_types' => "*",
        'overwrite' => TRUE,
        'max_size' => "5048000", // Can be set to particular file size , here it is 2 MB(2048 Kb)
        'max_height' => "3000",
        'max_width' => "3000"
    );
    $this->upload->initialize($config);
    $this->load->library('upload', $config);

    if($this->upload->do_upload('myFile')) { //<input type="file" name="myFile" />
        $response   =    array('upload_data' => $this->upload->data());
        $this->do_resize($response['upload_data']['file_name']);
        //return $response;
    }
    else{
        $error              =   array('error'=>$this->upload->display_errors());
        print_r($error);die();

    }
 }
}

Call this function in your controller like this
if(isset($_FILES)){

            $config                 =   $this->image_model->img_upload();
            $file_data              =   $this->upload->data();
            $data['img']            =   $file_data['file_name'];
        }


text:
Q: I dont understand xaml alignment So I struggle with the XAML alignment a bit and I hoped for someone who could help me get trough it.
This is the Code. I will break it down below:
<Grid x:Name="Output" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Row="0">
    <StackPanel>
        <Button Style="{StaticResource AppBarButtonStyle}" Click="ShowPopupOffsetClicked"/>
        <Image Source="Assets/images/icon_thumbnail.png"></Image>
    </StackPanel>
    <Popup VerticalOffset="60" HorizontalOffset="0" x:Name="StandardPopup">
        <Border BorderBrush="{StaticResource ApplicationForegroundThemeBrush}"
            Background="{StaticResource ApplicationPageBackgroundThemeBrush}"
            BorderThickness="2" Width="300" Height="350">
            <StackPanel >
                <TextBlock>
                    <Run x:Name="MyRun" Text=""/>
                </TextBlock>
                <StackPanel Orientation="Horizontal">
                    <StackPanel HorizontalAlignment="Left" VerticalAlignment="Top">
                        <TextBox x:Name="searchTextBox" Width="200" Height="30"   />
                    </StackPanel>
                    <StackPanel HorizontalAlignment="Right" VerticalAlignment="Top">
                        <Button x:Name="firstSearch"  Style="{StaticResource AppBarButtonStyle}" Tapped="OnOptionItemTapped" >
                            <Image Source="Assets/images/view_search.png"/>
                        </Button>
                    </StackPanel>
                </StackPanel>
                <StackPanel Orientation="Horizontal">
                    <Button x:Name="previous" Style="{StaticResource AppBarButtonStyle}" Tapped="OnOptionItemTapped">
                        <Image Source="/Assets/images/left_arrow.png"/>
                    </Button>
                    <Button x:Name="next" Style="{StaticResource AppBarButtonStyle}"  Tapped="OnOptionItemTapped">
                        <Image Source="/Assets/images/right_arrow.png"/>
                    </Button>
                </StackPanel>
                <Button Content="Close" Click="ClosePopupClicked" HorizontalAlignment="Center" VerticalAlignment="Bottom"/>
            </StackPanel>
        </Border>
    </Popup>
</Grid>

This part will be MyRun Text later:
<TextBlock>
    <Run x:Name="MyRun" Text=""/>
</TextBlock>

This part is the SearchBar and the search-button which should be perfectly in line. How do I do this?
<StackPanel Orientation="Horizontal">
    <StackPanel HorizontalAlignment="Left" VerticalAlignment="Top">
        <TextBox x:Name="searchTextBox" Width="200" Height="30"   />
    </StackPanel>
    <StackPanel HorizontalAlignment="Right" VerticalAlignment="Top">
        <Button x:Name="firstSearch"  Style="{StaticResource AppBarButtonStyle}" Tapped="OnOptionItemTapped" >
            <Image Source="Assets/images/view_search.png"/>
        </Button>
    </StackPanel>
</StackPanel>

This is the next and previous button. It should be perfectly in line with MyRun. How would I do that?
<StackPanel Orientation="Horizontal">
    <Button x:Name="previous" Style="{StaticResource AppBarButtonStyle}" Tapped="OnOptionItemTapped">
        <Image Source="/Assets/images/left_arrow.png"/>
    </Button>
    <Button x:Name="next" Style="{StaticResource AppBarButtonStyle}"  Tapped="OnOptionItemTapped">
        <Image Source="/Assets/images/right_arrow.png"/>
    </Button>
</StackPanel>

And at last will be the "Close" Button. I guess it is kinda already perfect?:
<Button Content="Close" Click="ClosePopupClicked" HorizontalAlignment="Center" VerticalAlignment="Bottom"/>

Now a screenshot of how it Looks like and how I want it to look:
This is how it is:

This is how I want it to be:

I know that I can Change the height of the popup. But when I Change the height some Things disappear (for example the close Botton won't be visible because it is too far down while the popup height is too low).
Sorry for the long post. I hope someone can help me out here.

A: You should be able to use a Grid with three RowDefinitions. Something like this:
<Popup VerticalOffset="60" HorizontalOffset="0" x:Name="StandardPopup">
    <Border BorderBrush="{StaticResource ApplicationForegroundThemeBrush}"
                Background="{StaticResource ApplicationPageBackgroundThemeBrush}"
                BorderThickness="2" Width="300" Height="350">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition />
                <RowDefinition />
                <RowDefinition />
            </Grid.RowDefinitions>

            <!-- row 1 -->
            <StackPanel Orientation="Horizontal">
                <TextBox x:Name="searchTextBox" Width="200" Height="30" Margin="0,0,3,0" />
                <Button x:Name="firstSearch"  Style="{StaticResource AppBarButtonStyle}" Tapped="OnOptionItemTapped" >
                    <Image Source="Assets/images/view_search.png"/>
                </Button>
            </StackPanel>

            <!-- row 2 -->
            <Grid Grid.Row="1">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto" />
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>
                <StackPanel Orientation="Horizontal">
                    <Button x:Name="previous" Style="{StaticResource AppBarButtonStyle}" Tapped="OnOptionItemTapped">
                        <Image Source="/Assets/images/left_arrow.png"/>
                    </Button>
                    <Button x:Name="next" Style="{StaticResource AppBarButtonStyle}"  Tapped="OnOptionItemTapped">
                        <Image Source="/Assets/images/right_arrow.png"/>
                    </Button>
                </StackPanel>
                <TextBlock Grid.Column="1" HorizontalAlignment="Center">
                    <Run x:Name="MyRun" Text=""/>
                </TextBlock>
            </Grid>

            <!-- row 3 -->
            <Button Grid.Row="2"
                    Content="Close" Click="ClosePopupClicked"
                    HorizontalAlignment="Center" VerticalAlignment="Bottom"/>
        </Grid>
    </Border>
</Popup>

You can adjust the space between the controls using the Margin property.


text:
Q: NHibernate 3.1 Query equals I just updated from NHibernate 2.1 to NHibernate 3.1. I found out that the equals operator for the use of Linq was not implemented for other types then string.
I found an article on the internet to solve this problem. This works fine for the basic types but now I want to compare a custom entities and I can't get it to work.
I tried some implementations but none work:
ReflectionHelper.GetMethodDefinition<CustomEntity>(x => x.Equals(<CustomEntity>(0)))
ReflectionHelper.GetMethodDefinition<CustomEntity>(x => x.Equals(typeof(CustomEntity))

The query I want to execute is as follows:
Session.Query<SomeEntity>().Where(x => x.CustomEntity.Equals(CustomEntity);

How can I extend the equals to allow this and not get an NotSupportedException?

A: .Equals method cannot be translated to SQL which is done by the system when you execute Query<>() method. Try using equation like this:
Session.Query<SomeEntity>().Where(x => x.CustomEntity.Id == CustomEntity.Id);


text:
Q: Get value from SQLite3 using for loop as a seperate variable I have three values stored inside my SQLite Table, i.e. question-hyperlink, excerpt, pl8 js-gps-track nav-links--link.
I want them to get each value inside a separate variable.
For example :
x = question-hyperlink,
y = excerpt and
z = pl8 js-gps-track nav-links--link.
Here is my code :
import sqlite3

cur.execute("""CREATE TABLE Classes (id VARCHAR(30));""")
cur.execute("""INSERT INTO Classes VALUES ("question-hyperlink");""")
cur.execute("""INSERT INTO Classes VALUES ("excerpt");""")
cur.execute("""INSERT INTO Classes VALUES ("pl8 js-gps-track nav-links--link");""")
conn.commit()

cur.execute("""select * from Classes;""")

for class_Names in cur.fetchall():
    print(class_Names)

This gives me :
('question-hyperlink',)
('excerpt',)
('pl8 js-gps-track nav-links--link',)

I have tried nested loops for this but failed. How to get them a seperate variable as listed in the example above?
Any help would be appreciated...

A: Maybe try the following:
all_values = tuple()
for class_Names in cur.fetchall():
    # let's merge all tuples into one
    all_values += class_Names
# then we can upack the tuples into different variables
x,y,z = all_values


text:
Q: Can't install firebase-tools on ubuntu 16.04 i'm trying to install firebase-tools in ubuntu (16.04) but i get an error
after i execute the command line:
npm install -g firebase-tools

The error:
npm ERR! tar.unpack untar error /home/rezk/.npm/firebase-tools/3.2.1/package.tgz

npm ERR! Linux 4.4.0-59-generic
npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "install" "-g" "firebase-tools"
npm ERR! node v4.4.7
npm ERR! npm  v2.15.8
npm ERR! path /usr/lib/node_modules/firebase-tools
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! syscall mkdir
npm ERR! Error: EACCES: permission denied, mkdir '/usr/lib/node_modules/firebase-tools'
npm ERR!     at Error (native)
npm ERR!  { [Error: EACCES: permission denied, mkdir '/usr/lib/node_modules/firebase-tools']
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'mkdir',
npm ERR!   path: '/usr/lib/node_modules/firebase-tools',
npm ERR!   fstream_type: 'Directory',
npm ERR!   fstream_path: '/usr/lib/node_modules/firebase-tools',
npm ERR!   fstream_class: 'DirWriter',
npm ERR!   fstream_stack:
npm ERR!    [ '/usr/lib/node_modules/npm/node_modules/fstream/lib/dir-writer.js:35:25',
npm ERR!      '/usr/lib/node_modules/npm/node_modules/mkdirp/index.js:47:53',
npm ERR!      'FSReqWrap.oncomplete (fs.js:82:15)' ] }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.
npm ERR! Please include the following file with any support request:
npm ERR!     /home/rezk/npm-debug.log
how could i solve that?
Note: i have installed Node.js

A: i think it just about using sudo before the command line:
sudo npm install -g firebase-tools

thank you!


text:
Q: Baffled: Django "could not import app.views" but can import app, in WSGI? I'm having an odd Django problem, running Django with mod_wsgi.
Django is finding urls.py, and then saying:
ViewDoesNotExist: Could not import app.views. Error was: No module named views

Bizarrely, if I have
import app

in the import statements in urls.py I don't get an error (until it hits app.views as above), but if I have
from app import views

in my import statements, I get an error.
My python path, as shown in the Django debug info, has both the containing folder and the app folder on it. If I run Python from the command line, I can import app.views just fine. I can run the app using python manage.py runserver just fine.
I've tried printing the python path to stderr from urls.py too, and it has the path to app in it.
What could be going on?
My first thought was that there might not be an __init__.py in the app folder, but there is.
Thanks!
UPDATE
In the runserver app, if I try
print app.__file__
>> \path\to\app\__init__.py

But in the wsgi version, I only see:
print app.__file__
>> \path\to\app\

In other words, it's just not finding __init__.pyc.

A: Probably a circular dependency - something in views is importing another module, which itself is trying to import views.

A: Your web server is out of file handles. Reconfigure the WSGI app for daemon mode.


text:
Q: New Windows Phone 8.1 Silverlight App I am writing a new Windows Phone 8.1 Silverlight App BUT WITHOUT MVVM/MVC.

*

*I have to implement Push notifications to this app sooner.

*This app must run in the background

Will this be possible without MVVM/MVC?
Also, please tell me where from to learn MVVM/MVC from beginning?

A: It's definitely possible to develop apps that do not follow the MVVM or MVC patterns. You can develop your apps however you like; these are merely architectural patterns that many programmers follow when developing Windows Phone apps. MVVM, in particular, is suited to Windows Phone app development (and WPF) because of the data binding mechanism provided by XAML.
For example, you might choose to write your code entirely in code-behind (*.xaml.cs) files and subscribe to events directly on the view. This might be fine for small apps, but may not be suitable for larger apps, especially when there are multiple people working on different parts of the app (e.g. a designer working in XAML and a coder working in C#) and when testability is extremely important.
I won't provide links to learning materials for MVVM/MVC; a mere bing search results in an abundant amount of information at your fingertips. Good luck!


text:
Q: Is there a way to override the exception page like a 404 page? | CodeIgniter4 We have introduced the Twig template engine to CodeIgniter 4.
The template folder has been changed directly under the project folder(/templates).
The 404 error page has been replaced.
$routes->set404Override('App\Controllers\Template::notFound')

App\Controllers\Template

//...

class Template extends BaseController
{
  // ...
  public function notFound ()
  {
      return $this->twig->display('errors/custom404'); // <- /templates/errors/custom404.twig
  }

And in production, other errors are reading the production.php file (/app/Views/errors/html/production.php).
I also want to overwrite the exception handling page, what should I do?
Specifically, I want to load the production.twig file (/templates/errors/production.twig) instead of the production.php file (/app/Views/errors/html/production.php).
Is there a way to override the exception page like a 404 page controller?

vendor/codeigniter4/framework/system/Debug/Exceptions.php

I can see that production.php is hardcoded in the method determineView, is it possible to override this method?
And is it okay to overwrite?


text:
Q: YII2 Не сохраняются значения в сессии Мне нужно сохранить значение в сессии после авторизации. Пишу:
Yii::$app->user->login($user, 3600 * 24);
Yii::$app->session['__param'] = '1111';

После этого кода в сессии:
array(4) {
    ["__flash"]=> array(0) { }
    ["__id"]=> int(1)
    ["__param"]=> string(4) "1111"
}

Перехожу на другую страницу, а в сессии нет моего параметра:
array(4) {
    ["__flash"]=> array(0) { }
    ["__id"]=> int(1)
}

Почему сессия при каждом запросе затирается?

A: У меня работает так:
**В одном контроллере:**
Yii::$app->session->set('test', 'test');

**В другом:**
print_r(Yii::$app->session->get('test')); // выведет "test"

**Но если вывести**
print_r(Yii::$app->session); // действительно значения "test" мы не найдем


text:
Q: winrt(metro) getthumbnailasync returns icon So using the GetThumbnailAsync() call returns icons when there are no thumbnails available.
Does anyone know if there is a way to just get the thumbnail if there is one but never return the icon when there isn't one?
Thanks!


text:
Q: Как реализовать условие в конструкторе компонента ReactJS в es6? В коде, который был написан на es5  у меня был getInitialState :
getInitialState: function () {

            if(condition ) {
                ....
                }
                return $.extend({}, state);
            }
            return {
                showAdvancedParams: true,
                size: '',
                region: '',
                showModal: false,
                window_url:''
            }
     },

Сейчас хочу переписать это дело под ecmascript6, но там вместо getInitialState используется constructor. Можно ли как-то мой InitialState подогнать, или это условие придется вынести в отдельный метод?

A: Ну я бы как-то так написал если аналогично вашему.
construstor(){
    /* какой то код выше в котором определяются перменные condition, state и делается все что надо в конструкторе*/

    const defaultInitialState = {
              showAdvancedParams: true,
              size: '',
              region: '',
              showModal: false,
              window_url:''
          };

    this.state = condition ? {...state} : defaultInitialState;
}

Обратите внимание здесь вместо $.extend я использую spread оператор, для него не нужно jQuery но нужен stage-2 preset бабеля =)
Если у вас state и condition в конструкторе определяются как-то хитро, то логично это вынести в отдельный метод, да. В вынесении в отдельные методы нет ничего противоестественного.


text:
Q: Getting the rootelement from a streamed xml I'm streaming an xml document using a buffer. I set the buffer quite low (50) to keep performance good. I then use the buffered string to try and extract the rootelement name from the xml (in this case i would need "abc" in the xml below):
<?xml version="1.0"?>
<!--foobar-->
<!--<foo:bar></foo:bar>-->
<foo:abc xmlns:foo="url"><a><b>...

I should only get the name itself, without the alias.
Also, processing instructions and xml tags in comments should be ignored.
When there's no match, i would make the buffer larger and try to match again, until i found the rootelement.
I've created a regex that does exactly this, and returns the rootelement name. using the replace function with $4.
However when the regex DOES NOT MATCH anything, it hangs for a very long time trying to resolve the pattern...
(?s)(.*?(<!--.*?-->)?.*?)*<(.*?:)?([^!\?].*?)((\s+|/).*)?>.*

The problem seems to be in the part that tries to match the comments
(.*?(<!--.*?-->)?.*?)*

But i cant figure out how to optimize it, without breaking it...
Any ideas?


text:
Q: Why is xxd -r cutting off the first character of my string? I am running the following command:
$ echo "50 40 73 73 77 30 72 64 40 31 32 33 21 21 31 32 33" | xxd -r
@ssw0rd@123!!123

For the life of me I don't know why the output does not start with 'P'

A: according to the man the first number is expected to be "line number" which is skipped
Using xxd -r -p fixes this


text:
Q: Is satisfying Lagrange's theorem sufficient to show a loop is a group? Consider a finite loop $L$, that is a set with an operation that has closure, identity, and invertibility (but not necessarily associativity). Consider a subloop of $L$, that is a set $H$ contained in $L$ that is itself a loop (with the same identity element). If the order of all subloops of $L$ divide the order of $L$ ("satisfies Lagrange's theorem"), is the loop $L$ necessarily a group?
Can this be proven or is there an easy counterexample of a finite loop satisfying Lagrange's theorem that is not a group?

A: No.
Consider the loop $Q^*$ obtained from the hyperbolic quaternions: The set $\{ \pm1, \pm i, \pm j, \pm k \}$ with the loop operation being multiplication defined by $i^2=j^2=k^2= +1$ and the other products just as in the quaternions. You can verify that this is clearly a loop but not a group. Associativity is not satisfied: $ i(jj)=i \not = -i = (ij)j$.
The subloops of $Q^*$ are $\{1\}, \{1,-1\} \{1,g\} \{1,g,-g,-1\}$ where $g \not = \pm 1$ and $Q^*$. Clearly, the orders of all the subloops divide $8$.

A: The smallest example is one of the non-associative loops of order 5. Its Cayley table can be displayed as:
01234
12043
23401
34120
40312

Since each row and column contains each number exactly once and since the first row and first column are the identity, this is a loop. Since $1 \cdot (1 \cdot 1) = 1 \cdot 2 = 0 \neq (1 \cdot 1) \cdot 1 = 2 \cdot 1 = 3$ this loop is not even power-associative (it is the unique loop of order 5 that is not power associative).
The subloop generated by each nonzero element is the entire loop, so the only subloops are order 1 (just the zero element) and order 5 (the whole loop).
Since every loop of order 4 or smaller is associative (a group), this is an example of minimal size. I just checked the other loops of order 5 and they have subloops of size 2, so this is the unique up to isomorphism non-associative loop of minimal size satisfying Lagrange's theorem.
I learned everything I know about loops from Stephen Gagola III. I recommend his articles, especially on Moufang loops (all of which satisfy Lagrange's theorem). The proof of that result mirrors a lot of finite group theory, including proceeding through odd order, solvable, and a classification of finite simple moufang loops as being basically PSL groups.


text:
Q: Issue with creating sub graphs from Los Angeles County graph I am trying to extract a subgraph using networkx ego_graph function from Los Angeles County graph.
When i plot this graph and compare it with graph generated from graph_from_point (which looks correct), they seem to be completely different.
Here is my code
G = ox.graph_from_place('Los Angeles County, California, USA')

node = ox.get_nearest_node(G, (34.6806, -118.1435))

Subgraph from networkx
sub_graph = nx.ego_graph(G, node, radius=2500, distance='length')

ox.plot_graph(sub_graph)

graph_from_point
g = ox.graph_from_point((34.6806, -118.1435), dist = 2500)
ox.plot_graph(g)

Both sub_graph and g look completely different.
Am i doing anything wrong here?


text:
Q: Generating a random, fixed-length byte array in Go I have a byte array, with a fixed length of 4.
token := make([]byte, 4)

I need to set each byte to a random byte. How can I do so, in the most efficient matter? The math/rand methods do not provide a Random Byte function, as far as I am concerned.
Perhaps there is a built-in way, or should I go with generating a random string and converting it to a byte array?

A:
Package rand
import "math/rand"

func Read
func Read(p []byte) (n int, err error)

Read generates len(p) random bytes from the default Source and writes
  them into p. It always returns len(p) and a nil error.
func (*Rand) Read
func (r *Rand) Read(p []byte) (n int, err error)

Read generates len(p) random bytes and writes them into p. It always
  returns len(p) and a nil error.

For example,
package main

import (
    "math/rand"
    "fmt"
)

func main() {
    token := make([]byte, 4)
    rand.Read(token)
    fmt.Println(token)
}

Output:
[187 163 35 30]

A: Go 1.6 added a new function to the math/rand package:
func Read(p []byte) (n int, err error)

which fills the passed byte slice with random data. Using this rand.Read():
token := make([]byte, 4)
if _, err := rand.Read(token); err != nil {
    // Handle err
}
fmt.Println(token)

rand.Read() has 2 return values: the number of "read" bytes and an (optional) error. This is to conform with the general io.Reader interface, but the documentation of rand.Read() states that (despite its signature) it will never actually return a non-nil error, so we may omit checking it, which simplifies it to this:
token := make([]byte, 4)
rand.Read(token)
fmt.Println(token)

Don't forget to call rand.Seed() to properly initialize it before you use the math/rand package, e.g.:
rand.Seed(time.Now().UnixNano())

Note: Prior to Go 1.6 there was no math/rand.Read() function, but there was (and still is) a crypto/rand.Read() function, but the crypto/rand package implements a cryptographically secure pseudorandom number generator, so it is much slower than math/rand.

A: Using math.Rand means that you are using the system CSPRNG that your operating system provides. This means using /dev/urandom/ and Windows' CryptGenRandom API.
Go's crypto/rand package, thankfully, abstracts these implementation details away to minimise the risk of getting it wrong.
import(
   "crypto/rand"
   "encoding/base64"
 )

// GenerateRandomBytes returns securely generated random bytes.
// It will return an error if the system's secure random
// number generator fails to function correctly, in which
// case the caller should not continue.
func GenerateRandomBytes(n int) ([]byte, error) {
     b := make([]byte, n)
    _, err := rand.Read(b)
    // Note that err == nil only if we read len(b) bytes.
    if err != nil {
       return nil, err
   }

   return b, nil
}


text:
Q: after loading html file into another html file, jquery show hide not working in chrome but it is working in firefox After loading html file into another html file, jquery show hide not working in chrome but it is working in firefox.
    <script type="text/javascript">
    $(document).ready(function() {
    $("#includedContent").load("dashboard-body.html");
    $("#includefolder").load("folder-setup.html");
    $("#foldercont").click(function(){
    $("#includedContent").hide();
    $("#includefolder").show();
    });

    $("#dashboard").click(function(){
    $("#includefolder").hide();
    $("#includedContent").show();
    });
    });
</script>

now follows a code block for Jquery hide and show:
    $(document).ready(function(){
    $('#folderclick').click(function(){
    $('#displayform').show();
    $('#displayview').hide();
    $('#tabcontent').hide();

    });
    $('#dissubmit').click(function(){
    $('#displayform').hide();
    $('#tabcontent').show();
    });

    $('#viewfolder').click(function(){
    $('#displayview').show();
    $('#displayform').hide();
    $('#tabcontent').hide();
    });
    $('#viewsubmit').click(function(){
    $('#displayview').hide();
    $('#editdis').show();
    });
    $('#editsub').click(function(){
    $('#editdis').hide();
    });
    $('#deleteclick').click(function(){
    $('#disalert').show();
    });
    });


text:
Q: Reverse voltage protection and high-side current switch Initially I chose a Infinion PROFET smart high side switch (ITS428L2). In the datasheet it is stated that this device can provide reverse battery protection with external resistor. Frankly, I am not able to figure out how this protection should work: The body diode of the internal MOSFET is placed in a way, that current can flow in case of reverse voltage. So where is the protection?

Therefore i tried to figure out a circuit that provide real reverse voltage protection and on/off-switching capabilities for currents in the ~10A region and as well for high currents (~100A). Is this a suitable approach?

simulate this circuit – Schematic created using CircuitLab
Edit: Changed Source and Drain of PMOS2
Looking at the datasheets of serveral p-channel MOSFETs i wondered about the max. Drain-Current value. Sometimes this current is specified negative, sometimes positive - sometimes there are both values given but of different value. I thought if the MOSFET is conducting there is no direction for the current flow?
Example of SUM110P04-05:

A: It seems to me that in the datasheet of the ITS428L2, reverse battery protection only means that the switch will not be destroyed in case of wrong polarity (see on page 8).
Concerning your circuit: even if it protects against reverse battery, you can never switch off the load because regardless of the MOSFET's gate potential the body diodes will always conduct (given that the battery is connected in correct polarity).
When it comes to the direction ID in a MOSFET datasheet you have to pay attention to the mode of operation. If the gate is driven, the channel is  defined by the RDSon. Here the direction of the current doesn't matter, as you correctly said. But suppose an inductive load is driving a current through the body diode into the battery when the MOSFET is off. The body diode is a much lossier conductor that a fully turned on channel and therefore the permissive current is significantly less.

A: With a high-current supply source and capacitive load, don't overlook inrush current. This is often managed by ramping turn-on, and can be achieved in the given circuit as follows...
Apply a series resistor from R2/SW1 junction to the gate of PMOS2.
Apply a capacitor (significantly greater than Cgs of PMOS2) between PMOS2 gate and drain.
I'll leave you to experiment or do the maths (based on choice of MOSFET and circuit conditions), though a good starting block might be 100nF and 10k+.


text:
Q: Why would Sauron want the one ring back? (Canon reference?) So, question should say everything, but I'll detail what answer I'm looking for. Including the "Rings of Power" that were forged by the elves under Sauron's guidance:

*

*3 Rings for the Elves

*7 Rings for the Dwarves

*9 Rings for the humans

"Three Rings for the Elven-kings under the sky,
  Seven for the Dwarf-lords in their halls of stone,
  Nine for Mortal Men doomed to die..."

Sauron secretly forged the One Ring for himself to control the other rings, making their total number 20, 19 of which were linked to the one ring which could control the other rings and manipulate their bearers according to the will of Sauron if used:

"...One Ring to rule them all, One Ring to find them,
  One Ring to bring them all and in the darkness bind them
  In the Land of Mordor where the Shadows lie."

There were other "Less Rings Of Power" made as practice by the forgers for said Rings Of Power, however, they don't play into my question.
The plan was to distribute the rings as described above and afterwards use the One Ring to gain complete control of middle earth without having to fight any of the nations because their leaders would have been under direct control of Sauron.
Apparently, not everything went as intended as:

*

*The Elves noticed the betrayal the "Lord Of Gifts" was planning on and put the rings off their fingers and hid them in secrecy, making the race of the elves invulnerable for the original plan. Also, I've been reading that the elven rings were never touched by Sauron so I'd wonder if he really could have any influence on the elven Rings Of Power?

*The Dwarves, due to a) their natural hardness and b) due to the fact that from the hard dwarves, only the Lords (The hardest of the hard, so to say.) got to wear the dwarven Rings Of Power. However, Sauron noticed, that the rings wouldn't take as much effect on the dwarves as they should as they didn't even turn them invisible. Later on, a few of them were destroyed by dragons and Sauron took the remaining few back.

*The Humans, whilst obviously successful in transforming them into evil creatures of immense power, were no kings anymore, meaning he couldn't actually use them to rule over the humans and keep the population thinking their rightful kings were doing all these things.
This brings me to the following conclusion: All those rings we're lost the one, or taken out of effect the other way around. That's why my question is:
WHY would Sauron want the One Ring back if everything he could do with it was controlling the other Rings Of Power whilst all of those rings were lost / destroyed / hidden by their original bearers? I assume that the current Kings / Throne-keepers of the humans would not have been stupid enough to accept a fresh wave of Rings Of Power linked to the One Ring.
The only reason I could think of now was to rebuild a body which, could have taken him another years and thinking about it, I see no other reason for it, as apparently he could perfectly be everywhere and control most creatures in middle earth just with the power of his ghost. But this is not a discussion board.
I'm looking for a canon reference what exactly would have happened if he got the One Ring back.


text:
Q: How to get Shared file system for docker containers running on different hosts? I have two docker containers running on two separate hosts. What can I do to make sure that both the containers use a share the data stored on a third host.
Because of some restrictions, I can not do volume mapping of host to container. And it seems you can't mount remote file systems directly on containers due to security restrictions.
What should be my approach in handling this requirement?

A: share via nfs the filesystem from your third host and mounting in the two hosts and after that, mapping the nfs share mountpoint to your container, you using docker run -v /nfsmount:/nfsmount -ti docker_tag /bin/bash

A: what restrictions?  Ensure you specify the mode when you mount the volume, like -v /from:/to:Z (to relabel the mount point) or -v /from:/to:rw (to mount in read write mode)


text:
Q: iCustom() buffer - how to get values from Custom Indicator buffers in MT4? I am trying to write an EA that will place a BUY, when the Custom Indicator shows an arrow { sell or buy }. I am using an iCustom() to do that, but I am struggling with comparing values.
Here is my code:

void OnTick()
  {
//---
       double sell=iCustom(NULL,0,"fx30",0,0);
       double buy=iCustom(NULL,0,"fx30",1,0);

       if(sell>0)//sell
       {
        //check if buy trade is running
        //close a buy trade
        //open a sell trade on success
         if(buyTicket>0)
          {
            bool ret=OrderClose(buyTicket, lot, Bid, slipage,clrBlue);
            if(ret==true)
              {
                printf("the sell number is: "+sell);
                sellTicket=OrderSend(Symbol(),OP_SELL,lot,Bid,slipage,NULL,NULL,"MATHUNYA SELL",magic,0,clrRed);
              }
          }
         else
         {
           //we dont have a buy trade open
           //place a sell trade
           //only one trade should be open
           if(sellTicket>0)
           {
             printf("sell order already running");
           }
           else
           {
             printf("the sell number is: "+sell);
             sellTicket=OrderSend(Symbol(),OP_SELL,lot,Bid,slipage,NULL,NULL,"MATHUNYA SELL",magic,0,clrRed);
           }
         }
       }
       else{
         Print("buy: "+buy+", sell: "+sell+" Time: "+TimeToStr(Time[1]));
         printf("awaiting sell order..");
       }

       if(buy>0)//buy
       {
       //check if sell trade is running
       //close a sell trade
       //open a buy trade on success
         if(sellTicket>0)
          {
            bool ret=OrderClose(sellTicket, lot, Ask, slipage,clrYellow);
            if(ret==true)
              {
                printf("the buy number is: "+buy);
                buyTicket=OrderSend(Symbol(),OP_BUY,lot,Ask,slipage,NULL,NULL,"MATHUNYA BUY",magic,0,clrGreen);
              }
          }
         else
         {
           //we dont have a sell trade open
           //place a buy trade
           //only one trade should be open
           if(buyTicket>0)
           {
             printf("buy order already running");
           }
           else
           {
              printf("the buy number is: "+buy);
              buyTicket=OrderSend(Symbol(),OP_BUY,lot,Ask,slipage,NULL,NULL,"MATHUNYA BUY",magic,0,clrGreen);
           }
         }
       }else
       {
         Print("buy: "+buy+", sell: "+sell+" Time: "+TimeToStr(Time[1]));
         printf("awaiting buy order..");
       }

  }
//+------------------------------------------------------------------+

// global variables

int    buyTicket  =   0;
int    sellTicket =   0;
double lot        =   0.01;
int    slipage    =   3;
int    magic      = 321;

A: what do you mean by comparing values? as I can see, you only compare sell>0 and buy>0. My advice: immediately below that comparing add line
Print(__LINE__," indicator value = "+DoubleToStr(sell,Digits));
and same with buy. It is likely, but of course we do not have crystal ball here, that your indicator returns value (e.g. 100 or 1.16000) on one buffer, and EMPTY_VALUE on another. EMPTY_VALUE is 2^31-1 in mql4 so it is larger then zero.
if you will see that indicator value is 2147483648.00000 or something like that, - you need to replace sell > 0 with sell != EMPTY_VALUE or combine.


text:
Q: phpMyAdmin Browse Button Is Gray While Data Exists I am facing a strange issue in phpMyAdmin where the Browse Button is gray while data exists in the table, I even tried to run a sql select statement on this table and the records where displayed !
I am using a shared hosting so my options of installing another GUI tool or using the command line are very limited, anyone encountered the same issue before and what is its cause?
Thanks


text:
Q: Django not accepting parsed csv date input even though it follows the YYYY-MM-DD format. What is the problem? I'm trying to populate my existing Django model with values from a csv file. I've tried to use datetime.strptime() but it also has not worked.
This is the code I'm trying to run from the Django python manage.py shell
loadcsv.py
import csv
from dashboard.models import Checkin
with open('foo.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')

    for row in csv_reader:
        new_checkin = Checkin(date=row[0],project_id=row[1],manager_id=row[2],user_id=row[3],hours=row[4])
        new_checkin.save()
        # # row[0] = date;
        # # row[1] = project
        # # row[2] = manager
        # # row[3] = user
        # # row[4] = hours

models.py (dashboard.models)
from django.db import models

# Create your models here.
class Checkin(models.Model):
    date = models.DateField(blank=False)
    project_id = models.IntegerField(blank=False)
    manager_id = models.IntegerField(blank=False)
    user_id = models.IntegerField(blank=False)
    hours = models.DecimalField(max_digits=5, decimal_places=2)

foo.csv sample entry
date,project_id,manager_id,user_id,hours
2019-09-11,134,1,1,3
2019-09-11,201,1,1,5
2019-12-23,14,8,2,0.46
2019-12-23,14,8,2,0.46

The error I'm getting
django.core.exceptions.ValidationError: ['"date" value has an invalid date format. It must be in YYYY-MM-DD format.']

I can save to the database when I manually create a single object in the shell like so:
from dashboard.models import Checkin

new_checkin = Checkin(date="2012-01-01", manager_id="5", project_id="5",user_id="3", hours="0.75")
new_checkin.save()

A: You need to skip headers while reading csv. Django is complaining about the header "date" which is not in date format.
You can use either next or DictReader to skip headers.


text:
Q: Replace integer value excel sheet I'm tyring to replace integer 7,6 in an excel by 8. However, following code is not really working as expected. It seems to subsitute strings. I have written a similar piece of code using the replace functionality but even that didn't produce the results I'm expecting. What am I doing wrong?
Sub MacroTest()
'
Dim rng As Range, cell As Range
Set rng = Sheets("Naomi").Range("H1:H10000")

For Each cell In rng
    If cell > 0 Then
    cell = WorksheetFunction.Substitute(cell, "7,6", "8")
    End If
Next

End Sub

Thanks for guiding me.

A: I guess Taosique provided the best way to do it.
This answers why it returns String instead of Number.
You already figure it out that Substitute returns a string when you try it inside WS.
Try using Val Function then to convert the value to a Number as in below.
With Application.WorksheetFunction
    For Each cell in rng
        If cell > 0 Then
            cell = Val(.Substitute(cell, 7.6, 8))
        End If
    Next
End With

Or you can use Evaluate as well like this:
If cell > 0 Then
    cell = Evaluate("Value(Substitute(" & cell & ",7.6,8))")
End If

No need to enclose 7.6 with "".
Substitute accepts numbers as arguments.

A: Use this:
If cell.Value = 7.6 Then
    cell.Value = 8
End If


text:
Q: How I can test a particular method in my Service class using Mock C#? Please help me with my issue. I have a Service class which is given below:
public class RateService:IRatesService
{
    ...
    public RatesDTO GetById(int Id)
    {
        return Mapper.Map<Rates, RatesDTO>(this.db.Rates.GetAll().Where(m => m.RateId == Id).First());
    }
}

An interface IRatesServicelooks like that sample of code:
public interface IRatesService
{
    .....
    RatesDTO GetById(int Id);
    ....
}

And now I try to test public RatesDTO GetById(int Id) method. My code is given below:
[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        Mock<IRatesService> mock = new Mock<IRatesService>();
        mock.Setup(m => m.GetById(It.IsAny<int>())).Returns<RatesDTO>(total=>total);

        Assert.IsNotNull(mock.Object.GetById(1));
    }
}

But  when I run test I get an error like this:

Test Name:    TestMethod1 Test
  FullName: Provider.Tests.Services.UnitTest1.TestMethod1
Result Message:
Test method Provider.Tests.Services.UnitTest1.TestMethod1 threw
  exception:  System.ArgumentException: Невозможно преобразовать объект
  типа "System.Int32" к типу "Provider.BLL.DTO.RatesDTO".

What is the best practice to test the Service classes and methods?

A: You are trying to test your mock. That doesn't make any sense.
You should strive to test your actual code.
In your case, you might want to make sure that your GetById returns RatesDTO with the right id value.
You could use Mock framework, to facilitate your testing.
e.g. if you are trying to perform a unit-test and you are using a DB layer you might want to mock the database layer GetAll function and return several objects and then run a test to check that you actually return the right object (same id).

A: Your RateService is the system under test. When creating mocks for your unit tests the norm is to mock the dependencies of your system under test.
So given your current service lets say it has a dependency on a data store.
public class RateService : IRatesService {
    private readonly IDbContext db;
    public RateService(IDbContext dbContext) {
        this.db = dbContext;
    }
    //...
    public RatesDTO GetById(int Id) {
        return Mapper.Map<Rates, RatesDTO>(this.db.Rates.GetAll().Where(m => m.RateId == Id).First());
    }
    //...
}

IDbContext would be the dependency of the system under test.
You would mock that up when testing RateService
[TestClass]
public class RateServiceUnitTests {
    [TestMethod]
    public void Given_ValidId_GetById_Should_Return_Dto() {
        //Arrange
        var validId = 1;
        var fakes = new List<Rates>() {
            new Rates { RateId = validId }
        };
        var mock = new Mock<IDbContext>();
        //Assuming IDbContext.Rates.GetAll() returns an IEnumerable<Rates>
        mock.Setup(m => m.Rates.GetAll()).Returns(fakes);
        var sut = new RateService(mock.Object);
        //Act
        var result = sut.GetById(validId);
        //Assert
        Assert.IsNotNull(result);
    }
}

Noticed that you are also using a mapper. You should make sure that is configured for the test as well otherwise the test will fail. When using static calls in your classes they can cause issues when you try to isolate your system for testing. Try adding the mapper as a dependency as well.


text:
Q: Linq dynamic queries for user search screens I have a database that has a user search screen that is "dynamic" in that I can add additional search criteria on the fly based on what columns are available in the particular view the search is based on and it will allow the user to use them immediately. Previously I had been using nettiers for this database, but now I am programming a new application against it using RIA and EntFramework 4 and LINQ.
I currently have 2 tables that are used for this, one that fills the combobox with the available search string patterns:
LastName
LastName, FirstName
Phone
etc....
then I have an other table that splits those criteria out and is used in my nettiers algorithms. It works well, but I want to use LINQ..and it doesnt fit this model very well. Besides I think I can pare it down to just one table with linq...
using a format similar to this or something very close...
ID          Criteria            WhereClause
1           LastName            'Lastname Like '%{0}%'
now I know this wont fit specifically into a linq query..but I am trying to use a univeral syntax for clarity here...
the real where clause would look something like this: a=>a.LastName.Contains("{0}")
My first question is: Is that even possible to do? Feed a lambda in to a string and use it in a Linq Query?
My second question is: at one point when I was researching this before I found a linq syntax that had a prefix like it.LastName{0}
and I appear to have tried using it because vestiges of it are still in my test databases...but I dont know recall where I read about it.
Is anyone doing this? I have done some searches and found similar occurances but they mostly have static fields that are optional, not exactly the way I am doing it...

A: As for your first question, you can do this using Dynamic Linq as described by Scott Gu here
var query = Northwind.Products.Where("Lastname LIKE "test%");

A: I'm not sure how detailed your dynamic query needs to be, but when I need to do dynamic queries, I create a class to represent filter values.  Then I pass that class to a search method on my repository.  If the value for a field is null then the query ignores it.  If it has a value it adds the appropriate filter.
public class CustomerSearchCriteria{
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public string PhoneName { get; set; }
}

public IEnumberable<Customer> Search(CustomerSearchCriteria criteria){
    var q = db.Customers();

    if(criteria.FirstName != null){
        q = q.Where(c=>c.FirstName.Contains(criteria.FirstName));
    }

    if(criteria.LastName!= null){
        q = q.Where(c=>c.LastName.Contains(criteria.LastName));
    }

    if(criteria.Phone!= null){
        q = q.Where(c=>c.Phone.Contains(criteria.Phone));
    }
    return q.AsEnumerable();
}


text:
Q: Is there a basic expiring Map in Dart? Is there an expiring map in dart ? I'm looking for something similar to PassiveExpiringMap in Apache common.
Thanks in advance.

A: There doesn't seem to be a package for this. However, in case anyone is just looking for a quick snippet to lazily copy and paste like I did, here's a start you can taylor to your needs:
class ExpiringMap {
  final Map<dynamic, dynamic> _map = {};

  Object operator [](Object key) => _map[key];

  void operator []=(Object key, Object value) {
    _map[key] = value;
    Future.delayed(Duration(minutes: 1), () => _map.remove(key));
  }
}


text:
Q: Minecraft will not launch Whenever I try to launch Minecraft the launcher loads perfectly but, once I hit play, the launcher disappears for a second and then reappears with the following error message:
Minecraft Version: 16w40a
    Operating System: Windows 10 (amd64) version 10.0
    Java Version: 1.8.0_25, Oracle Corporation
    Java VM Version: Java HotSpot(TM) 64-Bit Server VM (mixed mode), Oracle Corporation
    Memory: 52833096 bytes (50 MB) / 151068672 bytes (144 MB) up to 1060372480 bytes (1011 MB)
    JVM Flags: 6 total; -XX:HeapDumpPath=MojangTricksIntelDriversForPerformance_javaw.exe_minecraft.exe.heapdump -Xmx1G -XX:+UseConcMarkSweepGC -XX:+CMSIncrementalMode -XX:-UseAdaptiveSizePolicy -Xmn128M
    IntCache: cache: 0, tcache: 0, allocated: 0, tallocated: 0
    Launched Version: 16w40a
    LWJGL: 2.9.4
    OpenGL: ~~ERROR~~ RuntimeException: No OpenGL context found in the current thread.
    GL Caps:
    Using VBOs: Yes
    Is Modded: Probably not. Jar signature remains and client brand is untouched.
    Type: Client (map_client.txt)
    Resource Packs:
    Current Language: ~~ERROR~~ NullPointerException: null
    Profiler Position: N/A (disabled)
    CPU: <unknown>

I have tried deleting minecraft and reinstalling, repairing minecraft, etc. but nothing will work.

A: The error: "OpenGL: ~~ERROR~~ RuntimeException: No OpenGL context found in the current thread." makes me think that this might deal with your graphics card drivers.
Have you tried updating your graphics card drivers? If not that should be the first thing you should try.
If it still doesn't work after that you might consider updating Java as well.


text:
Q: drop down menu issue I am having a drop down menu issue. I wanted to put my menu on the top- right side but every time I resize the screen size, the menu starts falling on the bottom.
how to make it fixed on the multiple screen sizes?
thanks
[http://jsfiddle.net/6YZ8w/]

A: check this link
Do you want like this?

It is not clear from your question how the design should be.

BTW, the links were coming out because you were giving the inside div's position:absolute. So the links were losing relation with the main div Nav.

If you want to know more about working of positioning in CSS then go through this link.

A: you can try implemting the below example
.mymenu {
    widht:100%;
    background: url(../images/mbg.png) #F00;
    height:40px;
    border-bottom: #21b8ff solid 4px;
    margin:0px 0px 0px 0px;
    overflow:hidden;
}

.mymenu .menu {
    padding-top:5px;
    padding-right: 60px;
}

.mymenu .menu a{
    margin-top:3px;
    float:right;
    text-decoration: none;
    font-family: SC_DUBAI;
    font-size: 20px;
    color: #fff;
    padding-left: 10px;
    padding-right: 10px;
    margin:0px 0px 0px 0px;
    border-right: #4c4c4c solid 1px;
    border-left: #818181 solid 1px;
    height:40px;
}

.mymenu .menu a:hover{
    color:#636363;
    background: #21b8ff;
    margin:0px 0px 0px 0px;
}

JSFiddle is working fine.


text:
Q: MongoDB: Find the minimum element in array and delete it I have a documents in MongoDB, one of them looks like this:
{
"_id" : 100,
"name" : "Something",
"items" : [
    {
        "item" : 47,
        "color" : "red"
    },
    {
        "item" : 44,
        "color" : "green"
    },
    {
        "item" : 39,
        "color" : "blue"
    }
]
}

In every document I need to find the minimum item and delete it. So it should be like this:
{
"_id" : 100,
"name" : "Something",
"items" : [
    {
        "item" : 47,
        "color" : "red"
    },
    {
        "item" : 44,
        "color" : "green"
    }
]
}

It looks like findAndModify function should be used here but I can't go any further.
How to find the minimum element in array and delete it?
I'm using MongoDB and Pymongo driver.

A: Please find my solution written in plain javascript. It should work straight through MongoDb shell
cursor = db.students.aggregate(
[{ "$unwind": "$items" },
 { "$match": { "items.color": "green"}},
 { "$group": {'_id': '$_id', 'minitem': {
                '$min': "$items.item"
            }
        }
    }

]);

cursor.forEach(
function(coll) {
    db.students.update({
        '_id': coll._id
    }, {
        '$pull': {
            'items': {
                'item': coll.minitem
            }
        }
    })
})

A: If you are not restricted to having the query be in one single step, you could try:
step 1) use the aggregate function with the $unwind and $group operators to find the minimum item for each document
myresults = db.megas.aggregate( [ { "$unwind": "$items" },
    {"$group": { '_id':'$_id' , 'minitem': {'$min': "$items.item" } } } ] )

step 2) the loop through the results and $pull the element from the array
for result in myresults['result']:
    db.megas.update( { '_id': result['_id'] },
        { '$pull': { 'items': { 'item': result['minitem'] } } } )

A: Starting in Mongo 4.4, the $function aggregation operator allows applying a custom javascript function to implement behaviour not supported by the MongoDB Query Language.
And coupled with improvements made to db.collection.update() in Mongo 4.2 that can accept an aggregation pipeline, allowing the update of a field based on its own value,
We can manipulate and update an array in ways the language doesn't easily permit:
// {
//   "name" : "Something",
//   "items" : [
//     { "item" : 47, "color" : "red"   },
//     { "item" : 39, "color" : "blue"  },
//     { "item" : 44, "color" : "green" }
//   ]
// }
db.collection.update(
  {},
  [{ $set:
    { "items":
      { $function: {
          body: function(items) {
            var min = Math.min(...items.map(x => x.item));
            return items.filter(x => x.item != min);
          },
          args: ["$items"],
          lang: "js"
      }}
    }
  }],
  { multi: true }
)
// {
//   "name" : "Something",
//   "items" : [
//     { "item" : 47, "color" : "red"   },
//     { "item" : 44, "color" : "green" }
//   ]
// }

$function takes 3 parameters:

*

*body, which is the function to apply, whose parameter is the array to modify. The function here simply consists in first finding the minimum item from the array in order to then filter it out.

*args, which contains the fields from the record that the body function takes as parameter. In our case, "$items".

*lang, which is the language in which the body function is written. Only js is currently available.


text:
Q: Replace submatrix of NA entries with another matrix I have a matrix with property such that when you delete the non NA entries in each row, you are left with a smaller rectangular matrix. For example:
is_na_mat <- structure(c(TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE,
                         FALSE, TRUE, FALSE, TRUE), .Dim = c(4L, 3L))
tmp_b <- matrix(nrow = 4, ncol = 3)
tmp_b[!is_na_mat] <- 0

which is the matrix:
     [,1] [,2] [,3]
[1,]   NA   NA    0
[2,]    0   NA   NA
[3,]   NA   NA    0
[4,]   NA    0   NA

Deleting the non-NA entries of tmp_b leaves you with a 4x2 submatrix matrix of NA's.
I wish to replace this submatrix with tmp_a, the matrix:
tmp_a <- cbind(1:4,-(1:4))

     [,1] [,2]
[1,]    1   -1
[2,]    2   -2
[3,]    3   -3
[4,]    4   -4

so that the resultant matrix is:
     [,1] [,2] [,3]
[1,]    1   -1    0
[2,]    0    2   -2
[3,]    3   -3    0
[4,]    4    0   -4

I have tmp_b[is_na_mat] <- tmp_a but this produces:
> tmp_b
     [,1] [,2] [,3]
[1,]    1    4    0
[2,]    0   -1   -3
[3,]    2   -2    0
[4,]    3    0   -4

which is wrong, as the indexing into tmp_b causes the NA entries to be replaced in columnwise order.


text:
Q: How to get .hover to work with if statement I have a page with tabs (each tab labeled as column 1, 2, and 4). Trying to figure out how to get the .hover function to work and make said tab -> $('.column1').css("left", "calc(-100vw + 180px)"); grow to 190px when you hover over...? but only when the tab is in its "calc(-100vw + 180px)" state not $(".column1").css("left", "0"); which is when it is completely open.
$(".column1").on("click", function(){
    if ($('.column1').hasClass("closed")){
    $(".column1").css("left", "0");
    }
    else {
    $(".column1").css("left", "0");
    $(".column2").css("left", "0");
    $(".column4").css("left", "0");
    }

});

$(".column2").on("click", function(){
    if ($('.column2').hasClass("closed")){
        $(".column2").css("left", "0");
    }
    else {
        $(".column2").css("left", "0");
        $('.column1').css("left", "calc(-100vw + 180px)");
        $(".column4").css("left", "0");
    }

});

$(".column4").on("click", function(){
    if ($('.column4').hasClass("closed")){
        $(".column4").css("left", "0");
    }
    else {
        $('.column1').css("left", "calc(-100vw + 180px)");
        $('.column2').css("left", "calc(-100vw + 190px)");
        $(".column2").hasClass("closed");
        $(".column1").hasClass("closed");
    }
});

A: To change a property while the mouse is positioned over the object it would be better to use the "mouseover" event to add the effect you want to have when the mouse is over the element.
And the "mouseleave" event to remove the effect.
$(".column1,.column2,.column4").on("mouseover", function(){
    $(this).css("left", "doWhatYouWantWhenMouseIsOnTheElement()");
});

$(".column1,.column2,.column4").on("mouseleave", function(){
    $(this).css("left", "revertWhatYouHaveDoneInTheOv()");
});


text:
Q: RTC - Is it possible to have personal repo for each-user like Git provides I am new too RTC version control tool, before this I was using git as my version control tool. In git each user used to have one separate user(personal) repository, first we will commit all my local changes there and do all this jenkins build and review and other ceremonies. When everything successfully done we will go-ahead and merge our personal repo to our master. What is the advantage here is, my master build never used to fail.
But in RTC, we never find anything like that. Straight-away we will commit all our changes to master and mostly the builds are failing.
Is there any facility to do the above git setup in RTC.

A:
Straight-away we will commit all our changes to master

No, you commit to your personal repository workspace, and then, after controlling the quality of what is committed (through for instance a Jenkins build definition triggered on your own desktop, in a dedicated build workspace), you push (deliver) to the stream referenced by the repo workspace.
See "Repository workspaces in team environments":

As a team member, your repository workspaces are private development areas where you can work on your own or combine your work with contributions from your team.
  Your work remains private to the workspace until you decide to deliver it to a team flow target such as a shared stream.


text:
Q: Is there any method to share database in iphone? I want build a app, in that app i should  able to shear my database with every one.
Is there any method to do that?

A: Not in Apple's security model.  You can share it between several of your own applications, if your set things up correctly to begin with.


text:
Q: Find Gal$(f)$, here $f$ is the minimal polynomial of $x$ over $\Bbb{Q}(x^6)$ Let $f$ be the minimal polynomial of $x\in \Bbb{Q}(x)$ over $\Bbb{Q}(x^6)$. How to find the Galois group of $f$?
Here is my thought, $f(t)=t^6-x^6$ is the minimal polynomial. Factor it out, we can get the splitting field for $f$ is $\Bbb{Q}(x,\sqrt{3}ix)$. Then I got stuck, how to find the degree of the extension $[\Bbb{Q}(x,\sqrt{3}ix):\Bbb{Q}(x^6)]$ and how to proceed?

A: It is preferable to say that the splitting field is $L=K(x,\zeta_6)$, where $\zeta_6$ is a primitive $6$-th root of $1$ and $K=\mathbb{Q}(x^6)$. Now $[K(x,\zeta_6):K(x)]$ has degree $\leq 2$. But $K(x)=\mathbb{Q}(x^6)$ does not contain any imaginary complex number, so the degree is actually $2$, and then $[L:K]=[L:K(x)][K(x):K]=2\times 6=12$.
Now $K(x,\zeta_6)/K(\zeta_6)$ is a Kummer extension of degree $6$, hence its Galois group is cyclic. This subgroup is normal because it has index $2$.
Moreover, $K(x)/K$ is not a normal extension, so the Galois group contains a non normal subgroup of order $2$. In particular, it is not abelian. The only non abelian group of order $12$ with a normal cyclic subgroup of order $6$ is $D_6$, so $Gal(f)\simeq D_6$.
You can also see it more explicitely by considering $\sigma:L\to L$ such that $\sigma(x)=\zeta_6 x$ and $\sigma(\zeta_6)=\zeta_6$, and $\tau:L\to L$
 such that $\tau(x)=x$ and $\tau\zeta_6)=\zeta_6^{-1}$. You can easily check that $\sigma$ has order $6$, $\tau$ has order $2$ and $\tau\sigma\tau^{-1}=\sigma^{-1}$.

A: The splitting field for $ f $ is $ \mathbb{Q}(x, \sqrt{3}ix) = \mathbb{Q}(x, \sqrt{3}i) $, and the extension degree is $ [\mathbb{Q}(x, \sqrt{3}i) : \mathbb{Q}(x^6)] = [\mathbb{Q}(x, \sqrt{3}i) : \mathbb{Q}(x)][\mathbb{Q}(x) : \mathbb{Q}(x^6)] = 2 \cdot 6 = 12 $.
Conjugates of $ x $ over $ \mathbb{Q}(x^6) $ are $ x $, $ e^{\pi i/3} x $, $ \dots $, $ e^{5\pi i/3} x $, which are the possible values of $ \sigma(x) $ for $ \sigma \in \operatorname{Gal}(f) $. Similarly, the possible values of $ \sigma(\sqrt{3}i) $ are $ \pm\sqrt{3}i $. Since $ \sigma $ is determined by these values and $ \lvert\operatorname{Gal}(f)\rvert = [\mathbb{Q}(x, \sqrt{3}i) : \mathbb{Q}(x)] = 12 $, these possible $ 12 $ patterns actually appear. We can now determine $ \operatorname{Gal}(f) $.


text:
Q: Conditions for the existence of a minimal non-empty set Let $\{X_t\}_{t \in [0,1]}$ be a family of sets of real numbers, parametrized by a real number $t$. It is given that $X_0 = \mathbb{R}$ and $X_1=\emptyset$ and the family is weakly-decreasing, i.e.:
$$
t > s \implies X_t\subseteq X_s.
$$
In some cases, there exists a maximal $t\in [0,1]$ for which $z_t$ is non-empty. For example, if $X_t = [t,1-t]$, it is nonempty iff $t\leq 1/2$, so the maximal $t$ is $1/2$.
However, in other cases there is no such maximal $t$. For example, if $X_t = (t,1-t)$, it is nonempty iff $t< 1/2$.
My question is: what conditions on the family $X_t$ guarantee that there exists a maximal $t\in [0,1]$ for which $X_t\neq \emptyset$?


text:
Q: is this a subset of the set of all selfadjoint operators? Is the set $Q$  of all operators that have the property that the image is orthogonal to the kernel, and the kernel isn't the null space, only a subset of the set $T$ of the selfadjoint operators or equal to it ?
(would this hold in an infinite dimensional space (modulo some closures of the image or kernel) as well ?)
I know that $Q\subseteq T$, but does equality also hold ?

A: Take any non-symmetric invertible real matrix. Its image is the whole space, its kernel is zero and these are orthogonal. Yet the operator is not self-adjoint for the standard inner product.
[Added] Your edit does not make much difference, just othogonally project onto a proper finite-dimensional subspace and then apply a non-self-adjoint invertible operator of that subspace to itself; now the kernel is nonzero and orthogonal to the image (the space projected onto) but the operator is not self-adjoint. In spite of your "knowing" it, the claim $Q\subseteq T$ is just false.


text:
Q:  with changed path not working I want to extend <Route> component of react-router-dom so it would prepend some value before path property. It would look like this:
export default function MyRoute({path, ...rest}) {
    const newpath = '/app' + path;
    return <Route path={newpath} {...rest} />
}

I want to use it like:
<MyRoute path="/login" component={Login} />

So behind the scenes it should render:
<Route path="/app/login" component={Login} />

When I go to /app/login url it doesn't load. <Login /> still shows up only on /login.
What am I doing wrong here?
Edit
It doesn't work when used directly inside <Switch>:
<Switch>
    <MyRoute path="/login" />
</Switch>

But works when moved to another component:
<Switch>
    <Routes />
</Switch>

and Routes beeing:
<>
    <MyRoute path="/login" />
</>

A: I ended up using following code:
index.html

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <title>React App</title>

    You need to enable JavaScript to run this app.

Custom <MyRoute> is supposed to override all path attributes to include react_app_url defined in index.html. Ex. <MyRoute path="/home" /> should change into <Route path="/my-app-page/home" />.
MyRoute.js

import React from 'react';

export default function MyRoute({path, ...rest}) {
    let appUrl = '';
    if(window.hasOwnProperty('react_app_url')) {
        appUrl = window.react_app_url;
    }

    if( Array.isArray(path) ) {
        const paths = path.map(singlepath=>`${appUrl}${singlepath}`);
        path = paths;
    } else {
        path = appUrl + path;
    }
    return <Route path={path} {...rest} />;
}

In App.js we can now use custom <Routes> inside <Switch> and all paths will be replaced from, ex. /home to /my-app-page/home.
App.js

import React from 'react';

import {BrowserRouter, Switch} from 'react-router-dom';
import MyRoute from './MyRoute';

export default function App() {
    return (
        <BrowserRouter>
            <Switch>
                <>
                    <MyRoute path="/home" component={Home} />
                    <MyRoute path="/about" component={About} />
                    <MyRoute path="/contact" component={Contact} />
                </>
            </Switch>
        </BrowserRouter>
    );
}


text:
Q: Android: EditText temporarily cleared when SELECTED (not written) is there a method by which an EditText can be 'temporarily' cleared when SELECTED?
In other words, I'd like to achieve these steps:
1) at the beginning it is present a hint
2) as soon as I select the EditText, it appears cleared, empty, with only the lightening cursor visible
3) without clicking 'send', so whithout confirming the written text, I click on somewhere else in the activity
4) the intial hint will appears again
I tried using android:hint, but the text doesn't disappear when EditText is selected.
Can anyone help me?
Thanks.

A: You need the hint text color transparent when EditText is focused and gray in normal state. Create a text_color_hint.xml file in res/drawable:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:color="@android:color/transparent" />
    <item android:color="#808080" />
</selector>

Then assign the text_color_hint to android:textColorHint. Your EditText should look something like this:
<EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="HINT HERE"
        android:textColorHint="@drawable/text_color_hint"/>

To avoid the EditText being auto focused, you can:
1) Add  android:focusable="true" and android:focusableInTouchMode="true" in the parent layout of EditText, here I take LinearLayout as an example:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:focusable="true"
    android:focusableInTouchMode="true">

OR
2) Create a dummy LinearLayout which takes no space, add the above 2 elements to it, and put it right before the EditText:
<LinearLayout
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:focusable="true"
    android:focusableInTouchMode="true"/>

<EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="HINT HERE"
        android:textColorHint="@drawable/text_color_hint"/>


text:
Q: Is there any way to add default value to react-dropzone (useDropzone)? I would like to initialize the react-dropzone (useDropzone) with an image. The users should be able to override (replace) it with their own images if they want to.
My desire would be to be able to add the default image by URL.
(ex. https://hatrabbits.com/wp-content/uploads/2017/01/random.jpg)

A: You can implement the default image (a placeholder) as you defined the error section. you need to add an img element and pass the default image's URL to it .
with a prop checking, you can determine to show the placeholder image or use the user's uploaded image or even nothing.
I assume you store the DropZone result in a sample variable like result, so:
{
  !result && <img src={https://hatrabbits.com/wp-content/uploads/2017/01/random.jpg}>
}

so the placeholder image will show if there is not a result


text:
Q: Laravel 4 Auth::attempt returns false on correct values I have login code that is supposed to work by attempting to authenticate the user using Laravel's Auth::attempt() method. This code works on another site of mine, I have altered it as instead of the Password in the database, it is stored as passwdEncrypted. I cannot change it as the database is in use by another application as well.
The code is below:
// check if in database
        $isInDb = User::where('ReferenceCode', $username)->first();
        if($isInDb) {
            // is in database
            // check if password is encrypted yet
            if($isInDb->passwdEncrypted) {
                // password is encrypted
                if(Auth::attempt(array('ReferenceCode' => $username, 'passwdEncrypted' => $password))) {
                    // authenticated
                    $array = array();
                    $array['verified'] = 'true';
                    $array['type'] = Auth::user()->UserType;
                    return Response::json($array);
                } else {
                    // not authenticated
                    $array = array();
                    $array['verified'] = 'false';
                    $array['type'] = $type;
                    return Response::json($array);
                }
            } else {
                // password is not encrypted
                // check if plain text password is correct
                if($isInDb->Password == $password) {
                    // plain text password is correct
                    $hashed = Hash::make($password);
                    $arr = array('passwdEncrypted' => $hashed);
                    $updated = User::where('rsmsOnlineUserID', $isInDb->rsmsOnlineUserID)->update($arr);
                    if($updated) {
                        $newUser = User::find($isInDb->rsmsOnlineUserID);
                        echo $newUser->passwdEncrypted;
                        if(Auth::attempt(array('ReferenceCode' => $username, 'passwdEncrypted' => $password))) {
                            echo 'logged in';
                        } else {
                            dd(DB::getQueryLog());
                            echo 'could not log in';
                        }
                    } else {
                        echo 'did not update';
                    }
                } else {
                    // plain text password is incorrect
                    $array = array();
                    $array['verified'] = 'false';
                    $array['type'] = $type;
                    return Response::json($array);
                }
            }
        } else {
            // not in database
            return Respone::json(array('success' => 'false'));
        }

What is happening: I can't log in, the username and password in the database is 1234, even if I hard code that, it does not work.
It first checks to see if the user is in the database, if it is, it checks to see if there is an encrypted password, if there is not, it will create one from the password given if it matches the plain text password in the database and then log the user in (I have no choice but to have the plain text password stored in the database, that is how they want it).
But it returns the {"verified":"false","type":"prospective_employee"} from the not authenticated part of the code. So neither of the Auth::attempt() blocks work.
I was logging them in manually but even Auth::login() won't work.
I have the following in my User model (with the main database table):
public function getAuthPassword()
{
    return $this->Password;
}

/**
 * Get the token value for the "remember me" session.
 *
 * @return string
 */
public function getRememberToken() {
    return $this->remember_token;
}

public function setRememberToken($value) {
    $this->remember_token = $value;
}

public function getRememberTokenName() {
    return 'remember_token';
}

/**
 * Get the e-mail address where password reminders are sent.
 *
 * @return string
 */
public function getReminderEmail()
{
    return $this->email;
}

Please note that there is a field in the table called Password, but that is the plain text password, I need to authenticate against the passwdEncrypted field.

A: You cannot do this with Laravel, and for good reason, but it is ridiciously unsecure and dangerous.

I have no choice but to have the plain text password stored in the
  database, that is how they want it

I dont understand - why are you storing BOTH an "unencrypted" and "encrypted" password? There is no point. You should only ever store encrypted passwords. There is no need for any other way, and you need to educate the people as to why.

This code works on another site of mine, I have altered it as instead
  of the Password in the database, it is stored as passwdEncrypted. I
  cannot change it as the database is in use by another application as
  well.

The Laravel Auth code is hard coded to use the "password" column. You cannot simply change it to another colum. That is why your code is failing.
Since you are not using the password column, and since you are not using encrypted passwords, you might as well just create your own unsecure login system, customised to suit your requirements.


text:
Q: DataGridView, Virtual Mode and "lags" My code looks as follows:
private void dataGridView4_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
        {
            Records recordsTmp  = null;
            recordsTmp = (Records)this.ArrayOfRecords[e.RowIndex]; //ArrayList with string[] objects inside

            switch (dataGridView4.Columns[e.ColumnIndex].HeaderText)
            {
                case "#":
                    e.Value = recordsTmp.nr;
                    break;
                case "ip":
                    e.Value = recordsTmp.Ip;
                    break;
                case "long":
                    e.Value = recordsTmp.Long;
                    break;
                case "3":
                    e.Value = recordsTmp.type;
                    break;
                case "4":
                    e.Value = recordsTmp.time;
                    break;
            }

*

*ArrayOfRecords is updated with 10-100 new string[] objects per second.

*VirtualMode is set to true.

*SelectionMode is set to FullRowSelect.

*dataGridView is Read-only.

Now theres also a ProgressBar with Marquee style which shows me that with lets say 5000+ rows scrolling freezes the Form but i guess its just a matter of threading/backgroundworker etc.
What scares me most is selection. Having 8000 rows and clicking last one (8000) takes my form 4.2 seconds to select it. And its as follows:
4000 rows makes it 2.1 secs, etc. If 8000th row is selected minimazing and then maximizing takes 4.2 secs. Selecting row 1 "makes it" happy again. Its unacceptable. *Why is it so hard to "mark" 8000th row for my Form?
VirtualMode's pagination works perfectly but selection is a pain.
Theres also another issue/behaviour:
Why CellValueNeeded event is raised when im moving my mouse over the rows? They are already painted? So why is it wasting resources?
Is there any solution for this selection problem? Or i have to limit maximum records in the datagrid

A: One thing you want to play with is the autosizing of the cells, as the gridview will have to go through all your cells in order to find the one with the longest length. You should disable autosizing and you should do that programatically.
Regarding your selection problem: selecting causes a lot of redraws, my hunch is that is redraws all your cells, therefore the lag is proportional to your row/cell count.
In order to use Virtual Mode you need more than setting the VirtualMode to true. It would be interesting to see your dataGridView1_RowsAdded, dataGridView1_CellValuePushed and dataGridView1_CellValidating methods, since they are probably the culprit of the delays.


text:
Q: How to run conditional TestNG Tests with data from Excel I have a class with multiple @Test methods each with a different functionality.
class myTests
{
@Test
test1()
{
...............
}

@Test
test2()
{
...............
}
}

Am following the Data driven approach where I have the data in Excel. Each row in excel sheet corresponds to a different test case that should execute the test methods in above class.
Below is the sample data from excel sheet which contains the method name as one of the parameters(eg: test1, test2) and also a flag which determines if the case should be picked up for execution or not at runtime (eg: y,n)
case1 data1 data2 data3........test1 y
case2 data4 data5 data6........test1 y
case3 data7 data8 data9........test2 y
case4 data10 data11 data12........test1 n

Below are the questions I have:

*

*How to map the cases to corresponding test methods

*How to make the specific cases run based on the flag
My understanding is that using DataProvider annotation, a test method can run with different input data. But am not sure how to map the test methods with corresponding test data if there are multiple test methods in single class.
Also I tried looking for IAnnotationTransformer that can be used to alter the runtime behaviour of test method, but could not find a way to send the flag data from excel to the transformer class.
Thanks in advance..

A: There are bits and pieces of how this can be done, which you can do, but its going to require a lot of customization from your side. There's nothing in TestNG that gives you this sort of capability out of the box.
IAnnotationTransformer will not help you because, this listener only considers methods and is not aware of the instances. It also runs before anything runs and there's no way wherein you can have this iterate. So that can be ruled out.
Your best bet would be to use a @Factory and a @DataProvider wherein the @Factory will produce ONLY one instance of your test class and all your Test methods will have to mandatorily be part of that same test class.
Here's the idea :

*

*Create an additional column in your data source which represents the class that should basically be consuming the data source.

*Build a data provider such that, it reads the above data source, filters out all the rows whose fully qualified class names match with the current data provider's enclosing class.

*The data provider also should be built such that it creates a map (key is test method name and value is a list of values that are to be used for different iterations).

*Once it has all the filtered rows, it creates just one row of test data such that, TestNG creates only one test class instance.

*Have your test class also implement IHookable interface, so that you can to decide which test method will run and which can be skipped.

*Now if a method satisfies the check of being run, you will basically have the test method loop through all the test data it has (so its always 1 test method will run in a loop for all its data unlike a data provider setup wherein TestNG does it automatically for you), and you resort to using soft asserts, to assert all the validations. This way your test will pass/fail after all the iterations are done.

Here's a sample that shows some of this in action.
import org.testng.IHookCallBack;
import org.testng.IHookable;
import org.testng.ITestResult;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class TestclassSample implements IHookable {

    private List<String> methodsToRun = new ArrayList<>();

    @Factory(dataProvider = "dp")
    public TestclassSample(List<String> methodsToRun) {
        this.methodsToRun = methodsToRun;
    }

    @Override
    public void run(IHookCallBack callBack, ITestResult testResult) {
        String testMethodName = testResult.getMethod().getMethodName();
        if (methodsToRun.contains(testMethodName)) {
            System.err.println("About to run " + testResult.getMethod().getMethodName());
            callBack.runTestMethod(testResult);
        } else {
            testResult.setStatus(ITestResult.SKIP);
        }
    }

    @Test
    public void testMethod() {
        System.err.println("testMethod()");
    }

    @Test
    public void anotherTestMethod() {
        System.err.println("anotherTestMethod()");
    }

    @Test
    public void thirdTestMethod() {
        System.err.println("thirdTestMethod()");
    }

    @DataProvider(name = "dp")
    public static Object[][] getData() {
        return new Object[][]{
                {Arrays.asList("testMethod", "thirdTestMethod")}
        };
    }
}

Here's the output :
About to run testMethod
testMethod()
About to run thirdTestMethod
thirdTestMethod()

Test ignored.

===============================================
Default Suite
Total tests run: 3, Failures: 0, Skips: 1
===============================================


text:
Q: Finding the difference between the results of two queries in Access 2003 I would like to create a query in Access 2003 that combines two queries to find the difference between the results.
Query 1: [all]
SELECT mars.Name, mars.Location, mars.Business_Unit
FROM mars
GROUP BY mars.Name, mars.Location, mars.Business_Unit;

That returns
Name   Location   Business Unit
-----  ---------  -------------
John   Sydney     AU
Grace  Brisbane   AU
Lee    Melbourne  GU

Query 2: [not_zero]
SELECT mars.Name, mars.Location, mars.Business_Unit
FROM mars
WHERE ((mars.orc)<>0)
GROUP BY mars.Name, mars.Location, mars.Business_Unit;

It returns:
Name   Location  Business Unit
-----  --------  -------------
John   Sydney    AU
Grace  Brisbane  AU

My query that I am trying to create:
SELECT m.Name, m.Location, m.Business_Unit
FROM
    all AS m
    LEFT JOIN
    Not_Zero AS o
        ON (m.Name=o.Name)
            AND (m.Location=o.Location)
            AND (m.Business_Unit=o.Business_Unit)
GROUP BY m.Name, m.Location, m.Business_Unit;

I would like my query to achieve:
Name  Location   Business Unit
----  ---------  -------------
Lee   Melbourne  GU

But instead I get the same results as the [all] query:
Name   Location   Business Unit
-----  ---------  -------------
John   Sydney     AU
Grace  Brisbane   AU
Lee    Melbourne  GU

Ok, so this [mars] table is something like this:
Name   Location   Business Unit  ORC
-----  ---------  -------------  ---
John   Sydney     AU             0
Grace  Brisbane   AU             5
John   Sydney     AU             10
Grace  Brisbane   AU             0
Lee    Melbourne  GU             0
Lee    Paris      EU             0

what I'm trying to achieve is to get the names that have orc = 0 all the way i.e. which is why I want for example:
Name  Location   Business Unit  ORC
----  ---------  -------------  ---
Lee   Melbourne  GU             0
Lee   Paris      EU             0

A: Since the [not_zero] query results will always be a subset of the [all] query results, the "difference" between the two are the rows in [all] that do not appear in [not_zero]. The following query finds them:
SELECT all.*
FROM
    all
    LEFT JOIN
    not_zero
        ON (all.NAME=not_zero.NAME)
            AND (all.LOCATION=not_zero.LOCATION)
            AND (all.[BUSINESS UNIT]=not_zero.[BUSINESS UNIT])
WHERE
    (not_zero.NAME Is Null)
        AND (not_zero.LOCATION Is Null)
        AND (not_zero.[BUSINESS UNIT] Is Null);