text:
Q: Extracting part of a string based on its naming convention I'm trying to extract a piece of information about a certain file. The file name is extracted from an xml file.
The information I want is stored in the name of the file, I want to know how to extract the letters between the 2nd and 3rd period in the string.
Eg. name is extracted from the xml, it is stored as a string that looks something like this "aa.bb.cccc.dd.ee" and I need to find what "cccc" actually is in each of the strings I extract (~50 of them).
I've done some searching and some playing around with slicing etc. but I can't get even close.
I can't just specify the letter in the range [6:11] because the length of the string varies as does the number of characters before the part I want to find.
UPDATE: Solution Added.
Due to the fact the data that I was trying to split and extract part from was from an xml file it was being stored as an element.
I iterated through the list of Estate Names and stored the EstateName attribute for each one as a variable
for element in EstateList:
         EstateStr = element.getAttribute('EstateName')

I then used the split on this new variable which contains strings rather than elements and wrote them to the desired text file:
asset = EstateStr.split('.', 3)[2]
 z.write(asset + "\n")

A: If you are certain it will always have this format (5 blocks of characters, separated by 4 decimals points) you can split on '.' then index the third element [2].
>>> 'aa.bb.cccc.dd.ee'.split('.')[2]
'cccc'

This works for various string lengths so you don't have to worry about the absolute position using slicing as your first approach mentioned.
>>> 'a.b.c.d.e'.split('.')[2]
'c'
>>> 'eeee.ddddd.ccccc.bbbbb.aaaa'.split('.')[2]
'ccccc'

A: Split the string on the period:
third_part = inputstring.split('.', 3)[2]

I've used str.split() with a limit here for efficiency; no point in splitting the dd.ee part here, for example.
The [2] index then picks out the third result from the split, your cccc string:
>>> "aa.bb.cccc.dd.ee".split('.', 3)[2]
'cccc'

A: You could use re module to extract the string between 2 and third dot.
>>> re.search(r'^[^.]*\.[^.]*\.([^.]*)\..*', "aa.bb.cccc.dd.ee").group(1)
'cccc'


text:
Q: How to replace outlier after groupby? I have a dataframe of portfolios with risk numbers. I want to groupby by "Port" column in dataframe below and then replace the values in "Risk" column where it is greater than the 95% quantile of its group with the median of that portfolio group
df =
    Date           Port       Risk
   2019-04-30        a         21.8
   2019-03-29        a         22.6
   2019-02-28        a         500
   2019-01-31        a         26.1
   2019-04-30        b         36.4
   2019-03-29        b         43.3
   2019-02-28        b         40
   2019-01-31        b         364

I tried below code I found on stackoverflow but it doesn't work.
def replace(group):
    q = group.quantile(0.95)
    outlier = group>q
    group[outlier] = group.median()
    return group

    df.groupby('Port').transform(replace)

Also tried
q = pd.DataFrame(df.groupby('Port')['Risk'].quantile(0.95))
df.loc[(((q.loc[df.Port,'Risk']<df['Risk'].values)))]=q.loc[df.Port,'Risk']

Expected result will be to replace the third record of port "a" with median of group "a" which is 22.2 and the fourth record of port "b" with median of group "b" which is 41.6
df =
    Date           Port       Risk
   2019-04-30        a         21.8
   2019-03-29        a         22.6
   2019-02-28        a         22.2
   2019-01-31        a         26.1
   2019-04-30        b         36.4
   2019-03-29        b         43.3
   2019-02-28        b         40
   2019-01-31        b         41.6

A: To stick to the code you posted:
def replace(group):
    q = group.quantile(0.95)
    outlier = group>q
    group[outlier] = group.median()
    return group

df['Risk'] = (df.groupby('Port').transform(replace))
print(df)

output:
         Date Port   Risk
0  2019-04-30    a  21.80
1  2019-03-29    a  22.60
2  2019-02-28    a  24.35
3  2019-01-31    a  26.10
4  2019-04-30    b  36.40
5  2019-03-29    b  43.30
6  2019-02-28    b  40.00
7  2019-01-31    b  41.65

A: The medians seem to differ slightly with what you're saying (see comment in the output dataframe). Here's one approach using GroupBy.transform with where
g = df.groupby('Port').Risk
df['Risk'] = (df.Risk.where(g.transform('quantile', q=0.95) > df.Risk,
                            g.transform('median')))

      Date     Port  Risk
0  2019-04-30    a  21.80
1  2019-03-29    a  22.60
2  2019-02-28    a  24.35 # -> np.median([21.8, 22.6, 500, 26.1]) = 24.35
3  2019-01-31    a  26.10
4  2019-04-30    b  36.40
5  2019-03-29    b  43.30
6  2019-02-28    b  40.00
7  2019-01-31    b  41.65

A: Here is a way to do it :
df = pd.DataFrame({"Port" : ['a', 'a', 'a', 'a', 'b', 'b', 'b' ,'b'],
    "Risk" : [21.8, 22.6, 500, 26.1, 36.4,43.3,40,364]
})

for port in df['Port'].unique():
    mask_port = df['Port'] == port
    quantile_port = df[mask_port].quantile(0.95)
    median_port = df[mask_port].median()
    df.loc[(mask_port) & (df['Risk']>quantile_port.Risk), 'Risk'] = median_port.Risk

In [1] : print(df)
Out[1] :   Port   Risk
0    a  21.80
1    a  22.60
2    a  24.35
3    a  26.10
4    b  36.40
5    b  43.30
6    b  40.00
7    b  41.65

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot Compile RenderScript on Eclipse I have similar case as mentioned on https://code.google.com/p/android/issues/detail?id=55342 and stated FIXED.
But I still cannot make it works. I have updated SDK Tools to 22.0.5 (latest). SDK Platform Tools to 18.0.1 (latest) and SDK Build Tools 18.0.1 (latest).
But still I got Error executing Renderscript. Please check llvm-rs-cc is present at "D:\Android\android-sdk-windows\platform-tools\llvm-rs-cc.exe"
What did I miss? Can someone point me out?

A: @kamil. Thanks for your pointer. Yes, I forgot to update the ADT to 22.0.5. I did only update SDK Tools. Now everything works fine.


text:
Q: Where would a jaxrs:serviceBean be defined? I have a cxf-context.xml file that has the following serviceBean (I'm using spring boot for IoC):
<jaxrs:server id="cxfFactory" address="/">
        <jaxrs:serviceBeans>
            <ref
                bean="defaultService" />
        </jaxrs:serviceBeans>

However, there is no definition of what object this points to in the rest of the .xml file. I can't find where Spring would know what class this is talking about. I actually do know what class it is, but how does the framework know?
Any pointers?


text:
Q: Replace several parts of a string with values from a lookup table I have a cell with text: "aaa,bbb,ccc,ddd,eee".
I have a lookup table with values corresponding to the different strings. E.g. "aaa"=1, "bbb"=2 etc.
I need to create a single cell with text where the "aaa" etc. have been replaces with their corresponding value.
E.g. the string "aaa,bbb" should create the string "1,2".
Any way to do this?

A: If your lookup table is in columns A:B and the text you want to replace in cell C1 then try:
=JOIN(",",ArrayFormula(VLOOKUP(SPLIT(C1,","),A:B,2,0)))


text:
Q: Clear spaces and put on vector How can i get the values from edit text without getting the spaces between each one of them , and fill up a vector by these values
For example if the input on the edit text is: 5 500 60 90
I want to fill up a vector by these valuse when click on buttun

A: You can get the string by calling editText.getText().toString() and then call on split(" ") method. This gives you an array of strings separated by the space character. You can then parse each string from that array and get the values and then build the vector


text:
Q: WinRT C# Metro Play MediaElement Asynchronous Im trying to build Win8 metro style application. Im trying to play remote video which is on web in media element.
      MediaElement media = new MediaElement();
        Uri url = new Uri("some url on web");
        media.Source = url;
        media.Play();

The first streaming takes time. It takes time to video to start play, in this meantime application is locked. I want to do that playing ascnhronously. How can i achive this.

A: after some search, i find out that with dispatcher element, i can do my work asynchronously. Here is the sample:
await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
         {
            MediaElement media = new MediaElement();
            Uri url = new Uri("some url on web");
            media.Source = url;
            media.Play();
         }

        );

You have to mark the calling function as async in order this code block to work.


text:
Q: jQuery parse xml Invalid XML: HTTP/1.1 200 OK I am trying to parse this xml with jquery: https://feed.podbean.com/talkloudradio.com/feed.xml
var url = https://feed.podbean.com/talkloudradio.com/feed.xml

$.ajax({
        url: url,
        dataType: "json",
        cache: false
    }).done(function( d ) {
            console.log($.parseXML( d.contents ))

    }).fail(function(jqXHR, textStatus, errorThrown) {
        console.log(jqXHR, textStatus, errorThrown);

    });

And I am getting error with parseXML:
Uncaught Error: Invalid XML: HTTP/1.1 200 OK

If I try to search directly in done function with this, it doesnt find anything:
$(d).find("item").each(function(){
    console.log($(this))
})

What would be the issue, is it a valid rss?


text:
Q: flex performace, method calls or events I'm trying to knock some cpu cycles off my app and I want to know what the least cpu intensive methods are for executing code.
Take these 2 examples. The first is an enterframe running and calling various methods.
The second is the same enter frame but dispatching events instead.
1) Would it be likely for one of these enterframes to be less cpu intensive than the other?
2) In the first example does the frame have to wait until method 1 2 and 3 have been completed before the next frame can render and execute code?
3) In the 2nd example could the events dispatched to method 1 2 and 3 be executed in a frame other than the one that called it? EG, if the the cpu is under pressure can it defer the execution?
public function enterframe(e:Event):void
{
method1();
method2();
method3();
}

public function enterframe(e:Event):void
{
dispatchEvent(MethodEvent.Test, method1);
dispatchEvent(MethodEvent.Test, method2);
dispatchEvent(MethodEvent.Test, method2);
}

A: Edit: Since I got confused with events dispatched by built in features in the Flash player and custom events dispatched by as3 code my first answer is incorrect. Although the flash player itself is multithreaded, you can't access threading functionality in as3. Here's my amended answer:

1) Would it be likely for one of these
  enterframes to be less cpu intensive
  than the other?

Well if you look at the amount of instructions the one dispatching a event have more instructions until it actually executes the code in the methods. It first have to run through a list of event listeners and look for the right one in that particular object compared from the given event type.

2) In the first example does the frame
  have to wait until method 1 2 and 3
  have been completed before the next
  frame can render and execute code?

Yes. Same thing happens in the second example.

3) In the 2nd example could the events
  dispatched to method 1 2 and 3 be
  executed in a frame other than the one
  that called it? EG, if the the cpu is
  under pressure can it defer the
  execution?

No, they are executed in a procedural fashion.

Old answer:

1) Would it be likely for one of these
  enterframes to be less cpu intensive
  than the other?

Well if you look at the amount of instructions the one dispatching a event have more instructions until it actually executes the code in the methods. Although the event dispatching creates a new thread for each method so they run simultaneously. The time you spend for those extra instructions to call the method you will gain in the thread splitting. So if you have a lot of instructions in each method I would say the event dispatching is faster.

2) In the first example does the frame
  have to wait until method 1 2 and 3
  have been completed before the next
  frame can render and execute code?

Yes.

3) In the 2nd example could the events
  dispatched to method 1 2 and 3 be
  executed in a frame other than the one
  that called it? EG, if the the cpu is
  under pressure can it defer the
  execution?

Since the code is executed in a separate thread and the enter frame continues the methods can be executed multiple times before the first one finished depending on how much instructions there are in each method.

A: This is a classic case of premature optimization. Whether you use Event Driven approach or method call should be based on good design practices, not based on which  one is faster.
In any case, Flex is mostly asynchronous and it maintains loose component coupling and event chaining, using event driven model and in post probability the methodology you are looking in to will not help substantial performance improvement (especially cpu cycles ??). I suggest that you use Flex Profiler, if you think your performance is not optimal. (mostly its storing components in memory, that slows down flex application. As long as you free obsolete component reference...)

A: I think the best you can do about optimization is forget enterFrame event. Place a Timer in your code, and set the delay according to your exact needs. You can experience a huge optimization easily.
As far as I know enterFrame is connected to the fps. So if your movie is a 30 fps animation, then it will run 30 times a second.
Now, this means it is more like an interval (flash.utils.setInterval), or a Timer.
Therefore you can see, enterFrame is more or less an easy way to setup an interval, or an interval-like functionality. If you know your needs, the refresh rate and stuff, you can set the timer and interval more precisely to gain a huge performance increase.

A: It looks, you're mistaken in dispatchEvent(MethodEvent.Test, method1); You should use addEventListener function first.
addEventListener(MethodEvent.Test, method1);
addEventListener(MethodEvent.Test, method2);
addEventListener(MethodEvent.Test, method3);

And then dispatchEvent(MethodEvent.Test);. There's no significant difference in performance between these 2 variants. Dispatching event is just calling each function in array of listeners. So the only performance issue is in looping through listeners array.


text:
Q: Event listening timeout - node.js I'm trying to make a simple exchange between my node app and an UDP server. I'm calling a tracker server of the bittorrent network to be precise.
I need an event listner that, if it catch the 'message' event in a certain timeframe runs one callback function and stop listening but if it gets to the end of that timeframe it would run an other callback function and stop listening.
I feel like the solution lies somewhere close to Promises but I have trouble finding how to do that.
Or maybe there is a function that I haven't seen in the dgram library. The net package has socket.setTimeout(timeout[, callback]) but dgram seem not to have anything like it.

A:
Is it something you're looking for stackoverflow.com/a/8377810/980828? – LEQADA?

Yep!


text:
Q: Apex Rest API Public Web Service Cannot See Data? I saw how to implement public REST API with Salesforce,
Can I have a public APEX REST API?
https://developer.salesforce.com/blogs/developer-relations/2012/02/quick-tip-public-restful-web-services-on-force-com-sites.html
The problem is that when i want to expose data, i run soql on Contact object and i did not retrieve any data!
As I see in this documentation: https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_rest_exposing_data.htm the it is run as a system context and i should retrieve data :(
Did someone suceed to expose Data from object in a public rest webservice? what I should do in the Site exposing the rest web service?
@RestResource(urlMapping='/getmenu/*')

global with sharing class MenuService {

   @HttpGet
 global static String getMenuTree() {
    RestResponse res = RestContext.response;
    res.addHeader('Access-Control-Allow-Origin', '*');
    res.addHeader('Content-Type', 'application/json');
    String contactId = RestContext.request.params.get('contactid');

    JSONGenerator generator = JSON.createGenerator(true);
    generator.writeStartObject();
    if(contactId!=null && (contactId.length() == 15 || contactId.length() == 18) && Pattern.matches('^[a-zA-Z0-9]*$', contactId)) {
        Contact[] contacts = [Select Id,Name from Contact where Id=:contactId];
        if(contacts.size()>0){
             generator.writeStringField('Name',contacts[0].name);
        }else{
            generator.writeStringField('Name','Unknow contact');
        }
    }
    //... other logic

    generator.writeEndObject();

    return generator.getAsString();
    }

}

A: Could you please post your code. I think problem in code signature or modification.
With sharing modificator used for apply current sharing model to you class.
You can read docs about it - https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_keywords_sharing.htm


text:
Q: Without exiting from the ssh_tunnel, open new terminal I am using Python and wxpython for gui. I am trying to connect ssh tunnel. After connecting to ssh, wants a new terminal to open and have to continue my operation in local machine. How to achieve this?
I tried subprocess, pexpect and paramiko, but all are capable to connect to ssh but not open the new teminal
Below my code is there which I tried with pexpect:
import time
import sys
import pexpect
c = pexpect.spawn("ssh -Y -L xxxx:localhost:xxxx user @ host.com")
time.sleep(0.1)
c.expect("[pP]aasword")
c.sendline("xxxxxx")
time.sleep(0.2)
c.interact()
c.pexpect([user@host.com~]$)
# here after its connects to ssh then command wont be executed
c.sendline("xfce4-terminal")

On 24/04/2013
I am able to open new terminal but what happens is when the new terminal will open controls from gui doesn't go there. Any help?

A: Opening a new local terminal and connecting an existing process in to it is a little complicated.  There are at least three approaches:

*

*Open the terminal before you start connecting, and run all the code that tries to establish the connection from within it.  This is simplest.  The main drawback is that the terminal will appear even if the connection fails, which might be what you want to avoid.

*Run the connection attempt with a session of tmux or screen and if you detect that it succeeded then reattach that session in to a new terminal.

*Make your Python program provide a pty that the terminal can attach to - your program will need to hang around and pass input and output between the remote connection and the pty.


text:
Q: Why does this query return nil from Firestore I am trying to get the three most recent documents from my collection group userPosts using the following database structure and query:
-posts
   -{userID}
      -userPosts
         -{documentID}
            -postTime(Field)

Query:
postQuery = Firestore.firestore()
            .collectionGroup("userPosts")
            .order(by: "postTime", descending: true)
            .limit(to: 3)

function used to query Firestore:
func loadPosts() {
    postQuery.getDocuments{ [weak self](querySnapshot, error) in
        self!.q.async{
            var postsTemp = self?.postArray
            for doc in querySnapshot!.documents{
                self?.documents += [doc]
                let post = self!.createPost(doc)
                if(!self!.postArray.contains(post)){
                    postsTemp?.insert(post, at: 0)
                }

                DispatchQueue.main.async {
                    self!.postArray = postsTemp!
                    self!.tableView.reloadData()
                }
            }
        }
    }
}

However when I run this I get an error due to the fact that querySnapshot is nil. I am not sure why this happens since when I change descending to false I get a result but in the opposite order that I want. I have a feeling it has something to do with my query but am not sure where I went wrong.

A: The getDocuments callback gets called with two values (querySnapshot and `error), only one of which will have a value.
You're ignoring the error and assuming that querySnapshot has a value, which not only leads to the error you get, but also hides the likely cause.
I recommend following the pattern used in this example from the Firestore documentation on getting documents:
db.collection("cities").whereField("capital", isEqualTo: true)
    .getDocuments() { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            for document in querySnapshot!.documents {
                print("\(document.documentID) => \(document.data())")
            }
        }
}

By logging the error you can see what went wrong with your getDocuments() call.


text:
Q: Why is there a white screen after the Flutter keyboard is put away? When I use Flutter, when the keyboard is closed, there will be a short white screen under the page before I can see the content.

A: It's because the body of the Scaffold gets resized when you open the keyboard
You can avoid the resizing with resizeToAvoidBottomInset: false or use another backgroundColor on the Scaffold


text:
Q: SAS: How to select obs with condition My data look like this:
rep  model   x   Reject
 1    1    1.36    1
 1    2   -0.76    0
 1    3    3.74    1
 1    4   -0.42    0
 2    1   -0.56    0
 2    2   -5.78    0
 2    3   -2.00    0
 2    4   -3.67    0

and i want output look like this:
rep  model   x   Reject
 1    1     1.36   1
 2    1    -0.56   0

I want just 1 from 4 model where Reject=1 but if it can't find,every Obs could be.
Thanks!

A: Sort your data by REP and REJECT and take first record per REP.
Proc sort data=have;
   By rep descending reject model;
 Run;

Data select;
   Set have;
     By rep descending reject model;
   If first.rep;
 Run;


text:
Q: an error about liridar config concering Cmake CMake Error at /opt/ros/melodic/share/pcl_ros/cmake/pcl_rosConfig.cmake:113 (message):
Project 'pcl_ros' specifies '/usr/include/eigen3' as an include dir, which
is not found.  It does neither exist as an absolute directory nor in
'${{prefix}}//usr/include/eigen3'.  Check the issue tracker
'https://github.com/ros-perception/perception_pcl/issues' and consider
creating a ticket if the problem has not been reported yet.
Call Stack (most recent call first):
/opt/ros/melodic/share/catkin/cmake/catkinConfig.cmake:76 (find_package)
lslidar_c32/lslidar_c32_driver/CMakeLists.txt:22 (find_package)
find how to solve the error


text:
Q: How to find the positive maximum value of this total profit function? So I have this function and I want to find the maximum value and the plot for x

I'm not really sure if I wrote the integral function correctly in mathematica, but here is the code I attempt :
Clear["Global`*"];
Z = 1000;
W = 100000;
G = 250;
H = 100;
T = 38;
L = 4000;
P = 5;
S = 2.5;
Y = 2;
A = 0.1;
J = 8000;
a=1;
t=0.5;
Clear[f];
f[x_] = f[x_] = 1/x (Integrate[J*Z (1 - R/Y)^(1 - a*t + t), {R, 0,x}] -((W + T*G) + ((L + T*P)*Integrate[Z (1 - R/Y)^(1 - a*t), {R, 0, x}] + (H + T*S + A*L)*Integrate[Integrate[Z (1 - R/Y)^(1 - a*t), {R, v, T}], {t, 0, x}])));
Plot[Re@f[x], {x, 0, 2}]
FindMaximum[{Re@f[x], x > 0}, x]


text:
Q: How to get descendants with a specific tag name and text in protractor? I have the following structure (it's just for sample). In protractor, I am getting the top element by id. However, the other elements do not have id's. I need to get the "label" element that contains the text '20'. Is there an easy way in protractor to select the element with a specific tag that contains a specific text from all the descendants of a parent element?
  <pc-selector _... id="Number1">

                <check-box _...>

                          <input _ngcontent-c25="" type="checkbox">

                       20 More text to follow

                 </check-box>

  </pc-selector>

I could't find anythitng, so I have tried with xpath, but protractor complains that my xpath is invalid:
parentElement = element(by.id('Number1'));
return parentElement.element(by.xpath(".//label[contains(text(),'20'))]"));

Any ideas?

A: You can use the direct xpath to access the label.
element(by.xpath("//*[@id='Number1']//label"));

A: You have an additional bracket in your [contains(text(),'20'))] which is likely causing you issue but there are multiple other ways this can be achieved using a single XPath or chaining other locators.
The process is that you must find the div with the correct id first and then locate the label that is a child of it.
//Xpath
element(by.xpath("//pc-selector[@id='Number1']//label[contains(text(),'20')]"));

//Chained CSS
element(by.id('Number1')).element(by.cssContainingText('label','20'));

You also may be interested to learn about xpath axes which can allow us to do very dynamic selection.


text:
Q: Как сделать так чтобы слова из файла выводились русскими буквами В общем, при работе с файлом программа выводит случайное слово из файла со словами, но из-за проблем с кириллицей выводится непонятно что.
Код ниже:
import random

def charCount(word):
    dict = {}
    for i in word:
        dict[i] = dict.get(i, 0) + 1
    return dict

def possible_words(lwords, charSet):
    for word in lwords:
        flag = 1
        chars = charCount(word)
        for key in chars:
            if key not in charSet:
                flag = 0
            else:
                if charSet.count(key) != chars[key]:
                    flag = 0
        if flag == 1:
            print(word)

with open("words.txt") as f:
    input = f.read().splitlines() #создаем список с элементами через enter;

charSet = list(random.choice(input))
print(charSet)
possible_words(input, charSet)

Выводится это: ['Р', 'і', 'С', 'ѓ', 'Р', 'ґ', 'С', '‹']

РіСѓРґС‹

A: Нужно указать кодировку
with open("words.txt", encoding="UTF-8") as f:

PS. Не нужно использовать слова dict и input как имена переменных. Это встроенные функции языка.


text:
Q: trigonometry identity I have some problem with proving this identity:
$$2\left(1+\cos\alpha \right)-\sin^2\alpha=4\cos^4\frac{\alpha}{2}$$
I tried to start from the right side rewritting it to $(2\cos^2(2\frac{\alpha}{4}))^2$ but it's not working.

A: Replacing $\sin^2(x)=1-\cos^2(x)$ gives
$$
\begin{align}
2(1+\cos(\alpha))-\sin^2(\alpha)
&=1+2\cos(\alpha)+\cos^2(\alpha)\\[6pt]
&=(1+\cos(\alpha))^2\\
&=\left(2\cos^2\left(\frac\alpha2\right)\right)^2
\end{align}
$$
using the identity $\cos(\alpha)=2\cos^2\left(\frac\alpha2\right)-1$.

A: By considering the trigonommetric identity:
$$\cos^2{x} = \frac{1+\cos{2x}}{2},$$
you have:
$$2(1+\cos{\alpha}) = \sin^2 \alpha + 4 \left(\frac{1+\cos{\alpha}}{2}\right)^2 = \sin^2\alpha + 1 + 2 \cos\alpha + \cos^2\alpha, $$
which becomes an identity if you perform further simplification.
Cheers!

A: The most straightforward way is to use the Weierstrass substitution. Note that $\tan^2(\alpha/2)=\frac{1}{\cos^2(\alpha/2)} -1,$ that should help you with the RHS.

A: We have the double angle identities $sin(x)=2sin(\frac{x}{2})cos(\frac{x}{2})$ and $cos(x)=2cos^2(\frac{x}{2})-1$
Substituting into the left hand side of your expression, we have
$2(1+2cos^2(\frac{\alpha}{2})-1) - (2sin(\frac{x}{2})cos(\frac{x}{2}))^2$
$=4cos^2(\frac{\alpha}{2})-4sin^2(\frac{\alpha}{2})cos^2(\frac{\alpha}{2})$
$=4cos^2(\frac{\alpha}{2})[1-sin^2(\frac{\alpha}{2})]$
$=4cos^2(\frac{\alpha}{2})[cos^2(\frac{\alpha}{2})]$
$=4cos^4(\frac{\alpha}{2})$

A: Let there is a function $f(x) = \cos x + 1$, then $$f^2(x) = \cos^2 x + 2\cos x + 1 = 2(1 + \cos x) - \sin^2 x.$$ While $$f(x) = 2\cos^2\frac{x}{2} = \sqrt{4\cos^4\frac{x}{2}}.$$ Therefore $$ 4\cos^4\frac{x}{2} = 2(1 +\cos x) - \sin^2x.$$

A: begin by writing sin a = 2sin a/2 cos a/2 in left side ,easy by factoring you will have the answer


text:
Q: need help with the apex trigger the trigger should be on account to check the assets and if ALL the Assets belonging to  product family = "bla bla "  had their status "Canceled" the trigger should update bla bla Account stage (API Name = Account_Status__c )  to "Cancel".
below is a trigger I wrote but it doesn't work
trigger cancelAsset on Account (after update) {

    List<Asset> suite = [Select Id ,Status from Asset where Product_Family__c = '360 Suite'];
    List<Asset> tech = [Select Id ,Status from Asset where Product_Family__c = 'Ad Tech'];
    for(Account acc:Trigger.new){

        Integer z=0;
        for(Integer i=0 ; i<= suite.size() ;i++){
            if(suite[i].Status == 'Canceled'){
              z++;
            }
        }

        if (z == suite.size()){
            acc.Account_Status__c = 'Cancel';
        }
        update acc;
    }
}

A: There are a number of logical issues here.
Wrong Trigger Object
Triggers run on change to records in the object they are declared on. Your trigger is intended to react to Asset data, but it is declared as a trigger on Account. It will run only when Accounts are updated, not when Assets are updated. I suspect this is the reason why you say it "doesn't work" - when you make changes to Assets, nothing happens. You'd need to write a trigger on Asset for that to happen.
Unfiltered Queries
Your trigger assumes there is exactly one Account in your org, because its queries are not filtered.
List<Asset> suite = [Select Id ,Status from Asset where Product_Family__c = '360 Suite'];
List<Asset> tech = [Select Id ,Status from Asset where Product_Family__c = 'Ad Tech'];

These queries will find every Asset in your org that have the appropriate Product Families. They don't do any filtering by the parent Account. If your trigger were operating in a context where more than one Account existed, the results would be incorrect.
It's very common to accumulate a Set of the related record Ids you are looking for, and then to filter a query that way. For example, if this were an Asset trigger, as above, you might do
Set<Id> accountIds = new Set<Id>();
for (Asset a : Trigger.new) {
    accountIds.add(a.AccountId);
}

List<Asset> suite = [Select Id ,Status from Asset where Product_Family__c = '360 Suite' AND AccountId IN :accountIds];
List<Asset> tech = [Select Id ,Status from Asset where Product_Family__c = 'Ad Tech' IN :accountIds];

This ensures you are only querying the relevant information, which is important both for establishing correct behavior and respecting governor limits on SOQL rows and heap size.
Logic
You need to determine whether each and every Asset associated with a specific Account meets criteria. First, then, you need to sort your queried Assets into a multi-map, a Map between Account Id and a list of Assets. Something like this could do it:
Map<Id, List<Asset>> assetMap = new Map<Id, List<Asset>>();
for (Asset a : listOfAssets) {
    if (!assetMap.containsKey(a.AccountId)) {
        assetMap.put(a.AccountId, new List<Asset>());
    }
    assetMap.get(a.AccountId).add(a);
}

This is a very general pattern you'll use over and over again.
Then, you'd need to iterate over the Accounts whose Assets you are processing, use their Ids to index into the Map, and then iterate over the list of Assets to determine whether criteria are met.
Note: There is another, advanced, solution here using Aggregate Queries, but I'm not sure it's useful to go there at this point.
DML in a Loop
This is a classic problem in Salesforce development: you must always do your DML outside a loop to prevent consuming excess DML statements against your limit of 150 in a transaction. Remember that your trigger can be called with 200 (or more!) total Assets in a transaction.
Here, since you'd be updating Accounts, you'll probably want to maintain a Map<Id, Account>. As you find updates you need to make to an Account, you'll add each Account to the Map, with its Id as the key. Then, at the very end of your trigger, you'll do
update myAccountMap.values();

This ensures that

*

*Your DML is bulkified;

*You do not try to update the same record twice, which will net you an error.

Recommendations
I strongly recommend you go complete the Bulk Apex Triggers unit on Trailhead. The patterns involved take some getting used to, but you need to get acclimated to them to effectively develop triggers that work well and respect Salesforce governor limits.


text:
Q: How to insert vue component into contenteditable div I want to create simple wysiwyg editor with vue. I have found only one real wysiwyg editor created on vue.js. Here it is __https://quasar.dev/vue-components/editor (But I didn't find there ability to insert image). Others vue wysiwyg editors is only wrappers to tinymce or ckeditor etc.
I am planning to create SIMPLE vue-editor using base commands from example from mozilla developer site. Here it is https://codepen.io/chrisdavidmills/pen/gzYjag .
At first I want to know how to insert vue components into contenteditable div. What I mean? For example, I want to create editor plugin which will insert image on toolbar icon click. Inserted image should be with attached events (click event), it could be resizable etc. The base idea to this I found in answer here https://stackoverflow.com/a/59326255/1581741 , (author @AJT82 ). He gave me example of inserting vue-component (image) into contenteditable div. Here it is https://codesandbox.io/s/vue-template-m1ypk .
So, I have next questions.
User open empty editor and insert component into it. I need something to store to database.
1) What exactly should I store to database?
2) Stored text with images should be rendered somewhere at the site as article for viewing only. This means I should have generated html (for example, ). How I will take it from inserted vue-component?
3) User can edit stored earlier code from editor. How to insert (inserted and stored to database earlier) vue-component again?
I am lost in this questions.

A: I made you an example showing how you can inject absolutely anything into any WYSIWYG component (except for really bad ones :)
Using your first choice of WYSIWYG editor, and probably the slickest of them all...
https://quasar.dev/vue-components/editor
Here you can see how easy it is to inject a random cat image for example. You could pop up a dialog and ask for an image name, you could allow the user to upload an image, wait for a promise that returns the link, then insert that image via the returned link, or do even wilder things.
https://codepen.io/njsteele/pen/wvBNYJY
The component render is handled here:

  <component :is="renderThisComponent" v-bind="renderTheseProps">
  </component>

Clicking "Insert Random Cat" will insert a random animated cat GIF from Cats As A Service.
Clicking Insert Quasar Components will let you select from a q-icon component, and an animated indeterminate progress circle. You can also add your own components. This works with absolutely any Vue component, but it will not update it once it's been rendered in your WYSIWYG editor, and it's plain HTML after that.  I also used a ref render, which works but it's basic, to show you how easy it is to accomplish.  I would instead upgrade this to a proxy component so it never has to get rendered into the DOM the first time or wait for a $nextTick.
You can also see you can inject tokens (although this came from the Quasar playground). It shows how you can inject vars you might have related to the current user/etc.
If you want, you can also allow users to build their own components, or allow user-created templates to be injected, you can also insert a Emoji list, or even @mentions, which can insert live-views into if that user is currently online, etc.
Since this functionality is both really powerful and easy to implement it in theory, I wrote a really ultra-tiny and bug-free template generator that you can extend to infinity (372 bytes).  It's also safe for users, as it only uses function lists you pre-allow for your users.
Grab the source here and use it in your projects if you would like...
https://github.com/onexdata/nano-var-template


text:
Q: GWT Stackpanel handler for open event is there any way to get an event when I switch between widget on a Stackpanel?
something like an openhandler for stackpanel. I have to know the index of
an open Widget on a Stackpanel.

A: Using StackLayoutPanel: http://google-web-toolkit.googlecode.com/svn/javadoc/2.0/com/google/gwt/user/client/ui/StackLayoutPanel.html
Use the addSelectionHandler() method. To get the selected widget, you can use getVisibleIndex() or getVisibleWidget().
myStackPanel.addSelectionHandler(new SelectionHandler<Integer>() {
    @Override
    public void onSelection(SelectionEvent<Integer> event) {

        int selectedWidgetIndex = stackPanel.getVisibleIndex());

        //Do stuff with the selectedWidgetIndex
    }
});

EDIT: This is using StackLayoutPanel, the OP uses StackPanel. The difference between them is that StackPanel is for quirks mode and StackLayout Panel for Standards Mode. I would StackLayoutPanel or any Layout related widget as new GWT widgets uses them, like the new DataGrid.

A: You can add a click handler on a DecoratedStackPanel (and possibly a StackPanel) and use getSelectedIndex() as below:
myDecoratedStackPanel.addHandler(new ClickHandler()
{
    @Override
    public void onClick(ClickEvent clickEvent)
    {
        Window.alert("" + myDecoratedStackPanel.getSelectedIndex());
    }
}, ClickEvent.getType());

A: By overridding the showStack method, it is a breeze. Try something like:
public class StackPanelX extends StackPanel implements IHasChangeHandler {

    String ctx_id=null;
    IChangeHandler chandler=null;

    public StackPanelX() {
        super();
    }

    public void showStack(int index) {
        int currentStack = this.getSelectedIndex();

        super.showStack(index);

        if (currentStack!=index)
            if (chandler!=null)
                chandler.onChange(ctx_id, new Variant(index));

    }

    @Override
    public void setChangeHandler(String ctx_id, IChangeHandler handler) {
        this.ctx_id=ctx_id;
        this.chandler=handler;
    }

}


text:
Q: Bootstrap 4 carousel-fade not working properly I'm having some issues with bootstrap's carousel, I have some images with different resolutions and ratios, and when I use the carousel-fade effect and two images with different ratios are next to each other the animation comes out janky.
I was wondering if there was a way to alleviate or solve this problem entirely

demo:
https://jsfiddle.net/02fxt9de/2/

A: The main issue here is your image resolution
if they are different  it is obvious that the slide transition would appear janky . This can be solved by
setting resolution of image as equal
just replace this section in your code and try out

CSS code

.carousel-img-size {height:200px ; width:400px;}

change width and height as per your requirement. :)


text:
Q: C# math expression parser to work with big numbers I work on a .net project and need a math expression parser to calculate simple formulas.
I used mXparser but it seemed unable to work with big decimal numbers(more than 16 digits) .
For example, the result of formula has to be 2469123211254289589
but it returns 2.46912321125428E+17 and when I use decimal.parse to convert it to decimal it gives me 2469123211254280000.
Is there another parser to solve this problem?
or
Is there another way to deal with this problem?

A: If you're happy dealing with integers then you should be able to use BigInteger to carry out these  sorts of operations.
It has no theoretical upper or lower bounds so you shouldn't have a problem (unless you run out of memory to store that number that is).


text:
Q: How to Self Reference an Object when "this" Refers to Something Else I'm trying to create a modular series of element handlers for an app that has pages with varieties of configurations (eg: 'Hex T' config has elements 'A' thru 'O' that each has at least 1 DOM element that can be modified in different ways, but 'Square Pad' only has 'A' thru 'E' and the same lettered elements don't always refer to the same type of element, be it a dropdown or number input).
So what I've done is made classes like LengthElement that has 2 number inputs, one for Feet and one for Inches, and so LengthElement holds the value in inches, and then whenever one of the elements, Feet or Inches, gets updated, it registers that change to the inches value and then changes the Feet and Inches elements to properly display the correct measurement (eg: 10ft 0in => 10ft -1in => 9ft 11in).
There's also a config array that holds the list of all the various configurations the app can have, and what order the elements are in and what they are. I ID active inputs as 'input' and disabled inputs as 'box', it just helps me keep things straight. So, a Hex T active input pair for 'A' would have elements foot: '#ht-a-ft-input' and inch: '#ht-a-in-input'. I did this so I don't have to write out all the IDs for every single possible element (there are currently over 100 on just this page) more than once.
There's also an app requirement where certain lengths have to be divisible by 7, and I've got the logic in here. It's probably not relevant but I figured that I'd include it as it is just in case. Finally, there's an OnChange() function that gets passed into each object instance, that's a function with a callback that appears elsewhere that's working just fine so I don't think it matters.
Here's the class code in its entirety:
class LengthElement {
    inches;     //Value of the Two Elements in Inches
    foot;       //String of the Foot Element
    inch;       //String of the Inch Element
    div7;       //Flag to determine if change needs to be Divisible by 7
    OnChange;   //Function specific to the instance to be called whenever the input changes

    constructor(i, cfg, abrv, oC) {
        this.inches = i;

        if (cfg.foot == 'input') {
            this.foot = '#' + abrv + '-' + cfg.name + '-ft-input';
            $(this.foot).on('input', this.InputVal);
        }
        else {
            this.foot = '#' + abrv + '-' + cfg.name + '-ft-box';
        }
        if (cfg.inch == 'input') {
            this.inch = '#' + abrv + '-' + cfg.name + '-in-input';
            $(this.inch).on('input', this.InputVal);
        }
        else {
            this.inch = '#' + abrv + '-' + cfg.name + '-in-box';
        }

        this.div7 = cfg.div7;
        this.OnChange = oC;
    }

    GetFeet(i) {
        return Math.floor(i / 12);
    }

    GetInches(i) {
        return i % 12;
    }

    GetDiv7(i) {
        if (i % 7 > 5) {
            return i + (7 - (i % 7));
        }
        else {
            return i - (i % 7);
        }
    }

    GetVal() {
        return this.inches;
    }

    UpdateVal(i) {
        if (this.div7) {
            this.inches = this.GetDiv7(i);
        }
        else {
            this.inches = i;
        }

        $(this.foot).val(this.GetFeet(this.inches));
        $(this.inch).val(this.GetInches(this.inches));
    }

    InputVal() {
        var newInches = ($(this.foot).val() * 12) + $(this.inch).val();
        var change = newInches - this.inches;

        if (this.div7) {
            if (change > 0) {
                newInches = this.inches + ((Math.floor(change / 7) * 7) + 7);
            }
            else if (change < 0) {
                newInches = this.inches - ((Math.floor(change / 7) * 7) + 7);
            }
            else {
                newInches = this.GetDiv7(newInches);
            }
        }

        this.UpdateVal(newInches);
        this.OnChange();
    }
}

So what's the problem?
Whenever InputVal() gets called, this refers to a jQuery object, and not the object it's inside of. I believe the critical lines are the $(this.foot).on('input', this.InputVal); lines, but I'm not sure what exactly is wrong with them.
Again, this is to avoid writing out every single element's ID more than the one time where it's declared in the HTML, so any alternatives that I can use to perform the same task are appreciated.
I am about 4 months into solo development so I can't change frameworks off of jQuery. I would have an aneurysm.

A: you could try inserting this at the top of your constructor
this.InputVal = this.InputVal.bind(this)

so that this inside of the InputVal function always refers to LengthElement

A: the simple trick for that you should declare a variable name self, in constructor you binding self = this, in other method or callback you can using self instead of this


text:
Q: Put a text on fullscreen video (HTML5) I want to put text on fullscreen video at HTML.
I could make it non fullscreen but it is not working on fullscreen.
Is there any way to do it?
I use position:absoulute for text and position:relative/fixed/none for video.
Also I don't know if it works but I called .requestFullscreen(); function for browser unhappily I cannot resize video.
If .requestFullscreen(); is works. I need to resize video.
width and height of video tags is changing but video is not changing.

A: You can embed responsively with Youtube and vimeo with iframes, and with Viddler and Blip.tv with object embed. There is an article that explains it here and code is available on github
Sample code for Youtube (using jquery):
// Find all YouTube videos
var $allVideos = $("iframe[src^='//www.youtube.com']"),

    // The element that is fluid width
    $fluidEl = $("body");

// Figure out and save aspect ratio for each video
$allVideos.each(function() {

  $(this)
    .data('aspectRatio', this.height / this.width)

    // and remove the hard coded width/height
    .removeAttr('height')
    .removeAttr('width');

});

// When the window is resized
$(window).resize(function() {

  var newWidth = $fluidEl.width();

  // Resize all videos according to their own aspect ratio
  $allVideos.each(function() {

    var $el = $(this);
    $el
      .width(newWidth)
      .height(newWidth * $el.data('aspectRatio'));

  });

// Kick off one resize to fix all videos on page load
}).resize();

A: Had this problem before but it's pretty simple code in the end (it still took me ages to figure out and get the right balance) https://jsfiddle.net/tonytansley/xwuuttdt/
Just a little absolute positioning and using percentages as your widths heights and paddings.

            <video autoplay loop width="100%">
                <source src="http://view.vzaar.com/2710053.mp4" type="video/mp4"/>
                <source src="http://view.vzaar.com/2710053.ogg" type="video/ogg"/>
                <source src="http://view.vzaar.com/2710053.webm" type="video/webm"/>
            Your browser does not support the video tag. We suggest you upgrade your browser.
            </video>

text

subtext

css
#outer{
    width:100%;
    display:block;
    text-align:center;
    position:relative;
    overflow: hidden;
    height:10000px;
    min-height:100%;
}
#home-top-video{
    left:0%;
    top:0%;
    height:100%;
    width:100%;
    overflow: hidden;
    position: absolute;
    z-index: -1;
}
#home-text{
    left:0%;
    top:0;
    height:100%;
    width:100%;
    padding-top:10%;
    overflow: hidden;
    position: absolute;
    z-index: 0;
    color:white
}

A: You can acheive this in a couple different ways. I believe the easiest would be to create a div that's 100% width, embed the video responsively inside the div, and then absolutely position the text in the center of the div.


text:
Q: Proving that one can integrate a uniformly convergent series of functions term by term I aim to understand the following proof from Serge Lang's Introduction to Complex Analysis at a graduate level
[
and I have the following definitions

My question is: What does the last paragraph of the theorem in question actually mean? Does it mean that every $f_i$ is convergent, and if yes, how is this derived from the definition?

A: The last paragraph means that if for each $n$ we set
$$
s_n:=\sum_{k=1}^n f_k,
$$
then the sequence $(s_n)_{n=1}^\infty$ converges uniformly on $U$ to $s:=\sum_{k=1}^\infty f_k$. Then, by the first part of the Theorem
$$
\lim_n\int_{\gamma} s_n = \int_\gamma s
$$
which translates as
$$
\lim_n\int_{\gamma} \sum_{k=1}^n f_k = \int_\gamma \sum_{k=1}^\infty f_k
$$
and since
$$
\lim_n\int_{\gamma} \sum_{k=1}^n f_k =\lim_n   \sum_{k=1}^n \int_{\gamma}f_k =  \sum_{k=1}^\infty \int_{\gamma}  f_k
$$
the desired result follows.

A: "$\sum_n f_n$ is a series of continuous functions converging uniformly on $\Omega$"
means each $f_n$ is a continuous function on $\Omega$, and the series $\sum_n f_n$ converges uniformly on $\Omega$.


text:
Q: Proving a function is a bounded linear functional on C[0,1] I'm unsure of how to solve this problem (it's number 5 in section 18 of Kolmogorov's Introductory Real Analysis).
Prove that f(x) = ax(0) + bx(1) is a bounded linear functional on C[0,1]. What is its norm?
The book doesn't clarify what a and b are, but my attempt to solve the problem is as follows:
Let x,y $\in$ C[0,1]. Then f($\alpha x+\beta y$) = a$\alpha x(0) + a\beta y(0) +b\alpha x(1) + b\beta y(1)$ = $\alpha (ax(0) + bx(1)) + \beta (ay(0) + by(1)) $ (after re-arranging) = $\alpha f(x) + \beta f(y)$, thus f is linear.
Boundedness is what I'm unsure of. I've used the fact that continuous functions are bounded on closed intervals:
Let x$\in$C[0,1]. Then x(t) is bounded since it is continuous on a closed interval. Hence, $\exists M \in \mathbb{R}$ such that x(t) $\lt$ M and so f(x) = ax(0) + bx(1) $\lt$ (a+b)M, thus f is bounded.
I'm unsure of what a and b are, can I assume they are just real numbers and so this would work for showing boundedness? Or did I screw up? As for the norm of f, I believe it just is:
$\|f||$ = $sup_{||x||=1} {|f(x)|}/{||x||}$ = sup |f(x)| = a+b.

A: You have $\|f(x)\|=\|ax(0)+bx(1)\|\leq |a||x(0)|+|b||x(1)|\leq (|a|+|b|)\|x\|$ so the norm of $f$ is inferior to $|a|+|b|$.
On the other hand, construct $x$ such that $x(0)=1$ if $a>0$, $x(0)=-1$ if $a\leq 0$, $x(1)=1$ if $b>0$, $x(1)=-1$ if $b\leq 0$, $|f(x)|\leq 1$, you have $\|x\|=1$ and $\|f(x)\|=|a|+|b|$. You can suppose for example that $x$ is linear between in $[0,1/2]$ with $x(1/2)=0$ and $x$ is linear in $[1/2,1]$.


text:
Q: Ruby/Rails button and search filtering I've added the Active and Archived buttons to this page for extra filtering.

The existing search box functionality uses the following js.coffee which calls the controller index to pull the data from the db.
triggerSearch: (e) ->
    if searchCompanyTimer
      window.clearTimeout searchCompanyTimer
    searchCompanyTimer = window.setTimeout(( ->
      searchCompanyTimer = null
      query_text = $(e.currentTarget).val()
      el_id = $(e.currentTarget)[0].id
      $.get( "companies", "q[name_cont]": query_text )
      ), 500, e)

I have added 2 similar js.coffee methods which set an active flag to true or false depending on which button was pressed.
Here is one of those methods.
triggerShowActive: (e) ->
    if searchCompanyTimer
      window.clearTimeout searchCompanyTimer
    searchCompanyTimer = window.setTimeout(( ->
      searchCompanyTimer = null
      $.get( '/companies', {active: true} )
      ), 500, e)

here is part of my controller.
class CompaniesController < ApplicationController

  respond_to :js, :json, :html
  $active_inactive_flag = true

  def index
    puts "params are: #{params}"
    puts "active param is: #{params[:active]}"
    puts "@active_inactive_flag pre any conditions is: #{$active_inactive_flag}"
    $active_inactive_flag = params[:active] ? params[:active] : $active_inactive_flag
    puts "@active_inactive_flag after check on params[:active] is: #{$active_inactive_flag}"
    if $active_inactive_flag.try :nonzero?
      $active_inactive_flag = true
    end
    puts "@active_inactive_flag after check if it has a value, else true - is: #{$active_inactive_flag}"
    @companies =
      Company.search(params[:q])
        .result
        .order('created_at DESC')
        .page(params[:page])
        .per(Settings.paginate_limit)
        .where(is_active: $active_inactive_flag)
end

here is my index.html.erb file where the buttons and search code is.

            Filter By:
            <button class="show_active btn btn-primary" style="border-radius:10px">Active</button>
            <button class="show_inactive btn btn-primary" style="border-radius:10px">Archived   </button>

                Filter by name
                <input class="form-control" id="q_name_cont" name="q[name_cont]" type="text">

I am using a global variable (tried instance and class variables also) in the controller but it's not working as expected. Sometimes the value in $active_inactive_flag switches from false to true or vice versa incorrectly. I don't want to use a global variable but I am at a loss as to how to combine both filter and search correctly. When the page loads we want Active button to be on by default and return active companies. The problem I am having is knowing what button was pressed when the search box is used.
Edit:
Here is an example of what is happening.

Any direction would be grateful.

A: Thanks Dave,
in js.coffee added the following:
returnActiveInctiveFlag = true

and then to the triggerSearch updated to:
$.get( "companies", { "q[name_cont]": query_text, active: returnActiveInctiveFlag } )

In my new methods updated returnActiveInctiveFlag accordingly.
Was really overcomplicating it. Thanks again for getting me thinking in the correct way.


text:
Q: CS50 Speller (PSET 5) not loading dictionary I am working through the CS50 Speller problem and facing a problem that when running the program it returns an error of "Could not unload dictionaries/large."
I have looked at other people's solutions and can't for the life of me identify what is going wrong in my program. I am thinking it is in the has function, but have seen this has function in other people's working programs?
Any help would be greatly appreciated.
// Implements a dictionary's functionality

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>

#include "dictionary.h"

// Represents a node in a hash table
typedef struct node
{
    char word[LENGTH + 1];
    struct node *next;
}
node;

// Number of words in dictionary
int word_count = 0;

// Number of buckets in hash table
const unsigned int N = 26;

// Hash table
node *table[N];

// Returns true if word is in dictionary else false
bool check(const char *word)
{
    unsigned int n = hash(word);

    node *cursor = table[n];

    while (cursor != NULL)
    {
        if (strcasecmp(word, cursor -> word) == 0)
        {
            return true;
        }

        cursor = cursor -> next;

    }
    return false;
}

// Hashes word to a number
// Function credit to delipity(staff) on CS50 reddit page
unsigned int hash(const char *word)
{
    unsigned int hash_value = 0;

    for (int i = 0, n = strlen(word); i < n; i++)
    {
         hash_value = (hash_value << 2) ^ word[i];
    }
    return hash_value % N; //N is size of hashtable

}

// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
    // Open dictionary and check for memory issue
    // Open dictionary file and create word array
    FILE *dict = fopen(dictionary, "r");
    char word[LENGTH + 1];

    // Check for memory issue with dict
    if(dict == NULL)
    {
        printf("Dictionary is null\n");
        unload();
        return false;
    }

    // Read string 1 word at a time
    while (fscanf(dict, "%s", word) != EOF)
    {
        node *n = malloc(sizeof(node));
        if (n == NULL)
        {
            return false;
        }

        strcpy(n -> word, word);
        word_count++;

        // Index word using hash function
        int dict_index = hash(word);

        // Insert into hash table if already empty
        if (table[dict_index] == NULL)
        {
            n -> next = NULL;
        }
        // Insert work as new node if not empyty
        else
        {
            n -> next = table[dict_index];
        }

        table[dict_index] = n;

    }

    // Close dictionary file
    fclose(dict);

    // Indicate success
    return true;
}

// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
    return word_count;
    return 0;
}

// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
    for (int i = 0; i < N; i++)
    {

        node *cursor = table[i];
        node *tmp = cursor;

        while (cursor != NULL)
        {
            cursor = cursor -> next;
            free(tmp);
            tmp = cursor;

        }
    }
    return false;

}

A: bool unload(void)
{
    for (int i = 0; i < N; i++)
    {

        node *cursor = table[i];

        while (cursor)
        {
            node *temp = cursor;
            cursor = cursor->next;
            free(temp);
        }
    }
    return true;
}

Try this instead for the unload function


text:
Q: sequence with infinitely many limit points I am looking for a sequence with infinitely many limit points. I don't want to use $\log,\sin,\cos$ etc.!
It's easy to find a sequence like above, e.g. $1,1,2,1,2,3,1,2,3,4,1,2,3,4,5,1,\dots$
But how can you prove the limit points? The problem I am having is the recursion or definiton of the sequence which I can't name exactly. But for a formal proof I need this.
So what's a sequence with infinitely many limit points without using $\log,\sin,\cos$ or any other special functions?

A: You can use something like :{ $1/n$}$\cup${$1+1/n$}  $ \cup ....\cup$ {$k+1/n$} $\cup.... $

A: Let $\{r_n\}$ be the set of all rationals. Then sequence $\{r_1, r_1, r_2, r_1, r_2, r_3, r_1, r_2, r_3, r_4,r_1,r_2,r_3,r_4,r_5,...\}$ has all rationals as limit points.

A: I realize this question was asked a long time ago, but for posterity, you may formally describe the sequence $<1, 1, 2, 1, 2, 3, 1, 2, 3, 4, ...>$ as $<x_i>$ where $x_i = n$ precisely when $i = \frac {(n^2 + (2k-1)n + (k^2 - 3k + 2))}{2}$ for some $k \in \mathbb{N}$.
To justify this formula, we start by showing that $n$ first appears in the sequence in the term with index $\frac{n(n+1)}{2}$. By splitting the sequence into $(1),(1,2),(1,2,3),(1,2,3,4),...,(1,...,n)$, it is pretty clear that $n$ has index $1+2+3+4+...+n$, which can be shown to equal $\frac{n(n+1)}{2}$ by induction.
Then we continue this useful grouping of the sequence to show the indices of the subsequent terms. $(1),...,(1,...,n),(1,...,n,n+1),(1,...,n,n+1,n+2),...$ The the second appearance comes $n$ terms after the first appearance, the third appearance comes $(n+1)$ terms after the second, and so on. In general the $k^{th}$ appearance of $n$ will come $n + (n+1) + ... + (n+k-2)$ terms after the first appearance. This can be easily shown to be $\frac{(k-2)(k-1)}{2} - \frac{(n-1)n}{2}$.
But then the $k^{th}$ appearance of $n$ in the sequence will have index $\frac{n(n+1)}{2}+\frac{(k-2)(k-1)}{2} - \frac{(n-1)n}{2}$, which simplifies to $\frac {(n^2 + (2k-1)n + (k^2 - 3k + 2))}{2}$. I'll leave it to you to show that this expression defines the rule of assignment for a bijection  $f:\mathbb{N}\times\mathbb{N} \to \mathbb{N}$, meaning every index $i \in \mathbb{N}$, is mapped to by exactly one pair $(n,k)\in \mathbb{N} \times \mathbb{N}$, therfore showing that $x_i$ is well defined.
Once you have defined this sequence, showing it has infinitely many limit points is easy. We say that $m$ is a limit point of $<x_i>$ precisely if there is a subsequence of $<x_i>$ converging to $m$. Using $f(n,k) = \frac {(n^2 + (2k-1)n + (k^2 - 3k + 2))}{2}$ as our choice function, we choose the subsequence $<y_i>$ where $y_i = x_{f(m,i)} = m$. It stands that $<y_i>$ converges to $m$.


text:
Q: External Fonts not visible in Chrome until repaint Using Chrome I am experiencing an issue with a local site where when the site initially loads, none of the fonts are visible.  If I then hit F12 or resize the screen then the fonts all become visible.
The fonts are being loaded from Google Fonts using font-face, I am assuming that resizing the screen causes a repaint which is fixing the issue.
I have found a similar issue listed with Chromium at https://code.google.com/p/chromium/issues/detail?id=336476
Has anyone experienced anything similar?

A: You can fix this by including the javascript part of the font from google fonts..
It was annoying the heck out of me, so I did some experiementing and adding the javascript font insert instead of the css worked like a charm.. =D
From
<link href='http://fonts.googleapis.com/css?family=Orbitron' rel='stylesheet' type='text/css'>

to
<script type="text/javascript">
  WebFontConfig = {
    google: { families: [ 'Orbitron::latin' ] }
  };
  (function() {
    var wf = document.createElement('script');
    wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
      '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
    wf.type = 'text/javascript';
    wf.async = 'true';
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(wf, s);
  })(); </script>

Both found on the google fonts page fixed it LIKE A BOSS for me at least.. ;)


text:
Q: Meteor: There is no route for the path error. how to access SINGLE article within a nested object I have an array of 10 objects 'categories' and each category has sub objects such as posts within that category. This is how it looks.

I access the category list like this.
<template name="CategoriesMain">
  {{#each articles}}

{{name}}

  {{/each}}

</template>

this link

{{name}}

accesses the 'posts' list within the category which looks like this
<template name="CategoriesSingle">

This is a test

  {{#each articles}}
  {{#each posts}}

{{title}}

    {{/each}}
  {{/each}}

</template>

this link is supposed to target the SINGLE POST from the post list within the category

{{title}}

PROBLEM:
I get the error: There is no route for the path: /catsingle/ when ever i try to access the SINGLE POST
even though i have it in my routes.js like this
FlowRouter.route('/catsingle/:_id', {
    name: 'catsingle',
    action() {
        BlazeLayout.render("AppLayout", {main: "CategoryArticleSingle"});
    }
});

the template helper looks like this
  Template.CategoryArticleSingle.helpers({
      articles: function () {
        var id = FlowRouter.getParam('_id')
        return CategoryCollection.findOne({_id: id});
      }
    });

How can I successfully the single post within a category?

A: Your posts array doesn't have an _id key, it has an ID key.
Try:

{{title}}


text:
Q: ASP.NET MVC - Compare an end date with a start date with the start date already saved in the database My system will work as follows:
I have a start date and an end date.
When you make a appointment, it inserts the start date and saves this data. When making a new appointment the user should put the end date of that last appointment.
My question is how I would compare this final date that he entered, with the star date already in the bank.
My idea is that the end date is not less than or equal to the star date
 I tried that way, but it will not work because I'm not picking the last start date in the dataBase to compare

public class finalDateoftheAppointmentCannotbeLessthantheStartDate : ISpecification<Appointment>
{
    public bool IsSatisfiedBy(InfoAppointment  infoAppointment)
    {
        return infoAppointment.EndDate<= infoApontamento.StarDate;
    }
}

Im using repositorys:
Thats my repository class, maybe we can search the last date here to compare
   public virtual IEnumerable<TEntity> Buscar(Expression<Func<TEntity, bool>> predicate)
    {
        return Dbset.Where(predicate);
    }

public class InfoApontamentosRepository : Repository<InfoAppointment>, IAppointmentRepository
{
    public InfoAppointmentRepository(RveContext rveContext) : base(rveContext)
    {
    }

    public InfoAppointment FindLastStartDate(Date date)
    {
        throw new NotImplementedException();
    }

    //example
     public InfoApontamento FindByNumber(int number)
    {
        return Buscar(c => c.Atendimento == number).FirstOrDefault();
    }

To summarize: How can I get the last initial date saved in the database and compare with the end date entered by the user to prevent the end date being less than or equal to the starting date


text:
Q: React's map function problem with the sample I am trying to view data using below sample. my list.js file as below:
    import React, { Component } from 'react';
import { Person} from './Person';
export class List extends Component {
    render() {
        const persons = [
            {
                name:'Frank',
                age:30,
                city:'city 01'
            },
            {
                name:'Hameed',
                age:25,
                city:'city 02'
            },
            {
                name:'Jack',
                age:24,
                city:'city 03'
            }
        ]

        const personList = persons.map(person => <Person person={person}/>)
            return
 {personList}

    }
}

My person.js file is as below:
import React, { Component } from 'react';
export function Person (person){
    return (

               {person.name}

    );

}

I need to print my array value inside the HTML but still did not render the view. I could not fix this.
My App.js file as below:
import logo from './logo.svg';
import './App.css';
import { List} from './components/List'
function App() {
  return (

      <List></List>

  );
}
export default App;

A: You pass the prop person to each <Person />, but inside the <Person /> component you are not getting it well. Each prop you pass, is getting to the function under the props variable, Try this code:
import React, { Component } from 'react';
export function Person (props){
    return (

               {props.person.name}

    );
}

Or, alternatively, using destructuring:
import React, { Component } from 'react';
export function Person ({ person }){
    return (

               {person.name}

    );
}

A: In <Person /> component you wrongly used props, try instead as:
export function Person (props) {
   const { person } = props

   // ... rest
}

See the difference from Person (person) to Person ({ person }). In the explained solution the person is destructured from props.

A: person.js
import React, { Component } from 'react';
export const Person = (props) => {
    return (

               {props.person.name}

    );
}

or,
import React, { Component } from 'react';
export function Person (props){
    return (

               {props.person.name}

    );
}


text:
Q: I am stuck with a Query in Sql Server 2005? hi i want to write a query but i don't understand how to solve it
ID  Category    Volume
1   FFP         157
1   RBCD        279
2   FFP         146
2   PLT         70
2   RBCD        280
3   FFP         145
3   PLT         67
3   RBCD        275
4   FFP         148
4   RBCD        280

my result should be like this
ID  Category1   Volume1 Category2   Volume2 Category3   Volume3
1   FFP         157    RBCD          279    NULL        NULL
2   FFP         146    RBCD          280    PLT         70
3   FFP         145    RBCD          275    PLT         67
4   FFP         148    RBCD          280    NULL        NULL

By using Juergen D  i am getting like this
ID  Category1   volume1     Category2   volume2 Category3   Volume3
1   FFP         157         NULL        NULL    NULL        Null
1   NULL        NULL        RBCD        279     NULL        Null
2   FFP         146         NULL        NULL    NULL        Null
2   NULL        NULL        RBCD        280     NULL        Null
2   NULL        NULL        NULL        NULL    PLT         70
3   FFP         145         NULL        NULL    NULL        Null
3   NULL        NULL        RBCD        275     NULL        Null
3   NULL        NULL        NULL        NULL    PLT         67
4   FFP         148         NULL        NULL    NULL        Null
4   NULL        NULL        RBCD        280     NULL        Null

Anybody give me any idea how to do this

A: select id,
       min(case when Category = 'FFP' then Category end) as Category1,
       sum(case when Category = 'FFP' then Volume end) as Volume1,
       min(case when Category = 'RBCD' then Category end) as Category2,
       sum(case when Category = 'RBCD' then Volume end) as Volume2,
       min(case when Category = 'PLT' then Category end) as Category3,
       sum(case when Category = 'PLT' then Volume end) as Volume3
from your_table
GROUP BY id

SQLFiddle demo


text:
Q: The deprecation template must contain the "%service_id%" placeholder i'm new to symfony 4, i tried to install admin panel by composer require admin command, but it sounds error :
Executing script cache:clear [KO]
 [KO]
Script cache:clear returned with error code 1
!!
!!  In Definition.php line 770:
!!
!!    The deprecation template must contain the "%service_id%" placeholder.
!!
!!
!!
Script @auto-scripts was called via post-update-cmd

Installation failed, reverting ./composer.json and ./composer.lock to their original content.

A: a new commit that seems to fix this issue was merged today in the repo EasyCorp/EasyAdminBundle.
Until they release next version, you could do
symfony composer req admin:3.0.x-dev


text:
Q: How to create functional Methods What I want to approach is to create a custom Function that looks like this:
access('h1').content('Hello World');

And this is how I tried to accomplish that:
function access(Tag)
{
  var Element = document.getElementsByTagName(Tag)[0];

  this.content = function(Content)
  {
     if (Content !== undefined)
          return Element.innerHTML = Content;
     else return Element.innerHTML;
  }

  return Element;
}

So this Function shall be in the verge of changing the Content or just returning it.
Unfortunately it does not work this Way.
So far I played with it for about an Hour to rewrite it and find a Solution on my own, but I have not been successfull and I also do not know how to describe this Problem to Google it.
How can I solve this it?

A: Replace this with Element in your code.

function access(Tag)
    {
      var Element = document.getElementsByTagName(Tag)[0];

      Element.content = function(Content)
      {
         if (Content !== undefined)
              return Element.innerHTML = Content;
         else return Element.innerHTML;
      }

      return Element;
    }

access('h1').content('Hello World');

Hello

Or try something like this.

function access(Tag)
    {
      var Element = document.getElementsByTagName(Tag)[0];

      var content = function(Content)
      {
         if (Content !== undefined)
              return Element.innerHTML = Content;
         else return Element.innerHTML;
      }

      return {content: content};
    }

access('h1').content('Hello World');

Hello


text:
Q: Include initial position with CSS Steps I'm using css steps to create a "light board" you could say.
So there's a column of 18 divs that act as a "bulb".
The animation moves a div behind it that acts as the "lit up bulb "
My keyframes are set as:
@keyframes strobe{
    to{
        transform:translateX(1800%);
    }
}

And my animation is set as:
animation:strobe 2s steps(18, start) infinite;

Currently the animation never includes it's original position. (I also tried using 0% - 100% for the keyframes)
How can I include the initial position in the steps? And why is it currently not?
Included a fiddle for reference. Still working on responsive, so it doesn't show as 18 divs across.
https://jsfiddle.net/btxffgfj/

A: Playing around with your fiddle, I tried changing start to end and that seems to work.
animation:strobe 2s steps(18, end) infinite;

Fiddle


text:
Q: Finding asymptotic expansion Let $\{ \delta_n (\varepsilon) \}$ be an asymptotic sequence as $\varepsilon \rightarrow 0$, and $a_n$ be independent of $\varepsilon$ and $\delta_n (\varepsilon)$. A series $\sum \limits_{n=0}^{\infty} a_n \delta_n (\varepsilon)$ is said to be an asymptotic expansion of a function $f(\varepsilon)$ as $\varepsilon \rightarrow 0$ if for all $N>1$, $f(\varepsilon)-\sum \limits_{n=0}^{N} a_n \delta_n (\varepsilon)=o(\delta_N (\varepsilon))$ as $\varepsilon \rightarrow 0$.
Write down an asymptotic expansion for the function $$f(\varepsilon)=\cos(2\varepsilon)$$ in the limit $\varepsilon \rightarrow 0^+$.
Following the definition, I need $$\frac{\cos(2\varepsilon)-\sum \limits_{n=0}^N a_n \delta_n (\varepsilon)}{\delta_N (\varepsilon)} \rightarrow 0$$as $\varepsilon \rightarrow 0^+$
so I need to choose my $a_n$ and $\delta_n(\varepsilon)$ so that this is satisfied, right?
But how can I do this because the numerator is always going to have the negative of the largest $N$ term as the denominator.
Please help.

A: For finite limit points, convergent power series in the neighbourhood of the point are examples of asymptotic series.
For a bit more detail,
If $$f(x) = \sum_{n=0}^\infty a_n (x-x_0)^n$$ converges then for each $N$, $$f(x) = \sum_{n=0}^N a_n (x-x_0)^n + R_N$$ where $$R_N = (x-x_0)^{N+1}\left(\sum_{n=N+1}^\infty a_n (x-x_0)^{n-(N+1)}\right)$$ is bounded so $$R_N \in o((x-x_0)^N) \text{ as } x \to x_0$$


text:
Q: How to loop a Magento collection? Basically, I need to get a CSV file of my customers, generated automatically in a script every day.
I've tried several ways, but they are too slow or actually exhausted of memory.
*1) foreach through collection resource *
$collection = Mage::getResourceModel('customer/customer_collection')
->addAttributeToSelect('email')
->addAttributeToSelect('created_at')
->joinAttribute('billing_company', 'customer_address/company', 'default_billing', null, 'left')
->joinAttribute('billing_street', 'customer_address/street', 'default_billing', null, 'left')
->joinAttribute('billing_postcode', 'customer_address/postcode', 'default_billing', null, 'left')
->joinAttribute('billing_telephone', 'customer_address/telephone', 'default_billing', null, 'left')
->joinAttribute('billing_city', 'customer_address/city', 'default_billing', null, 'left')
->joinAttribute('billing_region', 'customer_address/region', 'default_billing', null, 'left')
->joinAttribute('billing_country_id', 'customer_address/country_id', 'default_billing', null, 'left');

foreach($collection as $customer) {
echo $customer->getFirstname() . ",";
}

2) foreach and load customer
$collection = Mage::getResourceModel('customer/customer_collection');
foreach($collection as $customer) {
  $fullcustomer = Mage::getModel("customer/customer")->load($customer->getId());
  echo $fullcustomer->getFirstname() . ",";
}

Any ideas?
Thanks!

A: Using a load() on each Customer object will significantly slow down your code.  I would suggest that your first approach of adding the required attributes to the collection is the right one, but finish it with something like:
$collection->toArray([$arrRequiredFields = array()]);

That way, the individual customers are never loaded, but toArray() (doco here) will give you the fields you want, then you can iterate over the multi-dimensional array to produce your comma-separated string.
Alternatively, you could try $collection->toXml() and work with XML if you're comfortable with that.  The Google will point you to xml->csv conversion methods.

A: Try paging a large collection!
The idea is if you can load the collection in smaller chunks, you won't use as much memory.
Load a chunk(page), then do something with it like saving it out to a text file and then load the next chunk. The result being, you've worked with the whole larger collection, but only incurred the memory cost of the largest page.
We use something similar to this to export orders from our store.
I plugged in your collection and it seems to work.
<?php

 if(php_sapi_name()!=="cli"){
 echo "Must be run from the command line.";
 };

/**
 * Setup a magento instance so we can run this export from the command line.
 */

require_once('app/Mage.php');
umask(0);

if (!Mage::isInstalled()) {
    echo "Application is not installed yet, please complete install wizard first.";
    exit;
}

// Only for urls // Don't remove this
$_SERVER['SCRIPT_NAME'] = str_replace(basename(__FILE__), 'index.php', $_SERVER['SCRIPT_NAME']);
$_SERVER['SCRIPT_FILENAME'] = str_replace(basename(__FILE__), 'index.php', $_SERVER['SCRIPT_FILENAME']);

Mage::app('admin')->setUseSessionInUrl(false);
Mage::setIsDeveloperMode(true); ini_set('display_errors', 1); error_reporting(E_ALL);

try {
    Mage::getConfig()->init();
    Mage::app();
} catch (Exception $e) {
    Mage::printException($e);
}
ini_set('memory_limit','500M');

$customerCount = 0;
try{
    //configure the collection filters.
    $collection = Mage::getResourceModel('customer/customer_collection')
    ->addAttributeToSelect('email')
    ->addAttributeToSelect('created_at')
    ->joinAttribute('billing_company', 'customer_address/company', 'default_billing', null, 'left')
    ->joinAttribute('billing_street', 'customer_address/street', 'default_billing', null, 'left')
    ->joinAttribute('billing_postcode', 'customer_address/postcode', 'default_billing', null, 'left')
    ->joinAttribute('billing_telephone', 'customer_address/telephone', 'default_billing', null, 'left')
    ->joinAttribute('billing_city', 'customer_address/city', 'default_billing', null, 'left')
    ->joinAttribute('billing_region', 'customer_address/region', 'default_billing', null, 'left')
    ->joinAttribute('billing_country_id', 'customer_address/country_id', 'default_billing', null, 'left');

    //Add a page size to the result set.
    $collection->setPageSize(100);
    //discover how many page the result will be.
    $pages = $collection->getLastPageNumber();
    $currentPage = 1;
    //This is the file to append the output to.
    $fp = fopen('/tmp/customers.csv', 'w');
    do{
         //Tell the collection which page to load.
         $collection->setCurPage($currentPage);
         $collection->load();
         foreach ($collection as $customer){
            //write the collection array as a CSV.
            $customerArray = $customer->toArray();
            //var_dump($customerArray); echo "\n\n";
            fputcsv($fp, $customerArray);
            $customerCount++;
         }
         $currentPage++;
         //make the collection unload the data in memory so it will pick up the next page when load() is called.
         $collection->clear();
    } while ($currentPage <= $pages);
    fclose($fp);
} catch (Exception $e) {
    //$response['error'] = $e->getMessage();
    Mage::printException($e);
}
echo "Saved $customerCount customers to csv file \n";
?>

I saved it as exportCustomers.php.
Then setup your cron task to run:
php -f /path/to/your/magento/exportCustomers.php


text:
Q: Formatting table in Jupyter I was trying to make a table in Python, but there are some elements that don't fit... I've tried everything that I know and I'm not getting why this is getting like this

The code is this:
    print("Year nº \t\t Stdts 1st year \t\t Stdts 2nd year \t\t Stdts 3rd years \t\t Stdts 4th year \t\t Stdts 5th year \n") #1st line of the table
    print(" %d \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t \n" %(actualYear, N1, N2, N3, N4, N5)) #Year 0 of the table

    while actualYear < 19:
          ...
    print(" %d \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t  %3.2f \t\t \n" %(actualYear, N1, N2, N3, N4, N5))

Thanks in advance.

A: The easiest way to do this, is using pandas.DataFrame.
There are two ways to reach the result you want:
Method 1: typing values in Python to create Pandas DataFrame
import pandas as pd

cars = {'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','Audi A4'],
        'Price': [22000,25000,27000,35000]
        }

df = pd.DataFrame(cars, columns = ['Brand', 'Price'])

print (df)

Method 2: importing values from an Excel file to create Pandas DataFrame
import pandas as pd

data = pd.read_excel(r'Path where the Excel file is stored\File name.xlsx')
df = pd.DataFrame(data, columns = ['First Column Name','Second Column Name',...])

print (df)

Hope this helped you.

A: Two solutions:

*

*Don't use tabs. They advance to the next tab stop which is usually the column number divisible by 8. Notice how your first values are shorter so it throws off where the tab stop ends up.

*Set your field widths correctly. %3.2f means your field has a width of 3, but your largest numbers have a width of 6. Use %6.2f instead.


text:
Q: Set command can't handle lines constituting of a \n (word/line counting script) I have a problem with execution of a while loop, I have found out that the problem  involves the execution of the set command, the assigment of the \n character to an environmental variable constitutes a problem. Why does it happen and how to solve it?
my code is:
echo "Enter a filename:\c"
read fname
terminal=`tty`
exec < $fname
nol=0
now=0
while read line
do
    nol=`expr $nol + 1`
    set $line
    now=`expr $now + $#`
done
echo "Number of lines:$nol"
echo "Number of words:$now"
exec < $terminal

When it encounters a line with nothing but a newline character in it, it prints system data and all of the variables:
CINNAMON_VERSION='1.8.8'
COLORTERM='gnome-terminal'
(...)
fname='drunk'
line=''
nol='19'
now='137'
terminal='/dev/pts/0'

(...) indicates omission of an entire block of system data

A: Instead of
set $line

use
set -- $line

Read help set to see why this works.


text:
Q: SAS importing multiple datasets to save name of dataset as variable I need to access a directory with some sas datasets named all_ci, all_pd, all_vs, etc.  ci would be 'care info', pd would be 'patient data' and vs would be 'vital stats.'  I am reading them in as such:
data ci_all;
set DIRECTORY.all:; run;

I get a table that looks like this:
No.
16
25
20

This works in only setting all the sets that begin with all.  The issue is that I need an output that looks like this:
Category          No.
Patient Data      16
Vital Statistics  25
Care Info         20

Since the original all_ datasets do not have the category label, I have to manually count in which order the all_ dataset was read, and then label it.  I was wondering if there was a way which saves the name of the dataset that's being read in so I can easier label them in the rows.

A: Use the INDSNAME option on the SET statement.  You need to copy the value to a new variable since the variable referenced in the dataset option is automatically dropped.
libname DIRECT 'mydirectory' ;
data ci_all;
  lenght dsname indsname $41 ;
  set DIRECT.all: indsname=indsname;
  dsname=indsname;
run;


text:
Q: Как сложить цифры разрядов числа? Например, есть число - 1204. Надо, чтобы оно сложило цифры каждого разряда (1 + 2 + 0 + 4). Как это сделать?

A: int solution(int number) {
    int sum = 0;
    while (number) {
        sum += number % 10;
        number /= 10;
    }
    return sum;
}

A: Вот так вот:
#include <string>
#include <iostream>
#include <numeric>

int main() {
    constexpr auto x = 1204;

    const auto s = std::to_string(x);
    std::cout << std::accumulate(std::cbegin(s), std::cend(s), 0, [](auto acc, auto x) {
        return acc + (x - '0');
    }) << '\n';
}

A: Я бы учел, что число может быть отрицательным. Ну и еще один вариант:
unsigned g(int n)
{
    n = std::abs(n);
    if (n < 10)
        return n;
    std::stringstream io;
    io << n;
    n = 0;
    char t;
    while (io >> t)
        n += t - '0';
    return n;
}

A: Раз тут начались споры, что быстрее... Эксперимент
unsigned int Hovsepyan()
{
    unsigned int sum = 0;
    for(int n = 0; n < Count; ++n)
    {
        n = std::abs(n);
        if (n < 10) { sum += n; continue; }
        std::stringstream io;
        io << n;
        char t;
        while (io >> t)
            sum += t - '0';
    }
    return sum;
}

unsigned int olkhovich()
{
    unsigned int sum = 0;
    for(int n = 0; n < Count; ++n)
    {
        int number = n;
        while (number) {
            sum += number % 10;
            number /= 10;
        }
    }
    return sum;
}

unsigned int dIm0n()
{
    unsigned int sum = 0;
    for(int n = 0; n < Count; ++n)
    {
        const auto s = to_string(n);
        sum += accumulate(cbegin(s), cend(s), 0,
                          [](auto acc, auto x) {
                              return acc + (x - '0');});
    }
    return sum;
}

int main(int argc, const char * argv[])
{
    {
        muTimer mt;
        unsigned int s = Hovsepyan();
        mt.stop();
        cout << "Hovsepyan() == " << s << "  for " << mt.duration<>() << " mks\n";
    }
    {
        muTimer mt;
        unsigned int s = olkhovich();
        mt.stop();
        cout << "olkhovich() == " << s << "  for " << mt.duration<>() << " mks\n";
    }
    {
        muTimer mt;
        unsigned int s = dIm0n();
        mt.stop();
        cout << "dIm0n()     == " << s << "  for " << mt.duration<>() << " mks\n";
    }
}

(полный код здесь) дает на моей машине (VC++ 2019) и на Ideone (GCC) следующие результаты в мкс:
                 VС++ 2019          GCC

olkhovich()         8324            6970
dIm0n()            19634           80521
Hovsepyan()      1310028          434293

Так что моя рекомендация - принять ответ olkhovich - остается в силе :)


text:
Q: convert string to point name I have:
for(int b = 0; b <num; b++)
{
    string naz_pkt = "punkt_" + b.ToString();

    Point naz_pkt = new Point(i,j);
    ....
}

And what, I need to do:
I want make Points, where name of the Point will be change with the loop. And i will have for ex.
Point punkt_1 = new Point(0,1);
Point punkt_2 = new Point(0,2);
Point punkt_3 = new Point(0,3);
etc.

After that I want drow this points by polygon.
Thanks for help.

A: If you don't really care about the name of the points, you can use a list to hold them:
List<Point> allPoints = new List<Point>();
for(int b = 0; b < num; b++)
{
    Point naz_pkt = new Point(i,j);
    allPoints.Add(naz_pkt);
}

If you care about the name you can use something like KeyValuePair:
List<KeyValuePair<string, Point>> allPoints = new List<KeyValuePair<string, Point>>();
for (int b = 0; b < num; b++)
{
    var pointName = "punkt_" + b.ToString();
    var pointObject = new Point(i, j);
    KeyValuePair<string, Point> point = new KeyValuePair<string, Point>(pointName, pointObject);

    allPoints.Add(point);
}


text:
Q: D3 Multiple Visualizations Per Page Namespace IRI Conflicts I'm using D3 to generate multiple visualizations per page, but I'm having a problem when it comes to IRIs or functional IRIs.
Namely, code with textPaths:
this.linkGroup.selectAll(".text_path")
 .attr("xlink:href", function(d) { return "#" + d.id })
 .text(function(d) { return d.text })

or markers:
this.linkGroup.selectAll(".link")
  .attr("marker-start", function(d) { return "url(#startArrow)" })

With both of these, if any SVG I create after the first has the same IRI id as a previous one, it will use the first id found in the HTML, even if that is from a different SVG than the current context.
As an example:
<body>
  <svg>
    <defs>
      <marker id="startArrow"...>...</marker>
    </defs>
  </svg>
  <svg>
    <defs>
      <marker id="startArrow"...>...</marker>
    </defs>
  </svg>
</body>

If in the second SVG I reference the marker with url(#startArrow), it will instead get the first #startArrow in the entire document, in this case, the first SVG.
Is there a way to use only the ids/IRIs within the current SVG instead of the entire document? Not sure if this would require some namespacing or not.


text:
Q: Salesforce Site.login returns null when used in a REST API I am trying to write a custom login screen for a portal user in react JS. I had a controller exposed as a rest API which is using SIte.login(username, password, url) for the user credential validation. But I was, always, getting null from Site.login call. I am using below code.
@RestResource(urlMapping='/my_login/*')
global class My_custom_SiteRegisterController {
    public static final String USERNAME = 'username';
    public static final String PASSWORD = 'password';

    /**
     * Response body
     */
    global class MyLoginResponse {
        Boolean success {get; set;}
        Integer statusCode {get; set;}
        String uusername {get; set;}
        String ppassword {get; set;}
    }

    @HttpGet
    global static void login() {
        RestRequest req = RestContext.request;
        String username = req.params.get(USERNAME);
        String password = req.params.get(PASSWORD);

        PageReference pr = Site.login(username, password, '/apex/home');
        if(pr != null){
            createRestResponse(200,true,username,password);
        }else{
            createRestResponse(200,false,username,password);
        }

        return;
    }

    private static void createRestResponse(Integer statusCode, Boolean success,String username,string password) {
        MyLoginResponse my_Login_Response = new MyLoginResponse();
        my_Login_Response.statusCode = statusCode;
        my_Login_Response.success = success;
        my_Login_Response.uusername = username;
        my_Login_Response.ppassword = password;

        RestResponse res =  RestContext.response;
        res.addHeader('Content-Type', 'application/json; charset=UTF-8');
        res.statusCode = my_Login_Response.statusCode;
        res.responseBody = Blob.valueOf(JSON.serialize(my_Login_Response));
        RestContext.response = res;
        return;
    }
}

A: It will return null if the Login failed to login.   Use a Try Catch , and catch for null to handle the correct REST response.


text:
Q: Non-Domian Windows DNS Servers communication ports Our public DNS is hosted on Non-Domain-Joined Windows servers.
Internally we have NS1 that is read/write where we manage our DNS.
Externally we have NS2 that is in the DMZ and is a read only copy of NS1.
Right now the firewall between NS1 and NS2 is wide open. I want to close it down to only what is required.
I have not been able to find what ports are used when NS1 copies the DNS data to NS2.
Is it just port 53?
Are there others required for authentication between the Primary and the read only server?
Thank you


text:
Q: how to send dynamically created text field value to php mail

$('input[type="radio"]').click( function(){
$val = $(this).val();
$('#container').html('');
$content = '';
$val = $(this).attr('count')
var i = 1;
for( i = 0; i < $val; i++ ) {
    $content += '

<input type="text" name="f1-email" placeholder="Name" class="f1-email form-control" id="f1-email">

<input type="text" name="f1-email" maxlength="2"  placeholder="Age" class="f1-email form-control" id="f1-email">

<select class="form-control"><option value="M" selected="">Male</option><option value="F">Female</option></select>

';
}
   $('#container').html($content);
 });

<input  type="radio" name="optradio" value="1">1
 PERSON

<input  type="radio" name="optradio" value="2" >2
PERSON

<input  type="radio" name="optradio" value="3" >3
PERSON

i created text field using javascript depends on the usr radio button selection, how to get the values of dynamically created field value,i need to send these value to php mailer

A: There must be a way to send data through js to PHP, but since you want to retrieve that in php why not make it directly so?
Since is a form you can use the type of method of sending that data (POST OR GET) and getting it through php!
<form action="yourphpfile.php" method="post">
Some data: <input type="text" name="data">
<input type="submit">
</form>

when someone clicks on submit it get's registered through PHP so if in your php code you use
 $_POST["data"]

You'll get the value of the input you've made


text:
Q: Input Sequences using CSV-Reader and Queues in Tensorflow Referring to: https://www.tensorflow.org/how_tos/reading_data/
GOAL:
I would like to train a LSTM using preceding sequences in the following form:
[t0 t1 t2], [t1 t2 t3], [t2 t3 t4] ...
Furthermore these sequences should also shuffled.
e.g. [t2 t3 t4], [t0 t1 t2], [t1 t2 t3] ...
My data are stored in a csv-file, each row representing a time step. The columns contain the different features & target value.
QUESTION:
Is there a way to feed shuffled coherent sequences using csv-reader and queues (not placeholder and feed_dict) in Tensorflow?
I cannot think of a way to implement that with: tf.TextLineReader() and tf.train.shuffle_batch().
My workaround does what it's supposed to, but is horribly slow:
train_filename_queue = tf.train.string_input_producer([path])
rand_ind_q = tf.train.range_input_producer(data_len-seq_len, shuffle=True)

def read_csv(filename_queue, ncols, header_lines):
''' returns a list of tensors with content of csv-file
'''
    # content <- [(data_len,) ... ncols ... (data_len,)]

    whole_reader = tf.WholeFileReader()
    _, content = whole_reader.read(filename_queue)
    content = tf.string_split([content], delimiter='\n').values[header_lines:]
    record_defaults = ncols*[[0.]]
    content = tf.decode_csv(content, record_defaults, field_delim=',')
    return content

def slice_seq(q, content, seq_len):
''' returns a list of tensors with sequences
'''
    # seq <- [(1,seq_len,) ... ncols ... (1,seq_len,)]

    start_ind = q.dequeue()

    seq = list(map(lambda tensor: tf.slice(tensor, [start_ind], [seq_len]), content))
    seq = list(map(lambda tensor: tf.reshape(tensor, (1,seq_len,)), seq))
    return seq

A: How large is the csv file you are loading? If it is large, then using WholeFileReader is problematic; if it is small, then I would suggest creating the sequences outside TensorFlow.
That said, if you want to do this in TensorFlow, you could try
block_size = 10
seq_len = 3
batch_size = 4
queue_capacity = 32
num_threads = 4
csv_path = '/path/to/some.csv'

filename_queue = tf.train.string_input_producer([csv_path])
block = tf.TextLineReader().read_up_to(filename_queue, block_size).values
subsequences = [tf.slice(block, [i], [block_size - seq_len + 1]) for i in range(seq_len)]
batched = tf.train.shuffle_batch(subsequences,
                                 batch_size,
                                 capacity=queue_capacity,
                                 min_after_dequeue=queue_capacity/2,
                                 num_threads=num_threads,
                                 enqueue_many=True)
decoded = [tf.decode_csv(b, [[0.]] * ncols, ',') for b in batched]

The only downside here is that you will miss roughly seq_len/batch_size of the subsequences.
Hope this helps.


text:
Q: To append the attribute name with an input variable I want to append the node attribute name with an input integer value.
Eg:
count=1
node["example_#{count}"]

expected value: node[example_1]
But we are getting a nil value. Please let us know the right way of appending.

A: there is a different between setting and attribute, and retrieving an attribute.
in the snippet you shared, a node attribute is being retrieved but not assign to any other variable.
if you would like to assign a value to a node attribute, do it as follows:
count = 1
node.default["example_#{count}"] = 'foo'


text:
Q: How can I show a LWC ToastEvent message in Visualforce? I have an LWC component which has multiple showToastEvents which works in Lightning Exp without any issue.
But when I am calling the same LWC component from a VF page, I am not able to see toastevent.
I know ShowToastevent is not supported in Ltng:outApp, but is there an alternative or can I replace the existing showToastEvent?

A: You could use slds-toast
Then you can use setTimeout() to make the custom toast disappear after a few seconds
    handleClick(){
        let delay = 1000
        setTimeout(() => {
            this.visible = false;
        }, delay );
    }

    <template if:true={visible}>

Succeeded

                    <lightning-icon icon-name="utility:success" alternative-text="success" variant="Success" size="small" ></lightning-icon>

    </template>

A: You can make use of ui:message component which will work in lightning out. The only thing is UI components have been deprecated but it would be a quick win.

Or, You have to use slds -Toast in your lightning component so that it will work in visualforce page as well. check out this:- Display and close toast in SLDS