Q: MS Access SQL Left Joins Not Working Can't get this ms JET sql query (querying a 2007 Access database that I didn't write) to work. Error mentions "too few parameters, expects 4". I believe it has to do with my JOINs.
Anyone know what I'm missing?
SELECT TOP 500 [Load Items].[LoadItemsID] AS load_order_line_id,
        lo.[LoadOrderID] AS load_order_id,
        sp.[Description] AS product_description,
        sp.[Common Name] AS product_common_name,
        c.[Bill To Name] AS company_name,
        lp.[Ship Date] AS ship_date,
        al.[Ordered] AS order_quantity,
        al.[Price] AS sell_price,
        a.[Order Date] AS order_date,
        a.[Due Date] AS due_date
        FROM ((((((([Load Items]
            LEFT JOIN [Acknowledgement Lines] AS al
                ON al.[AcknowledgmentLineID] = [Load Items].[AcknowledgmentLineID])
            LEFT JOIN [Product] AS p
                ON p.[ProductID] = al.[ProductID])
            LEFT JOIN [Product Master] AS pm
                ON pm.[ProductMasterID] = p.[ProductMasterID])
            LEFT JOIN [Species] AS sp
                ON sp.[SpeciesID] = pm.[SpeciesID])
            LEFT JOIN [Acknowledgement] AS a
                ON a.[AcknowledgmentID] = al.[AcknowledgmentID])
            LEFT JOIN [Customer] AS c
                ON c.[CustomerID] = a.[CustomerID])
            LEFT JOIN [Load Orders] AS lo
                ON lo.[LoadOrderID] = [Load Items].[LoadOrderID])
            LEFT JOIN [Load Planner] AS lp
                ON lp.[LoadPlannerID] = lo.[LoadPlannerID]
        GROUP BY [Load Items].[LoadItemsID],
            lo.[LoadOrderID],
            sp.[Description],
            sp.[Common Name],
            c.[Bill To Name],
            lp.[Ship Date],
            al.[Ordered],
            al.[Price],
            a.[Order Date],
            a.[Due Date];

A: The most likely cause is typos in field names. Each bracketed field name that doesn't correctly match the field name that you are trying to access in the tables is one missing parameter, as far as the parser is concerned.


Q: Complex query on more than one child in cloud functions Here is the structure of my firebase database:
/UserData
  /DeviceMgmt
      /Counters
          /NumberOfAll:
          /NumberOfSelected
          /TotalDownloaded
        ...
      /Devices
          /pushId1
            /uid
            /signOutTime
            /toSelect=true (optional)
            /downloaded
            /lastDownload

          /pushId2
          /pushId3
           ...

And this is my cloud function:
exports.markDevicesForDownload = functions.database.ref('/UserData/DeviceMgmt/Counters/NumberOfSelected').onUpdate( (change) => {

   const changeRef = change.after.ref;
   const deviceMgmtRef = changeRef.parent.parent;   // /UserData/DeviceMgmt

   if (change.after.val() === 0 ) { //NumberOfSelected gets 0 value

        return deviceMgmtRef.once('value')
            .then((snap) => {

                const devicesRef = snap.child('Devices').ref;

                var average;
                var numberOfAllDevices;
                var totalDownloaded;

                numberOfAllDevices = snap.child('Counters/NumberOfAll').val();
                totalDownloaded = snap.child('Counters/TotalDownloaded').val();
                average = Math.round(totalDownloaded/numberOfAllDevices);

                return devicesRef
                        .orderByChild('signOutTime')
                        .equalTo(0)
                        .once('value',(devices) => {
                        return devices.ref
                                .orderByChild('downloaded')
                                .endAt(average)
                                .once('value',(devices) => {
                                    devices.forEach((device) => {
                                        device.child('toSelect').ref.set(true);
                                    });
                        });
                });
            });

   } else {
       return false;
   }

});

The function triggers when the counter NumberOfSelected = 0;
This happens when under any of device pushId there is no child toSelect. Then the query on downloaded child makes all devices with downloaded less than average set toSelect=true.
I wanted to limit the devices only to those which have signOutTime equal 0.
Somehow that query does not work and all devices are considered.
What I did wrong???

A: I would push all async tasks into a promise array and then return them all when all tasks complete:
exports.markDevicesForDownload = functions.database.ref('/UserData/DeviceMgmt/Counters/NumberOfSelected').onUpdate((change) => {
  const changeRef = change.after.ref;
  const deviceMgmtRef = changeRef.parent.parent; // /UserData/DeviceMgmt
  if (change.after.val() === 0) { //NumberOfSelected gets 0 value
    return deviceMgmtRef.once('value')
      .then((snap) => {
        const promises = [];
        const devicesRef = snap.child('Devices').ref;
        var average;
        var numberOfAllDevices;
        var totalDownloaded;
        numberOfAllDevices = snap.child('Counters/NumberOfAll').val();
        totalDownloaded = snap.child('Counters/TotalDownloaded').val();
        average = Math.round(totalDownloaded / numberOfAllDevices);
        const dR = devicesRef
          .orderByChild('signOutTime')
          .equalTo(0)
          .once('value', (devices) => {
            const dW = devices.ref
              .orderByChild('downloaded')
              .endAt(average)
              .once('value', (devices) => {
                devices.forEach((device) => {
                  if (device.child("signOutTime").val() === 0){
                    promises.push(device.child('toSelect').ref.set(true));
                  }
                });
              });
              promises.push(dW);
          });
          promises.push(dR);
          return Promise.all(promises);
      });
  } else {
    return false;
  }
});


Q: RoR: How to use *_path in a model? I need to generate a “report” in a model. This “report” has to include links. However, all the *_path functions seems to be unavailable in the model classes (a simple test show me that new_post_path raises an Exception in my models, but works fine in my controllers)
Is there any way to use polymorphic_url or, at least, *_path methods in my models ?

A: if you:
include ActionController::PolymorphicRoutes

In your model:
class SomeModel < ActiveRecord::Base
  include ActionController::PolymorphicRoutes
end

you get polymorphic_path and polymorphic_url.  These can then be used by passing self into the methods if you're generating a route for the current AR object.


Q: At what point should data be sent back to server? A good example would be the stackexchange "rate" button. When a post is upvoted the arrow changes color immediately. However there is a grace period for one to edit one's vote decision (oops! voted by mistake?). Is the upvote action processed immediately or does is only process after a set time period, or when the user leaves the page? How exactly is this rating processed?
What is the standard for handling dynamic page edits (e.g. stackexchange rating, facebook posts?)

A: Generally I would recommend that you make the changes immediately. If there's to be a "grace period", then implement that on the server side (you can do it client side too if it will improve user experience).
So if someone upvotes a post, it is saved immediately via ajas, but then if they change their minds within the grace period, the server undoes the vote. Once the "grace period" is up, the server rejects the change.
A Facebook post would (obviously) be saved when you click "Post", etc. -- but it wouldn't be saved before then.
Something like Blogger or Google Docs is another issue altogether -- where it's automatic saving every x number of seconds. That is purely up to the developer. Generally you want to make it as often as possible without impacting performance or decreasing the user experience.


Q: How to get releases for golang/go with go-github Learning Go and try to get the release list of golang/go with go-github.
Here is my code:
package main

import (
    "github.com/google/go-github/github"
    "fmt"
)

func main() {
    client := github.NewClient(nil)

    opt := &github.ListOptions{Page: 2, PerPage: 10}
    releases, rsp, err := client.Repositories.ListReleases("golang", "go", opt)

    if err != nil {
        fmt.Println(err)
    }

    fmt.Printf("\n%+v\n", releases)
    fmt.Printf("\n%+v\n", rsp)

}

When I run it, the release list is empty (as below):
[]

github.Rate{Limit:60, Remaining:59, Reset:github.Timestamp{2015-12-05 14:47:55 +1100 AEDT}}

I don't know what I am doing wrong.

A: Edit:
Taking a closer look at the Go repository, the releases are actually just tags and not Github releases, that's why it's returning an empty array. Try this:
// https://api.github.com/repos/jp9000/obs-studio/releases
releases, rsp, err := client.Repositories.ListReleases("jp9000", "obs-studio", opt)

This should correctly return all releases for jp9000's obs-studio repository.
Original Answer:
Looking at the docs, the code looks good but this might be an issue with Github's API though. For instance, if you go to https://api.github.com/repos/golang/go/releases you get an empty array, but if you search for the tags using https://api.github.com/repos/golang/go/tags it lists all tasks without any problem.
And if you go to https://api.github.com/repos/golang/go/releases/1 you get a 404. I took these addresses from the Github Developer's page: https://developer.github.com/v3/repos/releases/#list-releases-for-a-repository


Q: Can't insert any values in Judy I'm getting strange behavior with Judy Array. The documentation just says you can use it like an usual PHP array. But whatever I do it seems to me that it won't store any information.
For example if I do this:
$this->_history = new Judy(Judy::STRING_TO_MIXED);
$this->_history['test'] = 'testString';
echo $this->_history['test']; // output nothing; no warnings no text nothing
var_dump($this->_history); // class Judy#126 (0) { }
$this->_history->getType() // correctly (int) 5
$this->_history->getTypeFoo() // warning no method

Am I doing something wrong? Did I forget something? I tested it both an an Ubuntu and Debian System, both the same.
Also funny is, that when I run the bench-script which is provided in the pecl package and extracted under /usr/share/php/doc/Judy/examples/judy-bench-string_to_int.php the Judy Array works fine.
Here's how I installed it:
sudo aptitude install libjudydebian1 libjudy-dev
sudo pecl install judy

It said installation was succesful and I added extension=judy.so to php.ini.
What should I do to get Judy working?

A: Well it works now. But actually I don't know why. I shouldn't care.
I copied the working code from the bench-*.php file from the /docs into my own file and it worked. Here's the code:
echo "\n-- Judy STRING_TO_INT \n";
echo "Mem usage: ". memory_get_usage() . "\n";
echo "Mem real: ". memory_get_usage(true) . "\n";

$s=microtime(true);
$judy = new Judy(Judy::STRING_TO_MIXED);
for ($i=0; $i<500; $i++)
    $judy["$i"] = 'test';
var_dump($judy);
unset($judy["102"]);
echo $judy["192"];
var_dump($judy["102"]);
echo "Size: ".$judy->size()."\n";
$e=microtime(true);
echo "Elapsed time: ".($e - $s)." sec.\n";
echo "Mem usage: ". memory_get_usage() . "\n";
echo "Mem real: ". memory_get_usage(true) . "\n";
echo "\n";

unset($judy);


Q: Associative table many on many with varying level of entity specificity I have the need to associate a message or a group of messages with a display or a group of displays.
A message has a type, and a display has a type and a location ( for example, a city)
I would like to associate a message or all messages of a certain type to a display or all display of a certain type and/or location.
My first idea was to build an associative table many on many, with the foreign keys:

*

*Message_id

*Message_type_id

*Display_id

*Display_location_id

*Display_type_id

And when adding an entry, set a value for the fields i am interested in ( for example message_type and display_location), and null to the others.
However, i was interested in the downsides of this approach, and wondering if there are better methods to handle this kind of problems. After some days searching (in vain) for this kind of pattern when designing a database, i ultimately decided to ask here.
Thanks for the help.

A: The approach is sound.
It occurs to me that you only need Message_id  and Display_id  in the "intersection entity", as the other columns would probably come from the "parent" entity.
Message_type_id
Display_location_id
Display_type_id


Q: Does Apple Catalyst support iPhone There are many resources and tutorials mentioning iPad and/or iOS being compatible with Apple's Catalyst framework,
So, the same source-code runs on Mac OS X as well.
But does Catalyst support iPhone?
(Please tell me your personal experience to clarify this, and not that the name of iPhone operating-system is iOS)

A: Mac Catalyst allows iOS apps to be built for and run on macOS.
So, by definition, Catalyst apps support iOS, and usually the iPhone. The only case in which they wouldn't is if the app was specifically an iPad-only app that runs on Catalyst on the Mac, but was not enabled to run on the iPhone.
More about Catalyst: https://developer.apple.com/mac-catalyst/
You asked for personal experience: I have apps in the App Store for iOS, iPad, and Mac, via both Catalyst and non-Catalyst builds.


Q: Selectize.js destroy() method changes select value I'm using selectize.js in my project. What I need to do is clone part of the form (with selectized elements) and append it to the end of the form.
I've decided to destroy selectized elements before cloning, and after appending new subform initialize selectize again.
Here is a code for destroying selectized elements:
  var selectElements = $(plusButtonElement).parents(".subform_wrapper").first().find("> .subform_fields_wrapper").find("select");
$.each(selectElements, function(index, element){
    console.log(element);
    console.log($(element).val());    //Here we got value "10"
    $(element)[0].selectize.destroy();
    console.log($(element).val());    //Here we got value "A6"
});

It works - elements transform to the regular selects, BUT value of the select elements are changing. Did anyone face with this problem?
I checked selectize.js source and the only thing I can say is that value is changed in this code:
    self.$input
            .html('')
            .append(revertSettings.$children)
            .removeAttr('tabindex')
            .removeClass('selectized')
            .attr({tabindex: revertSettings.tabindex})
            .show();

A: Hi Tamara yes I think this is a bug of the Selectize.js.
I alter the following destroy method in selectize.js
destroy: function() {
        var self = this;
        var selectedValue = self.$input.val();
        var eventNS = self.eventNS;
        var revertSettings = self.revertSettings;

        self.trigger('destroy');
        self.off();
        self.$wrapper.remove();
        self.$dropdown.remove();

        self.$input
            .html('')
            .append(revertSettings.$children)
            .removeAttr('tabindex')
            .removeClass('selectized')
            .attr({tabindex: revertSettings.tabindex})
            .show();

        self.$control_input.removeData('grow');
        self.$input.removeData('selectize');

        $(window).off(eventNS);
        $(document).off(eventNS);
        $(document.body).off(eventNS);

        delete self.$input[0].selectize;

        self.$input.val(selectedValue);
    },

Here you can download my selectize.js file.


Q: Debug Dockerized Flask app in VSCode not breaking on breakpoints I followed this tutorial to set up debug in my VSCode.
My launch.json file is below.
{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Remote Attach",
            "type": "python",
            "request": "attach",
            "connect": {
                "host": "localhost",
                "port": 5678
            },
            "pathMappings": [
                {
                    "localRoot": "${workspaceFolder}/server/project/views",
                    "remoteRoot": "/server/project/views"
                }
            ]
        }
    ]
}

My code does break on raised and user uncaught exceptions but it does not break on the breakpoints that I set. The code is reaching the breakpoints and I checked it using print statements, but my breakpoints are not working. VSCode debugger does seem to listen to my docker app (seen in the logs in screenshot) but not sure why it is not breaking at my breakpoints. However, it does give an error saying:

pydev debugger: unable to find translation for:
"/home/vvarma9/DTNetworkRepos/ip2m-metrr/server/project/utils/assessments.py"
in ["/home/vvarma9/DTNetworkRepos/ip2m-metrr/server/project/views/",
"/home/vvarma9/DTNetworkRepos/ip2m-metrr/server/project/views"]
(please revise your path mappings).

Kindly help!

A: Make sure your local and remote paths are correct. You can check your remote path by logging into the container's terminal. There you can find the absolute path of your "app".
I also cannot tell where you ${workspaceFolder} is actually is. Could be DTNetworkRepos or ip2m-metrr. You will need to make sure you clarify the path.
Also it would help if you posted up your folder stucture, Docker file for the server project and docker compose for all your container projects. Docker file will explain your path on the remote server. Dockerfile & Docker-compose file will ensure us that you have the right cmd or entrypoint for your environment. It may not line up with the tutorial that you set up.


Q: how to use geometry manager grid inside . which already has slaves managed by pack I found the code below on the net, and I tried to adapt it to my personal needs in my code but I have as error: tkinter.TclError: cannot use geometry manager grid inside . which already has slaves managed by pack.
Here is the code I found on the net that allows to display large images by clicking on small images :
import tkinter as tk

nb_rows = 10
images = (
    ("images/small_images/small_image1.png", "images/big_images/big_image1.png"),
    ("images/small_images/small_image2.png", "images/big_images/big_image2.png"),
    ("images/small_images/small_image3.png", "images/big_images/big_image3.png"),
    ("images/small_images/small_image4.png", "images/big_images/big_image4.png"),
    # ...
)

def visualize(event):
    event.widget.unbind("<Button-1>")
    window = tk.Toplevel(event.widget)
    window._image = tk.PhotoImage(file=event.widget._filenames[1])
    tk.Label(window, image=window._image).pack()
    window.protocol("WM_DELETE_WINDOW", lambda: on_close(window))

def on_close(window):
    window.master.bind("<Button-1>", visualize)
    window.destroy()

root = tk.Tk()

labels, row, column = [], 0, -1
for index, filenames in enumerate(images):
    label = tk.Label(root)
    label["image"] = label._image = tk.PhotoImage(file=filenames[0])
    label._filenames = filenames
    label.bind("<Button-1>", visualize)
    if not index % nb_rows:
        column, row = 0, row + 1
    label.grid(column=column, row=row)
    row += 1
    labels.append(label)

root.mainloop()

here is part of my code that works correctly, and I want to integrate the code above on the left side (Text left) and adapt it to be functional :
#!/usr/bin/python3
# -*- coding: utf-8 -*-

from tkinter import *

root=Tk()
root.iconbitmap(r'images/cev.ico')

text_part1_loc35R="\n===============================\n"
text_part2_loc35R="Emetteur Directif 1 :\n"
text_part3_loc35R="===============================\n"+\
"Puissance directe (P+BL)   : 4.47 w\n"+\
"Puissance reflechie (P+BL) : 0.13  w\n"+\
"Puissance directe (BLS)    : 0.09  w\n"+\
"Puissance reflechie (BLS)  : 0.00  w\n"+\
"===============================\n"

text_part4_loc35R="Emetteur Clearance 1 :\n"
text_part5_loc35R="===============================\n"+\
"Puissance directe (P+BL)   : 0.55 w\n"+\
"Puissance reflechie (P+BL) : 0.09  w\n"+\
"Puissance directe (BLS)    : N/A w\n"+\
"Puissance reflechie (BLS)  : N/A w\n"+\
"###############################\n\n"

generalites = Frame(root,bg="powder blue",width=750,height=250)
generalites.pack()
##########################################
#les sous frames de generalites(top,bottom):
generalites_top=Frame(generalites,relief=RIDGE,bd=18,bg='cadet blue')
generalites_top.pack(side=TOP,fill=X)

titre_generalites_top=Label(generalites_top,text='Generalites Techniques LOC 35R',font=('arial',22,'bold'),bg='cadet blue',padx=120)
titre_generalites_top.pack()

###############################################
generalites_bottom=Frame(generalites,bg='powder blue',width=750,height=270)
generalites_bottom.pack(side=BOTTOM)

#################################################
generalites_bottom_left=Frame(generalites_bottom,bg='powder blue',width=375)
generalites_bottom_left.pack(side=LEFT)

generalites_bottom_right=Frame(generalites_bottom,bg='powder blue',width=375)
generalites_bottom_right.pack(side=LEFT)

##################################################

T_generalites_left = Text(generalites_bottom_left,padx=20, height=26, width=30)
s_generalites_left = Scrollbar(generalites_bottom_left, command=T_generalites_left.yview)
T_generalites_left.configure(yscrollcommand=s_generalites_left.set)

T_generalites_left.tag_configure('style_loc35R',font=('arial',12,'bold'),foreground='blue',justify='center')

photo1=PhotoImage(file='images/test/image1.png')
photo2=PhotoImage(file='images/test/image2.png')
photo3=PhotoImage(file='images/test/image3.png')
photo4=PhotoImage(file='images/test/image4.png')
photo5=PhotoImage(file='images/test/image5.png')

for (j,k) in [('\nphoto 1\n',photo1),('\n\nphoto 2\n',photo2),('\n\nphoto 3\n',photo3),('\n\nphoto 4\n',photo4),('\n\nphoto 5\n',photo5)]:
    T_generalites_left.insert(END,j,'style_loc35R')
    T_generalites_left.image_create(END, image=k)

T_generalites_left.insert(END,'\n\n')
T_generalites_left.pack(side=LEFT,anchor=NW)
s_generalites_left.pack(side=LEFT, fill=Y)

T_generalites_right = Text(generalites_bottom_right, bg='powder blue',font=('arial',14,'bold'),padx=15, height=18, width=52)
s_generalites_right = Scrollbar(generalites_bottom_right, command=T_generalites_right.yview)
T_generalites_right.configure(yscrollcommand=s_generalites_right.set)

T_generalites_right.tag_configure('style_loc35R', foreground='blue',justify='center',font=('arial', 12, 'bold'))

T_generalites_right.insert(END,text_part1_loc35R)
T_generalites_right.insert(END,text_part2_loc35R,'style_loc35R')
T_generalites_right.insert(END,text_part3_loc35R)
T_generalites_right.insert(END,text_part4_loc35R,'style_loc35R')
T_generalites_right.insert(END,text_part5_loc35R)
T_generalites_right.pack(side=LEFT)
s_generalites_right.pack(side=RIGHT, fill=Y)

root.mainloop()

Thanks for help


Q: Assigning colors to a d3.js bar chart? I'm trying to create a color-coded bar chart using d3. I am SO CLOSE. Here's my bl.ocks chart:
http://bl.ocks.org/sconnors37/b99070b055f125c9dff1/1cb53954be3f20e3c4492066eccd749b5cf04bbe
What I'm trying to do is assign color values based on the "teams" field in my .tsv file. So grey for Mercedes, red for Ferrari, etc. I have the teams in the var color domain and the colors in the var color range, and I'm pulling var color into the bar attrib.
For some reason though, the entire chart is just taking on the first item in the range - I changed it from grey to red just to see if that was what was going on, and it is.
So! How do I get the rest of my colors to pull through onto the bar chart? Help me, stackoverflow, you're my only hope.

A: In your .tsv file the last column team is not separated from the previous column by a tab, but rather through two spaces. If you look at the data passed to the d3.tsv callback I think you will find that you have one date  team column instead of a date and team column.
This means that the field d.team is undefined and ordinal(undefined) will just return the first value from the range.


Q: Material-UI CardContent has a 3px Bottom Padding Note: I already looked into this question: Cant remove padding-bottom from Card Content in Material UI
But the accepted answer did not fix my issue.
I am using the Material UI React Library attempting to recreate the below image:

I am completely new to using the Material UI, so most of my code will likely not be optimized and probably does not follow best practices. Indeed, I'd be interested to hear how it could be made better.
Here is my code thus far:
<Card className={classes.card}>
  <CardActionArea containerStyle={{ paddingBottom: 0 }}>
    <CardMedia
      className={classes.media}
      title="Contemplative Reptile"
      image="none"
    >

        <AccessAlarmIcon className={classes.icon}/>
        <Typography className={classes.mainText} variant="h5" component="h2">Delayed</Typography>
        <Typography className={classes.subText} variant="subtitle1" component="h5">9:30pm Departure</Typography>

    </CardMedia>
    <CardContent className={classes.content}>

    </CardContent>
  </CardActionArea>
</Card>

With these styles:
const styles = {
  card: {
    maxWidth: 300,
  },
  media: {
    height: 60,
    backgroundColor: "#FF1547",
    padding: 16
  },
  icon: {
    color: "white",
    fontSize: 25,
    marginRight: 10
  },
  mainText: {
    color: "white",
    display: "inline-block",
    position: "relative",
    top: -3
  },
  subText: {
    color: "white",
    marginLeft: 36,
  },
  heading: {
    padding: 0
  },
  mainPic: {
    width: 300,
    height: 200,
    marginBottom: 0,
    padding: 0
  },
  content: {
    padding: "0 !important",
    '&:last-child': {
      paddingBottom: "0 !important",
    },
  }
};

This is what it looks like when rendered:

Notice the bottom padding. The Chrome Developer Tools show a 3px bottom padding under the User Agent Stylesheet. I imported a CSS Reset which did not help.
Again, I'm sure that my styles and JSX could be made better, but efficiency, optimization, and elegance were not of my concern.
Thanks,
Jamie

A: That padding at the bottom is actually caused by the box-shadow styling tied to the "elevation" property of Paper (which Card is based on). Setting the elevation to 0 gets rid of it:
<Card className={classes.card} elevation={0}>

However that also gets rid of the raised look of the card. The correct way to deal with this is to specify the image in a CardMedia element rather than using a separate img tag inside a CardContent element.
<CardMedia
          className={classes.mainPic}
          image="http://images1.fanpop.com/images/image_uploads/Golden-Gate-Bridge-san-francisco-1020074_1024_768.jpg"
        />

Here's a CodeSandbox showing this:

You can also see this approach used in this demo:
https://material-ui.com/demos/cards/#ui-controls

A: See if this is what you want. I changed  mainPic and content.
This syntax containerStyle={{ paddingBottom: 0 }} does not seem correct even gets the alert in the browser. Maybe you want to change the styleor classes={{root}} of the api CardActionArea.
mainPic: {
  width: 300,
  marginBottom: 0,
  padding: 0,
  borderRadius: '0 0 4px 4px',

},
content: {
  height: 225,
  padding: "0 !important",
  '&:last-child': {
    paddingBottom: "0 !important",
  },
}


Q: Exception when adding new method in a working Service using gRPC-Web and protobuf-net I am getting the following exception:

Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: The type initializer for 'DefaultProxyCache1' threw an exception. System.TypeInitializationException: The type initializer for 'DefaultProxyCache1' threw an exception. ---> System.ArgumentException: Invalid generic arguments
Parameter name: typeArguments
at (wrapper managed-to-native) System.Reflection.RuntimeMethodInfo.MakeGenericMethod_impl(System.Reflection.RuntimeMethodInfo,System.Type[])
at System.Reflection.RuntimeMethodInfo.MakeGenericMethod (System.Type[] methodInstantiation) <0x342def8 + 0x000d6> in :0
at ProtoBuf.Grpc.Internal.ContractOperation.TryGetClientHelper () [0x0001b] in //src/protobuf-net.Grpc/Internal/ContractOperation.cs:291
at ProtoBuf.Grpc.Internal.ProxyEmitter.EmitFactory[TService] (ProtoBuf.Grpc.Configuration.BinderConfiguration binderConfig) [0x00477] in //src/protobuf-net.Grpc/Internal/ProxyEmitter.cs:238
at ProtoBuf.Grpc.Internal.ProxyEmitter.CreateFactory[TService] (ProtoBuf.Grpc.Configuration.BinderConfiguration binderConfig) [0x0006d] in //src/protobuf-net.Grpc/Internal/ProxyEmitter.cs:123
at ProtoBuf.Grpc.Configuration.ClientFactory+DefaultProxyCache`1[TService]..cctor () [0x00000] in //src/protobuf-net.Grpc/Configuration/ClientFactory.cs:81

My project uses gRPC-Web, Blazor web assembly and protobuf-net
This is my service contract:
[ServiceContract(Name = "Services.Customer")]
public interface ICustomerService
{
    ValueTask<Customer> CreateCustomer(Customer customerDTO);

    ValueTask<CustomerResultSet> GetCustomers();
}

The implementation is:
public class CustomerService : ICustomerService
{
    private readonly CustomerUseCases customerLogic;

    public CustomerService(CustomerUseCases customerLogic)
    {
        this.customerLogic = customerLogic;
    }

    public async ValueTask<Customer> CreateCustomer(Customer customerDTO)
    {
        var result = await customerLogic.CreateCustomer(customerDTO);

        return customerDTO;
    }

    public async ValueTask<CustomerResultSet> GetCustomers()
    {
        CustomerResultSet result = new CustomerResultSet { Customers = await customerLogic.GetCustomer() };
        return result;
    }
}

As for the Datacontracts:
[DataContract]
public class CustomerResultSet
{
    [DataMember(Order = 1)]
    public IEnumerable<Customer> Customers { get; set; }
}

And,
[DataContract]
public partial class Customer
{
    [DataMember(Order = 1)]
    public int CustomerId { get; set; }
    [DataMember(Order = 2)]
    public string CustomerName { get; set; }
}

Before I was returning a List of customers in the service but I realize I needed a class to model the message in order to protobuf-net be able to serialize that is why CustomerResultSet. Still, it is not working.
Any help much appreciated

A: That is... odd. I can't repro it here, so I'm guessing it is something specific to Blazor. I've checked what the code does in the "regular" frameworks, and at least for me it seems to do the right things - using UnaryValueTaskAsync<Customer, Customer>() and UnaryValueTaskAsync<Empty, CustomerResultSet>(), which is what I would expect. I've improved the exception handling in that code path, to at least give us a clue what it is trying to do, so my suggestion is:

*

*update to protobuf-net.Grpc version >= 1.0.119 (I'll get it deployed as soon as CI finishes)

*retry, and let me know exactly what it says now
Alternatively, if you have a minimal repro including the blazor bits on, say, a GitHub repo, I can happily take a look there.
(tip: I try to keep an eye on both Stack Overflow and GitHub, but GitHub is probably more appropriate for this kind of question - I'd happily say that this is a bug, so: https://github.com/protobuf-net/protobuf-net.Grpc/issues)

A: I was having a similar problem.
System.InvalidOperationException: Error obtaining client-helper 'UnaryValueTaskAsync' (from: 'System.Guid', to: 'Test.DTO.OpResult'): Invalid generic arguments
My entire ServiceContract on that service stopped working. This happened after I added
ValueTask ChangeCompany(Guid companyGuid);
I changed it to
ValueTask ChangeCompany(string companyGuid);
And that got it working again. The error was a bit confusing since i wasn't using ChangeCompany, but like a said, not calls were working.


Q: What is the input data structure for HERMES toolbox for EEG connectivity analysis? I wanted to use HERMES for connectivity analysis of my EEG dataset which includes 32 subjects and 40 trials for each subject. There are two conditions/classes. I do not know how my data should be defined to be known by HERMES!
Could you please kindly tell me what should the structure of input to HERMES be?
Or is there a better alternative like Brainstorm to use in my MATLAB scripts (I mean without using its GUI manually and do my connectivity analysis automatically by using loops instead)?
Any help in this regards is greatly appreciated.
HERMES toolbox
Brainstorm toolbox

A: HERMES accepts MAT files (*.mat) and Fieldtrip structures.
MAT files should consist on one single matrix with as many columns as channels and as many rows as temporal points (and, in the case of event-related data, the third dimension will be for the different trials).
For example, for one subject and condition: a matrix of (30 channels x 1000 samples (x 50 trials)).
Therefore, to be able to load your data easily, you'll need to obtain your MAT files as described above.
Thanks to Guiomar Niso for providing this answer.


Q: Error installing PATCH_SUPEE-9767_CE_1.9.3.0_v1-2017-05-25-09-09-56 on Magento 1.9.2.4 I'm getting the following error and have no idea why. All my extensions are properly installed to not effect any code code.
Any ideas?
sudo sh ./PATCH_SUPEE-9767_CE_1.9.3.0_v1-2017-05-25-09-09-56.sh
./PATCH_SUPEE-9767_CE_1.9.3.0_v1-2017-05-25-09-09-56.sh: 14: ./PATCH_SUPEE-9767_CE_1.9.3.0_v1-2017-05-25-09-09-56.sh: 127: not found
./PATCH_SUPEE-9767_CE_1.9.3.0_v1-2017-05-25-09-09-56.sh: 14: ./PATCH_SUPEE-9767_CE_1.9.3.0_v1-2017-05-25-09-09-56.sh: 127: not found
./PATCH_SUPEE-9767_CE_1.9.3.0_v1-2017-05-25-09-09-56.sh: 25: ./PATCH_SUPEE-9767_CE_1.9.3.0_v1-2017-05-25-09-09-56.sh: 0: not found
Checking if patch can be applied/reverted successfully...
-e ERROR: Patch can't be applied/reverted successfully.

checking file app/code/core/Mage/Admin/Model/Session.php
checking file app/code/core/Mage/Adminhtml/Block/Checkout/Formkey.php
checking file app/code/core/Mage/Adminhtml/Block/Notification/Symlink.php
checking file app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Date.php
checking file app/code/core/Mage/Adminhtml/Model/Config/Data.php
checking file app/code/core/Mage/Adminhtml/controllers/Catalog/Product/GalleryController.php
checking file app/code/core/Mage/Checkout/controllers/MultishippingController.php
checking file app/code/core/Mage/Checkout/controllers/OnepageController.php
Hunk #1 succeeded at 350 (offset 1 line).
Hunk #2 succeeded at 370 (offset 1 line).
Hunk #3 succeeded at 417 (offset 1 line).
Hunk #4 succeeded at 446 (offset 1 line).
Hunk #5 succeeded at 485 (offset 1 line).
checking file app/code/core/Mage/Checkout/etc/system.xml
checking file app/code/core/Mage/Cms/Model/Wysiwyg/Images/Storage.php
Hunk #1 succeeded at 282 (offset -1 lines).
checking file app/code/core/Mage/Core/Controller/Front/Action.php
checking file app/code/core/Mage/Core/Controller/Request/Http.php
checking file app/code/core/Mage/Core/Model/File/Validator/Image.php
checking file app/code/core/Mage/Core/etc/system.xml
checking file app/code/core/Mage/Customer/Model/Session.php
checking file app/code/core/Mage/Dataflow/Model/Convert/Adapter/Zend/Cache.php
checking file app/code/core/Mage/Dataflow/Model/Convert/Container/Abstract.php
checking file app/code/core/Mage/Dataflow/Model/Convert/Parser/Csv.php
checking file app/code/core/Mage/Dataflow/Model/Convert/Parser/Xml/Excel.php
checking file app/code/core/Mage/ImportExport/Model/Import/Uploader.php
checking file app/code/core/Mage/Sales/Model/Quote/Item.php
checking file app/code/core/Mage/Widget/Model/Widget/Instance.php
checking file app/code/core/Mage/XmlConnect/Helper/Image.php
checking file app/code/core/Mage/XmlConnect/controllers/Adminhtml/MobileController.php
checking file app/design/adminhtml/default/default/layout/main.xml
checking file app/design/adminhtml/default/default/template/notification/formkey.phtml
checking file app/design/adminhtml/default/default/template/notification/symlink.phtml
checking file app/design/adminhtml/default/default/template/page/head.phtml
checking file app/design/frontend/base/default/template/checkout/cart/shipping.phtml
checking file app/design/frontend/base/default/template/checkout/multishipping/billing.phtml
checking file app/design/frontend/base/default/template/checkout/multishipping/shipping.phtml
checking file app/design/frontend/base/default/template/checkout/onepage/billing.phtml
checking file app/design/frontend/base/default/template/checkout/onepage/payment.phtml
Hunk #1 succeeded at 35 (offset -1 lines).
checking file app/design/frontend/base/default/template/checkout/onepage/shipping.phtml
checking file app/design/frontend/base/default/template/checkout/onepage/shipping_method.phtml
checking file app/design/frontend/base/default/template/persistent/checkout/onepage/billing.phtml
checking file app/design/frontend/rwd/default/layout/page.xml
checking file app/design/frontend/rwd/default/template/checkout/cart/shipping.phtml
checking file app/design/frontend/rwd/default/template/checkout/multishipping/addresses.phtml
checking file app/design/frontend/rwd/default/template/checkout/multishipping/billing.phtml
checking file app/design/frontend/rwd/default/template/checkout/onepage/payment.phtml
Hunk #1 succeeded at 36 (offset -1 lines).
checking file app/design/frontend/rwd/default/template/checkout/onepage/shipping.phtml
checking file app/design/frontend/rwd/default/template/persistent/checkout/onepage/billing.phtml
checking file app/etc/config.xml
checking file app/locale/en_US/Mage_Adminhtml.csv
Hunk #1 succeeded at 1281 (offset -4 lines).
checking file app/locale/en_US/Mage_Core.csv
Hunk #1 succeeded at 406 (offset -1 lines).
checking file app/locale/en_US/Mage_Dataflow.csv
checking file app/locale/en_US/Mage_XmlConnect.csv
checking file downloader/Maged/Connect.php
Reversed (or previously applied) patch detected!  Assume -R? [n]
Apply anyway? [n]
Skipping patch.
3 out of 3 hunks ignored
checking file downloader/Maged/Controller.php
Reversed (or previously applied) patch detected!  Assume -R? [n]
Apply anyway? [n]
Skipping patch.
2 out of 2 hunks ignored
checking file downloader/Maged/Model/Session.php
Hunk #1 succeeded at 96 with fuzz 2 (offset 14 lines).
Hunk #2 succeeded at 302 with fuzz 2 (offset 29 lines).
checking file js/lib/jquery/jquery-1.12.0.js
checking file js/lib/jquery/jquery-1.12.0.min.js
checking file js/lib/jquery/jquery-1.12.0.min.map
checking file js/varien/payment.js
checking file skin/frontend/base/default/js/opcheckout.js
Hunk #1 succeeded at 711 (offset 27 lines).

A: The hunk error normally came because it will not match the file lines. In this case you can do 2 things.

*

*Replace those mention error files with new same version Magento setup and then try to install the patch using SSH.

*Install the patch manually.

In this patch in front end only form key is added in checkout and cart files so you can do it manually.
Thanks.

A: I had a similar issue.
The solution for me was next:

*

*Check if you have 'downloader' folder in your project, if not (usually it is not under git) - download it (better from the current project, versions can be different);

*Revert the previous version of this patch (description of the patch - "Note that you must revert SUPEE-9767 version 1 before deploying version 2.")
($ bash ./PATCH_SUPEE-9767_CE_1.9.3.0_v1-2017-05-25-09-09-56.sh -R)
and after that try to patch 2nd version.


Q: Tools to determine video orientation I receive videos from different devices and want to encode them using the correct orientation.
I've seen some of examples of how to determine the orientation of a video from a iPhone.
With exiftool and mediainfo I can indeed tell if an iPhone video has to be rotated.
However, for android videos, both portrait and landscape videos have the same rotation and matrix structure as each other.
Maybe this is just with my phone, I'm trying to find videos taken from newer droid phones.
My question however is whether there's other tools or a different way to determine the orientation that'll work with all devices.
EDIT:
I just checked a video from a Samsung Galaxy S II, and I can get the orientation from exiftool. So it's not a problem with all android phones.
My android phone is a HTC Desire running on android 2.2.
And actually (I didn't even notice before) a portrait video will not be correctly oriented even when playing on the phone. So I guess it's not about the tools, the orientation data just doesn't seem to be correct at all.

A: Some phones include the rotation information, some phone don't, but the best way to know on videos that include this information is with mediainfo:
mediainfo --Inform="Video;%Rotation%"


Q: assign process id to an asynchronous request tornado I would like to create consistent logs so that I can compute statistics on each tornado request, I have a request as below:
@tornado.web.asynchronous
    def post(self):
    try:
        process_id = uuid.uuid4()
        logging.info("Incoming request (process_id: %s) to %s" % (str(process_id), self.__class__.__name__))

which would print some info when a request comes in, but the request gets completed in tornado code, which would only print this:
[I 150331 10:55:09 web:1728] 200 POST /transform (127.0.0.1) 3017.19ms

Is there a way to pass my process id to tornado (or make it create one), so that I can connect the first and the last log events of a request?
thanks,

A: In general, the best way to record something like this is to attach it to the RequestHandler instance. For logging, you can override Application.log_request, which has access to the handler. You may need to pass either the request ID or the RequestHandler instance around to other parts of your code if you need to use this in multiple places.
It is possible but tricky to use StackContext as something like a threading.Local if you really need this to be pervasive, but explicitly passing it around is probably best.


Q: executing samtools in terminal: "command not found", but it is installed I have samtools installed, and I have used it before on my computer. I am trying to get it to work now, but when I type in samtools in terminal (mac os), it returns "command not found". I have navigated into my samtools folder too and it is still not working. Am i missing something? Thank you for your help


Q: Strange behaviour in Material datepicker I'm trying to use materialize date picker (http://materializecss.com/forms.html). With that, I want to popup the date picker when I click on an icon. I have implemented two implementations where the only difference between the two is putting an alert('clicked') with the code.
without the alert('clicked'): http://jsfiddle.net/1bnnkhbw/
with the alert('clicked'): http://jsfiddle.net/1bnnkhbw/1/
The second one works while the first one doesn't.. (in chrome)!!!
Anybody knows the reason for this behavior?
And a way to make the 1st one work?

A: I think I found a solution for you man check this out:
<i id="icon">click</i>
<input class="datepicker" style="display:none;" value="click"></input>

$('.datepicker').pickadate({
    selectMonths: true,
    selectYears: 15
  });

$('#icon').click(function(event){
    event.stopPropagation();
    $(".datepicker").first().pickadate("picker").open();
    console.log("test1");
});

Fiddle: http://jsfiddle.net/k2qtzp7p/1/
Code taken from here and here


Q: VBA define property in a variable I am new to the forum, and also new to VBA (only started learning it a week ago).
Is it possible to define a property in a variable? I have a line that looks kind of like this:
Cells(i, j).Formula = "=" & .Cells(i, j).Address(External:=True, RowAbsolute:=False, ColumnAbsolute:=False)

I have to write several cells, so I end up having many of these lines; if possible, I would like to do something like:
dim prop as string

prop = "Address(External:=True, RowAbsolute:=False, ColumnAbsolute:=False)"

Cells(i, j).Formula = "=" & .Cells(i, j).prop

Can something like this be done?

A: You mean like this?
Function MyProp(ByVal r as Range) as String
    MyProp = r.Address(External:=True, RowAbsolute:=False, ColumnAbsolute:=False)
End Function

...
Cells(i,j).Formula = "="& MyProp( Cells(i,j) )

This of course makes a cell reference itself, which is generally a bad idea and may lead to circular references. Best if you describe more on what you are trying to do in order to get better answers.

A: As mentioned in the comments this cannot be done in the way you describe.  There are two alternatives:

*

*Write a Private Function that you call with your input and expected output (more complicated)

*Write a loop with the code only appearing once. (less code)

To write a loop for all cells from A1 to Last used row, last used column:
Dim LastRow As Long, LastCol As Long

LastRow = Range("A" & Rows.Count).End(xlUp).Row
LastCol = Cells(1, Columns.Count).End(xlToLeft).Column

For i = 1 To LastRow
    For j = 1 to LastCol
        `Do your stuff here
    Next j
Next i

Edit:
I'm going to assume you need to invest in the Range.Offset() method found here because right now, you are setting the cell's formula as equal to itself...


Q: How to build lighter version of opencv_java3 for android? I'm following these lines to build OpenCV's libraries for Android.
Usage Linux:
$ export ANDROID_NDK=/absolute/path/to/the/android-ndk
$ mkdir build && cd build
$ cmake -DCMAKE_TOOLCHAIN_FILE=path/to/the/android.toolchain.cmake ..
$ make -j8

The built libopencv_java3.so file for one architecture (armeabi-v7a) is 8.3MB large.
Is there a way to omit some unused modules on build to get lighter libraries ?


Q: Outlook + Perl + Win32::Ole: How do you select calendar entries sorted by date? Current code opens up an Outlook Calendar database as follow:
my $outlook = Win32::OLE->GetActiveObject('Outlook.Application') || Win32::OLE->new('Outlook.Application', 'Quit');

my $namespace = $outlook->GetNamespace("MAPI");

## only fetch entries from Jan 1, 2007 onwards
my $restrictDates = "[Start] >= '01/01/2007'";

A: Since you don't show the code that gets the date of your object, this question is impossible to answer without some knowledge of the Outlook object you are trying to access.
If you have an array of objects you can sort them by date and filter ones prior to a certain one.
my $sub = sub {
       my $ad = $a->date_string_accessor;
       my $bd = $b->date_string_accessor;
       $ad =~ s:(\d+)/(\d+)/(\d+):$3 . sprintf('%0d', $1) . sprintf('%0d', $2):e;
       $bd =~ s:(\d+)/(\d+)/(\d+):$3 . sprintf('%0d', $1) . sprintf('%0d', $2):e;
       return $ad cmp $bd;
};

my @sorted = sort $sub @unsorted;

print join("\n", @sorted);

But it would seem to me that you should use the application itself to do this -- presumably Outlook has some sort of query/sort functionality.


Q: How to compress a size of 1024*1024*1024*4 sparse array I have a sparse array which is size of 1024 * 1024 * 1024 * 4.  This array's item is byte. So the memory for the array is 4G. It is a sparse array, that is, non-zero item only about 600M. Hopefully, a storage structure can be proposed to compress the sparse array (compressed to 2 ~ 3G), and have good access speed.

A: The suitable representation depends on what operations is desired on the sparse array. The general approach is to store the locations of non-zero items and their values in a data structure.
One option is to use a hash table.
enum {NumDimensons = 4};
struct ArrayLocation {
  int16_t location[NumDimensions];
};

typedef uint8_t ArrayValue;

// Hash Table with key as ArrayLocation and value as ArrayValue

With hash table operations like get() and put() are straightforward, but iteration is not. If iteration is important, one option is to use a binary search tree.


Q: GCDWebServer always aborts on options check I started using GCDWebServer version 3.1 in an app last year, and this line in the addHandlerWithMatchBlock method of GCDWebServer.m always caused the system to abort immediately:
GWS_DCHECK(_options == nil);

I ended up just changing it to this to avoid the problem:
GWS_DCHECK(_options != nil);

Now I'm updating to the latest version 3.3.2 and see the same problem. My hack still works here, but I would like to know what a real solution would be. Can someone explain?

A: See docs in header:

Addling handlers while the server is running is not allowed.

Attempting to do this will result in undefined behavior.


Q: Sql Group by datetime I have a MySql table :
+--------------------+----------------+
| datetime           | energy         |
+--------------------+----------------+
| 2010-06-15 10:00:00|               1|
| 2010-06-15 10:15:00|               3|
| 2010-06-15 10:30:00|               6|
| 2010-06-15 10:45:00|               7|
| 2010-06-15 11:00:00|               9|
| 2010-06-15 11:15:00|              12|
| 2010-06-15 11:30:00|              15|
| 2010-06-15 11:45:00|              28|
| 2010-06-15 12:00:00|              52|
| 2010-06-15 12:15:00|              75|
| 2010-06-15 12:30:00|              88|
| 2010-06-15 12:45:00|             102|
| 2010-06-15 13:00:00|             150|
| 2010-06-15 13:15:00|             189|
| 2010-06-15 13:30:00|             200|
| 2010-06-15 13:45:00|             205|
| 2010-06-15 14:00:00|             209|
| 2010-06-15 14:15:00|             400|
| 2010-06-15 14:30:00|             450|
| 2010-06-15 14:45:00|             480|
| 2010-06-15 15:00:00|             500|
+--------------------+----------------+

I would obtain the production of every hour as difference between max and min of every hour:
example:
production of hour 10 is given by prod. of hour 11 (value = 9)  less production of hour 10 (value = 1)  -> result = 8
Expected result
+--------------+----------------+
| datetime     | energy         |
+--------------+----------------+
| 2010-06-15 10|               8|
| 2010-06-15 11|              43|
| 2010-06-15 12|              98|
| 2010-06-15 13|              69|
| 2010-06-15 14|             291|
+--------------+----------------+

select max(energy) - min(energy)
FROM tableA
group by hour(datetime)

this query doesn't work because make the difference between 10:45 and 10:00 ( not 11:00 and 10:00)
Any advice ?

A: To get the difference between each hour, use a self-join that relates times that are an hour apart.
SELECT a.datetime, b.energy - a.energy AS energy
FROM tableA AS a
JOIN TableA AS b ON a.datetime = DATE_SUB(b.datetime, INTERVAL 1 HOUR)
WHERE MINUTE(a.datetime) = 0

DEMO

A: EXAMPLE WITH MISSING DATA
+--------------------+----------------+
| datetime           | energy         |
+--------------------+----------------+
| 2010-06-15 10:00:00|               1|
| 2010-06-15 10:45:00|               7|
| 2010-06-15 11:00:00|               9|
| 2010-06-15 11:15:00|              12|
| 2010-06-15 11:30:00|              15|
| 2010-06-15 11:45:00|              28|
| 2010-06-15 12:15:00|              75|
| 2010-06-15 12:30:00|              88|
| 2010-06-15 12:45:00|             102|
| 2010-06-15 13:00:00|             150|
| 2010-06-15 13:15:00|             189|
| 2010-06-15 13:30:00|             200|
| 2010-06-15 13:45:00|             205|
| 2010-06-15 14:00:00|             209|
| 2010-06-15 14:15:00|             400|
| 2010-06-15 14:30:00|             450|
| 2010-06-15 14:45:00|             480|
| 2010-06-15 15:00:00|             500|
+--------------------+----------------+
In this example some samples are missing.
Expected result:
+--------------+----------------+
| datetime     | energy         |
+--------------+----------------+
| 2010-06-15 10|               8|  11:00 to 10:00
| 2010-06-15 11|              17|  11:45 to 11:00
| 2010-06-15 12|             150|  13:00 to 12:15
| 2010-06-15 13|              69|  13:00 to 14:00
| 2010-06-15 14|             291|  14:00 to 15:00
+--------------+----------------+
I always want to group by a complete hour:
From 10:00 to 11:00 included
From 11:00 to 12:00 included
From 12:00 to 13:00 included
ecc....
immagine


Q: Dyamically Assign JSON Property by Depth I would like to assign a variable on a json object by layers of depth.
For Example:
veryDeepTree[branch][branch][branch][branch] = value

would be achieved by executing the function:
assignByDepth(4, value, branch)

A: One way you can do this is by using a recursive function. Where each iteration of the function goes 1 level deeper until it reaches the desired level to set the value. This is a basic version assuming objects exists with correct depth before calling the function. As it is now, there can be multiple errors if used incorrectly, should be amended to add more error checks.

var veryDeepTree = {
    branch : {
       branch : {
          branch : {
          }
       }
    }
};

function assignByDepth(subTree, currentTreeDepth, objProperty, value){
   if(currentTreeDepth == 1){
      subTree[objProperty] = value;
   }else{
      assignByDepth(subTree[objProperty], --currentTreeDepth, objProperty, value);
   }
}

assignByDepth(veryDeepTree, 3, "branch", {branch:10});
console.log(veryDeepTree);

assignByDepth(veryDeepTree, 4, "branch", 5555);
console.log(veryDeepTree);


Q: Error Eclipse Project library see my screen :
http://it.tinypic.com/r/xpa240/8
I can not fix these errors. It seems that it does not generate the class R.
I've tried everything!
Clean the project,
Install all tools
help me thanks

A: The R class is generated automatically by the Android Eclipse plugin when it can. Here, I can see a red cross on your "res" folder so I think you should have some errors on your resources naming or type or something else : just look what your IDE is telling you !
Fix all errors that are not "R class missing" related and this class will be generated.

A: try this :
1 - File->Import (android-sdk\extras\android\support\v7). Choose "appcompat"
2 - Project-> properties->Android. In the section library "Add" and choose "appCompat"
3 - That is all!


Q: Integer array of resource ids returns 0 I have a set of resource ids stored in an array. This is accessed inside the recycler view to populate an image view. The problem is when I access the array, all values returned is 0.
// arrays.xml
<array name="array_category_icons">
    <item>@drawable/autumn</item>
    <item>@drawable/backpack</item>
</array>

// inside recycler view adapter
int[] myIcons = getActivity().getResources().getIntArray(R.array.array_category_icons);

myIcons[i] always returns 0.

The drawables are in the hdpi folder only.

A: Do this:
TypedArray ta = getResources().obtainTypedArray(R.array.array_category_icons);
Drawable[] icons = new Drawable[ta.length()];
for (int i = 0; i < ta.length(); i++) {
    int id = ta.getResourceId(i, 0);
    if (id != 0) {
        icons[i] = ContextCompat.getDrawable(this, id);
    }
}
ta.recycle();


Q: Saving the current data before updating the form in Django I would like to create a history of changes in one of my models. That every time I will update it, the current data will be saved to a different table and at the same time, the new data enters to another table. How will I be able to do that? I saw examples and they are based from the admin. But I still don't get the idea of it. This maybe a noob question but I'm still learning Django.
models.py
class tblTicket(models.Model): #new data will be entered here
    remarks = models.TextField("Action Taken", max_length=500,default='')
class LogChanges(models.Model): #table to save the changes
    prevRemarks = models.CharField(max_length=500,default='')

forms.py
class troubleTicket(ModelForm):
    class Meta:
        model = tblTicket
        fields = '__all__'

class history(ModelForm):
    class Meta:
        model = LogChanges
        fields = '__all__'

views.py
def updateTicket(request, ticket_id):
    ticketDetails=tblTicket.objects.get(id=ticket_id)
    updateTicketForm = troubleTicket(request.POST or None,instance=ticketDetails)
    if updateTicketForm.is_valid():
        updateTicketForm.save()
        return HttpResponseRedirect('/ticket/')
    return render(request,'updateTicket.html', {'updateTicketForm':updateTicketForm,'ticketDetails':ticketDetails,'ticket_id':ticket_id})

I am using django 1.8.3

UPDATE:
I found a link related to my question. But it gives me an error NameError: name 'tblTicket' is not defined
def make_copy(sender, **kwargs):
    obj = kwargs['instance']
    try:
        orig_obj = tblTicket.objects.get(pk=obj.pk)
    except: #If it is a new object
        orig_obj = None

pre_save.connect(make_copy, sender=tblTicket) <- this is where the error leads me

To my understanding, in this link, the Country there is the model. So I switched it to my model which is tblTicket. I don't understand why it isn't defined.

A: cIt sounds like you want to override the save method of your tblTicket model so that it creates a new LogChanges object. Like this..
class tblTicket(models.Model):
    ...

    def save(self):
        super(tblTicket, self).save()
        LogChanges.objects.create(prevRemarks=self.remarks)


Q: How to update ProgressBar with respect to downloaded data while downloading text data from web using Asynctask in android I want to show progressbar wrt to downloaded data from the web. Whether I have to create dynamically or have to reference by Id by creating it in xml.I am a little bit confused. Here is my code. Could you please tell me how?
package com.example.telugumovies;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

public class MainActivity extends ListActivity {
String category ="";
String[] cat = {"Upcoming","Telugu"};
private List<String> categories ;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    categories = new ArrayList<String>();
    int i=0;
    for(i=0;i<2;i++)
    {
        categories.add(cat[i]+" Movies");
    }
    ArrayAdapter<String> myAdapter = new ArrayAdapter <String>(this,
            R.layout.listview_rowlayout, R.id.tv, categories);

     // assign the list adapter
     setListAdapter(myAdapter);
}
 // when an item of the list is clicked
@Override
protected void onListItemClick(ListView list, View view, int position, long id) {
    super.onListItemClick(list, view, position, id);
    Bundle giveCategory = new Bundle();
    if(position == 0)
    {
        try {
            new GetData().execute();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally
        {
        }
    }
    else if(position == 1)
    {
        giveCategory.putString("cate", cat[position]);
        Intent a = new Intent(MainActivity.this,Show_Years.class);
        a.putExtras(giveCategory);
        startActivity(a);

    }
    else
    {
        Toast.makeText(getApplicationContext(), "Sorry This option is not Available for Now ",
               Toast.LENGTH_SHORT).show();
    }
    //String selectedItem = (String) getListView().getItemAtPosition(position);

}

class GetData extends AsyncTask<String,Integer,String>
{
    ProgressBar pb ;
    protected void onPreExecute()
    {
        pb = new ProgressBar(MainActivity.this);
        pb.setVisibility(View.VISIBLE);
    }
    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub
        String alldata = "";
        int flag=1;
        String data = "";
          URL url = null;
          int i=0,j=0,count=0,c=0;
          URLConnection con = null;
          InputStream is = null;
          String line = null;
        try
        {
            url = new URL("http://www.filmibeat.com/telugu/upcoming-movies.html");
            con = url.openConnection();
            is = con.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            while ((line = br.readLine()) != null) {
               //System.out.println(line);
                alldata = "";
                flag=0;
                if(line.contains("<h3"))
                {j=0;
                flag=1;
                    for(i=0;i<line.length();i++)
                {
                    if(line.charAt(i)=='<')
                    {
                        j=1;
                    }
                    else if(j==1 && line.charAt(i)=='>')
                    {
                        j=0;
                    }
                    else if(j==0)
                    {
                        alldata = alldata + (line.charAt(i));
                    }
                }
                }
                data=data+alldata;
                if(flag==1)
                {
                data=data+"$";
                }

        }
            System.out.println(data);
            return data;
        }
            catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally
        {
            return data;
        }
        }
    protected void onPostExecute(String someting)
    {
        Bundle givedata = new Bundle();
        givedata.putString("moviedata",someting);
        Intent a = new Intent(MainActivity.this,Show_upcomingmovies.class);
        a.putExtras(givedata);
        pb.setVisibility(View.INVISIBLE);
        startActivity(a);
    }
    }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

A: Using dynamically created progress bar or referencing it from an id, are both fine.
Using a reference from XML allows you to have more control on the progress bars appearance, as you would have designed it sepcifically for your need (like appearance, where it has to appear, etc..). But if that is not the case, you can use a dynamically created one as in your current code as well.

A: There is a lot of ways. One is to define ProgressDiaolog as a field in your AsyncTask, then add it to your onPreExecuted():
pDialog = new ProgressDialog(this);
pDialog.setMessage("some downloading massage");
pDialog.setIndeterminate(false);
pDialog.setMax(100); //you can adjust this
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(false);
pDialog.show();

Then you can update the progress by override updateProgress() in your AsyncTask and call pDialog.setProgress();


Q: App crashes with storage exception,while dealing with images in firebase storage Following is my piece of code.
this code runs in a loop for many images and images are shown( the whole code runs as expected).
and suddenly app crashes with this error.

Error:: StorageException: StorageException has occurred.
                                                       Object does not exist at location.
                                                        Code: -13010 HttpResult: 404

And no line of my code is directed for the cause of the error.
StorageReference storageRef = FirebaseStorage.getInstance().getReferenceFromUrl("storage_location");
StorageReference pathReference = storageRef.child("imgPath");
pathReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
    @Override
    public void onSuccess(Uri uri) {
        holder.ivIcon2.setImageUrl(uri.toString(), MySingleton.getInstance(activity).getImageLoader());

    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception e) {
        Log.d("tag", e.toString());
    }
});

Don't have any idea of the origin of the issue.
Deleting and reuploading all the images in Storage solve the problem for the time.


Q: Cannot access a disposed Object C# I am having a hard time. I am new to this. Can someone help me with this. Every time I call the _clientSocket.Close(); I got an error message.

Cannot access a disposed object. Object name:
  System.net.Sockets.Socket

There's no error in my code. It can run smooth but every time I open and close a form it comes up. I want to get rid of it. The program can run with it but its to irritating. Because when I try to open a client it will pop up. And when the time of the client is done, the form will close and the login will come out with another pop up of

Cannot access a disposed object. Object name:
  System.net.Sockets.Socket

I use _clientSocket.Close() because if I'm not closing the sockets it will be doubled in Server side. I close it so it will not be double IP in Checklistbox of the Server.
I'm doing this for my project and I'm just studying myself so some of the comments I really don't understand but I'm trying my best to learn from it thank you!
Your suggestions will much appreciated. Correct me if I'm wrong thank you!
This code is the Loginform when Server sends -O it will _clientSocket.Close(); and open the Form2. If Form2 use all the time it will back to Loginform and form2 _clientSocket.Close(); I call the _clientSocket.Close(); because the Server Checklistbox that catches all the connected sockets will be doubled if I don't close the Sockets.
Edited
Server
namespace RealVersion2
{
        public partial class Server : Form
        {
            public class SocketT2h
            {
                public Socket _Socket { get; set; }
                public string _Name { get; set; }
                public SocketT2h(Socket socket)
                {
                    this._Socket = socket;
                }
            }
            private byte[] _buffer = new byte[1024];
            public List<SocketT2h> __ClientSockets { get; set; }
            List<string> _names = new List<string>();
            private Socket _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            public Server()
            {
                InitializeComponent();
                CheckForIllegalCrossThreadCalls = false;
                __ClientSockets = new List<SocketT2h>();
                this.list_Client.SelectionMode = System.Windows.Forms.SelectionMode.None;
            }

            private void Send_Click(object sender, EventArgs e)
            {
                {
                    for (int i = 0; i < list_Client.CheckedItems.Count; i++)
                    {
                        string t = list_Client.CheckedItems[i].ToString();
                        for (int j = 0; j < __ClientSockets.Count; j++)
                        {
                            if (__ClientSockets[j]._Socket.Connected && __ClientSockets[j]._Name.Equals("@" + t))
                            {
                                Sendata(__ClientSockets[j]._Socket, "Server: " );
                            }
                            else
                            {

                                Sendata(__ClientSockets[j]._Socket, "Server: " + txt_Text.Text);
                            }

                        }
                    }
                    rich_Text.AppendText("\nServer: " + txt_Text.Text);
                    txt_Text.Text = "";
                }
            }
                    void Sendata(Socket socket, string noidung)
            {
                byte[] data = Encoding.ASCII.GetBytes(noidung);
                socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket);
                _serverSocket.BeginAccept(new AsyncCallback(AppceptCallback), null);
            }
            private void SendCallback(IAsyncResult AR)
            {
                Socket socket = (Socket)AR.AsyncState;
                socket.EndSend(AR);
            }
            private void SetupServer()
            {
                try
                {
                    lb_stt.Text = "Setting up server . . .";
                    _serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8000));
                    _serverSocket.Listen(1);
                    _serverSocket.BeginAccept(new AsyncCallback(AppceptCallback), null);
                }

                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            private void AppceptCallback(IAsyncResult ar)
            {
                Socket socket = _serverSocket.EndAccept(ar);
                __ClientSockets.Add(new SocketT2h(socket));
                list_Client.Items.Add(socket.RemoteEndPoint.ToString());

                lb_soluong.Text = "Number of clients connected: " + __ClientSockets.Count.ToString();
                lb_stt.Text = "Client connected. . .";
                socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
                _serverSocket.BeginAccept(new AsyncCallback(AppceptCallback), null);
            }

            private void ReceiveCallback(IAsyncResult ar)
            {

                           Socket socket = (Socket)ar.AsyncState;
                if (socket.Connected)
                {
                    int received;
                    try
                    {
                        received = socket.EndReceive(ar);
                    }
                    catch (Exception)
                    {
                        // client close connection
                        for (int i = 0; i < __ClientSockets.Count; i++)
                        {
                            if (__ClientSockets[i]._Socket.RemoteEndPoint.ToString().Equals(socket.RemoteEndPoint.ToString()))
                            {
                                //taga tapoon ng panget
                                list_Client.Items.RemoveAt(i);
                                __ClientSockets.RemoveAt(i);
                                lb_soluong.Text = "Number of clients connected: "+__ClientSockets.Count.ToString();
                            }

                        }
                        //delete in list
                        return;
                    }
                    if (received!=0)
                    {
                        byte[] dataBuf = new byte[received];
                        Array.Copy(_buffer, dataBuf, received);
                        string text = Encoding.ASCII.GetString(dataBuf);
                        //lb_stt.Text = "Text received: " + text;

                        string reponse = string.Empty;
                        //reponse = "Server: Hi! You're Connected to the Librarian.";

                            if (text.Contains("@@"))
                        {
                            for (int i = 0; i < list_Client.Items.Count; i++)
                            {
                                if (socket.RemoteEndPoint.ToString().Equals(__ClientSockets[i]._Socket.RemoteEndPoint.ToString()))
                                {
                                    list_Client.Items.RemoveAt(i);
                                    list_Client.Items.Insert(i, text.Substring(1, text.Length - 1));
                                    __ClientSockets[i]._Name = text;
                                    socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
                                    return;
                                }

                            }
                        }

                        for (int i = 0; i < __ClientSockets.Count; i++)
                        {
                            if (socket.RemoteEndPoint.ToString().Equals(__ClientSockets[i]._Socket.RemoteEndPoint.ToString()))
                            {
                                rich_Text.AppendText("\n" + __ClientSockets[i]._Name + ": " + text);
                            }
                        }

                    }
                    else
                    {
                        for (int i = 0; i < __ClientSockets.Count; )
                        {
                            if (__ClientSockets[i]._Socket.RemoteEndPoint.ToString().Equals(socket.RemoteEndPoint.ToString()))
                            {
                                __ClientSockets.RemoveAt(i);
                                lb_soluong.Text ="The number of clients connected: " + __ClientSockets.Count.ToString();
                            }
                        }
                    }
                }
                    socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
            }

            private void tabPage1_Click(object sender, EventArgs e)
            {

            }

            private void Server_Load(object sender, EventArgs e)
            {
                SetupServer();
            }

            private void Restartbtn_Click(object sender, EventArgs e)
            {
                string Restart = string.Empty;
                Restart = "-r";
                {
                    for (int i = 0; i < list_Client.CheckedItems.Count; i++)
                    {
                        string t = list_Client.CheckedItems[i].ToString();
                        for (int j = 0; j < __ClientSockets.Count; j++)
                        {
                            if (__ClientSockets[j]._Socket.Connected && __ClientSockets[j]._Name.Equals("@" + t))
                            {
                                Sendata(__ClientSockets[j]._Socket, "Server: " + Restart);
                            }
                        }
                    }
                    rich_Text.AppendText("\nServer: " + txt_Text.Text);
                }
            }

            private void Shutdownbtn_Click(object sender, EventArgs e)
            {
                string Shutdown = string.Empty;
                Shutdown = "-s";
                {
                    for (int i = 0; i < list_Client.CheckedItems.Count; i++)
                    {
                        string t = list_Client.CheckedItems[i].ToString();
                        for (int j = 0; j < __ClientSockets.Count; j++)
                        {
                            if (__ClientSockets[j]._Socket.Connected && __ClientSockets[j]._Name.Equals("@" + t))
                            {
                                Sendata(__ClientSockets[j]._Socket, "Server: " + Shutdown);
                            }
                        }
                    }
                    rich_Text.AppendText("\nServer: " + txt_Text.Text);
                }
            }

            private void list_Client_SelectedIndexChanged(object sender, EventArgs e)
            {
                for (int i = 0; i < list_Client.Items.Count; i++)
                {

                    if (list_Client.GetItemRectangle(i).Contains(list_Client.PointToClient(MousePosition)))
                    {
                        switch (list_Client.GetItemCheckState(i))
                        {
                            case CheckState.Checked:
                                list_Client.SetItemCheckState(i, CheckState.Unchecked);
                                break;
                            case CheckState.Indeterminate:
                            case CheckState.Unchecked:
                                list_Client.SetItemCheckState(i, CheckState.Checked);
                                break;
                        }

                    }

                }
            }

            private void openPCToolStripMenuItem_Click_1(object sender, EventArgs e)
            {
                string Open = string.Empty;
                Open = "-O";
                {
                    for (int i = 0; i < list_Client.CheckedItems.Count; i++)
                    {
                        string t = list_Client.CheckedItems[i].ToString();
                        for (int j = 0; j < __ClientSockets.Count; j++)
                        {
                            if (__ClientSockets[j]._Socket.Connected && __ClientSockets[j]._Name.Equals("@" + t))
                            {
                                Sendata(__ClientSockets[j]._Socket, "Server: " + Open);
                                //use [i] if u dont want name in list
                            }
                        }
                    }
                    //rich_Text.AppendText("\nServer: " + txt_Text.Text);
                }
                }

            private void Server_FormClosing(object sender, FormClosingEventArgs e)
            {
                string Ext = string.Empty;
                Ext = "exit";
                {
                    for (int i = 0; i < list_Client.CheckedItems.Count; i++)
                    {
                        string t = list_Client.CheckedItems[i].ToString();
                        for (int j = 0; j < __ClientSockets.Count; j++)
                        {
                            if (__ClientSockets[j]._Socket.Connected && __ClientSockets[j]._Name.Equals("@" + t))
                            {
                                Sendata(__ClientSockets[j]._Socket, "Server: " + Ext);
                            }
                        }
                    }
                    //rich_Text.AppendText("\nServer: " + txt_Text.Text);
                    Application.Exit();
                    _serverSocket.Close();
                }
            }

            private void End_Click(object sender, EventArgs e)
            {
                string Ext = string.Empty;
                Ext = "close";
                {
                    for (int i = 0; i < list_Client.CheckedItems.Count; i++)
                    {
                        string t = list_Client.CheckedItems[i].ToString();
                        for (int j = 0; j < __ClientSockets.Count; j++)
                        {
                            if (__ClientSockets[j]._Socket.Connected && __ClientSockets[j]._Name.Equals("@" + t))
                            {
                                Sendata(__ClientSockets[j]._Socket, "Server: " + Ext);
                            }
                        }
                    }
                    //rich_Text.AppendText("\nServer: " + txt_Text.Text);
                }
            }

        }
    }

Client
public partial class UserLog : Form
{

    private Socket _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    TimeSpan countdownClock = TimeSpan.Zero;

    public UserLog()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        string Username = "User";
        string Pass = "123";

        if (Username == textBox1.Text && Pass == textBox2.Text)

        {
            MessageBox.Show("Login Successfully");
            Usertimer User = new Usertimer(textBox1.Text);
            User.Show();
            this.Hide();
            _clientSocket.Dispose();
            _clientSocket.Close();

        }
        else
        {
            MessageBox.Show("Please Enter valid Username or Password");
        }
    }

    byte[] receivedBuf = new byte[1024];
    protected override void OnClosing(CancelEventArgs e)
    {
        base.OnClosing(e);
        if (_clientSocket != null && _clientSocket.Connected)
        {
            _clientSocket.Close();
        }
    }

    private void ReceiveData(IAsyncResult ar)
    {

        try
        {
            int received = _clientSocket.EndReceive(ar);
            if (received == 0)
            {
                return;
            }

            Array.Resize(ref receivedBuf, received);
            string text = Encoding.Default.GetString(receivedBuf);
            Array.Resize(ref receivedBuf, _clientSocket.ReceiveBufferSize);
            AppendtoTextBox(text);

            if (text == "Server: -O")
            {

                Thread NT = new Thread(() =>
                {
                    this.BeginInvoke((Action)delegate ()
                    {

                         textBox1.Text = "Guest";
                         this.Hide();
                        _clientSocket.Close();
                        Usertimer us = new Usertimer(textBox1.Text);
                us.Show();

                    });

                });
                NT.Start();

            }
            if (text == "Server: exit")
            {
                _clientSocket.Close();
                Application.Exit();

            }

            _clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), null);

        }

        catch (ObjectDisposedException ex)
        {
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

    }

    private void AppendtoTextBox(string text)
    {
        MethodInvoker invoker = new MethodInvoker(delegate
        {
            textBox4.Text += text + "\r\n";

        });
        this.Invoke(invoker);
    }
    private void LoopConnect()
    {
        int attempts = 0;
        while (!_clientSocket.Connected)
        {
            try
            {
                attempts++;
                _clientSocket.Connect(IPAddress.Parse(textBox5.Text), 8000);
                //_clientSocket.Connect(IPAddress.Parse(textBox4.Text), 100);

            }
            catch (SocketException)
            {
                //Console.Clear();
                lb_stt.Text = ("Connection attempts: " + attempts.ToString());
            }
        }
        AppendtoTextBox(reponse);
    }

    private void button2_Click(object sender, EventArgs e)
    {
        LoopConnect();
        // SendLoop();
        _clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), _clientSocket);
        byte[] buffer = Encoding.ASCII.GetBytes("@@"+txName.Text);
        _clientSocket.Send(buffer);
    }

    private void UserLog_Load(object sender, EventArgs e)
    {
        LoopConnect();
        _clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), _clientSocket);
        byte[] buffer = Encoding.ASCII.GetBytes("@@"+txName.Text);
        _clientSocket.Send(buffer);
    }

    private void UserLog_FormClosed(object sender, FormClosedEventArgs e)
    {
        Application.Exit();
    }
}

}
Form2 of the client
    public partial class Usertimer : Form
    {
        private Socket _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        public Usertimer(string pass)
        {
            InitializeComponent();
            label3.Text = pass;

        }

        byte[] receivedBuf = new byte[1024];
        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            this.btnConnect_Click(null, null);
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            base.OnClosing(e);
            if (_clientSocket != null && _clientSocket.Connected)
            {
                _clientSocket.Close();
            }
        }
        private void ReceiveData(IAsyncResult ar)
        {
            try
            {
                int received = _clientSocket.EndReceive(ar);
                if (received == 0)
                {
                    return;
                }

                Array.Resize(ref receivedBuf, received);

                string text = Encoding.Default.GetString(receivedBuf);

                if (text == "Server: close")
                {
                    Thread NT = new Thread(() =>
                    {
                        this.BeginInvoke((Action)delegate ()
                        {

                            UserLog Log = new UserLog();
                            Log.Show();
                            this.Close();
                            _clientSocket.Close();

                        });

                    });
                    NT.Start();

                }

                Array.Resize(ref receivedBuf, _clientSocket.ReceiveBufferSize);
                AppendtoTextBox(text);
                _clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void AppendtoTextBox(string text)
        {
            MethodInvoker invoker = new MethodInvoker(delegate
            {
                richTextBox1.Text += text + "\r\n";

            });
            this.Invoke(invoker);
        }

        private void LoopConnect()
        {
            int attempts = 0;
            while (!_clientSocket.Connected)
            {
                try
                {
                    attempts++;
                    _clientSocket.Connect(IPAddress.Parse(textBox4.Text), 8000);

                }
                catch (SocketException)
                {
                    //Console.Clear();
                    lb_stt.Text = ("Connection attempts: " + attempts.ToString());
                }
            }
            AppendtoTextBox(reponse);
        }
        private void btnConnect_Click(object sender, EventArgs e)
        {
            LoopConnect();
            // SendLoop();
            _clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), _clientSocket);
            byte[] buffer = Encoding.ASCII.GetBytes("@@" + txName.Text);
            _clientSocket.Send(buffer);
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            if (_clientSocket.Connected)
            {

                byte[] buffer = Encoding.ASCII.GetBytes(txt_text.Text);
                _clientSocket.Send(buffer);
                AppendtoTextBox(txName.Text + ": " + txt_text.Text);
            }
            txt_text.Text = "";

        }

        private void button1_Click(object sender, EventArgs e)
        {
            UserLog log = new UserLog();
            log.Show();
            this.Close();
            _clientSocket.Close();
        }
    }
}

A: Like I answered in your previous question, you should spend the time to read these two pages. They will help you get your answer much faster.

There's no error in my code.

If you're getting an error message, then there's an error in your code.

every time I open and close a form

What form? There is no form in your example.

it will be doubled in Server side. I close it so it will not be double IP in Checklistbox of the Server.

What server? What checklistbox? We don't know what you are referring to here.
Without a minimal, complete and verifiable example, we can't help you very well. That being said, it looks like you are closing your _clientSocket. Once you've closed a socket you must re-open it or create a new one before you can use it again. You cannot call BeginReceive after you've closed your socket.
I was able to reproduce your error by creating a complete, minimal and verifiable example. Here is the code:
   public partial class Form1 : Form
    {
        Socket _clientSocket;
        public Form1()
        {
            InitializeComponent();
        }

        const int buffSize = 1024;
        byte[] receivedBuf = new byte[buffSize];
        Socket listenerSock;
        Socket handlerSock;

        private void Form1_Load(object sender, EventArgs e)
        {
            IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

            listenerSock = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            listenerSock.Bind(localEndPoint);
            listenerSock.Listen(10);
            listenerSock.BeginAccept(ServerAcceptAsync, null);
            _clientSocket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            _clientSocket.Connect(localEndPoint);
            _clientSocket.BeginReceive(receivedBuf, 0, buffSize, SocketFlags.None, ReceiveData, null);
        }

        private void ServerAcceptAsync(IAsyncResult ar)
        {
            handlerSock = listenerSock.EndAccept(ar);
        }

        private void ReceiveData(IAsyncResult ar)
        {
            //try
            //{
            Debug.WriteLine("received data");
                int received = _clientSocket.EndReceive(ar);
                if (received == 0)
                {
                    return;
                }
                Array.Resize(ref receivedBuf, received);
                string text = Encoding.Default.GetString(receivedBuf);
            Debug.WriteLine(text);
                if (text == "Server: -O")
                {
                    Thread NT = new Thread(() =>
                    {
                        this.BeginInvoke((Action)delegate ()
                        {
                            textBox1.Text = "Guest";
                            this.Hide();
                            _clientSocket.Close();
                            //Usertimer us = new Usertimer(textBox1.Text);
                            //us.Show();
                        });
                    });
                    NT.Start();
                }
                Array.Resize(ref receivedBuf, _clientSocket.ReceiveBufferSize);
                //AppendtoTextBox(text);
                _clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), null);
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            //}
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var message = Encoding.UTF8.GetBytes("Server: -O");
            handlerSock.Send(message);
        }
    }

I commented the code that was not necessary to reproduce. As expected, the problem is that you call ReceiveAsync after you call _clientSock.Close(). You can't do that. If you close the socket, you should not execute anymore code. Here is an example of how to fix this:
        if (text == "Server: -O")
        {
            Thread NT = new Thread(() =>
            {
                this.BeginInvoke((Action)delegate ()
                {
                    textBox1.Text = "Guest";
                    this.Hide();
                    _clientSocket.Close();
                    //Usertimer us = new Usertimer(textBox1.Text);
                    //us.Show();
                });
            });
            NT.Start();
        }
        else
        {
            Array.Resize(ref receivedBuf, _clientSocket.ReceiveBufferSize);
            //AppendtoTextBox(text);
            _clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), null);
        }


Q: Change default value for Job Activity Monitor Is there a way for me to programmatically (some config table, I'm hoping) change the default value in the Auto Refresh setting to 5 seconds instead of 60, and to set the Auto Refresh to ON?
I need a way to make this a permanent setting - hopefully so that it applies to all users of the server.

A: According to this thread,you can do like below
Open Job activity monitor
In the left pane you can see "View refresh settings"
Click on it and you have a check box for "Auto refresh"
Enable the check box and provide the refresh interval.
Then click ok.

https://social.msdn.microsoft.com/Forums/sqlserver/en-US/d040105c-9d09-46d3-bb37-c69e771190ab/refresh-settings-job-activity-monitor?forum=sqlkjmanageability


Q: Running an axios.get inside a map function is returning a promise I have a React application where I get a list of books' ids from my DB and I display them using these IDs to get the information from the GoogleBooks API. So I'm mapping through my props and for each book, I'll go for the API using the axios.get().
My problem is that it's returning an object Promise that I couldn't find where to handle.
this is the error it games me
Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
thanks!
class HomeGroup extends Component {
    componentDidMount() {
        this.props.fetchBooks();
    }
    renderBooks() {
        return this.props.books.map(async (book, index) => {
            const res = await axios.get(`https://www.googleapis.com/books/v1/volumes?q=isbn:${book.ISBN}`);
            return
{res.data.items[0].id}
;
        });
        }
    render() {
        return
{this.renderBooks()}
;
    }


Q: git subtree push failed for behind its remote counterpart I have a github repository and wanted to make a mockup live with my domain.
Since the index.html is located inside a folder named "development" (but not directly in the root), what I did was
a. Create another github repo called "USERNAME.github.io"
b. Add the remote-url by
git remote add demo-origin git@github.com:USERNAME/USERNAME.github.io.git

c. push the repo subtree "development" by
git subtree push --prefix development demo-origin master

d. create "CNAME" file in my "USERNAME.github.io"
e. update the DNS to match the CNAME
Now everything works fine. However when I want to push updates again, I got the error message:
git push using:  demo-origin master
To git@github.com:SMARTEDU/SMARTEDU.github.io.git
! [rejected]        a5f0176dc6e0b10fa77a88cffe89a67d087d1f96 -> master (non-fast-forward)
error: failed to push some refs to 'git@github.com:SMARTEDU/SMARTEDU.github.io.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

This was due to the CNAME file added in "USERNAME.github.io" repo, but even if I pull it to local, it is still failed when I want to do git subtree push --prefix development demo-origin master again.
Any idea on how to fix it? Very appreciate!


Q: Logic behind HTML5 Placeholder I am working with a form. Each input field name is identified by its Placeholder. My form working fine in Chrome and Mozilla but fail in IE7 and IE8 because these browser does not support Placeholder attributes of HTML5.
My form is divided into 4 parts. When user fills the first part and click on save and proceed a trigger is fired on database and it shows second part of form and so on
To achieve placeholder in IE , I have tried various plugins and i also create one of my own but everything fails because the placeholder values save in database if i leave the field blank.
HTML5 placeholder worked fine for me in chrome. So if anyone can provide me the logic of HTML5 placeholder i will write it down in jquery to get a same functionality in IE.

A: You can make a jquery function, that initializes the value of the input to some text when the document is loaded (this should be your placeholder) and then put this value to "" (nothing) when there is an onclick event in the input. Hope it helps

A: Try this JSFiddle.
_selector is a custom variable that I've made. Just change the line to the ID of whatever field you want to put this placeholder on. You can chance the _placeholder to contain whatever placeholder text you want inside the field :).
I just change the css and html properties of the input field on when the user clicks inside it (or outside).
One problem with this technique is that when you post the form, it will think the value's are set (since the value is _placeholder (or "Address" in this example). Your best bet would be to check if the value is equal to your placeholder in the PHP script. If it is you can just tell your script to use "" instead of the var.

A: Going with @Hamdi, you can try jQuery. This is a very good article for that.


Q: Sending emails from outlook with Python not working I have been running some code for a while which automates some emails using win32com.client. All has been working for months but today I am getting an error.
import win32com.client

olMailItem = 0
obj = win32com.client.Dispatch("Outlook.Application")
newMail = obj.CreateItem(olMailItem)

Today I get the error AttributeError: module 'win32com.gen_py.00062FFF-0000-0000-C000-000000000046x0x9x6' has no attribute 'CLSIDToPackageMap'
If I try "Excel.Application" or "Word.Application" then I don't get an error and Outlook is installed and working on my system. Last week I came across the issue where mail.Bcc and mail.HTMLbody changed to mail.BCC and mail.HTMLBody respectively but I've not found that a change in the string has helped.
Can anyone shed any light on what might be happening?
Thanks in advance.

A: You might have to remove some old files:
# If errors are found, do this
# clear contents of C:\Users\<username>\AppData\Local\Temp\gen_py
# that should fix it, to test it type
import win32com.client
app = win32com.client.gencache.EnsureDispatch("Outlook.Application")
app.Visible = True

This gist also has other solutions that remove the files automatically. Application needs to be adjusted.
1.)
from pathlib import Path
 try:
        xl = win32.gencache.EnsureDispatch('Excel.Application')
    except AttributeError:
        f_loc = r'C:\Users\<username>\AppData\Local\Temp\gen_py'
        for f in Path(f_loc):
            Path.unlink(f)
        Path.rmdir(f_loc)
        xl = win32.gencache.EnsureDispatch('Excel.Application')

2.)
try:
    xl = client.gencache.EnsureDispatch('Excel.Application')
except AttributeError:
    # Corner case dependencies.
    import os
    import re
    import sys
    import shutil
    # Remove cache and try again.
    MODULE_LIST = [m.__name__ for m in sys.modules.values()]
    for module in MODULE_LIST:
        if re.match(r'win32com\.gen_py\..+', module):
            del sys.modules[module]
    shutil.rmtree(os.path.join(os.environ.get('LOCALAPPDATA'), 'Temp', 'gen_py'))
    from win32com import client
    xl = client.gencache.EnsureDispatch('Excel.Application')

A: I was having the same issue and managed to resolve it by doing the following
from win32com.client import gencache.py
gencache._Dump()

The _Dump() command will print the location of the cache directory. Deleting the directory resolved the issue for me.