text:
Q: Unable to establish SSL connection while setting up SSL on Ubuntu/Apache2     root@www:/etc/apache2# wget https://www.domainname.com
--2013-09-19 09:15:12--  https://www.domainname.com/
Resolving www.classmint.com (www.domainname.com)... 198.*.124.142
Connecting to www.domainname.com (www.domainname.com)|198.*.124.142|:443... connected.
OpenSSL: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
Unable to establish SSL connection.

If I put Listen 443 in ports.conf, i can't restart apache.
I am able to access http://domainname.com:443 but i can't use https. What could be wrong?
What are best ways to troubleshoot this?

A: I hope this will help you http://www.ssl.ua/news/how-to-create-and-install-an-apache-self-signed-certificate/
And you need to install SSL "apt-get install libssl-dev"


text:
Q: How to group the rows by two conditions? I am doing some work with pandas with a little database, I have 5 rows ID, X, Y, Z and Frame, and I would like to just have a Data-frame where the X, Y and Z are close by a threshold of 12 in each axis and they have the same ID, because probably they are repetitive data or noise. I will illustrate this with a little example, this is what I have:
ID,    X,    Y, Z, Frame
5,  0.,   239., 0, 135
5,  10.,  242., 0, 136
4,  12.,  355., 0, 137
3,  10.,  254., 0, 138
4,  180., 370., 0, 138
4,  182., 225., 0, 138
5,  170., 383., 0, 139
5,  162., 391., 0, 140
3,  446., 285., 0, 141
4,  528., 209., 0, 142
4,  520., 211., 0, 143
4,  405., 292., 0, 144
4,  397., 289., 0, 145
4,  390., 290., 0, 146
4,  384., 294., 0, 147
4,  382., 296., 0, 148
4,  444., 212., 0, 149
6,  469., 275., 0, 149

and I expect with those values this result:
ID,    X,    Y, Z, Frame  Repetitions
5,  5.,   241., 0, 135    2
4,  12.,  355., 0, 137    1
3,  10.,  254., 0, 138    1
4,  180., 370., 0, 138    1
4,  182., 225., 0, 138    1
5,  166., 387., 0, 140    2
3,  446., 285., 0, 141    1
4,  524., 210., 0, 142    2
4,  391.6, 292.2, 0, 144  5
4,  444., 212., 0, 149    1
6,  469., 275., 0, 149    1

I tried with numpy and pandas a lot of ideas, but the only way I make it work is with 4 for loops, which has a really bad performance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: different "python" and "python3" versions My python --version is Python 3.9.6
And my python3 --version is  Python 3.10.8
I believe because of this I have a problem with running flask applications in VsCode. When I run one I receive ModuleNotFoundError: No module named 'flask error, however, I did install flask module
Requirement already satisfied: flask in /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages (2.2.2)

I know that sometimes this problem is caused by the wrong interpreter version, I tried all of them but no one worked

Does anybody know what is the reason for my error and how can I fix it?

A: Use the following code to print out the currently used interpreter.
import sys
print(sys.executable)

Then use the command to install flask for the current interpreter.
<pythonpath> -m pip install flask

Referencing this link will help.

A: Try this either of this commands;
---python3 -m venv venv
--python -m venv venv
---py -m venv venv
if that doesn't work then get your Python version and make sure you are installing the package using the correct Python version.
But If the  error persists, restart your IDE and development server/script.
You can check if you have the Flask package installed by running the pip show Flask command.


text:
Q: Iphone Statusbar message Does anybody know how to show a color bar below the status bar (just like "return to call" when call minimized)? I need to do the same thing with my app, but my app is not a audio, music, VoIP, or location related app. I want to show to the user when app is minimized and the be able to just click the status and go back to app.

A: That is not possible in iOS.  Sorry :(


text:
Q: How to calculate mean of array with type numpy64float? I have a very big cycle in which I need to calculate mean. In this cycle I generate 1000 possible oddsratio. Just look at the end of my code:
oddsratio=(cross_tab[1][1]*cross_tab[0][0])/(cross_tab[1][0]*cross_tab[0][1])
lst = [oddsratio]
np_lst = np.array(oddsratio)
new_array = np_lst.astype(type('float', (float,), {}))
mean_arr = np.mean(new_array)
print(sum(new_array)/len(new_array))

the output (many numbers) of oddsratio is numpyfloat64 and I got error using np.mean() or statistics.mean()
I tried to convert it in np.array, but got error again: 'float' object is not iterable If i just run print(mean_arr) it gives me all numbers of oddsratio
Initially, I tried to convert in list, but output created for every value in list with additional '[]', for example I had lst = [[0.9][0.7][0.6]....]. I tried to remove inner list, but it does not work also.
Output of oddsrato
I never worked with numpy previously,and the mistake is not understandable for me. Please could anybody give me advice how to fix it?

A: the numpy reference for np.mean says that np.mean return value is an ndarray, but if you don't specify the axis argument it will return a single float. that's why sum(mean_arr) throws a TypeError (object not iterable).
i don't understand when you say that print(mean_arr) gives you all numbers of oddsratio: the screen you  posted shows print(oddsratio). mean_arr is just a float. either you're always printing oddratio, or you're not showing us the entirety of your code.

A: Have you tried to call mean() on your array?
np_lst.mean()


text:
Q: Saving memory in an array/class members without losing too much performance I have a programms which stores 100.000s of files and its information. Typically the class definition is like this:
class DSPhotoFile: NSObject, NSCopying, Comparable {
    let key: Int                    // may I need an numeric ID? Easy and fast
    let initUrl              : URL  // initial, never changed (could also be used as key)
    // derived data from filepath
    // string parts
    var fullpath        = String()   // "/rootfolder/sub/sub2/pic1234.jpg"
    var path            = String()   // "/rootfolder/sub/sub2"  (path without tailing /)
    ...                              //  12345678901234567890 12345678901
}

I want to save memory, but not at all costs.
First: How can I dynamically calculate the amount of bytes an instance of this definition uses? There are string members which are dynamic! So I need the complete occupied space including all subtypes.
My next idea is to store only an Int for the length of the suffix or prefix if needed. E.g. path is the first 20 items of fullpath. If I store the Int16 "20", it needs 2 bytes, and then I calculate the member path as fullpath.prefix(20). This could also be done for all other members which rely on another constant string.
Any idea about performance difference from String vs String.prefix? Some recommendations?

A: There is no easy way to compute the actual memory requirements of one record. As you note, the data is stored in a number of complicated ways that frustrate that. What is better is to run Instruments on an app that generates 100k real records and look at the total memory usage.
Making this an NSObject subclass is likely going to be wasteful compared to a struct (or even a pure Swift class, but I'd still start with a struct).
If your paths may be long, you can likely save substantial memory by storing the directory information separately and just storing the name. Copies of a string enjoy copy-on-write benefits, but strings that happen to be identical (but from different sources) do not get de-duplicated. So if you have something like:
let directory = "..."
let file1 = File(directory: directory, name: "file1")
let file2 = File(directory: directory, name: "file2")

Then you should expect the two copies of directory to share storage. This could matter a lot if the directory can be long. However:
let file1Name = "longdirectorypath/file1"
let file2Name = "longdirectorypath/file2"
let file1dir = String(file1Name.prefix(dirlen))
let file2dir = String(file2Name.prefix(dirlen))

In this case, you should not expect file1dir and file2dir to share storage, even though the string happens to have the same value.
Alternately, if you store you data in a tree structure (likely using Swift classes, not structs), then you may be able to avoid ever storing the whole path. Just store your parent and compute the path by walking the tree.
String.prefix returns a Substring, which is an O(1) operation, and very fast to access. So that's a fine approach, but I think still more expensive if you have many copies of the same directory path.
I would explore the cost of URL vs String for initUrl. I expect that URL is a bit larger (and you can compute an URL if you need it).
If you're just going to have a ton of URLs in kind of random order, so it's hard to share parts of the string, then I'd probably just store initUrl as a String, and slice it up for fullpath and path if possible. As long as they all live together in a struct, you can store a Substring (which is just a range), or use use two integers to point to the path start and the filename start. With those you can compute the rest.
If you're precomputing things for performance, make sure to profile that carefully to make sure it's a win. Using a lot of memory can also cost you heavily in speed (due to memory allocations, locality issues, and other costs of dealing with RAM). There's an old CS belief in time/space tradeoffs, but in modern systems there is often no such tradeoff. Saving space can also save time in nonintuitive ways. Profile profile profile.
With records on this scale, wise data structures and good algorithms become really important. I would definitely look at a trie or prefix tree for this kind of structure. In my experience, if this lives in an array, I would lean heavily towards structs. But for list- or tree-like structures, you will generally want classes in Swift.


text:
Q: Contact form HTML to PHP What is the easiest way to get this HTML contact form to send Emails?

Hire Me

    <form role="form">

            <input type="name" class="form-control" placeholder="Your Name">

            <input type="email" class="form-control" placeholder="Your Email">

        <textarea class="form-control" rows="3" placeholder="Tell me about your project..."></textarea>

        <button type="submit" class="btn btn-success">SUBMIT</button>
    </form>

A: As stated in this answer :
How to create an email form that can send email using html
You cannot do it directly via HTML. See the proposed answers.

A: You will have to create a .php file with the php program to send the email..
you can refer to this website which will show how to do that and just call the php file you submit your form..
http://www.w3schools.com/php/php_mail.asp
Good luck! :)

A: Add this to the form row

Then create a file called email-sending.php
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent=" From: $name \n Email: $email \n Order Number: $order_number \n Sign Up for Newsletter: $newsletter \n Message: $message";
$recipient = "your email";
$subject = "Subject from $name";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank You! We will get back to you as soon as possible!" . " -" . " Back to site";
?>

A: You can either use the PHP code in the answer above or you can use other programs out there that have been "battle-tested" already and are much safer to use.
A quick Google search gave PHPMailer from github: https://github.com/PHPMailer/PHPMailer


text:
Q: Radio Waves propagation (Intuitive Understanding of Wave propagation) I have few similar questions regarding Radio waves communication particularly FM and AM type of Radio wave communication. Please bear with the naivety of the questions.
Questions:
Radio waves in FM and AM communications are transmitted through Air and we pick those signals with the help of our receivers.
Assume few FM Radio stations such as 91.1MHz, 93.5MHz and 94.3MHz. (Area size radius - 10-15km)
All these stations are operating simultaneously and depending on what frequency I tune receiver, that radio station is played. But the idea is that all the above 3 radio stations are working and operating simultaneously.
Since the radio waves are EM waves, they propagate in air in the form of waves. So, technically, do these EM Waves propagate through the atmosphere by disturbing the air particles, I mean like, compression and rarefaction? I just want to understand how does these waves move from the transmitter to the receiver.
Question 1 : Do the EM waves travel by creating disturbances in the air particles such as compression and rarefaction?
If they travel like that, won't the compression and rarefaction pattern of the 91.1MHz radio station affect the compression and rarefaction pattern of the 93.5MHz radio station and cause any disturbance/interference/cross-talk between each other before they even reach my receiver? How won't those 2 radio stations interfere between each other ?
Question 2 : What would be typical distance range in terms of radius (in km) of an FM/AM radio station? I tried to find. But unable to find it. Somewhere, I have read that the distance coverage is dependent upon the power of the FM Radio Transmitter? Could someone please throw some more information like a certain table which would provided the distance covered and the radius of coverage of the FM Radio?
Question 3 : If the FM Radio communication are a type of line of sight communication, how am I able to receive the FM Signal even if my receiver is not in direct line of sight of the FM Transmitter?
P.S. The reason why I didn't make it as 3 separate questions because all these questions are very closely related so that I didn't want to burden the answer-er to the question or a similar fellow person who is having the same queries to find the answer under a single question itself.

A:
Do the EM waves travel by creating disturbances in the air particles such as compression and rarefaction?

No.
Radio waves are electromagnetic waves. They propagate in the electromagnetic field itself.
They do not require any physical medium to travel through and can travel through vacuum just as well (better, actually) than through air. If EM waves couldn't travel through vacuum, we wouldn't be able to see the sun.

What would be typical distance range in terms of radius (in km) of an FM/AM radio station? I tried to find. But unable to find it. Somewhere, I have read that the distance coverage is dependent upon the power of the FM Radio Transmitter? Could someone please throw some more information like a certain table which would provided the distance covered and the radius of coverage of the FM Radio?

What you read is correct: It depends a great deal on the transmitter power. Other factors such as antenna configuration, terrain, atmospheric conditions, etc., can also strongly affect broadcast range.
Normally, transmitter power is limited by regulations to allow for transmission over a few 100 km or less.
AM radio often has greater range than FM due to the lower frequencies used. The most powerful stations in the US (for example, KGO can be heard over nearly half the country, a range of well over 1000 km.
For US stations, sites like radio-locator.com provide coverage maps showing the areas stations are licensed to broadcast to.
Here's an example for one of my local stations, broadcasting with 8.9 kW from an altitude of 412 m (but in fairly hilly terrain):

If the FM Radio communication are a type of line of sight communication, how am I able to receive the FM Signal even if my receiver is not in direct line of sight of the FM Transmitter?

FM radio at broadcast frequencies is not truly a line-of-sight transmission. Due to diffraction, the signal can often be received even if a building or hill intervenes.

A:
Question 1 : Do the EM waves travel by creating disturbances in the
air particles such as compression and rarefaction?

No.  They are an electromagnetic field.  They are the same type of thing as light (and travel at the same speed).  For AM/FM radio stations the only difference is that the wavelengths are a lot longer than visible light.

*

*They can travel in space where there is no air (that's how all space based communications work)

*They can also pass through solid objects like wood for short distances (that's how you can pick up the radio from inside your house).

*They can pass through water (for short distances), for example to control a small unmanned submarine.

If they travel like that, won't the compression and rarefaction
pattern of the 91.1MHz radio station affect the compression and
rarefaction pattern of the 93.5MHz radio station and cause any
disturbance/interference/cross-talk between each other before they
even reach my receiver? How won't those 2 radio stations interfere
between each other ?

The radio waves essentially pass right through each-other the same way that two flashlight beams pass right through each-other.  While they are crossing, the field values just add together, and emerge out the other side at their original values.
At the receiver, the waves for multiple stations are all present and being received by the antenna.  For an AM or FM radio there is a band-pass filter that selects only the waves falling within a specific frequency range (for example only 93.4MHz to 93.6MHz).  Typically such filters can be made using transistors, op-amps, inductors capacitors, and resistors.
The operation of such filters depends on mathematical tricks that exist for linear systems, which make it easy to separate the signals.  You would need a background in linear circuit theory, and calculus to understand the math.  The basic principle is that even if you have a signal composed of multiple frequencies added together the filter can take just the part that is of the desired frequency and mostly reject the other part (though nothing is perfect).

Question 2 : What would be typical distance range in terms of radius
(in km) of an FM/AM radio station? I tried to find. But unable to find
it. Somewhere, I have read that the distance coverage is dependent
upon the power of the FM Radio Transmitter? Could someone please throw
some more information like a certain table which would provided the
distance covered and the radius of coverage of the FM Radio?
Question 3 : If the FM Radio communication are a type of line of sight
communication, how am I able to receive the FM Signal even if my
receiver is not in direct line of sight of the FM Transmitter?

The range of the signal does depend on the transmitter power, and also on the sensitivity of the receiver.  As the signals spreads out from the source antenna it covers a larger and larger area.  As a consequence the amount of power in any given spot "thins out" the further you go.
The signal never really disappears, but at some point there is not enough power at the receiver for you to use the signal.  That distance is determined by how much RF background noise there is as well as the sensitivity of the receiver.  Receivers made to communicate with spacecraft (for example the mars rovers) use gigantic antennas in order to pick up really weak signals.
Radio towers are usually pretty tall, so their view of the horizon extends many miles.  Additionally signals from AM/FM radio stations can travel through some amount of trees and buildings.  Lastly, AM/FM radio waves at the frequencies used by music radio stations can reflect off of parts of the earth's atmosphere (like a mirror) to extend their range beyond the horizon by bouncing back and forth between the atmosphere and ground.


text:
Q: Place text between two tikzpicture environment How can I type my text between two tikzpicture environments? When I type my text, the second  tikzpicture go to next page! What I should to do?
Thanks so much
\documentclass{article}
\PassOptionsToPackage{dvipsnames,svgnames}{xcolor}
\usepackage[object=vectorian]{pgfornament}
\begin{document}
    \begin{tikzpicture}[remember picture,overlay]
    \node[below left] at ([xshift=-2cm,yshift=-1cm]current page.north east) {\pgfornament[width = .8cm,
        color = MidnightBlue]{15}
        \hspace{-6pt}\pgfornament[width = 1.6cm,
        color = MidnightBlue,
        symmetry=h]{15}
        \hspace{-8pt}\pgfornament[width = 2.4cm,
        color = MidnightBlue]{15}};

    \node[below right,rotate=270] at ([xshift=-1cm,yshift=-2cm]current page.north east) {\pgfornament[width = 2.4cm, color = MidnightBlue,symmetry=v]{15}
        \hspace{-8pt}\pgfornament[width = 1.6cm,
        color = MidnightBlue,
        symmetry=h,symmetry=v]{15}
        \hspace{-6pt}\pgfornament[width = 0.8cm,
        color = MidnightBlue,
        symmetry=v]{15}
    };
    \end{tikzpicture}

    I want to type my text here but the second tikzpicture go to next page! What I should to do?

    \begin{tikzpicture}[color=Maroon,
    every node/.style={inner sep=0pt}]
    \node[minimum size=\linewidth](vecbox){};
    \node[anchor=north west] at (vecbox.south west)
    {\pgfornament[width=5cm]{9}};
    \end{tikzpicture}
\end{document}

A: The package ornaments are inserted as a node in the tikzpicture environment with the remember picture and overlay options.
These two options allow you to memorize the different images and make, for example, an arrow that goes from one figure to another.
That's why there are two compilations.
As you have inserted these images as a node, their placement is governed by the options available on these nodes (see section 17.5 Positioning Nodes in TikZ manual 3.1.4). Its color color =LimeGreen is governed by the color options of the nodes.
TikZ predefines a node that corresponds exactly to the entire page (see section 17.13.2 Referencing the Current Page Node - Absolute Positioning in TikZ manual 3.1.4).
Here, I positioned this node at the bottom left of the page (i.e. at its South West: at (current page.south west)) and anchored it to the South West, i.e. the image is hung on the page from its southwest corner: anchor=south west.
 \node[anchor=south west,color =LimeGreen] at (current page.south west)
    {\pgfornament[width=5cm]{9}};

Translated with www.DeepL.com/Translator
\documentclass{article}
\PassOptionsToPackage{dvipsnames,svgnames}{xcolor}
\usepackage[object=vectorian]{pgfornament}
\begin{document}
    \begin{tikzpicture}[remember picture,overlay]
    \node[below left] at ([xshift=-2cm,yshift=-1cm]current page.north east) {\pgfornament[width = .8cm,
        color = MidnightBlue]{15}
        \hspace{-6pt}\pgfornament[width = 1.6cm,
        color = MidnightBlue,
        symmetry=h]{15}
        \hspace{-8pt}\pgfornament[width = 2.4cm,
        color = MidnightBlue]{15}};

    \node[below right,rotate=270] at ([xshift=-1cm,yshift=-2cm]current page.north east) {\pgfornament[width = 2.4cm, color = MidnightBlue,symmetry=v]{15}
        \hspace{-8pt}\pgfornament[width = 1.6cm,
        color = MidnightBlue,
        symmetry=h,symmetry=v]{15}
        \hspace{-6pt}\pgfornament[width = 0.8cm,
        color = MidnightBlue,
        symmetry=v]{15}
    };
%    \end{tikzpicture}

%    \begin{tikzpicture}[color=Maroon,
%    every node/.style={inner sep=0pt}]
%    \node[minimum size=\linewidth](vecbox){};
    \node[anchor=south west,color =LimeGreen] at (current page.south west)
    {\pgfornament[width=5cm]{9}};
    \end{tikzpicture}

        I want to type my text here but the second tikzpicture go to next page! What I should to do?
\end{document}

A: There are packages especially for such purposes, with one of them being eso-pic. On benefit is that they help to avoid spurious spaces, another benefit is that you can have these ornaments on all pages of the document. If you only want them on one specific page, use \AddToShipoutPictureBG*{...} on that page (and drop the \AddToShipoutPictureBG in the preamble).
\documentclass{article}
\PassOptionsToPackage{dvipsnames,svgnames}{xcolor}
\usepackage[object=vectorian]{pgfornament}
\usepackage{eso-pic}
\AddToShipoutPictureBG{%
    \begin{tikzpicture}[remember picture,overlay]
    \node[below left] at ([xshift=-2cm,yshift=-1cm]current page.north east) {\pgfornament[width = .8cm,
        color = MidnightBlue]{15}
        \hspace{-6pt}\pgfornament[width = 1.6cm,
        color = MidnightBlue,
        symmetry=h]{15}
        \hspace{-8pt}\pgfornament[width = 2.4cm,
        color = MidnightBlue]{15}};

    \node[below right,rotate=270] at ([xshift=-1cm,yshift=-2cm]current page.north east) {\pgfornament[width = 2.4cm, color = MidnightBlue,symmetry=v]{15}
        \hspace{-8pt}\pgfornament[width = 1.6cm,
        color = MidnightBlue,
        symmetry=h,symmetry=v]{15}
        \hspace{-6pt}\pgfornament[width = 0.8cm,
        color = MidnightBlue,
        symmetry=v]{15}
    };
    \node[anchor=south west,color = MidnightBlue] at
    (current page.south west)    {\pgfornament[width=5cm]{9}};
\end{tikzpicture}}%
\begin{document}
I want to type my text here but the second tikzpicture go to next page! What I
should to do?
\end{document}


text:
Q: ElementUI - How to Word wrap: break-word in el-table-column Using ElementUI I'd like to be able to wrap the text in a column on whitespace rather than in the middle of a word.  Normally you'd apply
white-space: normal;
word-wrap: break-word;

To the  in a normal column, or wrap in a div with that styling but when using ElementUI el-table and el-table-column it doesn't have any effect.  I've tried on the el-table-column as a class and as a direct applied style but nothing changes.
Does anyone have any experience of making this work?

A: Inspect the element and check if the properties are correctly set.
Should be a problem of CSS Specificity from other parts of the library.
Edit, solution
Try to put this CSS in a position that is after the CSS library, it should fix the problem.
.el-table .cell {
    word-break: break-word;
}


text:
Q: How to add additional Azure Blob Storage output to ImageResizer functionapp? While creating a ImageResizer function app on azure portal for accomplishing image resizing functionalities I see only two Azure Blob Storage outputs:
Path 1: sample-images-sm/{name}
Path 2: sample-images-md/{name}

Here my requirement is generate images of different sizes with the following combination:
<width,height> : (260,260) , (280,150) , (340,140), (115,140), (76,140)

Can anyone help me to know how to add additional Azure Blob Storage output to the existing list.

A: Go ahead and create a Function based on those settings.
Then navigate to Integrate tab on the left and click New Output on the right:

Select Azure Blob Storage and then fill the fields similar to this:

Finally, change the code to add an extra parameter:
public static void Run(
    Stream image,                           // input blob, large size
    Stream imageSmall,
    Stream imageMedium,
    Stream imageMy)  // output blobs
{
    // ...
    // use imageMy to write another size of image
}


text:
Q: Why does binary serialization byte layout differ on iOS and Android In Unity3d, I use binary serialization with [Serializable] decorators to create snapshots of my game world state. Then to compare equality of different world states I count a hash from the byte array created by BinaryFormatter.
On different platforms, namely iOS and Android, the serializer produces different byte layouts for the same game state. Both are valid and deserialize to the same state. However, as the layout differs, I get different hashes for the same state on different platforms. Why do the layouts differ? Does reflection go through object fields in different order on different platforms? Is there a workaround to get same layouts on different platforms using BinaryFormatter?
As a quick fix I implemented a light old-school binary serialization with interfaces and hand-tunable serialization order, but in the long run it is not as easily maintainable as automated serialization.


text:
Q: Exposing the contract object in the customer portal I have a customer portal where we expose different types of records to users who need to see only records that belong to the same Account as theirs. The portal is built using Visualforce pages and a Force.com site completely overriding the native portal.
As of now I am achieving this using profiles and sharing settings that come with high volume customer portal user licenses.
I will also need to display CONTRACT (standard object) records to users authorized to see them. When I try to assign security to Contracts, I see its not directly possible. I saw that the Account object security page lists Contracts at the field level. My user's profile has access to this.
Now I am trying to display a link conditionally using the code:
                <apex:variable var="contact_var" rendered="{!$ObjectType.Contract.accessible}" value="Contract">

CONTRACTS

                </apex:variable>

But this link does not appear which means that the user does not have access to CONTRACTS. What am I missing here? Can we display CONTRACT records in a customer portal? And what needs to be done so that portal users can see those records.
Thank you.

A: Unfortunately Contracts are not accessible through Customer Portal. You can create a second, custom, object and essentially persist duplicate information of the Contract to this custom object. By creating essentially a duplicate object type, you can expose that object type to the customer portal. Here is a blog post regarding it.
http://techblog.appirio.com/2008/10/michael-mclaughlin-overcoming-customer.html

A: You can turn on Entitlement Management Setup --> Customize --> Entitlement Management.
This will allow you to use "Service Contracts" which can be accessed from the Customer Portal.
They are very similar to Contracts, but allow you to associate entitlements and enforce SLAs.

A: Can you try some kind of last resort before going with @MichaelWelburn's answer...
Recently I had to create an "admin panel" for our power users that would let them submit many different batch jobs (less work for IT). I wanted to display status of past jobs (data from AsyncApexJob table). For the life of me I couldn't get it to work, page was throwing "insufficient privileges" when I was logged in as non-SysAdmin user. Even though profile had rights to both page and controller.
Long story short:

*

*Use debug logging to check if query for Contracts actually returns something on the Portal page.

*If it does - construct a helper ContractWrapper class which would hold Strings, Ids, Date fields etc. You need to stupidly painstakingly copy over the values from fields, simple member variable Contract won't work.

*Create a list of these and SF should allow you to display it in <apex:dataTable /> etc. like any other query result.

It's a tiny ray of hope and I have no idea if it won't be closed up in future... but it worked for me so maybe can work on the Portal too.


text:
Q: SQL order by and left outer join doesn't have correct order I have a view that is joining two tables and ordering by the first table.  Except that the order isn't correct.  It misses an occasional record, and then at the end, most of those records exist in order, and then at that end, the rest of the records exist in order.  So it has records such as
1  (most of the records in order)
2
4
5
6
7
8
10
11
13
15
3  (the first set of missing records)
12
9 (the rest of the missing records)
14

My view is below.  Do I need to do the order by before I do the join?  What am I doing wrong?  (I've acquired this view, and the exact same view in another db instance works correctly.)
CREATE VIEW [dbo].[SampleView]
AS
SELECT     TOP 100 PERCENT blp.*, ISNULL(YEAR(DATEADD(month, 2, tb.[End of D&D])), 0) AS DEMO_FY
FROM         dbo.Table1 AS blp LEFT OUTER JOIN
                      dbo.Table2 AS tb ON blp.FACIL_NAME = tb.[Structure ID]
ORDER BY blp.ID

(edit)  The type for the sort field is  [ID] [int] NOT NULL IDENTITY(1, 1),

A: Read Create a sorted view in SQL Server 2005 and SQL Server 2008 there is a hotfix and you HAVE to run in 2000 compatibility mode for it to work. Why not just do the order by when selecting from the view?

A: I would remove the ORDER BY clause from the view entirely.  Instead, specify your order at the time you query the view.

A: A comment in this blog entry makes it pretty clear.
Just once again the text from BOL:

"When ORDER BY is used in the definition of a view, inline function, derived table, or subquery, the clause is used only to determine the rows returned by the TOP clause. The ORDER BY clause does not guarantee ordered results when these constructs are queried, unless ORDER BY is also specified in the query itself."
"Although the view definition contains an ORDER BY clause, that ORDER BY clause is used only to determine the rows returned by the TOP clause. When querying the view itself, SQL Server does not guarantee the results will be ordered, unless you specify so explicitly, as shown in the following query:

SELECT * FROM TopView
ORDER BY LastName

"

A: Most likely the two SQL Servers are slightly different versions.  There's a known hotfix for this:
http://support.microsoft.com/kb/926292/

A: You should always "order" at the last possible point, since sorting is slow (N log N). When you perform a select on a view, you will usually include a where-clause. You only want to sort that result set.


text:
Q: Split the list in apex I am having the list . List has 28 records. I need to split the records in the list into 13 + 13 + 2 in the code. Is it possible?. If it is possible how to do that? Can anyone help me with this?
Thanks in Advance.

A: you can do it by means of the while loop and checking the current size of the partition. Here is a class, that allows a splitting list of any list type.
public with sharing class Lists {

    public static List<List<Object>> doPartions(List<Object> records, Integer size, Type destType){
        checkNotNull(records);
        checkArgument(size > 0);
        checkNotNull(destType);
        return new Partition(records, size, destType).doPartition();
    }

    private static void checkNotNull(Object reference) {
        if (reference == null) {
            throw new NullPointerException();
        }
    }

    private static void checkArgument(Boolean expression) {
        if (!expression) {
            throw new IllegalArgumentException();
        }
    }

    private class Partition{
        private List<Object> items;
        private Integer splitSize;
        private Type destType;

        Partition(List<Object> records, Integer size, Type destType){
            this.items = records;
            this.splitSize = size;
            this.destType = destType;
        }

        List<List<Object>> doPartition(){
            List<List<Object>> result = (List<List<Object>>)destType.newInstance();
            List<Object> protoList = items.clone();
            protoList.clear();
            List<Object> tempList = protoList.clone();
            Integer index = 0, count = 0, size = items.size();
            while(index < size) {
                tempList.add(items.get(index++));
                ++count;
                if(count == splitSize) {
                    result.add(tempList);
                    tempList = protoList.clone();
                    count = 0;
                }
            }
            if(!tempList.isEmpty()) {
                result.add(tempList);
            }
            return result;
        }
    }

    public class IllegalArgumentException extends Exception {}
}

Usage of it
List<Integer> input = new List<Integer> {1, 2, 3, 4, 5, 6, 7};
List<List<Integer>> result = (List<List<Integer>>) Lists.doPartions(input, 2, List<List<Integer>>.class);
System.debug(result);

DEBUG|((1, 2), (3, 4), (5, 6), (7))


text:
Q: How to extractimage at a specified position using htmlagilitypack I am able to use htmlagilitypack to extract first image from a website. But I want to be able to extract blog post feature image. I am using firstOrDefault and it gives me the first image on the given url.
Please help me.
Thanks.


text:
Q: Petrel - Ocean - Get well name and type I'm getting all boreholes (Borehole Collection) from my Petrel project using the following code:
WellRoot wr = WellRoot.Get(PetrelProject.PrimaryProject);
BoreholeCollection bhc = wr.BoreholeCollection;

I can get the borehole name (bellow code), but I'm struggling to find the type of this borehole (producer or injector) and what simulation case this borehole is comming from (I have two simulation cases in my Petrel project).
foreach (Borehole bh in bhc)
  PetrelLogger.InfoOutputWindow("Borehole name " + bh.Name);

Anyone could help me?
Thanks in advance!

A: This touches the display/UI domain; the access is decoupled via
Borehole borehole; // this is the object you have
IBoreholeSettingsFactory factory = CoreSystem.GetService<IBoreholeSettingsFactory>();
IBoreholeSettings settings = factory.GetBoreholeSettings(borehole);
WellSymbolDescription symbolDescription = settings.WellSymbol;


text:
Q: How can deadlocks occur if objects are accessed in the same order? On the MS Technet page on "Minimizing Deadlocks", it says that "deadlocks cannot be completely avoided". More specifically, it states that

If all concurrent transactions access objects in the same order, deadlocks are less likely to occur.

This implies that deadlocks could theoretically occur, even if all transactions access objects in the same order. Could someone give an example of how that would be possible?

A: One way is when using Isolation Level Serializable.
If you have a parent child relationship, as for example in an accounting database with customers, customer accounts, and individual financial debits and credits into those accounts, then:
you have a database transaction consisting of multiple balancing debit and credit entries into the child table, and an accompanying update of an account balance in the customer table.
At isolation level serializable, in order to prevent what are called phantom reads the DB engine places range locks on all records which the SQL statement has to read, (In this case, the credit and debit table). This ensures that no other transaction can insert new credits or debits into the table while this Tx is calculating the new customer balance.  Any attempt to insert a new credit or debit is blocked by the lock.
Meanwhile, the first Tx is blocked as well, since the other insert Tx will have placed a lock on the Customer Table row, since it also needs to update the customer Balance.  The locks aer not released until the entire Tx is committed, so both Transactions are blocking each other... Deadlock.

A: Just to provide a simple code example further to Charles's answer
CREATE TABLE T(X INT)

Then run in two concurrent connections
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE

BEGIN TRAN

SELECT * FROM T

WAITFOR DELAY '00:00:10'

INSERT INTO T VALUES(1)

COMMIT

Deadlock.
The issue is that both connections can aquire shared locks on a resource but then block each other when they need to convert that to an exclusive lock.


text:
Q: Postfix reject_rbl_client: client or recipient restriction? This and this say the reject_rbl_client is a smtpd_recipient_restriction. However, the Postfix docs show it's only a smtpd_client_restriction, which makes sense to me. So, which is it?
Also, why when I configure nonsense, postfix check and service postfix reload just accept it?
smtpd_client_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unknown_client_hostname, reject_rbl_cliena bl.spamcop.net

And:
root@server: /etc/postfix # postfix check
root@server: /etc/postfix # echo $?
0
root@server: /etc/postfix #

And:
# service postfix reload
Reloading Postfix configuration...done.

Version: 2.9.6-2
Debian 7 (Wheezy)

A: If you scroll down to the end of smtpd_recipient_restrictions in the Postfix documentation, it explains that SMTP command specific restrictions for client, helo and sender are also valid in the sender context. In other words: you may put the reject_rbl_client restriction in either list.
When receiving mail, Postfix wil apply the smtpd_*_restrictions in this order: client, helo, sender, relay, recipient, data and end_of_data. When a restriction evaluates to REJECT or DEFER, the restrictions that follow are skipped. Ideally the fast and cheap checks are done first, so that you can skip relatively expensive checks (like looking up an external blacklist) most of the time. By moving the reject_rbl_client value out of the smtpd_client_restrictions and into the smtpd_recipient_restrictions, you will decrease the number of times Postfix needs to look up that blacklist.
The postfix check will complain about a typo in the name of your parameter, but not about a typo in the value of the parameter (as was your case). Quoting a post by the Postfix author (Wietse Venema):

In many cases, the syntax of the 1000+ parameter values is checked
  only when a value is used.  For example, the syntax of the mynetworks
  value is checked only when a specific IP address is matched against
  this list (and if the syntax error is at the end of the list, it may
  yaake a while before the error is noticed).


text:
Q: Hibernate database connection configuration We have 2 different server environments using the same Hibernate configuration. One server has JNDI support for datasource, but the other does not. Currently the Hibernate configuration is configured to use JNDI, which is causing problem on the server that does not support JNDI.
I have also tried to put the direct JDBC configuration together with JNDI configuration into the configuration file, but it looks like hibernate always favors JNDI over direct JDBC configuration if both exist.
My question is, will it be the same if both JNDI and connection_provider configuration both exists? Will Hibernate still use JNDI over connection_provider?  Or is there any way to change the precedence of the database connection property?
I do not have access to the server all the time, so I thought I do ask the question before my window of the sever time.
Thanks in advance.

A:
We have 2 different server environments using the same Hibernate configuration.

Well, it may not be the expected answer but I have the feeling that you are creating the problem yourself here: if your environments are different, use different configurations. What I would do is the following:

*

*put everything common in hibernate.cfg.xml (bundled in the application)

*put specific things in hibernate.properties files and place the "right one" in a root directory of the class path for each application (but outside the application).

For example, this would be the content of the hibernate.properties for the "JNDI environment":
hibernate.connection.datasource = java:/comp/env/jdbc/test
hibernate.transaction.factory_class = org.hibernate.transaction.JTATransactionFactory
hibernate.transaction.manager_lookup_class = org.hibernate.transaction.JBossTransactionManagerLookup
hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect

And this would be the content of the hibernate.properties for the "non JNDI environment":
hibernate.connection.driver_class = org.postgresql.Driver
hibernate.connection.url = jdbc:postgresql://localhost/mydatabase
hibernate.connection.username = myuser
hibernate.connection.password = secret
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.timeout=1800
hibernate.c3p0.max_statements=50
hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect

A: Use the URL method in the configuration file.  In the code, manually try to get a connection to the JNDI source using the context.lookup("java:comp/env/..."). If that succeeds, set the Hibernate data source property and unset the url-related properties.  If it fails let Hibnerate continue with the url configuration.
if (jndiDataSourceExists()) {
  configuration.setProperty(Environment.DATASOURCE, "jdbc/jndiname")
  configuration.setProperty(Environment.URL, null);
}
configuration.buildSessionFactory();


text:
Q: loadFile() function in C to load users from a file at the time I execute the program I am starting to program in C, and I am doing a program in which it adds users to a file.
I have managed to add users to the file and I can see what users I have added while the program is still running.
But when I close the program and open again, if I press to see the users it doesn't show anything because it doesn't load it from the file.
How can I create a function that will read the whole file when I run the program and display the users in the file when I select the option show users at the beginning??
the file contains users with three fields Id name and surname.

A: Here is what you should do:

*

*Read each line one by one by using fgets.

*Use strtok to break the line and then,parse the ID,name and surname.

*Print them.

Put the above 3 in a loop which exits when fgets returns 0 or EOF.

A: When you are writing to the file make sure you open it in append mode otherwise the program will erase the previous contents of the file.
To open in append mode use this:
FILE *F=fopen("filename","a");


text: Q: Codeigniter open paypal redirect url in popup I am using paypal REST API SDK. I want to open the redirect url in popup & if payment is success, then close it & update the payment status in previous/original window or tab. Like this


text:
Q: Reformatting dates from a csv and writing them into a new csv I just started to learn python so that I could make a program that could manipulate bank statement cvs files, but I do not know very much. I have one csv file with a column of dates in the format: month+day+year. Examples include 3/3/20, 12/2/20, 9/13/20, etc.
I would like to take these dates from the column and reformat them into the format: year+month+day. Examples of the format that I need them to be in include 200303, 201202, 200913, etc.
But I do not know how to get information from my original csv file and proceed to reorder it and write it into my new csv file. I am going to need a lot of explaining of the steps because I am so new to this. All help is appreciated though :)
Here is what I have tried so far:
        bank_statement = '/Users/annamobley/Library/Mobile Documents/com~apple~CloudDocs/Python/3 March 2020.csv'
# import initial bank statement
import csv

with open(bank_statement, 'rt')as initial_file:
    data = csv.reader(initial_file)
    for row in data:
        original_dates = str(row[1])

# find number of rows in the initial bank statement
file = open(bank_statement)
reader = csv.reader(file)
lines = len(list(reader))
num_lines = int(lines) - int(1)

# variables in new csv
upload_statement = 'manip_bank_statement.csv'
bank_abbreviation = "GCB"
acc_num = input('Enter the account number : ')
acc_name = input("Enter the Account Name/Description (): ")
# date format manipulation
first_2_num_year = input(
    "Input the first two numbers in the year that it is currently. Ex: If it is the year 2019, input '20': ")
import datetime as dt

post_date_original = row[1]
manipulated_date = (dt.datetime.date(dt.datetime.strptime(original_dates, '%m/%d/%y')).strftime('%y%m%d'))
final_date = str(first_2_num_year + manipulated_date)
# writing the new csv
import csv

with open(upload_statement, 'w', newline='') as file:
    writer = csv.writer(file)
    for somevariable in range(num_lines):
        writer.writerow([bank_abbreviation, acc_num, acc_name, final_date])

I get the error message:
        Traceback (most recent call last):
  File "/Users/annamobley/PycharmProjects/CSV_Manipulation_Project/Project.2.redo.py", line 41, in <module>
    manipulated_date = (dt.datetime.date(dt.datetime.strptime(original_dates, '%m/%d/%y')).strptime('%y%m%d'))
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/_strptime.py", line 568, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/_strptime.py", line 352, in _strptime
    raise ValueError("unconverted data remains: %s" %
ValueError: unconverted data remains: 19

A: You can convert the date using the datetime module.
import datetime as dt

day = '3/3/20'

print(
    dt.datetime.date(
        dt.datetime.strptime(day, '%m/%d/%y')
    ).strftime('%y%m%d')
)

Output:
200303

Here is a good resource for the datetime module https://docs.python.org/3/library/datetime.html


text:
Q: pyQt5 scrollbar auto follow I cannot seem to get the scrollbar in pyqt5 to autofollow and to not autofollow when the y position is not at the end.
I've tried this:
    ccursor=self.textCursor()
    sbar=self.verticalScrollBar()
    # get the max value
    csbarval=float(sbar.value())
    maxsbarval=float(sbar.maximum())

    print("sbar value:{}".format(csbarval))
    print("sbar max:{}".format(maxsbarval))

    self.append(data)
    if (float(maxsbarval) > 0.0) and (csbarval/maxsbarval > 0.98):
        ccursor.movePosition(QtGui.QTextCursor.End)

Is there api in there that can do this automatically?

A: Right so I had a little think about it in a quiet place, and here's the result:
class TEdit(QtWidgets.QTextEdit):
 def scrollbarBehaviour(self,data):

  scrollbar=self.verticalScrollBar()
  current_pos=scrollbar.value()
  current_max=scrollbar.maximum()

  at_bottom_of_text=(current_pos>=current_max -4)

  self.append(data)
  if at_bottom_of_text:
   scrollbar.setValue(scrollbar.maximum())
  else:
   scrollbar.setValue(current_pos)

The part to note is to figure out if the scrollbar is at the max/end before appending data to the textarea. Also the scrollbar needs to be set explicitly or it will automatically scroll to the end.


text:
Q: QSQLDatabase doesnt open connection to Microsoft SQL Database (QT, Linux, C++) I have a problem with debugging my software.
I installed the Package libqt4-sql-odbc after i found out my QT cant find the ODBC driver.
After installation the Error is away.
For connecting i made
QSqlDatabase db=QSqlDatabase::addDatabase("QODBC");
db.setHostName("The IP Adress of the MSSQL-Database");
db.setDatabaseName("the Databasename");
db.setUserName("The Database accountname");
db.setPassword("the Database account password");
db.setPort(1433);

if(db.open())
{
    qDebug()<<"open Database";
}
else
{
    qDebug()<<"closed Database";
}

after starting the application and executing this method i always get the Debug-Message "closed Database")
What did i wrong?
Maybe i installed wrong the ODBC?
Should i use ODBC3?
is the host-name as IP correct or cant i take the IP of the database?


text:
Q: Find matching keys in dictionary and nested array & replace array with values from I have sort of a similar question as Find matching keys in dictionaries & replace keys with values
However my situation looks like this.
d1 = {"1": "DNS Compromise", "2": "DNS Poisoning", "3": "Fraud Orders"}
d2 = {... ,"categories": [1, 2], ...}

I would like to have the following output:
d2 = {..., "categories": [DNS Compromise, DNS Poisoning], ...}

Is there a way to construct a for loop or use comprehension? I am sort of new to this.

A: With dictionary you can easily get a list of the values with the method values().
d2 = {"categories": d1.values()}

A: This is the solution you are searching for :
d3 = {k:[ d1[str(v_i)] for v_i in v] for k,v in d2.items() }


text:
Q: Trace of the matrix power Say I have matrix $A = \begin{bmatrix}
a & 0 & -c\\
0 & b & 0\\
-c & 0 & a
\end{bmatrix}$.
What is matrix trace
tr(A^200)
Thanks much!

A: You may do it by first computing matrix powers and then you may calculate whatever you want. Now question is how to calculate matrix power for a given matrix, say $A$? Your goal here is to develop a useful factorization $A = PDP^{-1}$, when $A$ is $n\times n$ matrix.The matrix $D$ is a diagonal matrix (i.e. entries off the main diagonal are all zeros).
Then $A^k =PD^kP^{-1} $. $D^k$ is trivial to compute. Note that columns of $P$ are n linearly
independent eigenvectors of $A$.

A: For this kind of problems, first you have to get eigenvalues and their corresponding eigenvectors. For this problem,
$$ \lambda_1=b,\lambda_2=a-c,\lambda_3=a+c, v_1=(0,1,0)^T,v_2=(\frac{1}{\sqrt{2}},0,\frac{1}{\sqrt{2}})^T,v_3=(-\frac{1}{\sqrt{2}},0,\frac{1}{\sqrt{2}})^T. $$
Let
$$ P=(v_1,v_2,v_3)=\left(\begin{matrix}0&\frac{1}{\sqrt{2}}&-\frac{1}{\sqrt{2}}\\
1&0&0\\
-\frac{1}{\sqrt{2}}&0&\frac{1}{\sqrt{2}}
\end{matrix}\right). $$
Then it is easy to check $P^T=P^{-1},P^TAP=\text{diag}(\lambda_1,\lambda_2,\lambda_3)$. Hence
\begin{eqnarray*}
\text{Tr}(A^{200})&=&\text{Tr}(P^TA^{200}P)\\
&=&\text{Tr}((P^TAP)^{200})\\
&=&\lambda_1^{200}+\lambda_2^{200}+\lambda_3^{200}\\
&=&b^{200}+(a-c)^{200}+(a+c)^{200}.
\end{eqnarray*}

A: You just need to calculate Eigen values bcoz sum of eigen values =$tr(A)$ and if "a" is the eigen value of matrix $A$ then "$a^n$" is the eigen value of $A^n$.
thus,
$$Tr(A^{200})=b^{200}+(a−c)^{200}+(a+c)^{200}$$


text:
Q: permissionOverwrites not working properly while creating channel While creating I'd like to deny the VIEW_CHANNEL permission for the @everyone role. While creating the channel it doesn't work. However after handling the promise using permissionOverwrites.edit does work. Does anyone why it behaves this weird. I've included the code below:
client.on('messageCreate', (message) => {
    let guild = message.guild;
    if(message.content === '.raid'){
        const ch = guild.channels.create(`${message.member.displayName}\'s raid`, {
            type: 'GUILD_VOICE',
            parent: state.categories.raids,
            userLimit:50,
            permissionOverwrites: [
                {
                    //@everyone ID
                    //This does not work.
                    id: state.roles.everyone,
                    deny: ['VIEW_CHANNEL'],
             },
         ],
        }).then(channel => {
            //This works
            client.channels.cache.get(channel.id).permissionOverwrites.edit(state.roles.everyone, {VIEW_CHANNEL : false});
        })
    }
})


text:
Q: How to run .exe file and .batch file passing with arguments using java servlet application? protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out=response.getWriter();
    String values=request.getParameter("t1");

    ServletContext servletContext = request.getSession().getServletContext();
    servletContext = request.getSession().getServletContext();
    String path="//sequence.FASTA";
    String uploadFile=servletContext.getRealPath(path);

    File outputFile = new File(uploadFile);
    FileWriter fout = new FileWriter(outputFile);
    fout.write(values);
    fout.close();

    servletContext = request.getSession().getServletContext();
    String blastPath="//blast.bat";
    String blastBat_path=servletContext.getRealPath(blastPath);
    Process process = new ProcessBuilder(blastBat_path).start();

    try {
        process.waitFor();
        } catch (InterruptedException e) {e.printStackTrace();}
        process.destroy();
    }


text:
Q: Drag and sacale a rectangle drawn using UIBezierPath IOS/Swift I am developing a program which identifies a rectangle in an image and draws a path on the border of that identified rectangle. Now I want to reposition that path in case if it is not on the exact position. For an example look at this image

In cases like this i need to drag the corners of the path and reposition it as it fits the rectangle.
To draw the path I used CAShapeLayer and UIBezierPath. Here is the code I used to draw the path.
// imgView is the UIImageView which contains the image with the rectangle

let line: CAShapeLayer = CAShapeLayer();
line.frame = imgView.bounds;
let linePath: UIBezierPath = UIBezierPath();

linePath.moveToPoint(CGPointMake(x1, y1);
linePath.addLineToPoint(CGPointMake(x2, y2);
linePath.addLineToPoint(CGPointMake(x3, y3);
linePath.addLineToPoint(CGPointMake(x4, y4);
linePath.addLineToPoint(CGPointMake(x1, y1);
linePath.closePath();

line.lineWidth = 5.0;
line.path = linePath.CGPath;
line.fillColor = UIColor.clearColor().CGColor;
line.strokeColor = UIColor.blueColor().CGColor;

imgView.layer.addSublayer(line);

The thing is I tried to add a gesture to UIBezierPath. But there is nothing like that as I noticed. Couldn't find anything regarding this. So can someone please let me know a way to get my work done. Any help would be highly appreciated.

A: You are right that there is no way to attach a gesture recognizer to a UIBezierPath. Gesture recognizers attach to UIView objects, and a UIBezierPath is not a view object.
There is no built-in mechanism to do this. You need to do it yourself. I would suggest building a family of classes to handle it. Create a rectangle view class. It would use a bezier path internally, as well as placing 4 corner point views on the vertexes and installing pan gesture recognizers each corner point view.
Note that Cocoa rectangles (CGRects) can't be rotated. You'll need to use a series of connected line segments and write logic that forces it to stay square.


text:
Q: Папка создается не в нужном месте C# Добрый день. Написал приложение-1 на C#, которое создает папку. Основное приложение-2 качает его, и закидывает в другую папку внутри себя, что-то вроде "firstApp\secondApp\приложение-1.exe", после чего приложение-2 запускает приложение-1, которое создает папку не в secondApp\firstApp\приложение-1-folder, а в secondApp\приложение-1-folder. При этом, когда вручную запускать приложение-2, оно работает как нужно и создает папку в secondApp\firstApp\приложение-1-folder. То есть при запуске приложения-1 из вне, оно создает директорию не внутри себя, а в корне каталога, из которого была запущена. Как решается данная проблема?
Код приложения-2, которое запускает приложение-1
ZipFile.ExtractToDirectory(DownloadName, DownloadName.Remove(DownloadName.Length - 4));
Process.Start(DownloadName.Remove(DownloadName.Length - 4) + "\\" + DownloadName.Replace(".zip", ".exe"), "-sd");

Код приложения-1, которое создает папку
Directory.CreateDirectory("data");

A: Путь папки приложения.
string path = Directory.GetCurrentDirectory();
string path = Application.StartupPath;

A: Вы не должны использовать относительные пути, если не хотите таких сюрпризов.
Дело в том, что относительный путь — это путь относительно текущего каталога, а не относительно положения программы на диске. (Нет, это не одно и то же.) Программа сама не контролирует стартовое значение текущего каталога, поэтому либо она должна в самом начале устанавливать его, либо просто всегда работать с полными путями.
Связанный вопрос: Как определяется каталог поиска файла?
О том, как получить каталог, в котором лежит приложение, здесь: Как задать относительный путь для создания файла в C#?

A: Необходимо указать рабочую директорию приложения, проще всего это сделать в свойствах ярлыка, который будет запускать ваше приложение. В свойствах назначенного задания, также присутствует аналогичная настройка.
Внутри кода программ,это можно сделать так
string exeDir =Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Directory.SetCurrentDirectory(exeDir);


text:
Q: Image upload using retrofit2 Put method I am new to retrofit2. I want upload image through api service as a file. I have tried with postman by selecting a file and found its working. But through mobile how can I upload the image file.
Here is the Header section of Api
--header 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \

In the body section I am having, "picture", "name", "email" and "phone"
I am trying like,
i have created a class with body parameters
UpdateRequest Class
    public class UpdateRequest {
        @SerializedName("picture")
        MultipartBody.Part picture;
        @SerializedName("name")
        public String name;
        @SerializedName("email")
        public String email;
        @SerializedName("phone")
        public String phone;

//Also Generated Getters and Setters for the parameters

    }

Api Interface function
public interface MediaUploadApiInterface {

    @Headers({
            "content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"
    })
    @PUT("api/employee")
        Call<UpdateResponse> updateDetails(@Body UpdateRequest request, @Header("X-TOKEN") String token);

}

Now How can i bind the details and send.
Please Help me..

A: You have to create Multipart Request like below.
File file = new File(filePath);

RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("picture", file.getName(), reqFile);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "picture");

RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "your_name");
RequestBody email = RequestBody.create(MediaType.parse("text/plain"), "your_email");
RequestBody phone = RequestBody.create(MediaType.parse("text/plain"), "your_phone");

HasMap<String,RequestBody> map = new HasMap<>();
map.put("name",name);
map.put("email",email);
map.put("phone",phone);

postImage(map, picture)

Interface is like below.
@Multipart
    @PUT("/")
    Call<ResponseBody> postImage(@PartMap Map<String, RequestBody> map, @Part MultipartBody.Part image);
}

Also, don't forget to add @Multipart in your interface.


text:
Q: Run PHP function once a day and cache the loaded file I have the following code in the functions.php file and I am trying to modify it so it only loads the google sheets file once a day, stores that data, and for the rest of the day the shortcode reads the data from the loaded file instead of accessing the google sheet at each page load.
function sheet_value_shortcode($atts) {
    $API = 'XXX';
    $google_spreadsheet_ID = 'XXX';
    $api_key = esc_attr( $API);

    $location = $atts['location'];

    $get_cell = new WP_Http();
    $cell_url = "https://sheets.googleapis.com/v4/spreadsheets/$google_spreadsheet_ID/values/$location?&key=$api_key";
    $cell_response = $get_cell -> get( $cell_url);
    $json_body = json_decode($cell_response['body'],true);
    $cell_value = $json_body['values'][0][0];
    return $cell_value;
}
add_shortcode('get_sheet_value', 'sheet_value_shortcode');

Any suggestions? Thanks a lot!


text:
Q: jquery: tired of css().css().css() I'm really tired of syntax like this:
.css('position','absolute').css('z-index',z-index)
.css('border','1px solid #00AFFF').css('margin','-1px 0px 0px -1px')
.css('left',pleft)

I wonder if there's any way to pass all parameters in one function, something like:
.foo('position':'absolute','z-index':z-index,
     'border':'1px solid #00AFFF','margin':'-1px 0px 0px -1px',
     'left':pleft)

Much appreciate any help.

A: Define style in separate class
css
.myCustomClass
{
     position: absolute;
     border: 1px solid #00AFFF
}

And js
.addClass('myCustomClass');

And this is very simple to manage if styles go too complex

A: Yes, pass an object to .css() (also mentioned in the docs):
.css({
    position: 'absolute',
    left: pleft,
    zIndex: 123
    ...
});

Note that you can use both syntaxes for the keys: zIndex, i.e. the camelcase version that can be used directly in JavaScript and 'z-index' (quotes required as the - would break things otherwise).
For options that are always the same - in your case probably position, border and margin - it might be a good idea to a classic CSS rule set via a class/id selector. Then you'd just have to set the remaining (dynamic) options via .css().

A: $(element).css({'position':'absolute','z-index':zIndex,
     'border':'1px solid #00AFFF','margin':'-1px 0px 0px -1px',
     'left':pleft});


text:
Q: targeting last word of post title I am using Wordpress which I bring in a post's title using
<?php the_title( '
', '
' ); ?>

I want to target the last word in the title to apply different css to it. The Wordpress admin doesn't let me css the title or apply span classes.

A: Here it is using the original WP stuff, basically I think what you're asking for in the most simple format:
<?php
$post_title = get_the_title();
$title_as_array = explode(' ', $post_title);
$last_word = array_pop($title_as_array);
$last_word_with_span = '' . $last_word . '';
array_push($title_as_array,$last_word_with_span);
$modified_title = implode(' ', $title_as_array);
echo $modified_title;
?>

Try out this in this PHP sandbox. You can see where I substituted a string of words ("here is my title") for the title in the sandbox - it should work like that with get_the_title() too.
Here is what happens after you press "Execute Code", in case you don't see that.
PS: For an explanation, basically this: 1) gets the title as string, 2) turns that into an array, 3) gets the last item in the array, 4) adds the span html, 5) puts that back onto the end of the title array, 6) turns array into string again, 7) prints it out.

A:

var sliced = $('h1').text().split(' ');
var lastword = sliced.pop();
console.log(lastword)

Im the Last Word

Try this way.. split() the H1 then get last word using pop()

A: Do split you text and take the last word by using split, and must replace the text with span around that. Use .html(function()) like so :
var text = $('h1').text().split(' ');
var lstWord = text.pop();
// find the h1 with above word
$("h1:contains('" + lstWord + "')").html(function( i, old) {
   // replace the old content(specified words)
   // with span tag around that
   return old.replace(lstWord, ''+lstWord+'');
});

DEMO

A: Working with Php scripting language and requirement like set menu link active base on current loading page than 1st task is you have to identify which page loaded and based on that you able to assign active or similar any other class to Menu link which make menu different (active).

$current_page = basename(parse_url($_SERVER['REQUEST_URI'],
  PHP_URL_PATH));


text:
Q: Are there a limited number of artefacts? Is there a limited number of artefacts, i.e. a limited number of times I can travel to?
If so, should I just be sticking to the main storyline and use the fewest artefacts possible? If I do use a lot of artefacts early on will it affect my endgame?
I'm asking this because the brother of a friend said he was restarting his game because he had messed up with the artefacts.

A: There are in fact, a finite number of artefacts in the game. These are split into two categories:

*

*Wild artefacts - There are only ten of these in game. You can only use them on gates that don't need a specific artefact. If you are stuck finding these, there's a handy guide here

*Regular artefacts - Each of these correspond to a specific gate and are generally to do with story progression. As you'd expect there is one for each gate. Likewise, you can find a guide to finding these here. I wouldn't recommend using this guide though, whereas the wild artefacts can be difficult to find, these are part of the natural story progression and not that difficult to obtain. They're generally awarded as a sort of 'Level Complete' reward
On another note, it is strange that your brother of a friend should restart the game. You can complete the game without locating all of the Wild Artefacts. You will only need them all to collect all 160 fragments, and they don't need to be collected and/or open gates in a specific order.


text:
Q: how do i dispose of a class that is a property of another class? How do I dispose of DC in this situation where DC is a property of Service class?
 class Service()

  {

     public DataContext DC= new DataContext();

     public void SomeMethod()
       {
          DC is used here.

       }

     public void SomeOtherMethod()
       {
          DC is also used here.
       }

  }

A: Your "Service" class should implement IDisposable if it maintains references to unmanaged resources.  This tells clients of your class that they need to call Dispose() on instances of "Service".  You can call Dispose() on "DC" in your class' Dispose() method.
class Service : IDisposable
{
    public DataContext DC= new DataContext();

    public void Dispose( )
    {
        DC.Dispose( );
    }
}

As an aside, I would avoid creating public fields in C# where properties are the common idiom.

A: Make your Service IDisposable and dispose the DataContext in the Dispose method. It is a common pattern.

A: You could implement IDisposable on your hosting class and dispose of the hosted DC in the Dispose() method. Then use the hosting class using 'using'..
using(Service service = new Service())
{
    // do something with "service" here
}

A: Your Service class should take care of disposing DataContext.
Use the standard Dispose pattern.

A: Implement IDisposable:
MSDN: Implementing a Dispose Method
public void Dispose()
{
    Dispose(true);

    // Use SupressFinalize in case a subclass
    // of this type implements a finalizer.
    GC.SuppressFinalize(this);
}

protected virtual void Dispose(bool disposing)
{
    // If you need thread safety, use a lock around these
    // operations, as well as in your methods that use the resource.
    if (!_disposed)
    {
        if (disposing) {
            if (DC != null)
                DC.Dispose();
        }

        // Indicate that the instance has been disposed.
        DC = null;
        _disposed = true;
    }
}


text:
Q: Where does the number "74" belong? I have written something in assembly, and after that I try to look at it using objdump. Then I see the following:
 .....
 8048082:     70 2f                jo   80480b3 <GoToCall2+0x23>
 8048084:    66 69 6c 65 74 78     imul bp, WORD PTR [ebp+eiz*2+0x2e]
74
 804808b:    74 5c                 je   80480e9 <GoToCall2+0x59>
 .... (and so on)

So, as you can see:
In the middle we have the number "74" and I ask myself where it does belong? Is it a part of the opcodes? Or belongs it to the assembly column of line 8048084 ?
I make the size of the screen a little bigger but it was still there,
I hope someone can help me.

A: It belongs here:
8048084: 66 69 6c 65 74 78 74  imul...
                           ^^
804808b: ...

Look at the addresses in the left column: they are seven bytes apart.


text: Q: How do I run "terraform show" or equivalent in Terraform Cloud? I have used Terraform from my desktop for a number of years, but I'm a newbie to Terraform Cloud.  Is there a way in Terraform Cloud to run the "terraform show" command or to get the equivalent output to what you get when running that command locally?


text:
Q: How to execute SQL Script with hdbcli in python I use the hdbcli in python to connect to a hana db.
SQL command execution works via cursor an my connection:
conn = dbapi.connect(
    address=os.environ['HOST'],
    port=dbconnectport,
    user=dbusername,
    password=dbpasswd,
    databasename=dbconnectdbname

)

...
   cursor=conn.cursor()

and execution looks like:
cursor.execute("Select USER_NAME from \"SYS\".\"USERS\" WHERE USER_NAME=\'%s\'" % varcrdbust)

For single queries it works fine. But how can I execute a sql script with a lot of spcial characters?
Via bash shell I can do this fo example in this way:
Create file on os level:
tee >> $PRIVFILE << EOF
WITH
/*

[NAME]

- HANA_Security_CopyPrivilegesAndRoles_CommandGenerator_2.00.000+

[DESCRIPTION]

- Generates SQL commands that can be used to grant roles and privileges assigned to one user to another user or role
SQL script text here.........

And then execute this via hdbsql with argument -I <pathname/filename>
Is there any alternativ in python? Maybe without usage of file creation on os level?
Thanks David

A: All SAP HANA clients allow the execution of only a single command at a time.
The monitoring script that you chose as an example is in fact just one single command: a relatively large SELECT statement.
So, for every command, you want to have executed, you will need to send a separate .execute.
If you want to process a larger "script" file with several commands, you will need to look out for a "command separator" character (like ; in HANA Studio or hdbsql) and build the individual commands from the strings between those separators.


text:
Q: iOS 7+ partial swipe to back issue In my app I am partially swiping my ViewController and swiping back to the same view. While doing this viewDidLoad is not getting called. But if I swipe fully and come back to the view again, viewDidLoad gets called. It is creating some issue.
So even if I swipe partially and stay in the same view viewDidLoad needs to be called (currently only viewWillAppear is getting called). How to do this?

A: Half swipe of the back button is just like a back to the previous viewcontroller. When you half swipe the viewcontroller and again come to that viewcontroller viewdidload will never be called.
Its better you put the swipegesture disable.
if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}


text:
Q: Get the ID of an element using Selenium Web Driver in PHP I am building an application in PHP/MySQL/jQuery and it displays a list of items to the user, with a blank field at the bottom to add a new item. There's an Ajax blur event that saves your data to the database, then replaces the "new" row with a regular row, which includes the text you entered and an edit button. If you click the edit button, you it turns the text back into an input. All of these have IDs like item_n and edit_n where n is the ID in the database. What I'm really after is n.
Using Selenium (I've been focusing on Web Driver, but I'm open to using IDE), I'd like to create a new item, then click the edit button and alter it, but I don't know the ID of the edit button.
I've been able to create tests where I create a new row, then confirm that it's there using assertTextPresent, but I can't find a way to get the ID of the new row (which will be item_n).
I've tried using :contains, but it always returns an empty string. I've tried a few CSS and Xpath selectors, ranging from general to specific:
$elem = $this->_session->element('css', 'div.item_row div.item_title:contains("'.$new_item.'")');
$elem = $this->_session->element('xpath', '//div:contains("'.$new_task.'")');

I also tried just getting the second to last element in the list (since the last is the new-row field), but I'd really prefer to not have to rely on sorting.
The question below indicates Selenium RC could call JavaScript:
Selenium RC: How to check if an element has a given attribute?
I know Web Driver succeeded Selenium RC, but I'm not sure if Web Driver supports RC commands such as the above. That said, I gave it a try anyway. The JavaScript function I wrote to get the ID returns null. I did test the function outside of Selenium, so I know it's working.
I'm using the Facebook PHP Web Driver implementation, but I'm not married to it:
https://github.com/facebook/php-webdriver
Any help would be much appreciated. Thank you.

A: Create an IWebElement instance of the element. Then get the id attribute of the IWebElement. Below is the C# code for the same:
IWebElement element = driver.FindElement(By.XPAth("//XpathOfTheElement"));
string id = element.GetAttribute("id")

I hope this helps


text:
Q: Regular expressions to delete things from the first line in multiple txt files I searched the internet for days trying to fix this myself but didn't succeed. I can not show any code because everything I tried was just wrong. So my question is maybe a bit long, but I hope someone can help me with it.
I got a folder that contains a lot of .txt files with scraped data (1000+). Now I would like a script that loops through all this files, changes the first line and then saves the files again. On the first line of a .txt file, there is a title. But I want certain things to be removed from that title. Here are a few first line examples from 5 different .txt files:
Hello world my name is awesome, but you knew that video c5
Hello world my name is awesome  video3 v: Everybody knows I am r
Hello world my name is awesome: It got 100 likes in 10 min 1f
Hello world my name is awesome 43 video 2: Did you know that:
Hello world my name is awesome a3: It is Mr smokealot 1f,

I think I covered all possible combinations that are present. What I would like is that only this part Hello world my name is awesome stays in every file on the first line and the rest must be deleted. I also got text on the other lines in the .txt files, but those must stay untouched. Every title is different per .txt file but I used Hello world my name is awesome to show wich part of the first line contains the title.
I think that these are the things that must be done to fix the titles for me.

*

*Delete all character after the first coma or colon including the coma and colon itself.

*Delete all the words and letters that contain a number in it like a3 in the  fifth first line examples.

*Delete all the numbers.

*Delete the word video.

*Delete all single characters except for the letter "I". This is to remove the "v" from the second first line example
When this is done I would like to save the file on the current place with the current name.
Is this possible?

A: REGEX Support of Batch is very restricted (only implemented in findstr, but a very small subset).So let's do it (nearly) without REGEX:
@echo off
setlocal enabledelayedexpansion
REM t.txt contains your first-line-examples
for /f "delims=" %%a in (t.txt) do call :getTitle %%a

goto :eof

:getTitle
set title=%*
REM get rid of all characters after (including) comma or colon:
for /f "delims=,:" %%a in ("%title%") do set title=%%a

REM get rid of every word with numbers and anything after it:
set "line="
for %%a in (%title%) do (
  REM if the word contains a number, Exit the Loop, else add the word to the line:
  echo %%a|findstr "[0-9]" >nul && goto :endOfTitle ||set line=!line! %%a
  )
:endOfTitle

REM get rid of the leading space (included with the SET in the last FOR)
if defined line set line=%line:~1%

echo(%line%

Contents of t.txt:
Hello world my name is awesome, but you knew that video c5
Hello world my name is awesome  video3 v: Everybody knows I am r
Hello world my name is awesome: It got 100 likes in 10 min 1f
Hello world my name is awesome 43 video 2: Did you know that:
Hello world my name is awesome a3: It is Mr smokealot 1f,
Hello world my name is John Doe, but you knew that video5c
Hello world my name is Jane Doe  video3v: but you knew that
Hello world my name is Superman: but you knew that 1f
Hello world my name is Asterix, Gallier 43: but you knew that 1f
34: this is obviously an invalid title
Any string is a title until it hits a comma or colon, this is scrap
Any word that contains a number ends the title l1ke this one

Output:
Hello world my name is awesome
Hello world my name is awesome
Hello world my name is awesome
Hello world my name is awesome
Hello world my name is awesome
Hello world my name is John Doe
Hello world my name is Jane Doe
Hello world my name is Superman
Hello world my name is Asterix

Any string is a title until it hits a comma or colon
Any word that contains a number ends the title

(@Mofi: I included some of your examples - I like the names :) )
EDIT to process all files in the current Folder
@echo off
setlocal enabledelayedexpansion

REM for all .txt files in the current folder do:
for /f "delims=" %%a in ('dir /b *.txt') do call :process "%%a"
goto :eof

:process
set file=%1
REM get first line of this file:
set /p first=<%1

REM
call :getTitle %first%

REM when %line% is empty, skip the edit:
if defined line (
  echo %line% >"%~n1.tmp"
  more +1 %file% >>"%~n1.tmp"
  @ECHO move /y "%~n1.tmp" "%file%"
)
goto :eof

:getTitle
set title=%*

REM get rid of all characters after (including) comma or colon:
for /f "delims=,:" %%a in ("%title%") do set title=%%a

REM get rid of every word with numbers and anything after it:
set "line="
for %%a in (%title%) do (
  REM if the word contains a number, Exit the Loop, else add the word to the line:
  echo %%a|findstr "[0-9]" >nul && goto :endOfTitle ||set line=!line! %%a
  )
:endOfTitle

REM get rid of the leading space (included with the SET in the last FOR):
if defined line set line=%line:~1%

goto :eof

Remove the @ECHO if you are satisfied with the Output.

A: I created the text file Test.txt with following content:
Hello world my name is John Doe, but you knew that video5c
Hello world my name is Jane Doe  video3v: but you knew that
Hello world my name is Superman: but you knew that 1f
Hello world my name is Asterix, Gallier 43: but you knew that 1f
34: but you knew that this is an invalid title
, but you knew that this is also an invalid title
 but you knew that this is an invalid title, too

Then I developed following commented batch file to evaluate all the title lines:
@echo off
setlocal EnableDelayedExpansion
set "FileTitle="
for /F "usebackq delims=" %%L in ("Test.txt") do (
    call :GetTitle "%%L"
    echo Get from  "%%L"
    echo the title "!FileTitle!"
    echo.
)
endlocal
goto :EOF

:GetTitle
set "Line=%~1"

rem Replace the string " but you knew that" case insensitive
rem by character # with a comma before which is always removed.

set "Line=%Line: but you knew that=,#%"

rem Use character # as separator to get everything left of this character.

for /F "tokens=1 delims=#" %%T in ("%Line%") do set "FileTitle=%%T"
if "%FileTitle%" == "," goto TitleError
set "FileTitle=%FileTitle:~0,-1%"

:RemoveSpaces
if "%FileTitle%" == "" goto TitleError
if "%FileTitle:~-1%" == " " set "FileTitle=%FileTitle:~0,-1%" & goto RemoveSpaces

rem Is the last character a comma, remove this character, too.

if "%FileTitle:~-1%" == "," (
    set "FileTitle=%FileTitle:~0,-1%"
    if "!FileTitle!" == "" goto TitleError
    goto RemoveSpaces
)

rem Is the last character not a colon, we have the file title.

if not "%FileTitle:~-1%" == ":" goto :EOF

rem Otherwise remove the colon and the word left to the
rem colon if this word contains also at least 1 digit.

set "FileTitle=%FileTitle:~0,-1%"
set "LastWord="

rem The first condition in code below should be never true according to
rem provided sample data, but it is necessary to avoid an endless loop.

:RemoveWord
if "%FileTitle%" == "" goto TitleError
if "%FileTitle:~-1%" == " " goto EvaluateWord
set "LastWord=%FileTitle:~-1%%LastWord%"
set "FileTitle=%FileTitle:~0,-1%"
goto RemoveWord

:EvaluateWord
for /L %%C in (0,1,9) do (
    if not "!LastWord:%%C=!" == "%LastWord%" goto RemoveSpaces
)

rem Append the removed word as it does not contain a digit.
rem Then we have the file title and can exit the subroutine.

set "FileTitle=%FileTitle%%LastWord%"
goto :EOF

:TitleError
set "FileTitle=Error: No file title found^!"
goto :EOF

This batch file executed in a command prompt window outputs:
Get from  "Hello world my name is John Doe, but you knew that video5c"
the title "Hello world my name is John Doe"

Get from  "Hello world my name is Jane Doe  video3v: but you knew that"
the title "Hello world my name is Jane Doe"

Get from  "Hello world my name is Superman: but you knew that 1f"
the title "Hello world my name is Superman"

Get from  "Hello world my name is Asterix, Gallier 43: but you knew that 1f"
the title "Hello world my name is Asterix, Gallier"

Get from  "34: but you knew that this is an invalid title"
the title "Error: No file title found!"

Get from  ", but you knew that this is also an invalid title"
the title "Error: No file title found!"

Get from  " but you knew that this is an invalid title, too"
the title "Error: No file title found!"

The function GetTitle in this batch file uses massively string substitutions with the commands FOR and SET to determine each title.
Use the function GetTitle if the output is what you expect for those lines.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

*

*call /?

*echo /?

*endlocal /?

*for /?

*goto /?

*if /?

*rem /?

*setlocal /?

My next version using updated example data:
Hello world my name is awesome
Hello world my name is awesome, but you knew that video c5
Hello world my name is awesome  video3 v: Everybody knows I am r
Hello world my name is awesome: It got 100 likes in 10 min 1f
Hello world my name is awesome 43 video 2: Did you know that:
Hello world my name is awesome a3: It is Mr smokealot 1f,

The batch code is now much easier than before with the first time defined rules:
@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "FileTitle="
for /F "usebackq delims=" %%L in ("Test.txt") do (
    call :GetTitle "%%L"
    echo Get from  "%%L"
    echo the title "!FileTitle!"
    echo.
)
endlocal
goto :EOF

:GetTitle

rem Get string left from first comma or first colon. The entire line
rem is returned if the line does not contain any comma or colon.

for /F "tokens=1 delims=,:" %%T in ("%~1") do set "WordsList=%%T"

rem Process each word from list and check for containing any digit, or being
rem a single letter different than upper case "I", or being the word "video".
rem Those words are ignored on building the file title from the words list.
rem It is expected here that non of the words contain a non word character
rem as this could result in a syntax error on processing the words.

set "FileTitle="
for %%I in (%WordsList%) do (
    set "Skip=0"
    for /F "tokens=1 delims=0123456789" %%W in ("#%%I#") do set "Word=%%W"
    if "!Word!" NEQ "#%%I#" set "Skip=1"
    set "Word=%%I"
    if "!Word:~0,1!" EQU "%%I" (
        if "%%I" NEQ "I" set "Skip=1"
    )
    if /I "%%I" EQU "video" set "Skip=1"
    if "!Skip!" EQU "0" set "FileTitle=!FileTitle! %%I"
)

rem Was there not at least 1 valid word found?

if "%FileTitle%" == "" set "FileTitle= Error: No file title found."

rem Remove the leading space and exit subroutine GetTitle.
set "FileTitle=%FileTitle:~1%"
goto :EOF

The output for the example input data is:
Get from  "Hello world my name is awesome"
the title "Hello world my name is awesome"

Get from  "Hello world my name is awesome, but you knew that video c5"
the title "Hello world my name is awesome"

Get from  "Hello world my name is awesome  video3 v: Everybody knows I am r"
the title "Hello world my name is awesome"

Get from  "Hello world my name is awesome: It got 100 likes in 10 min 1f"
the title "Hello world my name is awesome"

Get from  "Hello world my name is awesome 43 video 2: Did you know that:"
the title "Hello world my name is awesome"

Get from  "Hello world my name is awesome a3: It is Mr smokealot 1f,"
the title "Hello world my name is awesome"

And here is one more version which is very similar to version of Stephan:
@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "FileTitle="
for /F "usebackq delims=" %%L in ("Test.txt") do (
    call :GetTitle "%%L"
    echo !FileTitle!
)
endlocal
goto :EOF

:GetTitle

rem Get string left from first comma or first colon. The entire line
rem is returned if the line does not contain any comma or colon.

for /F "tokens=1 delims=,:" %%T in ("%~1") do set "WordsList=%%T"

rem Process each word from list and check for containing any digit, or being
rem a single letter different than upper case "I", or being the word "video".
rem Those words are ignored and all other remaining words on building the
rem file title from the words list. It is expected here that non of the words
rem contain a non word character as this could result in a syntax error on
rem processing the words.

set "FileTitle="
for %%I in (%WordsList%) do (
    for /F "tokens=1 delims=0123456789" %%W in ("#%%I#") do set "Word=%%W"
    if "!Word!" NEQ "#%%I#" goto CheckTitle
    set "Word=%%I"
    if "!Word:~0,1!" EQU "%%I" (
        if "%%I" NEQ "I" goto CheckTitle
    )
    if /I "%%I" EQU "video" goto CheckTitle
    set "FileTitle=!FileTitle! %%I"
)

:CheckTitle
rem Was there not at least 1 valid word found?

if "%FileTitle%" == "" set "FileTitle= Error: No file title found."

rem Remove the leading space and exit subroutine GetTitle.
set "FileTitle=%FileTitle:~1%"
goto :EOF

The output on example input data posted in Stephan´s answer is:
Hello world my name is awesome
Hello world my name is awesome
Hello world my name is awesome
Hello world my name is awesome
Hello world my name is awesome
Hello world my name is John Doe
Hello world my name is Jane Doe
Hello world my name is Superman
Hello world my name is Asterix
Error: No file title found.
Any string is
Any word that contains

The difference to output produced by Stephan´s code is that a single character word not being I results in exiting the words processing loop and therefore truncating the title at this word.
This single character word behavior can be changed by removing the code lines:
    set "Word=%%I"
    if "!Word:~0,1!" EQU "%%I" (
        if "%%I" NEQ "I" goto CheckTitle
    )

Then the output of this third batch code would be same as what batch code written by Stephan produces with the exception of an error message instead of a blank line.

PS: This is a good example what happens if a questioner does not make it clear what the output data should be for provided input data by posting also in question the expected output data.


text:
Q: GAM - Splines at selected covariate values I am trying to answer a biology question regarding the antibody kinetics with one or two major breakpoints at 21 days and three months. It is possible for me to use linear splines using GLM framework, but I am wondering if it is possible to do so in GAM but to have non-linear splines.
K argument does the splines according to data. Can I specify K at selected covariate values?

A: One approach would be to use an explicit parameterized spline function, and fix, rather than estimate, the specific value(s) of the predictor variable where the spline(s) sits.
For a simple example, I like to call $\max(x_i - \theta,0)$ a 'hinge function', because if I build a model with it like $y_i = \beta_0 + \beta_x x_i + \beta_{cx}\max(x_i - \theta,0)+\varepsilon_i$ what I get is a simple linear regression for values of $x\le \theta$, and then the slope of that linear regression changes by $\beta_{cx}$ for values of $x>\theta$. This works because $\max(x_i - \theta,0)$ is a variable with values equal to zero at or below $\theta$, and values that increase by exactly 1 unit for every 1 unit $x$ increases by thereafter. Keep in mind that the value of $\theta$—like $\beta_0$, $\beta_x$, etc.—is a parameter which is estimated. You might prefer 'broken stick' or some other term to 'hinge'. :)
However, we do not actually have to estimate $\theta$!
Consider instead using $y_i = \beta_0 + \beta_x x_i + \beta_{cx}\max(x_i - C,0)+\varepsilon_i$, where $C$ is some arbitrary constant—such as a theorized or known value in some biological or ecological process. We still get a simple line with a change in slope at the value $x=C$, but now we fix $C$.
Finally, the hinge function as I have described it is pretty bare bones, and there are reasons to find it distasteful (e.g., it's not smooth, and maybe you, or your estimator, care about things like differentability). You could ensmoothen it by squaring it, although that's still a pretty particular functional form, and there are other spline functions which we can be explicit about. Thus, we can be explicit about our spline functions, and explicitly fix their locations, rather than estimate them, or algorithmically "spread" them out. Our ability to do this in practice will depend on both the flexibility of a particular software implementation, and on our understanding of spline function specification.


text:
Q: errno 2 at webpack -p I got the errno 2 when I run the command webpack -p.
When I run only webpack everything is ok.
So I have the following commands at my package.json:
"dev": "rimraf dist && NODE_ENV=development webpack",
"build": "rimraf dist && NODE_ENV=production webpack -p",

And have this configuration for my webpack.config.js:
const path = require('path');
const webpack = require('webpack');
const SassLintPlugin = require('sasslint-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

const extractSass = new ExtractTextPlugin({
  filename: '[name].css',
  disable: process.env.NODE_ENV === 'development',
});

const plugins = [
  new webpack.DefinePlugin({
    'process.env': {
      NODE_ENV: JSON.stringify(process.env.NODE_ENV),
      STAGE: JSON.stringify(process.env.STAGE),
    },
  }),
  new CopyWebpackPlugin([
    { from: path.join(__dirname, 'app/js/pwa/manifest.json'), to: path.join(__dirname, 'dist') },
    { from: path.join(__dirname, 'app/js/pwa/sw.js'), to: path.join(__dirname, 'dist') },
    { from: path.join(__dirname, 'app/js/pushstream/pushstream.js'), to: path.join(__dirname, 'dist') },
    { from: path.join(__dirname, 'app/img/favicon.png'), to: path.join(__dirname, 'dist') },
    { from: path.join(__dirname, 'app/img/tecnoseniorIcon.png'), to: path.join(__dirname, 'dist') },
  ]),
  new SassLintPlugin({
    configFile: '.sass-lint.yml',
    context: [path.resolve(__dirname, './app/')],
    ignoreFiles: [],
    ignorePlugins: [],
    glob: '**/*.s?(a|c)ss',
    quiet: false,
    failOnWarning: false,
    failOnError: true,
    testing: false,
  }),
  extractSass,
  new HtmlWebpackPlugin({
    title: 'Contactto Anywhere',
    template: 'app/index-template.html',
    // minify: {
    //   collapseWhitespace: process.env.NODE_ENV === 'production',
    // },
  }),
];

if (process.env.NODE_ENV === 'development') {
  plugins.push(new webpack.HotModuleReplacementPlugin());
}

if (process.env.NODE_ENV === 'production') {
  plugins.push(new CompressionPlugin({
    asset: '[path].gz[query]',
    algorithm: 'gzip',
    test: /\.js$|\.css$|\.html$/,
    threshold: 10240,
    minRatio: 0.8,
  }));
  plugins.push(new webpack.optimize.ModuleConcatenationPlugin());
}

module.exports = {
  entry: process.env.NODE_ENV === 'development' ?
  {
    main: [
      'webpack-hot-middleware/client?reload=true',
      'react-hot-loader/patch',
      './app/index.jsx',
    ],
    pwa: './app/js/pwa/mainPwa.js',
  }
  :
  {
    main: './app/index.jsx',
    pwa: './app/js/pwa/mainPwa.js',
  },
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/',
  },
  target: 'web',
  devtool: process.env.NODE_ENV === 'development' ? 'inline-source-map' : 'source-map',

  module: {
    rules: [
      {
        test: /\.jsx?$/,
        include: path.resolve(__dirname, './app/'),
        exclude: /node_modules/,
        loader: 'babel-loader',
      },
      {
        test: /\.scss$/,
        include: path.resolve(__dirname, './app/'),
        loader: extractSass.extract({
          use: [
            { loader: 'css-loader?modules&localIdentName=[name]__[local]___[hash:base64:5]' },
            { loader: 'sass-loader' },
          ],
          // use style-loader in development
          fallback: 'style-loader',
        }),
        exclude: /node_modules/,
      },
      {
        test: /\.(eot|ttf|woff|woff2)$/,
        loader: 'file-loader?name=fonts/[name].[ext]',
      },
      {
        test: /\.(png|svg|jpg|webp)$/,
        use: {
          loader: 'file-loader',
        },
      },
    ],
  },
  resolve: {
    extensions: ['.js', '.jsx'],
    modules: [path.resolve(__dirname, 'node_modules')],
  },
  plugins,
};

The webpack -p was working a few days ago, but now it is giving this error.
I do not changed my webpack.config.js for long time.
The log file:
0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/bin/node', '/usr/local/bin/npm', 'run', 'build' ]
2 info using npm@5.3.0
3 info using node@v8.0.0
4 verbose run-script [ 'prebuild', 'build', 'postbuild' ]
5 info lifecycle contactto-master@1.0.0~prebuild: contactto-master@1.0.0
6 info lifecycle contactto-master@1.0.0~build: contactto-master@1.0.0
7 verbose lifecycle contactto-master@1.0.0~build: unsafe-perm in lifecycle true
8 verbose lifecycle contactto-master@1.0.0~build: PATH: /usr/local/lib/node_modules/npm/bin/node-gyp-bin:/Users/alexfqc/Documents/contactto-master-frontend/node_modules/.bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/alexfqc/Library/Android/sdk/tools:/Users/alexfqc/Library/Android/sdk/platform-tools:/Users/alexfqc/mongodb-osx-x86_64-enterprise-3.4.6/bin
9 verbose lifecycle contactto-master@1.0.0~build: CWD: /Users/alexfqc/Documents/contactto-master-frontend
10 silly lifecycle contactto-master@1.0.0~build: Args: [ '-c', 'rimraf dist && NODE_ENV=production webpack -p' ]
11 silly lifecycle contactto-master@1.0.0~build: Returned: code: 2  signal: null
12 info lifecycle contactto-master@1.0.0~build: Failed to exec build script
13 verbose stack Error: contactto-master@1.0.0 build: `rimraf dist && NODE_ENV=production webpack -p`
13 verbose stack Exit status 2
13 verbose stack     at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/lib/utils/lifecycle.js:289:16)
13 verbose stack     at emitTwo (events.js:125:13)
13 verbose stack     at EventEmitter.emit (events.js:213:7)
13 verbose stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/lib/utils/spawn.js:40:14)
13 verbose stack     at emitTwo (events.js:125:13)
13 verbose stack     at ChildProcess.emit (events.js:213:7)
13 verbose stack     at maybeClose (internal/child_process.js:887:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:208:5)
14 verbose pkgid contactto-master@1.0.0
15 verbose cwd /Users/alexfqc/Documents/contactto-master-frontend
16 verbose Darwin 16.7.0
17 verbose argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "build"
18 verbose node v8.0.0
19 verbose npm  v5.3.0
20 error code ELIFECYCLE
21 error errno 2
22 error contactto-master@1.0.0 build: `rimraf dist && NODE_ENV=production webpack -p`
22 error Exit status 2
23 error Failed at the contactto-master@1.0.0 build script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 2, true ]

I do not know what is happening, can anyone help me?
Thanks in advance.

A: I found the error,
I was trying to use async and await without the preset.