text:
Q: Python: How can I calculate the average word length in a sentence using the .split command? new to python here. I am trying to write a program that calculate the average word length in a sentence and I have to do it using the .split command. btw im using python 3.2
this is what I've wrote so far
sentence = input("Please enter a sentence: ")
print(sentence.split())

So far i have the user enter a sentence and it successfully splits each individual word
they enter, for example: Hi my name is Bob, it splits it into ['hi', 'my', 'name', 'is', 'bob']
but now I'm lost I dunno how to make it calculate each word and find the average length of the sentence.

A: You might want to filter out punctuation as well as zero-length words.
>>> sentence = input("Please enter a sentence: ")

Filter out punctuation that doesn't count. You can add more to the string of punctuation if you want:
>>> filtered = ''.join(filter(lambda x: x not in '".,;!-', sentence))

Split into words, and remove words that are zero length:
>>> words = [word for word in filtered.split() if word]

And calculate:
>>> avg = sum(map(len, words))/len(words)
>>> print(avg)
3.923076923076923

A: >>> sentence = "Hi my name is Bob"
>>> words = sentence.split()
>>> sum(map(len, words))/len(words)
2.6

A: In Python 3 (which you appear to be using):
>>> sentence = "Hi my name is Bob"
>>> words = sentence.split()
>>> average = sum(len(word) for word in words) / len(words)
>>> average
2.6

A: The concise version:
average = lambda lst: sum(lst)/len(lst) #average = sum of numbers in list / count of numbers in list
avg = average([len(word) for word in sentence.split()]) #generate a list of lengths of words, and calculate average

The step-by-step version:
def average(numbers):
    return sum(numbers)/len(numbers)
sentence = input("Please enter a sentence: ")
words = sentence.split()
lengths = [len(word) for word in words]
print 'Average length:', average(lengths)

Output:
>>>
Please enter a sentence: Hey, what's up?
Average length: 4

A: def main():

    sentence = input('Enter the sentence:  ')
    SumAccum = 0
    for ch in sentence.split():
        character = len(ch)
        SumAccum = SumAccum + character

    average = (SumAccum) / (len(sentence.split()))
    print(average)

A:   def averageWordLength(mystring):
tempcount = 0
count = 1

wordcount = 0
try:
    for character in mystring:
        if character == " ":
            tempcount +=1
            if tempcount ==1:
                count +=1

        else:
            tempcount = 0
            try:
                if character.isalpha(): #sorry for using the .isalpha
                    wordcount += 1
            except:
                wordcount = wordcount + 0
    if mystring[0] == " " or mystring.endswith(" "): #i'm sorry for using the .endswith
            count -=1

    try:
        result = wordcount/count
        if result == 0:
            result = "No words"
            return result
        else:
            return result

    except ZeroDivisionError:
        error = "No words"
        return error

except Exception:
    error = "Not a string"
    return error

mystring = "What   big spaces   you  have!"
output is 3.0 and I didn't use the split

A: as a modular :
import re

def avg_word_len(s):
    words = s.split(' ') # presuming words split by ' '. be watchful about '.' and '?' below
    words = [re.sub(r'[^\w\s]','',w) for w in words] # re sub '[^\w\s]' to remove punctuations first
    return sum(len(w) for w in words)/float(len(words)) # then calculate the avg, dont forget to render answer as a float

if __name__ == "__main__":
    s = raw_input("Enter a sentence")
    print avg_word_len(s)

A: s = input("Please enter a sentence: ")
avg_word_len = len(s.replace(' ',''))/len(s.split())
print('Word average =', avg_word_len)

Output:
Please enter a sentence: this is a testing string
Word average = 4.0

note: this is a plain vanilla use case, additional boundary conditions can be applied as required.

A: text = input()

words=text.split()
single=''.join(words)
average=len(single)/len(words)
print(average)

A: def average():
    value = input("Enter the sentence:")
    sum = 0
    storage = 0
    average = 0

    for i in range (len(value)):
        sum = sum + 1
        storage = sum
        average = average+storage

    print (f"the average is :{average/len(value)}")

    return average/len(value)

average()


text:
Q: Pass by reference in python: Pass list and add characters? I'm trying to build a list of commands in a python list [] which gets passed to another python object. Nothing crashes but the recipient gets passed a null parameter.
The object is part of a python script menu.py comprised of panel, slot_handler and slot. together they make a scrolling panel object in pygame: panel is the top class. panel has an instance slot_handler which contains slots in a linked list.
I've never tried this before in python. I want to know if this is possible. I'm open to ideas in case this isn't workable.
class slot(object):
    def getcommands(self,mylist):
        if(self.has_phrase):
            if(self.phrase=="Move Up"):
                mylist.append('u')
            elif(self.phrase=="Move Down"):
                mylist.append('d')
            elif(self.phrase=="Move Left"):
                mylist.append('l')
            elif(self.phrase=="Move Right"):
                mylist.append('r')
            elif(self.phrase=="Open"):
                mylist.append('o')
            elif(self.phrase=="Close"):
                mylist.append('c')
            elif(self.phrase=="Rotate"):
                mylist.append('s')
        if(self.has_next):
            self.next.getcommands(mylist)

...
class slot_handler(object):
    def getcommands(self):
        commands = []
        self.top_slot.getcommands(commands)

...
class panel(object):
    def getcommands(self):
        return self.slots.getcommands()

A: Yes, it is possible to pass a list as an argument and append to it in a function:
>>> def f(x): x.append('u')
...
>>> mylist = []
>>> f(mylist)
>>> mylist
['u']

redpajama_set_name: RedPajamaStackExchange


text:
Q: Finding IP camera API I'm looking for a Network IP Camera Interface, to be more precise I bought a Neo Coolcam IP camera Model: NIP-02BGPW3A2. I'm looking for its API\Interface to play around with it.
I started tracking its request and response but unfortunately I'm not able to control it yet, nor can I find all the commands (this model has movement and light options).
I'm looking for a sample and\or a list of commands, any help is appreciated.

A: Found some documentation here. Seems to do the trick.


text:
Q: jQuery to calculate avg of values present inside a td of a table I am using googlecharts plugin in order to generate a column chart.
i also want to get an average of the values present in the td. Is it possible through google charts plugin or can anyone help me in writing ajquery to calculate the avg.
After calculating the avg I need to add it in paragraph tag with class "avg".
Thanks for the help.
My code is:

                            Mar
                            Apr
                            May
                            Jun
                            Jul
                            Aug

                            Weather
                            20
                            22
                            18
                            24
                            20
                            22

And the javascript code:

A: Try something like this:
avg = 0, amount = 0;
$('td').each(function(){
    avg += +($(this).text());
    amount++;
});
avg /= amount;
$('.avg').text(avg);

But you might want to make sure it's the right td, so you could have the tr's id something like 'weather', then just change $('td').each() to $('#weather td').each()

A: You can use
var avg=0;

$('#weather td').each({function(){
            avg=avg+parseInt($(this).text());
         });

avg=avg/$('#weather td').length;

or
var avg=0;
var count=0;
   $('#weather td').each({function(){
                avg=avg+parseInt($(this).text());
                count=count+1;
             });

    avg=avg/count;

after you can add avg on p tag by
$('p.avg').html(avg);

A: This should return an average for you:
var totalVal = 0,
    iCount = $('#weather').find('td').length;
$('#weather').find('td').each(function(i,val){
    totalVal = totalVal + parseInt($(val).text());
});
alert('Avg = '+totalVal/iCount);


text:
Q: How do I generate an SVG file without the  element? I am using dot to generate SVG files but I'd like to remove the  element from its nodes since I am using a script to show other information at mouse over.
Is it possible to tell dot not to generate such elements?

A: As a workaround I used jQuery to remove the title elements from the SVG I embedded in my page


text:
Q: #php compare two times with strtotime parse function doesn't work I am struggling with comparing two times.
$t1 = "55:10.01";
$t2 = "11.2";

$res = strtotime($t1) > strtotime($t2);
print($t1.' > '.$t2.' = '.($res?'TRUE':'FALSE'));

And the result is FALSE. If I understand correctly, PHP documentation says that both strings $t1 and $t2 should be parsed by strtotime, but... :)
Any idea what am I doing wrong? :)

A: try
$t1 = "55:10.01";
$t2 = "11.2";
if (date($t1) > date($t2)){
  $res = 'true';
}else{
  $res = 'false';
}
print($t1.' > '.$t2.' = '.$res);


text:
Q: why pyspark find local hive metastore only from root directory? I've a question on hive metastore support for delta lake,
I've defined a metastore on a standalone spark session with the following configurations
pyspark --conf "spark.sql.catalog.spark_catalog=org.apache.spark.sql.delta.catalog.DeltaCatalog" --conf "spark.sql.extensions=io.delta.sql.DeltaSparkSessionExtension"
spark = SparkSession \
    .builder \
    .appName("Python Spark SQL Hive integration example") \
    .config("spark.sql.warehouse.dir", '/mnt/data/db/medilake/') \
    .config("spark.hadoop.datanucleus.autoCreateSchema", 'true') \
    .enableHiveSupport() \
    .getOrCreate()
and it all worked while i was in the session according to the doc https://docs.delta.io/latest/delta-batch.html#-control-data-location&language-python
then when i opened a new session i got this error
>>> spark.sql("SELECT * FROM BRONZE.user").show()
20/09/04 20:30:27 WARN ObjectStore: Failed to get database bronze, returning NoSuchObjectException
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/spark-3.0.0-bin-hadoop3.2/python/pyspark/sql/session.py", line 646, in sql
    return DataFrame(self._jsparkSession.sql(sqlQuery), self._wrapped)
  File "/opt/spark-3.0.0-bin-hadoop3.2/python/lib/py4j-0.10.9-src.zip/py4j/java_gateway.py", line 1305, in __call__
  File "/opt/spark-3.0.0-bin-hadoop3.2/python/pyspark/sql/utils.py", line 137, in deco
    raise_from(converted)
  File "<string>", line 3, in raise_from
pyspark.sql.utils.AnalysisException: Table or view not found: BRONZE.user; line 1 pos 14;
'Project [*]
+- 'UnresolvedRelation [BRONZE, user]

i can still see the data arranged in the folders but now databases are empty (used to be bronze/silver/gold)
>>> spark.catalog.listDatabases()
[Database(name='default', description='Default Hive database', locationUri='file:/mnt/data/db/medilake/spark-warehouse')]

folders:
root@m:/mnt/data/db/medilake# ll
total 16
drwxr-xr-x 9 root root 4096 Sep  4 19:05 bronze.db
-rw-r--r-- 1 root root  708 Sep  4 19:45 derby.log
drwxr-xr-x 4 root root 4096 Sep  4 19:36 gold.db
drwxr-xr-x 5 root root 4096 Sep  4 19:45 metastore_db

conf:
>>> spark.conf.get("spark.sql.warehouse.dir")
'/mnt/data/db/medilake/'

how can I set the property to work from any working directory?
.config("spark.sql.warehouse.dir", '/mnt/data/db/medilake/')

A: Barak, maybe I can help you add the spark sql syntax in the following way
spark.sql("CREATE TABLE BRONZE.user USING DELTA LOCATION '/mnt/data/db/medilake/spark-warehouse'")

I remember that to read a delta table it must be saved from a parquet or csv file, for more details consult the documentation
Delta Lake

A: just needed to follow the instructions.
setting the spark.sql.warehouse.dir on the spark-default.conf did the trick


text:
Q: How to create Bootstrap 3 responsive text using rem units I am attempting to create a rem based site using Twitter-Bootstrap 3. In particular my text is not behaving responsively. It is just wrapping without changing font size or line height. I added a color change to the @media statements to visually track the break points. I'm not seeing any color changes either so the custom @media code is also not working. From what I have researched, it should be working. Obviously, I'm missing something. Please take a look at https://jsfiddle.net/dlearman/995w62e0/4/ and steer me in the right direction.

html {
  font-family: 'NimbusSanNov-Reg', "HelveticaNeueLight", "HelveticaNeue-Light", "Helvetica Neue Light", "HelveticaNeue", "Helvetica Neue", sans-serif;
  font-size: 15px;
  /* set default 1rem = 15px  */
  color: #302C25;
  line-height: 1.618;
  -webkit-text-size-adjust: 100%;
  /* why is this needed? */
  -ms-text-size-adjust: 100%;
}
body {
  background-color: #FFF;
}
#page {
  position: relative;
  top: 5.33rem;
  left: 7.4rem;
  padding-bottom: 7.667rem;
}
.container-full-width {
  position: relative;
  padding-left: 0;
  padding-right: 0;
  margin-left: 0;
  margin-right: 0;
}
.row-centered {
  text-align: center;
}
#testBox {
  position: relative;
  display: inline-block;
  margin-top: 0;
  margin-left: 60rem;
  width: 10rem;
  height: auto;
}
.bigText {
  font-family: 'NimbusSanNov-Reg''HelveticaNeueLight', 'HelveticaNeue-Light', 'Helvetica Neue Light', 'HelveticaNeue', sans-serif;
  font-size: 1rem;
  margin: 0 0 1.667rem 0;
  letter-spacing: .0667rem;
}
.bigTextItalic {
  font-family: 'NimbusSanNov-RegIta', 'HelveticaNeueLightItalic', 'HelveticaNeue-LightItalic', 'Helvetica Neue LightItalic', 'HelveticaNeueItalic', sans-serif;
  font-size: 1rem;
  letter-spacing: .0667rem;
  margin: 0 0 1.667rem 0;
}
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet" />

Every writer is cursed or blessed with a unique creative metabolism: the distinctive speed and efficiency with which he or she converts the raw fuel of life into the mystical, dancing blue smoke of art.

A: Please make sure there is no space between the @ and media because CSS sees @media as a media query.
CSS:
@media only screen and (max-width 1200px) {
  html {
     font-size: 1.333rem;
    line-height:2.157;
    color:#000FFF;
  }
}

@media only screen and (max-width 992px) {
  html {
    font-size: 1rem;
    line-height:1.618;
    color:#FF0000
  }
}

@media only screen and (max-width 768px) {
  html {
    font-size: .933;
    line-height:1.510;
    color:#00FF00;
  }
}

@media only screen and (max-width 480px) {
  html {
    font-size: 1.067;
    line-height:1.726;
    color:0000FF;
  }
}

@media only screen and (max-width 320px) {
  html {
  font-size: 1.333;
    line-height:2.157;
    color:#FF00FF;
  }
}

Reference: http://www.w3schools.com/cssref/css3_pr_mediaquery.asp


text:
Q: MS-SQL 2008 Server : Wrong Syntax? I having a problem with this command line:
IF  EXISTS (SELECT * FROM sys.objects
            WHERE object_id = OBJECT_ID(N'dbo.njams_test_sql_2.[PROC_DELETE_DATA]')
             AND type in (N'P', N'PC'))
DROP PROCEDURE [PROC_DELETE_DATA]
GO

Following SubSelect-Command:
SELECT * FROM sys.objects
WHERE object_id = OBJECT_ID ( N'dbo.njams_test_sql_2.[PROC_DELETE_DATA]'

Gives the error that there is an syntax error in the near of
'dbo.njams_test_sql_2.[PROC_DELETE_DATA]'
What am I doing wrong?

A: a bracket is missing at the end
SELECT * FROM sys.objects
WHERE object_id = OBJECT_ID ( N'dbo.njams_test_sql_2.[PROC_DELETE_DATA]' )

A: Your first query runs perfectly..
but you are missing ')' in your second query.
Use following query
SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.njams_test_sql_2.[PROC_DELETE_DATA]')


text:
Q: Redmine email configuration on Ubuntu 14.04 with gmail I have an pre-installed Redmine on Digital Ocean, but the email for the application was not setup yet.
How can I configure the email with gmail smtp settings in Redmine?
The configuration file is: /srv/redmine/config/configuration.yml
I can send mail from console via SSH.

A: Okay, so I have found the solution.

*

*Log in your droplet via ssh from Putty (or other ssh tool).
1a. ) install sendmail: sudo apt-get install sendmail

*cd the following directory: /srv/redmine/config/

*create an you file and called it configuration.yml: configuration.yml
nano -w configuration.yml

*paste the following config:
production:
      email_delivery:
        delivery_method: :async_sendmail
        smtp_settings:
          enable_starttls_auto: true
          address: "smtp.gmail.com"
          port: '587'
          domain: "smtp.gmail.com"
          authentication: :plain
          user_name: "your_email@gmail.com"
          password: "your_password"

*save this file: CTRL + X + S + Y

*cd the following directory: /srv/redmine/tmp

*create an new blank file an named it: restart.txt

*restart the application: touch /srv/redmine/tmp/restart.txt

and voila, you can send notification mail from redmine :)


text:
Q: In C, how do you access elements in this struct? How do I access elements in this stuct if I initialize a list as follows:
group **list = (group **) malloc(sizeof(group));

typedef struct
{
    // ID of the group, 'A' to 'D'
    char id;

    // a list of members in the group
    char **members;
} group;

I tried using (*list)->id = 'A' and it compiles but then gets a segmentation fault error when running the program.

A: struct group
{
    // ID of the group, 'A' to 'D'
    char id;

    // a list of members in the group
    char **members;
};

//this initializes one group
group *a_group = malloc(sizeof(struct group)); //cast not needed in C

//this initializes an array of 10 group
group **list = malloc(sizeof(struct group *) * 10);

//initialize each one of the 10
for(int i = 0; i < 10; ++i){
  list[i] = malloc(sizeof(struct group));
}

//get something out of group
a_group->id;

//get first group out of list
list[0]->id;
*list->id;

// 10 elements continuous memory
group *array_of_groups = malloc(sizeof(struct group) * 10);
array_of_groups[0].id;
*array_of_groups.id;

A: Although it compiles fine, you didn't allocate memory correctly.
You allocated memory for group **list, which is eventually an array of pointers to struct group. What I think you intended to do doing is:
group** list = malloc(sizeof(group*) * 5);  // e.g. 5 pointers

Now for each pointer in the array, allocate its own memory:
int i;
for (i = 0; i < 5; i++) {
    list[i] = malloc(sizeof(group));
}

For instance, to access id in the 2nd struct, you do:
list[1]->id = 'A';

Note that *list access the first struct, and is equivalent to list[0].
Sidenote:
Two levels of indirection allow you to store the structs in a non-continuous way in the memory. Alternatively, you can use one level of indirection and store them continuously:
group list* = malloc(sizeof(group) * 5);  // Again, 5 structs

and then access the members with:
list[0].id = 'A';

A: Keep in mind the double-indirection pointer is just a pointer to a list that happens to point to the first entry by default. You need to allocate for the individual entry/entries, not just the list pointer (**list), some flavor of the following:
//rough code, not tested... std caveats apply :)
group *one_group = malloc(sizeof(group));

list[0]=one_group;
list[0]->id = 'A'; // or one_group->id='A';

A: Lets say i have to make a list of pointers. members of this list each points to a memory chunk mapped by type group.
now lets say i have 10 items,
so:
group *tmp = malloc(sizeof(group) * 10);

now tmp is pointing to the start of these chunks.
Now i want to to make a list of pointers, where every item in the list points to a chunk.
lets create 10 pointers,
group ** list = malloc(sizeof(group *) * 10)

now initialize this list of of pointers:
i = 10;
while(i--) {
    list++ = &(tmp++);
}

Now your list is initialized with pointers to chunks. One problem remained, your list is pointing to the last. If you don't want that
list-= 10;

Now you want to retrieve something from the list :
while(i--) {
    printf("%c\n", (*(list++))->a);
}

But this kind of list management is weird and not to mention error prone. you should seriously think about maintaining your list through "LINKED LIST". a trivial scenario like you have given can be easily implemented through a singly linked list.


text:
Q: Rails-admin-scaffold Пытался использовать гем , но видимо он багнутый. Я конечно же не хочу пользоваться нативными шаблонами, и попытался кастомизировать. Происходит то, что гем как бы не подхватывает мои шаблоны, хотя они и лежат в нужном месте. Есть решение?

A: Попробуйте воспользоваться гемом rails_admin: https://github.com/sferik/rails_admin


text:
Q: Component.find not working for lightning:input I need to enable the text boxes based on the value selected in combobox -
Below Picture -

Based on the Combobox changed I am trying to enable the corresponding input boxes, which is not working  with component.find
Below Code --
            <aura:iteration items="{!v.contributionList}"
            var="contriWrap">

                           {!contriWrap.classification}

                        <lightning:combobox id="{!contriWrap.contribution}"
                                            value="{!contriWrap.contributionType}"
                                            onchange="{!c.handleChange}"
                                            options="{!v.contributionType}"
                                            placeholder="Not Applicable"
                                            variant="label-hidden"
                                            />

                        <lightning:input aura:id="{!contriWrap.contribution}" label="For Employee" type="currency" variant="label-hidden" placeholder="0" value="{!contriWrap.contributionEmployee}" disabled="true"/>

                        <lightning:input aura:id="{!contriWrap.contribution}" label="For Dependent" type="currency" variant="label-hidden" placeholder="0" value="{!contriWrap.contributionDependent}" disabled="true"/>

            </aura:iteration>

handleChange: function (component, event) {
    // Get the string of the "value" attribute on the selected option
    var selectedOptionValue = event.getParam("value");
    var selectedId = event.getSource().get("v.id");
    console.log('Hi selectedOptionValue',selectedOptionValue);
    console.log('selectedId-->'+selectedId);
    var cmpTarget = component.find(selectedId);
    console.log(' cmpTarget'+cmpTarget);
    component.find(selectedId).set("v.disabled",false);
    console.log('after setting value');
    //component.set("v.seletedContributionType",selectedOptionValue);
},

A: aura:id cannot be dynamically created using {!} binding. It has to be static.

aura:id doesn't support expressions. You can only assign literal
  string values to aura:id.

So you can put everything between tr in separate child component and implement logic:
<aura:component >
    <aura:attribute name="contriWrap" type="Map" />

 {!v.contriWrap.classification}

        <lightning:combobox id="{!v.contriWrap.contribution}"
                            value="{!v.contriWrap.contributionType}"
                            onchange="{!c.handleChange}"
                            options="{!v.contributionType}"
                            placeholder="Not Applicable"
                            variant="label-hidden" />

        <lightning:input aura:id="findable_id1" label="For Employee" type="currency"
                         variant="label-hidden" placeholder="0"
                         value="{!v.contriWrap.contributionEmployee}" disabled="true" />

        <lightning:input aura:id="findable_id2" label="For Dependent" type="currency"
                         variant="label-hidden" placeholder="0"
                         value="{!v.contriWrap.contributionDependent}" disabled="true" />

</aura:component>

and in parent:
<aura:iteration items="{!v.contributionList}"
                var="contriWrap">

        <c:childTdComp contriWrap={!contriWrap} />

</aura:iteration>

Also implement handleChange in child component.


text:
Q: C# is there a better way to hide horizontal scroll bar using WinAPI messages? I have a class IndicatorPanel : FlowLayoutPanel that displays custom controls. When this panel is resized it also resizes its child controls widths to be the same size as its width. This is so that it never needs to show a horizontal scroll bar.
The issue I had was that without AutoScroll = true I had to re-implement all of the scroll functionality if I wanted a vertical scroll bar but it made it so a horizontal never appeared. I decided to go the other way and try to hide the horizontal scroll bar continually in WndProc and use auto scroll for the vertical scroll bar.
Here is my WndProc
const int WM_MOUSEWHEEL = 0x020A;

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool ShowScrollBar(IntPtr hWnd, int wBar, bool bShow);

private enum ScrollBarDir { SB_HORZ = 0, SB_VERT = 1, SB_CTL = 2, SB_BOTH = 3 }
protected override void WndProc(ref Message m)
{
    // Continually suppress; AutoScroll wants to show a scroll bar
    ShowScrollBar(this.Handle, (int)ScrollBarDir.SB_HORZ, false);
    // No scrolling when that flag is set
    if (m.Msg == WM_MOUSEWHEEL && NoScrollFlag)
        return;
    // Pass everything else through
    base.WndProc(ref m);
}

As you can see this is a little overboard. Anytime a message comes in the first thing that happens is I call the ShowScrollBar function to suppress the horizontal scroll bar, which more often than not is doing nothing but wasting cycles.
Is there a windows message I can catch so that I only call ShowScrollBar when it is needed?
I have looked through the windows scroll bar reference and none of the messages seem to apply to this, they all have to do with controlling a scroll bar after it is drawn/added to a control/form.

A: Execute your code to hide the horizontal scrollbar in response to WM_NCCALCSIZE Windows message

Sent when the size and position of a window's client area must be
calculated. By processing this message, an application can control the
content of the window's client area when the size or position of the
window changes.

https://learn.microsoft.com/en-us/windows/win32/winmsg/wm-nccalcsize
 Const WM_NCCALCSIZE As Integer = &H83

    Protected Overrides Sub WndProc(ByRef m As Message)

        If m.Msg = WM_NCCALCSIZE Then
            ShowScrollBar(Me.Handle, CInt(ScrollBarDir.SB_HORZ), False)
        End If

        MyBase.WndProc(m)

    End Sub


text:
Q: MsSql Subquery returned more than 1 value Can someone help me with this error?
Msg 512, Level 16, State 1, Procedure gen048upload, Line 101
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
here is my code:
ALTER PROCEDURE [dbo].[gen048upload]
    -- Add the parameters for the stored procedure here
    @fileDate varchar(20)

AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    DECLARE @IerrorCode int
    DECLARE @error int,

        @tDay varchar(2),
        @tMonth varchar(2),
        @tYear varchar(4)

SET @tMonth= MONTH(GETDATE())
SET @tDay= DAY(GETDATE())
SET @tYear= Year(GETDATE())

DECLARE @tempTable TABLE (
    tempRow varchar(1000)
)

--  DECLARE @command varchar(1000)
--  SET @command = 'copy Y:\FTP\RMT\' + @fileDate + '.txt'
--  INSERT into @tempTable EXEC master..xp_cmdshell @command

DECLARE @fne_count int
SET @fne_count = (SELECT COUNT(*) FROM @tempTable WHERE tempRow = 'The system cannot find the file specified.')

 IF @fne_count = 0
 BEGIN
     BEGIN TRAN
        DECLARE @fileName varchar(100)
        SET @fileName = @fileDate + '.txt'

    CREATE TABLE #temp1
    (
        WHOLEROW varchar(8000)
    )

    DECLARE @CMD varchar(8000)
    SET @CMD = 'BULK INSERT #temp1
    FROM ''Y:\FTP\RMT\' +@fileName+ '''
    WITH (DATAFILETYPE = ''char'', KEEPNULLS, FIRSTROW=1, MAXERRORS=0, ROWTERMINATOR =  '''+char(0x0A)+''')'
    EXEC(@CMD)

    SET @error=0
    SET @error =  @error + @@ERROR

    DECLARE @Flag bigint,@msg varchar(200)

    IF EXISTS(SELECT ISNULL(MAX(flag),0) FROM gen_048)
        BEGIN

            SET @Flag =(SELECT ISNULL(MAX(flag),0) FROM gen_048)+1
        END
    ELSE
        BEGIN
            SET @Flag = 1
        END

--      DELETE FROM #temp1 WHERE WHOLEROW IS NULL
--      DELETE FROM #temp1 WHERE WHOLEROW like '%Hostdate|Book Type|CCY|Portfolio|GUAVA |Chart Code Name|Input|Native debit amount|Native credit amount|Base Amount|Counterparty|Acct|Deal|Product|Source|Native amount%'
--      DELETE FROM #temp1 WHERE WHOLEROW like '%||||CHART CODE||Date|||||No|Ref|||%'
--      DELETE FROM #temp1 WHERE WHOLEROW = ''

    DECLARE @inputTable table(
        input_date varchar(100)
    )

IF EXISTS (
        SELECT fdate
        FROM gen048_fdate
        WHERE fdate IN (
                SELECT DISTINCT REPLACE(dbo.fn_Parsename(WHOLEROW, '|', 8), CHAR(9), '')
                FROM #temp1
        )
)

        IF EXISTS(SELECT fdate FROM gen048_fdate WHERE fdate = @input_date)
        BEGIN
                SET @msg = 'Error: File Exists, Duplication is not allowed'
        END
        ELSE
        BEGIN
            INSERT INTO gen048_fdate
            SELECT DISTINCT REPLACE(dbo.fn_Parsename(WHOLEROW,'|',8), CHAR(9), '') FROM #temp1
            SET @IerrorCode = @@ERROR
            IF (@IerrorCode <> 0) GOTO PROBLEM

            INSERT INTO gen_048 (
                            accname,
                            add1,
                            add2,
                            zip,
                            add3,
                            add4,
                            add5,
                            accdate,
                            bzip,
                            uname,
                            accnum,
                            pin)

                        SELECT
                        dbo.fn_Parsename(WHOLEROW,'|',0),
                        dbo.fn_Parsename(WHOLEROW,'|',1),
                        dbo.fn_Parsename(WHOLEROW,'|',2),
                        dbo.fn_Parsename(WHOLEROW,'|',3),
                        dbo.fn_Parsename(WHOLEROW,'|',4),
                        dbo.fn_Parsename(WHOLEROW,'|',5),
                        dbo.fn_Parsename(WHOLEROW,'|',6),
                        dbo.fn_Parsename(WHOLEROW,'|',7),
                        dbo.fn_Parsename(WHOLEROW,'|',8),-- input date
                        dbo.fn_Parsename(WHOLEROW,'|',9),
                        dbo.fn_Parsename(WHOLEROW,'|',10),
                        dbo.fn_Parsename(WHOLEROW,'|',11)
                        FROM #temp1
                        SET @IerrorCode = @@ERROR
                        IF (@IerrorCode <> 0) GOTO PROBLEM

            SET @msg = 'File has been successfully uploaded'
        END

END
ELSE
    BEGIN
        SET @msg = 'File for.' + @fileDate + 'not found. No file is uploaded.'
    END

    COMMIT TRAN
    SELECT @msg as msg, @fileDate as filedate

                        PROBLEM:
                            IF (@IerrorCode <> 0)
                            BEGIN
                                ROLLBACK TRAN
                                SELECT @IerrorCode as msg
                            END
  END
END

-- [dbo].[gen048upload] '07-07-2015'

A: IF EXISTS (
        SELECT fdate
        FROM gen048_fdate
        WHERE fdate IN (
                SELECT DISTINCT REPLACE(dbo.fn_Parsename(WHOLEROW, '|', 8), CHAR(9), '')
                FROM #temp1
            )
    )

update -
ALTER PROCEDURE [dbo].[gen048upload]
(
    @fileDate VARCHAR(20)
)
AS BEGIN

    SET NOCOUNT ON;

    IF OBJECT_ID('tempdb.dbo.#temp') IS NOT NULL
        DROP TABLE #temp

    CREATE TABLE #temp (WHOLEROW VARCHAR(8000))

    BEGIN TRY
        BEGIN TRANSACTION

        DECLARE @SQL NVARCHAR(MAX)
        SET @SQL = 'BULK INSERT #temp1
        FROM ''Y:\FTP\RMT\' + @fileDate + '.txt' + '''
        WITH (DATAFILETYPE = ''char'', KEEPNULLS, FIRSTROW=1, MAXERRORS=0, ROWTERMINATOR =  ''' + CHAR(0x0A) + ''')'

        EXEC sys.sp_executesql @SQL

        IF EXISTS (
                SELECT fdate
                FROM gen048_fdate
                WHERE fdate IN (
                        SELECT DISTINCT REPLACE(dbo.fn_Parsename(WHOLEROW, '|', 8), CHAR(9), '')
                        FROM #temp1
                    )
            )
        BEGIN

            SELECT 'Error: File Exists, Duplication is not allowed', @fileDate

        END
        ELSE BEGIN

            INSERT INTO gen048_fdate (fdate)
            SELECT DISTINCT REPLACE(dbo.fn_Parsename(WHOLEROW,'|',8), CHAR(9), '')
            FROM #temp1

            INSERT INTO gen_048 (accname, add1, add2, zip, add3, add4, add5, accdate, bzip, uname, accnum, pin)
            SELECT
                dbo.fn_Parsename(WHOLEROW,'|',0),
                dbo.fn_Parsename(WHOLEROW,'|',1),
                dbo.fn_Parsename(WHOLEROW,'|',2),
                dbo.fn_Parsename(WHOLEROW,'|',3),
                dbo.fn_Parsename(WHOLEROW,'|',4),
                dbo.fn_Parsename(WHOLEROW,'|',5),
                dbo.fn_Parsename(WHOLEROW,'|',6),
                dbo.fn_Parsename(WHOLEROW,'|',7),
                dbo.fn_Parsename(WHOLEROW,'|',8),
                dbo.fn_Parsename(WHOLEROW,'|',9),
                dbo.fn_Parsename(WHOLEROW,'|',10),
                dbo.fn_Parsename(WHOLEROW,'|',11)
            FROM #temp1

            SELECT 'File has been successfully uploaded', @fileDate

        END

        COMMIT TRANSACTION
    END TRY
    BEGIN CATCH

        PRINT ERROR_MESSAGE()

        IF XACT_STATE() <> 0 BEGIN
            ROLLBACK TRANSACTION
        END

    END CATCH

END

A: when you assign value in variable using query. Query must be return one value.
Please check this line
SET @input_date = (SELECT DISTINCT REPLACE(dbo.fn_Parsename(WHOLEROW,'|',8), CHAR(9), '') FROM #temp1)

In this line should be use aggregate function.
Max()
Min()


text:
Q: Copying register value in Verilog behavioral modelling I'm working to design encryption module in Verilog using behavioral modelling approach, but i'm stuck in passing register value to Data_out port. I'm making little mistake to copy register p value in Data_out port. Testbench is also attached. expected output of the module should be Data_out = (Data_in + Key) MOD 26. but we can't use % operator because of systhesis issue.
Your answer will be valuable for me.
module encription(Start,Clk,Reset,Data_In, Key,Data_out,Done);

parameter M='d26;
parameter S0=0, S1=1, S2= 2;
input Clk,Reset,Start;
input [4:0] Data_In,Key;
output reg [4:0] Data_out;
output reg Done;
 reg [1:0] state;
 reg [4:0] p,q,r,s;

 always @ (posedge Clk)
 begin
 r <= Data_In;
 s <= Key;
 end

 always @ (posedge Clk )
    begin
      if(Reset=='b0)
        begin
            Done <= 1'b0;
            p <= M;
        end
        else if (Reset == 'b1)
        case (state)
         S0:
         if (Start) begin
         q <= r + s;

         state <= S1;
         end
         S1:
         if (p >= q) begin
         p <= p - q;
         state <= S2;
         end
         S2:
         begin
               Data_out <= p;
               Done <= 1'b1;
               Done <= 1'b0;
               end
               default:
               state <= S0;
endcase

end
endmodule

module Encryption_tb();

reg Clk,Reset,Start;
reg [4:0] Data_In,Key;
wire [4:0] Data_out;
wire [4:0] q;
wire Done;

  encription DUT(Start,Clk,Reset,Data_In, Key,Data_out,Done);
initial
    begin
    Clk = 0;
    forever #5 Clk=~Clk;
    end

    initial
    begin
        #10 Start = 'b1;  Data_In = 'b000111; Key = 'b01110;
    #10 Start = 'b1;  Data_In = 'b000101; Key = 'b01100;
    #10 Start = 'b1;  Data_In = 'b000001; Key = 'b00110;
    #10 Reset = 'b1; Start = 'b1;
    //#10 Reset = 'b0;
    #10 Start = 'b1;  Data_In = 'b000111; Key = 'b01110;
    #10 Start = 'b1;  Data_In = 'b000101; Key = 'b01100;
    #10 Start = 'b1;  Data_In = 'b000001; Key = 'b00110;
    #10 $finish;
    end
endmodule

A: This does not need a state machine just some flops.
RTL:
module encription(Start,Clk,Reset,Data_In, Key,Data_out,Done);

parameter M='d26;
parameter S0=0, S1=1, S2= 2;
input Clk,Reset,Start;
input [4:0] Data_In,Key;
output reg [4:0] Data_out;
output reg Done;

  reg [6:0] sum;

assign sum = Data_In + Key;

 always @ (posedge Clk )
    begin
      if(Reset=='b1)
        begin
            Data_out <= 0;
            Done <= 0;
        end
        else
          begin
          if(sum < M)
            Data_out <= sum;
            else
              if(sum < 2*M)
                Data_out <= sum - M;
               else
                 Data_out <= sum - 2*M ;

            Done <= Start;
          end
    end

endmodule

Testbench with meaningful vectors:
    module Encryption_tb();

reg Clk,Reset,Start;
reg [4:0] Data_In,Key;
wire [4:0] Data_out;
wire [4:0] q;
wire Done;

  encription DUT(Start,Clk,Reset,Data_In, Key,Data_out,Done);

initial
    begin
    Clk = 0;
    forever #5 Clk=~Clk;
    end

    initial
    begin :initial_block

      $monitor("Data_In = %d,Key = %d, Data_out = %d",Data_In,Key,Data_out);

    Reset = 1;
    #20 Reset = 0;

    #10;

    #1;
    Start = 1;
      for(int i = 0; i < 30; i++)
        begin
          @ (posedge Clk);
          #1;
          Key = i;
          Data_In = i;
        end

    #10 $finish;
    end :initial_block

  initial
    begin
      $dumpfile("dump.vcd");
      $dumpvars;
    end

endmodule

Some of the outputs (note the answer is delayed by 1 clk because of the flops)
Data_In =  0,Key =  0, Data_out =  0
Data_In =  1,Key =  1, Data_out =  0
Data_In =  1,Key =  1, Data_out =  2
Data_In =  2,Key =  2, Data_out =  2
Data_In =  2,Key =  2, Data_out =  4
Data_In =  3,Key =  3, Data_out =  4
Data_In =  3,Key =  3, Data_out =  6
Data_In =  4,Key =  4, Data_out =  6
Data_In =  4,Key =  4, Data_out =  8
Data_In =  5,Key =  5, Data_out =  8
Data_In =  5,Key =  5, Data_out = 10
Data_In =  6,Key =  6, Data_out = 10
Data_In =  6,Key =  6, Data_out = 12
Data_In =  7,Key =  7, Data_out = 12
Data_In =  7,Key =  7, Data_out = 14
Data_In =  8,Key =  8, Data_out = 14
Data_In =  8,Key =  8, Data_out = 16
Data_In =  9,Key =  9, Data_out = 16
Data_In =  9,Key =  9, Data_out = 18
Data_In = 10,Key = 10, Data_out = 18
Data_In = 10,Key = 10, Data_out = 20
Data_In = 11,Key = 11, Data_out = 20
Data_In = 11,Key = 11, Data_out = 22
Data_In = 12,Key = 12, Data_out = 22
Data_In = 12,Key = 12, Data_out = 24
Data_In = 13,Key = 13, Data_out = 24
Data_In = 13,Key = 13, Data_out =  0
Data_In = 14,Key = 14, Data_out =  0
Data_In = 14,Key = 14, Data_out =  2
Data_In = 15,Key = 15, Data_out =  2
Data_In = 15,Key = 15, Data_out =  4
Data_In = 16,Key = 16, Data_out =  4
Data_In = 16,Key = 16, Data_out =  6
Data_In = 17,Key = 17, Data_out =  6
Data_In = 17,Key = 17, Data_out =  8
Data_In = 18,Key = 18, Data_out =  8

A: I see a couple issues.

*

*The only way to get out of S1 in your state machine is if "if (p >= q)". If p is already less than Q, you are stuck in that state forever.

*In your testbench, you are giving time between starts for your state
machine to run.
A few suggestions:
Better indentation make it easier to see what is inside a code block: Ex:
        S1:
          if (p >= q) begin
             p <= p - q;
             state <= S2;
          end

In your testbench, instead of using #10 to define the sequence of stimulus, use  @(posedge Clk), that way if your clock frequency changes or some other length delay is used in the TB, things will still line up with the clock.
Use @(Done) to wait for results.
I'm also curious, what synthesis tool you are using that doesn't support %?


text:
Q: Adding WCF service reference in .net core we are trying to add wcf service reference and show us TLS SSL issue. Would it be possible that if the end point is requiring credentials?
from connected service > chose wcf to add > add the URI (ends with .svc) > keeping all defaults in next pages, clicking on finish shows below message. there is no other details.
error image

A: This typically indicates that the server uses SSL certificates to protect its communication, and does not explicitly require the client to provide a certificate for authentication.
https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/working-with-certificates
In the SSL communication process, a trust relationship needs to be established. Therefore, the client needs to have the necessary conditions to establish SSL communication. When adding service references on the client-side, the server's WSDL will be downloaded and used. During this process, please trust the server certificate and ensure that TLS communication is supported on the client-side.
https://learn.microsoft.com/en-us/dotnet/framework/network-programming/tls
Besides, I advise you get the WSDL file by browser first. Likewise, this also requires the above. After establishing the trust relationship, the browser address bar should have a secure lock flag. Subsequently, try it again in the Adding service reference dialog.

Feel free to let me know if there is anything I can help with.


text:
Q: Refreshing DataTable from JSON object by calling $ajax function I have a JSON object like that:
{
    "column1":
        ["a","b","c","d","e"],
    "column2":
        [1,2,3,4,5]
 }

And I'd like to refresh it on a DataTable by calling $ajax function. How it works?


text:
Q: How I can acess to varibles? I try to use @frezzed tech. in my flutter ptoject for working with  DB-firbase.

How I can acess to class vars for manipulating?
import 'package:freezed_annotation/freezed_annotation.dart';
part 'Person.freezed.dart';

@freezed
class Person with _$Person {
  const Person._(); // Added constructor
  const factory Person(String name, {int? age}) = _Person;
  const factory Person.manager(String? ttt) = Manager;

  void method() {
    print('hello world');
    Person p = Person("name");
    p.
  }
}

A: @freezed
class Person with _$Person {
  factory Person({ String? name, int? age }) = _Person;
}

Which then allows you to write:
var person = Person(name: 'Remi', age: 24);
print(person.name); // Remi
print(person.age); // 24

source - freezed docs


text:
Q: Crashlytics: "MyApp could not be installed at this time" when adding entitlements I'm trying to distribute a beta version through Fiber/Crashlytics. I've been doing this for ages but this time I'm unable to make it work correctly (iOS9+).
My app uses icloud keyvalue store, IAP and push notifications, so it has an entitlements file. The thing is, when I archive and distribute the app, Crashlytics sends the email with the new version to testers and they are able to install it BUT, as soon as it ends installing, a "…could not be installed at this time" appears and the app deletes itself. In the other hand, if I remove the "code signing entitlements" value from Building Settings, the installation works ok (but icloud and other things aren't working, of course).
What am I doing wrong? Is there a workaround for this situation?

A: It turns out that the entitlements file had something wrong (even when I've never edited it by myself!). I had enabled and disabled the required capabilities trying to fix my problem but it didn't worked until I deleted the entitlements file and forced Xcode to recreate it by enabling capabilities again.
After that, I've hadn't any problem to archive and distribute my beta.


text:
Q: in Java, how do I know if certain port on a host is open??(besides using socket if possible) freshman, both here and in Java
i know codes like:
Socket clientSocket=null;

try
{
  clientSocket=new Socket(192.168.2.3,1111);
  System.out.println("port open");
  clientSocket.close();
}
catch(Exception   e)
{
  System.out.println("port closed");
}

can be used to test whether certain port is open(here is port 1111 on 192.168.2.3), just wandering is there any other way?? not using socket() maybe??

A: To simplyfy things a bit: yes, establishing a connection is correct way to probe for open port, and if you even find other method, it will be using socket() under the hood.
Complexity of the whole problem comes from the fact that "open port" is a number one suspect in every security book out there. System administrators use a bunch of tricks to fight so called "port scanning". This includes reporting a "false positive" (claiming that port is open while it is not) to any software that behaves like a port scanner (that is: makes a connection and disconnects without sending any data).
So in reality the best way is to establish connection, send request and process response. Every other approach can fail under certain network/host/security configurations, leaving your user puzzled as to why his application doesn't work when it claims there is no problem with connection.


text:
Q: android AD not shown if testdevice is added AdView adView = (AdView)v.findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder()
    .addTestDevice("device#")
    .build();
    adView.loadAd(adRequest);

I didnt include my actual device number (idk does it have to be a secret?) but I have it.
Anyhow this is my code and whenever i comment out the addTestDevice part i see the ads in my real device, but I dont see them when i have the addTestDevie part.
I dont think this is the way it supposed to be. My device should display the ads but ads should not be clikable. Any solution?

A: NB there is no value is hiding your your device ID AFAIK.
When you use addTestDevice you should see test ads. They tend to be quite different to real ads. Ie they say things like "Test ad" etc. And you should be able to click on them.


text:
Q: Calculate proportion of several binary variables by another variable I have data with several binary variables, and I want to calculate the proportion of each one, by another variable.
Example
I survey people and ask them: Please mark which of the following fruits you like (can mark more than one choice): ☐ Banana  ☐ Apple  ☐ Orange  ☐ Strawberry  ☐ Peach
Each person who checked the box gets 1 in the data, and when leaving blank it's denoted as 0. The data looks like that:
library(dplyr)

set.seed(2021)

my_df <-
  matrix(rbinom(n = 100, size = 1, prob = runif(1)), ncol = 5) %>%
  as.data.frame() %>%
  cbind(1:20, ., sample(c("male", "female"), size = 20, replace = T)) %>%
  setNames(c("person_id", "banana", "apple", "orange", "strawberry", "peach", "gender"))

my_df
#>    person_id banana apple orange strawberry peach gender
#> 1          1      1     1      1          0     0 female
#> 2          2      1     0      0          0     1 female
#> 3          3      0     0      1          0     1 female
#> 4          4      1     1      0          1     0 female
#> 5          5      1     1      1          0     0   male
#> 6          6      1     1      1          0     1 female
#> 7          7      0     1      0          1     1   male
#> 8          8      1     1      0          0     0   male
#> 9          9      1     1      1          0     0 female
#> 10        10      0     0      0          0     0   male
#> 11        11      1     1      1          1     1   male
#> 12        12      1     1      0          0     1   male
#> 13        13      1     1      0          1     0   male
#> 14        14      1     1      0          0     0   male
#> 15        15      0     0      0          0     1   male
#> 16        16      0     1      0          0     1   male
#> 17        17      1     0      0          0     1   male
#> 18        18      1     1      1          1     1   male
#> 19        19      0     0      1          1     1 female
#> 20        20      0     0      0          0     0 female

Created on 2021-02-01 by the reprex package (v0.3.0)
I want to get the proportion for each fruit, split by gender. From this answer I learned how to do it for one variable (for example, banana):
my_df %>%
  group_by(gender) %>%
  summarise(n_of_observations = n(), prop = sum(banana == 1)/n())

## `summarise()` ungrouping output (override with `.groups` argument)
## # A tibble: 2 x 3
##   gender n_of_observations  prop
##   <chr>              <int> <dbl>
## 1 female                10   0.6
## 2 male                  10   0.4

But how can I get such a table for all fruits?
Desired output:
##    fruit      gender  prop
##    <chr>      <chr>  <dbl>
##  1 banana     female   0.6
##  2 banana     male     0.4
##  3 apple      female   0.4
##  4 apple      male     0.3
##  5 orange     female   0.3
##  6 orange     male     0.1
##  7 strawberry female   0.4
##  8 strawberry male     0.4
##  9 peach      female   0.3
## 10 peach      male     0.6

I'm looking for a dplyr solution, if possible. Thanks a lot!

A: You can use across to summarize multiple variables at once:
my_df %>%
  group_by(gender) %>%
  summarise(across(banana:peach, list(n = ~length(.x), prop = ~sum(.x == 1) / n())))

# A tibble: 2 x 11
  gender banana_n banana_prop apple_n apple_prop orange_n orange_prop strawberry_n strawberry_prop peach_n peach_prop
  <chr>     <int>       <dbl>   <int>      <dbl>    <int>       <dbl>        <int>           <dbl>   <int>      <dbl>
1 female        8       0.625       8       0.5         8       0.625            8           0.25        8      0.5
2 male         12       0.667      12       0.75       12       0.25            12           0.333      12      0.583

Note that the first argument of across specifies the variables you want to summarize. Here, I wrote banana:peach meaning all columns between banana and peach.

A: You can use tidyr to pivot your data first and then summarize it:
library(tidyr)

tidyr::pivot_longer(my_df, banana:peach,
                    names_to = "fruit") %>%
  dplyr::group_by(gender, fruit) %>%
  dplyr::summarize(prop = sum(value) / n())

   gender fruit       prop
   <chr>  <chr>      <dbl>
 1 female apple      0.5
 2 female banana     0.625
 3 female orange     0.625
 4 female peach      0.5
 5 female strawberry 0.25
 6 male   apple      0.75
 7 male   banana     0.667
 8 male   orange     0.25
 9 male   peach      0.583
10 male   strawberry 0.333

You can pipe it to arrange if you want to sort by fruit. You can also add the number of observations in the summarize function with n = n().


text:
Q: Exposing a webHttpBinding WCF service to mobile clients I have created a very basic service operation that needs to write content to my database. This service looks like the following:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
[ServiceBehavior(IncludeExceptionDetailInFaults = false)]
public class myService : ImyService
{
  public MyServiceResult MyMethod(string p1, string p2)
  {
    try
    {
      // Do stuff
      MyResponseObject r = new MyResponseObject();
      r.Property1 = DateTime.Now;
      r.Property2 = "Some other data";
      return r;
    }
    catch (Exception ex)
    {
      return null;
    }
  }
}

ImyService is defined as shown here:
[ServiceContract]
public interface ImyService
{
  [OperationContract]
  [WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped)]
  MyServiceResult MyMethod(string p1, string p2);
}

This service will be exposed to both WP7 and iPhone client applications. Because of this, I believe I need to use webHttpBinding. This has caused me to use the following settings in my web.config file:
<system.serviceModel>
  <behaviors>
    <endpointBehaviors>
      <behavior name="myServiceBehavior">
        <webHttp />
      </behavior>
    </endpointBehaviors>
    <serviceBehaviors>
      <behavior name="">
        <serviceMetadata httpGetEnabled="true" />
        <serviceDebug includeExceptionDetailInFaults="false" />
      </behavior>
    </serviceBehaviors>
  </behaviors>

  <serviceHostingEnvironment
    aspNetCompatibilityEnabled="true"
    multipleSiteBindingsEnabled="true" />
  <services>
    <service name="myService">
      <endpoint address=""
        behaviorConfiguration="myServiceBehavior"
        binding="webHttpBinding"
        contract="ImyService" />
    </service>
  </services>
</system.serviceModel>

Both the service and WP7 app are part of the same solution. I can successfully add a reference to the service in my application. When I run the application though, the page that references the service throws an error. The error says:
Could not find default endpoint element that references contract 'MyServiceProxy.ImyService' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.
What am I doing wrong? It just seems like this should be a pretty straightforward thing. Thank you for your help.

A: Have you copied the file "ServiceReferences.ClientConfig" into your Windows Phone 7 project? This file is in your WCF project. Also, WP7 clients support basicHttpBinding only. So, you may see an empty "ServiceReferences.ClientConfig" file unless you switch over to basicHttpBinding


text:
Q: Html 5 File upload I've been trying to get Html 5 file uploading to work. I just don't seem to "get it". So rather than tell you about all the problems I'm facing I was wondering if someone  has already nicked this in the bud and would be willing to help.
Nice to have features would be
1. File upload progress
2. Time left
3. Some sort of confirmation once upload has completed

A: Uploading large file is equal to grabbing maximum resources from CPU and putting the user agent in block state, so we need to avoid these two things, for that we have to upload the large file as multiple parts(chunks), so we have to slice the file and we have to upload in background.
HTML5 introduced some APIs, useful APIs for uploading large file are webworkers and File API.
These two are helpful while uploading large file, we have to upload slice the file at client side to make the file as chunks then we need to upload at background to increase the performance of CPU.
For slicing the File API has slice call
var chunk=file.webkitSlice(start,stop)||file.mozSlice(start,stop);

we have to process the uploading in background Using Webworkers to free the user agent.
var worker=new worker('worker.js');
worker.postMessage(FileList);


text:
Q: Quickly changing Windows permissions for a huge directory tree? I have a huge directory on an NTFS file-system
(i.e. a top-level directory containing tens or hundreds of millions of descendant nodes with the file nodes probably on average about three levels deep) that I need to change permissions for. In particular, I need to give a new user (or group) read-only access to absolutely everything in the directory tree.
The most obvious place to do this is in Windows Explorer by right-clicking the top-level directory and going to the security tab of the directory properties window. However, when trying the obvious things there Windows Explorer seems excited to recursively traverse the whole directory tree and try to modify something or other about the permissions of each node in the tree. This is extremely inefficient for such a large directory!
Can anyone offer any tips for changing permissions without this recursive descent? Do I need to click something particular in the GUI? Do I need to use command-line tools? Could this potentially be the result of a previous sysadmin doing something weird to the permissions in this directory?
I also need to enable network sharing and let the user/group mount the directory over the network. Haven't tried that yet, so I don't know if there will be a similar can of worms when I try to enable sharing.
This is on Windows 2008 Server if it matters.
EDIT: People are right that it probably makes more sense to give permission to a domain group rather than a particular account, so I've made note of this above (That's what I was doing anyway. I don't know why I specifically asked about adding a user in the original question. Sorry for the sloppiness). But of course adding a group to a folder's permissions list isn't any faster than adding a user (None of the existing groups are assigned read-only permissions).

A: If you want the user to have read permission on a folder and all sub-folders, then the permissions of the sub-folders must be changed as well. It sounds like inheritance is already set and you just don't want to wait for this inheritance to propagate to all of the child objects. The only thing you can do besides wait is add the user to an existing group that has the appropriate permissions, assuming such a group exists.

A: There is no quick way to do this. Explorer will happily trundle off for hours (days?) applying the new permission to every file and folder (if inheritance is set).
Enabling a share is much easier, the user just needs at least read permissions on the share. The underlying NTFS permissions will determine what the user can actually do. Note that if the share permission is read-only, then that is the maximum access even if the NTFS security is set to modify (r/w).

A: In this case, there's no need to mess with the NTFS permissions.
Just create a Share to the top-level directory and add the users or groups to the share with Read-Only (or if you want Write) permission.
Even if Everyone has Full Control NTFS permissions on the top-level directory, the most restrictive permission (Share or NTFS) will be used.

A: You really should consider creating a Local or Domain Group and set it's permissions on the top-level directory, then you just add users to the Group as needed.

A: Depending on your use case, in an emergency you may be able to set the permissions and then cancel.
I needed to add specific permission to a high level directory containing millions of files and it was going to take a while. In my particular case, there is one specific directory deeper down into the structure that I needed permissions added to ASAP, and waiting a long time would not have been an acceptable option. I was able to overcome this by first adding the specific permissions to the needed folder, and even though that was also going to take a long time to propagate, I simply clicked "Cancel" right after it started. Doing this warns you that you'll leave the permissions in an inconsistent state, but it did leave the one directory I needed with the proper permissions. Then I went to the higher level directory and set the permissions there and let it go...
The trick is that "Cancel" doesn't undo what it already did, it just stops the propagation.


text:
Q: toast not working in my Samsung Fame, but work on others In my Samsung fame, my app won't display any Toast ( Before it was working)
Now, I tried with HTC Nexus One, and Samsung S3 Mini, and for the same app, both are displaying well Toasts.
I just don't know if there's a problem with my cel, or if a lot of cels can't see Toasts.
Do you have any idea of what can provoque this kind of problem???

A: On Jelly Bean 4.1 or higher,you can disable apps notifications from device settings. Just open notification bar, long tap on any of notifications and click App Info, you should see "Show notifications". Unchecking this option should disable toasts in your app.
If your app does not show any notifications, then you should be able to reach App Info screen from applications manager.
Maybe this is the cause of you missing toasts


text:
Q: Query to find for each CEO, the number of store types, and the max item number among its cities Store_Type  CEO_Name       *Table Store*
Store1      CEO1
Store2      CEO1
Store3      CEO2
Store4      CEO2
Store5      CEO2
Store6      CEO3

City        Store_Type  Items          *Table City*
NY          Store1      8000000
DC          Store1      600000
Philly      Store1      1500000
Ottawa      Store2      800000
Tortonto    Store2      2500000
Berlin      Store4      3500000
Hamburg     Store4      2000000
Bonn        Store4      300000
Paris       Store5      2000000
Lyon        Store5      700000
Bamako      Store6      2000000
Timbuktu    Store6      50000
Mopti       Store6      100000

From inspecting the tables, the result should be similar to this: The output is for each CEO, it list's the number of store types for that CEO and the max item number among its cities
CE01        2             8000000
CEO2        2 (3?)        3500000
CE03        1             2000000

I have tried multiple ways to do this and failed. I know that I can use COUNT(Store_Type) for counting how many store types each CEO has, but since there are duplicates, it's getting difficult to make this 3 column table so to speak. Then MAX(items) will be used but it has to be the max for the CEO as a whole.
I tried breaking it up but I kept getting group errors continuously. Here are some examples I managed to write down but I did try multiple brute forces in the command line once I thought I had an "epiphany" and changed tactics so I don't have those saved. Those mainly encompassed lots of tries with joins but I still couldn't achieve what I wanted to do. Hence, why I am here now asking a simple SQL question.
    select distinct B.CEO_Name
    from Store B, City C
    where B.Store_Type=C.Store_Type;
    -----
    select distinct B.CEO_Name
    from Store B, City C
    where B.Store_Type=C.Store_Type;
    INTERSECT
    select COUNT(distinct Store_Type)
    from City;
    -----
    select distinct C.Store_Type, D.CEO, COUNT(distinct C.Store_Type)
    from City C, Store D
    where C.Store_Type=D.Store_Type;
    ------
    select D.CEO, COUNT(C.Store_Type)
    from Store D, City C
    where D.Store_Type=C.Store_Type;
    ------
    select D.CEO, COUNT(C.Store_Type)
    from Store D full outer join City C
    on (D.Store_Type=C.Store_Type);

A: Something like this should work:
SELECT I.CEO_Name, J.num_stores, I.max_items

FROM
(SELECT S.CEO_Name, MAX(Items) AS max_items
FROM Store S
INNER JOIN City C ON C.Store_Type = S.Store_Type
GROUP BY S.CEO_Name) I

INNER JOIN

(SELECT S.CEO_Name, COUNT(DISTINCT S.Store_Type) AS num_stores
FROM Store S
INNER JOIN City C ON C.Store_type = S.Store_type
GROUP BY S.CEO_Name) J ON I.CEO_Name = J.CEO_Name

ORDER BY I.CEO_Name

The query consists of joining two subqueries to calculate the max_items and num_stores aggregations and then joining on CEO_Name.


text:
Q: Render PDF from URI in Android? I'm using Android Render in my app, but I've got problems with getting a PDF file from URI.
Here's how I get the URI of the file:
 public void performFileSearch() {
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);

    intent.addCategory(Intent.CATEGORY_OPENABLE);

    intent.setType("application/pdf");

    startActivityForResult(intent, READ_REQUEST_CODE);
}

@Override
public void onActivityResult(int requestCode, int resultCode,
                             Intent resultData) {
    if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
         uri = null;
        if (resultData != null) {
            uri = resultData.getData();
            pageNumber = 0;
            render(uri);

        }
    }
}

Then in render(Uri uri):
private void render(Uri uri) {

    try {
        img = (ImageView) findViewById(R.id.image);
        int width = img.getWidth();
        int height = img.getHeight();
        previous.setText(uri.toString());
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);
        File file = new File(uri.getPath());
        PdfRenderer renderer = new PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));

        if(currentpage<0){
            currentpage =0;

        }else if(currentpage>renderer.getPageCount()){

            currentpage = renderer.getPageCount() -1;

            Matrix matrix = img.getImageMatrix();

            Rect rect= new Rect(0,0, width , height);

            renderer.openPage(currentpage).render(bitmap,rect,matrix , PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY );

            img.setImageMatrix(matrix);
            img.setImageBitmap(bitmap);
            img.invalidate();

        }

    } catch (Exception e) {

        e.printStackTrace();
         Toast.makeText(getApplicationContext(), "Nope", Toast.LENGTH_LONG);

    }

}

The activity only shows white screen. I guess that the problem is with creating file from URI. Do you know how to make file from URI that I got? Thanks in advance.

A: Instead of:
File file = new File(uri.getPath());
PdfRenderer renderer = new PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));

Use this:
ParcelFileDescriptor fileDescriptor =context.getContentResolver().openFileDescriptor(uri, "r");
PdfRenderer renderer = new PdfRenderer(fileDescriptor, ParcelFileDescriptor.MODE_READ_ONLY);


text:
Q: wxPython - scaling UI elements with window? When I scale the window in my wxPython app, the elements remain the same size, so if I shrink it, some of them are "cut off" from view. How do I make everything scale with the window? Is it even possible in wx?

A: You use sizers to control layout in wxPython, including scaling widgets.
Here is a tutorial:
http://userpages.umbc.edu/~dhood2/courses/cmsc433/spring2012/?section=Notes&topic=Python&notes=14


text:
Q: Alias for frequently repeated expression I have a table of places like this
   placeid    offset1  effectivetill1         offset2  effectivetill2
   1          3600     2014-01-05 10:23:13    0        2014-07-05 10:23:13
   2          -7200    2014-01-05 10:23:13    -3600    2014-07-05 10:23:13

I run a very big query that needs to work with local time for each place. Therefore if
"ts" is the UTC timestamp for now, and "datetime" is current UTC date-time,  I use the following formula to find local time:
  IF(effectivetill1='0000-00-00' OR effectivetill1>=datetime, ts+offset1,
    IF(effectivetill2>=datetime, ts+offset2, 0)
  )

So I need to repeat the above code several times in my query which is stupid for both computation and code readability.
Is there anyway that I can define localtime once in my query and then use it multiple times?
Thanks.

A: Assuming you would be using the same variable at each row level,
Try:
@ts_with_offset:=IF( effectivetill1 = '0000-00-00' OR
                     effectivetill1 >= datetime,
                     ts + offset1,
                     IF( effectivetill2 >= datetime, ts + offset2, 0 )
                 ) as name_of_this_expression

And use the variable @ts_with_offset to fetch other values based on this value or something like that.
if ( @ts_with_offset >= now(), true, false ) as matched

Note that, when using group functions in the query, this way of using variables is not going to work.


text:
Q: Running Shutdown Script in Ubuntu Server 18.04 Through Crontab (I've searched for answers for this, but all seem to be for older versions of Ubuntu.)
Is there a similar crontab trigger such as "@reboot" for shutdown scripts, and if not, why not?

A: No, because @reboot is

Run once, at startup.

but running a script at shutdown that way makes no sense because your system is going down and the system would 'kill' your script.
When you shutdown your system, it will first send the SIGTERM and wait some time before killing any program, so you can react to that. Here is how.

A: I don't understand why you would want to run a script from cron when the system is shutting down, perhaps I am missing something. Instead of running a script at shutdown, why not just run a script which does what you need it to do before calling the shutdown command. For example, call the script preshutdown.sh:
Run command 1 and output results to a log file.
Run command 2 and append results to the log file ....etc
Shutdown when finished with sudo shutdown -h now

When you next power up the system you can view the log to see the results of the commands which ran in the script.
Edit: To answer the OP's question exactly, there is no crontab trigger for shutdown. If you want to run scripts when pressing the "Shutdown" button in the GUI, or by running the shutdown command in a terminal, put them in /etc/rc6.d, where they will be executed in alphabetical order. Their names must start with K99 and they must be executable.


text:
Q: NDSolve, Schrödinger equation, and decaying solution I am trying to solve a Schrödinger equation for a particle hitting a step potential using NDSolve in Mathematica. Here is my code:
mu = 6.;
m = mu;
R  = 5.;
Vs2 = 4./(2*m*R^2);
Vs = -10./(2*m*R^2) + Vs2;
Energy = 0.001
VCC[r_] = Vs*UnitStep[R - r] + Vs2*UnitStep[r - R];
L = 0;

system = {RC''[r] +
 2/r*RC'[r] + (-L*(L + 1)/r^2 - 2*mu*(VCC[r] - Energy))*RC[r] ==
0, RC[0.001] == 1.0, RC'[0.001] == 0.0 };

syssol = NDSolve[system, {RC[r]}, { r, 0.001, 1000.}, MaxSteps -> 10000000];

Plot[Evaluate[{RC[r]} /. syssol], {r, 0.001, 200.0}, PlotRange -> {-1.1, 1.1}]

There should be decaying wave when particle hits the potential step, but NDSolve gives an increasing result. I am sure there is some trick to fix this, so I am waiting for you help.

A: noeckel's answer on StackOverflow is spot on. This is not a Mathematica issue, this is a mathematical issue. Namely, Mathematica is giving you the correct solution to the system of differential equation and boundary conditions given. The conditions given (and in particular the derivative imposed at the origin) are incompatible with the expected decay. Bear in mind that, at $r \geq 5$, your wavefunction will have two components of the form $\exp(\alpha r)$ and $\exp(-\alpha r)$. For each set of boundary conditions, you get a different linear combination of these two, and the only conditions that make sense are those for which the diverging term is zero.


text:
Q: Back-transformation I have a simple linear regression model, and I have done transformations on the response and the explanatory variable (see call in code below), and I obtained an r-squared of 0.415. When I back-transformed the response variable back to its original units, I get an r-squared of 0.29. My questions are two fold:

*

*First, why is there such a difference in the r-squared values when the same dataset is used;

*Second, if I report the root mean squared error for the second model (which I have read is the most appropriate action), can I still report the r-squared from the first model (i.e. r-squared of 0.42)?

Please see the two summary reports below. Thank you.
1. Call:
lm(formula = sqrt(Clay_Tot) ~ Dose, data = PedonsTx.11.LatLong)

Residuals:
    Min      1Q  Median      3Q     Max
-3.9745 -0.6534 -0.1394  0.4876  4.5746

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) 1.203414   0.248964   4.834 2.42e-06 ***
Dose        0.075897   0.005848  12.977  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 1.161 on 235 degrees of freedom
Multiple R-squared:  0.4175,    Adjusted R-squared:  0.415
F-statistic: 168.4 on 1 and 235 DF,  p-value: < 2.2e-16

2. Call:
lm(formula = Clay_Tot ~ Back.Dose.11, data = PedonsTx.11.LatLong)

Residuals:
    Min      1Q  Median      3Q     Max
-22.316  -6.372  -2.337   2.649  60.211

Coefficients:
              Estimate Std. Error t value Pr(>|t|)
(Intercept)  7.8260736  1.4977945   5.225 3.84e-07 ***
Back.Dose.11 0.0070682  0.0007112   9.939  < 2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 11.75 on 235 degrees of freedom
Multiple R-squared:  0.2959,    Adjusted R-squared:  0.2929
F-statistic: 98.78 on 1 and 235 DF,  p-value: < 2.2e-16

A: When you transform, you change many things:
1) the amount of variation of the response
2) the shape of the relationship between y and x
3) the spread about the relationship
So you cannot expect $R^2$ to be similar across transformations. A transformed response is not "the same data set" -- the transformation changes things!

You could fit a relationship and transform back and try to compare fits, but then the $R^2$ isn't really meaningful for the backtransformed response.
--
When you say "can I...?"; if you mean "does it make sense?" - that depends. What are you using the $R^2$ for a different model to convey? What are you saying about it?


text:
Q: Insert duplicates values linq In a collection of values
[0, 2, 25, 30]

I'm trying to do with linq
[0, 0, 0, 2, 2, 2, 25, 25, 25, 30, 30, 30] //Replicate 2 times (values repeated 3 times)

Is there someway to do it with linq?

A: Of course Tim's answer does answer this question. But posting this as an alternative answer (if you have to repeat for fewer times)
List<int> list = new List<int>() { 0, 1, 2, 3 };
List<int> newList = list.SelectMany(x => new List<int>(3) { x, x, x }).ToList();

A: With value types it's easy, just use Enumerable.Repeat:
var result = collection.SelectMany(x => Enumerable.Repeat(x, 3));

If it was an array use ToArray if it was a list use ToList at the end.
With reference types it depends if you really want the same reference, then you can also use Repeat. Otherwise you need to create "deep-clones" of the instance, for example by using a copy constructor if available:
var result = collection
    .SelectMany(x => Enumerable.Range(1, 3).Select(i => new YourType(x)));


text:
Q: Warnings and errors validating iOS app for upload When trying to upload an app the following errors occur:

The images are in the project, so I'm not sure what the problem is. Also I am not sure what the armv7 error is

A: Like this answer says, you need to remove the CFBundleIconFile ("Icon file") parameter from your project's .plist file.  Also, you need to include armv7 as "Valid Architectures" for both your project and your target.


text:
Q: Grails: is it possible to exclude a plugin dependency of another plugin? I have a grails 2.2.2 app, and have decided to use cache-ehcache plugin.
The problem is that this plugin depends on the cache plugin with version 1.0.0 and my application has the cache plugin version 1.0.1 (i think it is the default for grails 2.2.2). Therefore when i try to compile the app i always get the same message:
You currently already have a version of the plugin installed [cache-1.0.1]. Do you want to update to [cache-1.0.0]? [y,n]

I have to answer this question every time i compile the application. I tried to change the project plugin dependency to cache-1.0.1 in .grails/2.2.2/my_project/plugins/cache-ehcache-1.0.0/dependencies.groovy and plugin.xml files. It does not seem to work.
I know that it is possible to exclude jars from plugin dependencies but is it possible to exclude another plugin?
I tried changing the section of BuildConfig.groovy to:
plugins {
    ...
    compile(':cache-ehcache:1.0.0') { excludes ":cache:1.0.0"}
}

but it still does not seem to work. I get the same question every time i compile the app.

A: Use as
plugins {
    ...
    compile(':cache-ehcache:1.0.0') { excludes "cache"}
}


text:
Q: Plotting: DensityPlot produces artifacts I am trying to plot the electric potentials of bouncing balls using the following code:
g = 0.1;
Tmax = 100;
n = 6;
pos = RandomReal[{-1, 1}, {n, 2}];
charge = RandomReal[{1, 10}, 10];

sol = NDSolve[
    Flatten@Table[{
        With[{i = i},
            {(x[i])''[t] == 0,
             (x[i])'[0] == 0,
             (y[i]'')[t] == -g,
             (y[i])'[0] == 0,
             x[i][0] == pos[[i, 1]],
             y[i][0] == pos[[i, 2]],
             WhenEvent[
                 y[i][t] < -1, {y[i]'[t] -> -0.95 y[i]'[t],
                 y[i][t] -> y[i][t] + 0.05}]
             }
         ]
 }, {i, 1, n}], Flatten@Table[{x[i], y[i]}, {i, 1, n}], {t, 0, Tmax}, PrecisionGoal -> 2];

Manipulate[Graphics[
    Table[
        With[{p = Evaluate[
            {x[i][t], y[i][t]} /. First[sol]]},
        Disk[p, 0.05]], {i, 1, n}], PlotRange -> 1.05], {t, 0, Tmax}]

PotentialAnimated[x_, y_, t_] :=
    Sum[charge[[i]]/
        If[Norm[({x, y} - {x[i][t], y[i][t]} /. sol)] > 0.001,
           Norm[({x, y} - {x[i][t], y[i][t]} /. sol)], 0.001],
    {i, 1, n}]

Manipulate[
    DensityPlot[PotentialAnimated[x, y, t], {x, -1, 1}, {y, -1, 1}], {t, 0, 10}]

This^ last command should plot the potentials in my box caused by the charged balls jumping up and down, but I get an almost fractal looking artifact from my lower left to my upper right corner. Any ideas why this is happening ?
// part 2
not directly related but I feel like it would be a waste to start a new question just for this.
Im now trying to combine the two plots like this:
Manipulate[
 Show[{DensityPlot[
    PotentialAnimated[x, y, t], {x, -10, 10}, {y, -10, 10},
    ColorFunction -> "SunsetColors"], Graphics[
    Table[
     With[{p = {x[i][t], y[i][t]} /. First[sol]},
      {ColorData["TemperatureMap", (charge[[i]] + 10)/20],
       Disk[p, 0.5]}
      ]
     , {i, 1, n}]
    , PlotRange -> 10.5, Background -> Black]}], {t, 0, Tmax}]
for charges ranging from -10 to 10 , but it seems like the colors get "clipped" on the density plot
how can I fix it so colours near the balls dont just go white.
thx for the help so far
catadoxas

A: This happens because sol contains the symbols x and y.  These are global symbols.  The function PotentialAnimated uses them without localization.  There's be a conflict when DensityPlot assigns temporary values to x and y.
The fix is to localize them:
PotentialAnimated[u_, v_, t_] :=
 Block[{x, y},
  Sum[charge[[i]]/EuclideanDistance[{u, v}, {x[i][t], y[i][t]} /. sol[[1]]], {i, 1, n}]
 ]

This function works as expected.
But what exactly happened when x and y were not properly localized to PotentialAnimated?
Here's an result I got while experimenting with Table:
In[39]:= Table[{x, y, PotentialAnimated[x, y, 20]}, {x, {.7}}, {y, {.7}}]
Out[39]= {{{0.7, 0.7, 1035.03}}}

In[40]:= PotentialAnimated[0.7, 0.7, 20]
Out[40]= 27.7281

Table, and DensityPlot too, localizes x and y using Block.  In other words, these functions assign temporary values to x and y.  Due to an accident PotentialAnimated still works in this case, as it relies on ReplaceAll.  It doesn't really matter if you make a replacement as x[i][t] /. {x -> ...} or 42[i][t] /. {42 -> ...}, up to the point where that magic number 42 gets repeated.  This happened in your case when x became equal to y, which changed the replacement.
Hope this hastily typed up explanation is clear enough ...
Morale: don't leave dangling global symbols when defining functions.  Or if you like: when using dynamic languages that support dynamic scoping, things can go wrong in weird and unexpected ways.
In your case you can try using NDSolveValue instead of NDSolve, which eliminates the need for these symbols.

A: I was able to solve the problem by using an auxiliary function ... See Szabolcs' answer for the explanation.
PotentialAnimated[u_, v_, t_] :=  Sum[charge[[i]]/
               EuclideanDistance[{u, v}, {x[i][t], y[i][t]} /. sol[[1]]], {i, 1,  n}]

q[f_, x_, y_, opts : OptionsPattern[]] := DensityPlot[f, {x, -1, 1}, {y, -1, 1}, opts]

GraphicsRow[{
  q[PotentialAnimated[x, y, 10], x, y, PlotPoints -> 20,  MaxRecursion -> 5],
  DensityPlot[PotentialAnimated[x, y, 10], {x, -1, 1}, {y, -1, 1},
              PlotPoints -> 20, MaxRecursion -> 5]}]


text: Q: Why is e acceptable in input type number I have an input with a type of number. When I was testing it out, I discovered that when I typed the letter e, it appeared in the text box. Any other letter did not: the input was a number. Why is a letter allowed in this input type?


text:
Q: How to write @ as string in Java How do I write @ as an string in java.
When I write "@" it indicate as missing resource type
This is my TextView
<TextView
android:height="wrap_content";
android:width="wrap_content";
android:text="@";
/>

A: The @ symbol is used for resources reference inside xml files.
The advisable way to do this is define the same inside values/string resources as
<string name="at_sign">"@"</string>
...

Then use it
...
<TextView
android:height="wrap_content"
android:width="wrap_content"
android:text="@string/at_sign"
/>

A: Instead of using @ you could use \u0040 (the unicode character). An other solution: define a string resource and use this in your TextView.

A: android:text="\@"

OR
Using backslash :
<string name="at">\@</string>

OR
Using quote :
<string name="at">"@"</string>

A: You can do this with a simple addition of backslash before such special character. It's not only for @ but for single quote, double quotes, colon etc.
Hope this helps. Put the below code and see if it helps.
<TextView
android:height="wrap_content"
android:width="wrap_content"
android:text="\@"/>


text:
Q: Is there a lazy Session IO Monad? You have a sequence of actions that prefer to be executed in chunks due to some high-fixed overhead like packet headers or making connections. The limit is that sometimes the next action depends on the result of a previous one in which case, all pending actions are executed at once.
Example:
mySession :: Session IO ()
    a <- readit  -- nothing happens yet
    b <- readit  -- nothing happens yet
    c <- readit  -- nothing happens yet
    if a       -- all three readits execute because we need a
      then write "a"
      else write "..."
    if b || c  -- b and c already available
      ...

This reminds me of so many Haskell concepts but I can't put my finger on it.
Of course, you could do something obvious like:
[a,b,c] <- batch([readit, readit, readit])

But I'd like to hide the fact of chunking from the user for slickness purposes.
Not sure if Session is the right word. Maybe you can suggest a better one? (Packet, Batch, Chunk and Deferred come to mind.)
Update
I think there was a really good answer last night that I read on my phone but when I came back to look for it today it was gone. Was I dreaming?

A: I don't think you can do exactly what you want, since what you describe exploits haskell's lazy evaluation to have the evaluation of a force the actions that compute b and c, and there's no way to seq on unspecified values.
What I could do was hack together a monad transformer that delayed actions sequenced via >> so that they could be executed all together:
data Session m a = Session { pending :: [ m () ], final :: m a }

runSession :: Monad m => Session m a -> m a
runSession (Session ms ma) = foldr (flip (>>)) (return ()) ms >> ma

instance Monad m => Monad (Session m) where
  return = Session [] . return
  s >>= f = Session [] $ runSession s >>= (runSession . f)
  (Session ms ma) >> (Session ms' ma') =
    Session (ms' ++ (ma >> return ()) : ms) ma'

This violates some monad laws, but lets you do something like:
 liftIO :: IO a -> Session IO a
 liftIO = Session []

 exampleSession :: Session IO Int
 exampleSession = do
   liftIO $ putStrLn "one"
   liftIO $ putStrLn "two"
   liftIO $ putStrLn "three"
   liftIO $ putStrLn "four"
   trace "five" $ return 5

and get
ghci> runSession exampleSession
five
one
two
three
four
5
ghci> length (pending exampleSession)
4

A: This is very similar to what Haxl does.
For more info:

*

*Open sourcing haxl - Facebook Code Blog

*ICFP 2014 talk

A: You could use the unsafeInterleaveIO function. It is a dangerous function that can introduce bugs to your program if not used carefully, but it does what you're asking for.
You can insert it into your example code like this:
lazyReadits :: IO [a]
lazyReadits = unsafeInterleaveIO $ do
  a <- readit
  r <- lazyReadits
  return (a:r)

unsafeInterleaveIO makes the action as a whole lazy, but once it starts evaluating it will evaluate as if it had been strict. This means in my above example: readit will run as soon as something tests whether the returned list is empty or not. If I'd used mapM unsafeInterleaveIO (replicate 3 readit) instead, then readit would only be run when the actual elements of the list are evaluated, which would make the contents of the list depend on the order in which its elements are inspected, which is one example of how unsafeInterleaveIO can introduce bugs.


text:
Q: How to work with less combinations of variables in R combn function? I'm creating a loop with combn function in R. My goal is to obtain every combination of 133 variables characters from 2 until 133 combinations from a vector with the names. However, when I start my code, the routine stop and gives me the following statment: "Error: Unable to allocate vector of size 2.4Gb". It happens when the routine starts with five combinations.
There is a condition to reduce the amount of combination that would help to turn the list smaller. I'm desire to keep just combinations that have the following string: "var_pib_nsa_interanual"
Below it's my code:

gc() #garbage collection - clear memory.
memory.limit (9999999999) # increase the memory size.

nome_series <- c("x.consu_energia_brasil_total","x.massa_sal_ampl","x.ibc_br","x.selic_aa","x.base_monetaria","x.ipca_adm_var","x.ipca_livre_var","x.ipca_alim_domic_var","x.cambio_real_efet_ipca","x.tx_media_juros_pf_total","x.utiliza_capac_ocio_fgv","x.pib_mensal","x.ipca_cheio_var_nsa","x.consu_energia_industr","x.consu_energia_residencia","x.consu_energia_comercial","x.economic_conditions","x.house_index,"x.sales_vehicles","x.sales_credit","x.usa_economic","x.Anfavea_Producao_de_automoveis_e_comerciais_leves","x.Anfavea_Producao_de_caminhoes_e_onibus","x.Fenabrave_Licenciamento_de_veiculos_novos","x.Funcex_Exportacao_total","x.Funcex_Exportacao_de_manufaturados","x.Funcex_Importacao_total","x.IAB_Producao_de_aco_bruto","x.capacity_utilization","x.exportssurvey","x.Abraciclo_Producao_de_motocicletas","x.industrial_production","x.manu_production","x.civil","x.prod_agro","x.civil_price","x.services","x.inflation","x.ABAL_Producao_de_aluminio_primario","x.exchangerate","x.consumer_survey","x.Receita_Federal_Arrecadacao_de_IPI","x.Receita_Federal_Arrecadacao_de_IR","x.Receita_Federal_Arrecadacao_IOF","x.BNDES_COM","x.BNDES_TOTAL","x.businesssurvey","x.igp_m_var_mensal","x.interestrate2","x.Funcex_Importacao_de_materias_primas","x.alcool","x.carne_bovina","x.carne_suina","x.carnes_aves","x.celulose","x.minerio_ferro",...)

num_elementos <- 1:5
combinacoes_possiveis <- list()
comb <- list()

for (i in 2:length(num_elementos)) {
    combinacoes_possiveis[[i]] <- combn(nome_series,
                                        num_elementos[i],
                                        simplify = FALSE
                                        )

     comb[[i]] <- Filter(function(x){"var_pib_nsa_interanual" %in% x},
                    combinacoes_possiveis[[i]]
                    )

     combinacoes_possiveis[[i]] <- NULL
}

A: Using Iterators
Generally speaking when you are dealing with memory problems, iterators are a great option for getting around this hardware limitation.
For example, the package RcppAlgos (I am the author) and the package arrangements offer combinatorial iterators. Instead of generating everything up front and then filtering, you would generate one combination at a time and carry out your check. Something like:
library(RcppAlgos)
iter <- comboIter(nome_series, num_elementos[i])
res <- iter@nextIter()

while (!is.null(res)) {
    ## Your check here as well as what you
    ## want to do with the current combination
    ## if the check is successful
    ## .
    ## .
    ## .

    res <- iter@nextIter()
}

And with the package arrangements we have:
library(arrangements)
iter <- icombinations(nome_series, num_elementos[i])
res <- iter$getnext()

while (!is.null(res)) {
    ## Same as above
    res <- iter$getnext()
}

Better Solution
A better solution is to think a little harder about your actual problem. It looks like you only want combinations that contain a certain value. In these instances, simply leave this value out and generate all combinations of n - 1 choose m - 1, then tack on your value of choice. Remember, with combinations, order doesn't matter, so c(1, 2, 3) is equivalent to c(2, 1, 3).
Below is a small example. Let's say we want only combinations of 5 choose 3 where 2 is in the combination. Using the method outlined by the OP, we have:
Filter(\(x) 2 %in% x, combn(5, 3, simplify = FALSE))
# [[1]]
# [1] 1 2 3
#
# [[2]]
# [1] 1 2 4
#
# [[3]]
# [1] 1 2 5
#
# [[4]]
# [1] 2 3 4
#
# [[5]]
# [1] 2 3 5
#
# [[6]]
# [1] 2 4 5

Now, using the method outlined above, we have:
## If the output doesn't matter, below is a very simple method
combn(c(1, 3, 4, 5), 2, \(x) c(x, 2))
#      [,1] [,2] [,3] [,4] [,5] [,6]
# [1,]    1    1    1    3    3    4
# [2,]    3    4    5    4    5    5
# [3,]    2    2    2    2    2    2

## Or using rbind
rbind(2, combn(c(1, 3, 4, 5), 2))
#      [,1] [,2] [,3] [,4] [,5] [,6]
# [1,]    2    2    2    2    2    2
# [2,]    1    1    1    3    3    4
# [3,]    3    4    5    4    5    5

## Or if the output really needs to be a list
combn(c(1, 3, 4, 5), 2, \(x) c(x, 2), simplify = FALSE)
# [[1]]
# [1] 1 3 2
#
# [[2]]
# [1] 1 4 2
#
# [[3]]
# [1] 1 5 2
#
# [[4]]
# [1] 3 4 2
#
# [[5]]
# [1] 3 5 2
#
# [[6]]
# [1] 4 5 2

Of course, if memory is still an issue, we could use iterators along with this approach. In fact, RcppAlgos::comboIter offers a FUN argument similar to combn which allows you to get the desired result while also keeping memory low:
iter <- comboIter(c(1, 3, 4, 5), 2, FUN = \(x) c(x, 2))
iter@nextIter()
# [1] 1 3 2

## Get more than one at a time
iter@nextNIter(2)
# [[1]]
# [1] 1 4 2
#
# [[2]]
# [1] 1 5 2

## Get the remaining combinations
iter@nextRemaining()
# [[1]]
# [1] 3 4 2
#
# [[2]]
# [1] 3 5 2
#
# [[3]]
# [1] 4 5 2

You can also make use of the FUN.VALUE argument to get simplified output.
iter <- comboIter(c(1, 3, 4, 5), 2, FUN = \(x) c(x, 2),
                  FUN.VALUE = c(1, 2, 3))
iter@nextNIter(3)
#      [,1] [,2] [,3]
# [1,]    1    3    2
# [2,]    1    4    2
# [3,]    1    5    2


text:
Q: GitLab - HTTP Basic: Access Failed I haven't pushed to this repo in a few weeks, but now i can't. I ran into an issue like this before and remedied it by clearing git credentials as i saw in another StackOverflow post. However none of the questions i have found have remedied this issue.
This is a new branch that i'm setting up and trying to push, i'm also up to date on the latest Git as of 6/5/2018, and i don't have 2FA set up on this account as of right now.
Any and all help in fixing this would be greatly appreciated because i can't find a way to fix this at all through their documentation or stack overflow.
$ git push --set-upstream origin updateToUnity2018.1
remote: HTTP Basic: Access denied
fatal: Authentication failed for 'https://gitlab.com/buffet-time/project-top-down.git/'

A: After submitting a support request on GitLab
I was pointed to this stackoverflow post, and this fixed my issue which ended up being GitLab for some reason not bringing up git credentials in the normal way.
Git: Failed to erase credential: Element not found

A: I was also facing same issue
remote: HTTP Basic: Access denied fatal: Authentication failed for 'https://:@gitlab********
so i opened terminal and checked for cat gitconfig and removed [url "https://:@gitlab.***"] insteadOf = https://gitlab.*****/  and then i tried pulling or pushing it asked me username and password again, and it worked.
Cheers.

A: i had the same issue but this was after the 2fa authentication my solution was use other terminal outside vscode and this prompted to enter the user name and password


text:
Q: how to insert text and images in database and retrieve in listview in android with values entered in edittext I want to insert values from edittext and select image and then store it into the database and retrieve in listview. I successfully inserted the edittext values like name and password in listview bt dont know how to insert images and retrieve it with name and all stuff. plz give some sample code.
thanks in advance!

A: First create a custom list view follow the link given below
http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/
and store data into DataBase use
http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/

A: hi the below link shows how to upload image to the locally server link and save the url,name,password in database table
load all images form the URL  and data & display it efficiently using lazy list view refer this lazylist link

A: Storing image in Sq lite using Blob is not an efficient way.
store the captured image in sdcard. and store the image uri to sqlite table.And retrieve from path. you can use timestamps for retrieving..


text:
Q: Cropping video using Amazon ElasticTranscoder From the docs it explicitely says "... affects the scaling that Elastic Transcoder applies to your output image ..."
Can I conclude that size scaling is for image only and not for video?
Is it possible to crop videos using elastic transcoder?


text:
Q: VBScript create and open a new file I try to make a script in VBScript for PowerAMC.
And I've got an error.
I checked all elements to make a file with the content (XSD file):
private Sub writeInFile(pathFolder, pathFile, val)
  Output "WriteInFile["&pathFolder&pathFile&"]"
  Dim fso, MyFile
  Set fso = CreateObject("Scripting.FileSystemObject")

  Set MyFile = fso.CreateTextFile(pathFolder&pathFile, true)
  If (fso.FileExists(pathFolder&pathFile)) Then
    MyFile.WriteLine(val)
  Else
    ouput "File can't be create"
  End If

  MyFile.Close
  end Sub

And the file exists with good content, but if I try to read it with:
public Function readFile(path)
  'Declare variables
  Dim objFSO, objReadFile, contents

  'Set Objects
  Set objFSO = CreateObject("Scripting.FileSystemObject")
  Set objReadFile = objFSO.OpenTextFile(path, 1, false)

  'Read file contents
  contents = objReadFile.ReadAll

  'Close file
  objReadFile.close

  'Cleanup objects
  Set objFSO = Nothing
  Set objReadFile = Nothing

  readFile = contents
   End Function

I get that : "ÿþ<" for only content, but if I try to read a file that is not created by the previous function, it runs perfectly.

A: I think the problem comes from Unicode format,
take a look at this => FileSystemObject - Reading Unicode Files