text:
Q: how to display data from DB on the .append input field i have a button that creates a new input field and a default field

   <button class="add_form_field">Add Title</button>

      <input type="text" id="title_name">

and this is the jquery that creates a new input field.
var max_fields      = 10;
var wrapper         = $(".container1");
var add_button      = $(".add_form_field");

var x = 1;
$(add_button).click(function(e){
    e.preventDefault();
    if(x < max_fields){
        x++;
        $(wrapper).append('
<input type="text" id="title_name"/>Delete
'); //add input box
    }
else
{
alert('You Reached the limits')
}
});

$(wrapper).on("click",".delete", function(e){
    e.preventDefault(); $(this).parent('div').remove(); x--;
});

and i have ajax call to get the title name from my database based on the user logged in.
$.ajax({
        url:'../ajax/getprofile.php',
        type:'POST',
        data:{userid:user},
        dataType:'JSON',
        success: function(result){
        $('#title_name').val(result.title_name);
        }
});

when i use console.log(result) to see what the data is being returned what happen is that only one data is being returned from my ajax request..
i just didn't include the other data on my question earlier cuz those data only return one data.. i only have problem with the title_name
this code works fine for only the default input field.. like the data from my database only shows up on the default input field not on the appended input field..
saying i have a user id of 10001 and my db is look like this
tbl_title
id    |   name
10001 | sample
10001 | test

what i want to achieve is that when i make a request from ajax and returned the requested value it will display on my input field.and since my id is similar to the tbl_title (id) it should display the two data on the input field. but unfortunately only the 1st data is being displayed only on the default input field what i wanted to make is that if the data is more than 1 it will also display on the appended input field.. but i dont have any idea how this works..
b4 i only got one data that is being returned so i updated my mysql to return all the data that have similar id so now i got array1 and array2 array1 is on the picture and the array2 is similar to the picture but the only difference is their title_name.. so what should i do to display my the two title_name on the array on my input field

A: The id is the same for each input. So jQuery takes the first catch in this line:
$('#title_name').val(result.title_name);

Thats why only the first input works ...
Try to change it something like this:
$(wrapper).append('
<input type="text" id="input_' + x + '"/> ...

and:
$('#input' + x ).val(result.title_name);

Probably not exactly right but a push in the right direction ;) The id is the problem.


text:
Q: Compile sub-project with regular JDK, add the result to my Android App I'm trying to add a local copy of jTDS into my Android App, because there seems to be a bug where interrupting a thread running a query leads to a finalizer timeout in the JtdsStatement class, and I'd like to debug and fix this.
The problem is, jTDS won't build with the Android SDK.  I have to build it with a regular JDK, because it uses some obscure JDK features like for instance the org.ietf.jgss Java package.
What certainly works is building a JAR of jTDS by compiling it outside Android Studio, then adding that JAR into my Android project.  But better would be if I could have the source code of jTDS within my project and build it all together, so I can more rapidly test changes to jTDS in my app.
So is there a way to have a sub-project in Android Studio built with regular JDK, say for instance to generate a JAR, and then add that JAR as a dependency to the main project?

A: I seem to have figured it out.

*

*Put the jTDS code into a jtds sub-directory under the top-level of your Android project.

*Create a build.gradle within this jtds sub-directory:
apply plugin: 'java-library'

java {
    sourceCompatibility = JavaVersion.VERSION_1_8
    targetCompatibility = JavaVersion.VERSION_1_8

    sourceSets.main {
        java.srcDirs = ['src/main']
        resources.srcDirs = ['src/main']
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'lib')
}

compileJava.options.encoding = 'UTF-8'

tasks.withType(JavaCompile) {
    options.encoding = 'UTF-8'
}

*Include the sub-project (the correct term might be "module", I'm not sure) in your top-level settings.gradle file:
include ':app', ':lib1', ':lib2', ':lib3', ':jtds'

*Add the module as a dependency to the app module by editing your app/build.gradle:
// ...

dependencies {
    // ...
    implementation project(':jtds')
    // ...
}

// ...

That's all, it works for me.
Some notes, for those who wish to understand more details:

*

*The original jTDS source code was encoded in the Windows-1252 charset.  I re-encoded the files to UTF-8 which is why I had to include the corresponding lines about file encoding in jtds/build.gradle.  I could have probably left the files in the Windows encoding and omitted those lines from jtds/build.gradle but I prefer to have all my source code in UTF-8.

*The resources.srcDirs = ['src/main'] line in jtds/build.gradle seems to be necessary to include some foo.properties files that are part of the jTDS source code into the generated JAR.  Otherwise, I was getting an error message saying no message resource found for message property prop.servertype upon trying to connect to SQL Server.

*The jTDS sources include a number of JAR files which they depend on, hence including them via the implementation fileTree(...) declaration in the dependencies block of jtds/build.gradle.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to group date between two past date in one column MYSQL I have this Query
SELECT
DATE_ADD(table1.date, INTERVAL -7 DAY) AS date7,
DATE_ADD(table1.date, INTERVAL -14 DAY) AS date14,
DATE_ADD(table1.date, INTERVAL -21 DAY) AS date21,
table1.hotel AS hotel,
table1.customer AS Customer,
table1.date AS Date,
table1.sell AS Sells,
table2.adr AS ADR,
table2.revpar AS RevPAR,
table3.name_hotel AS Hotel_name,
FROM `table1`
INNER JOIN table3 ON table1.hotel=table3.hotel
INNER JOIN table2
ON table1.hotel=table2.hotel
AND table1.date_occ=table2.date_occ

I would like to get a column "weeks" where Date in between Date and date7 then "last week", Date between date7 and date14 then "-2 week" and Date between in date14 and date21 then "-3week". Because I need to group in "weeks" to calculate sells last 7 days, 14 days and 21 days according current date

A: Something like this should work.
table1.date BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW()
table1.date BETWEEN DATE_SUB(NOW(), INTERVAL 14 DAY) AND DATE_SUB(NOW(), INTERVAL 7 DAY)
table1.date BETWEEN DATE_SUB(NOW(), INTERVAL 21 DAY) AND DATE_SUB(NOW(), INTERVAL 14 DAY)

https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_date-sub


text:
Q: Gnome shell disable "glued" tiled windows I often use tiled windows in GNOME, and it's great, but lately (I did not really notice when this started happening, I am running GNOME 3.26.2) I noticed a small change in behavior that I find really annoying: when two windows are tiled (one in the left half and the other in the right half), they are kind of "glued" together, and bringing one in the front will also bring the other in the front.
I wish to disable this behavior and being able to bring one window to front without having the other in the front as well.
The reason for this is that I often find myself with 3 windows in the workspace: a terminal window, maximized, and 2 windows with documentation. Since I use tmux in the terminal, I split the terminal window in there, and I do not tile the terminal, but I still want to bring a single documentation window on top, while having the terminal in the background.
Trying to make it clear, consider this is the window stack ("side-view")
+-----terminal-----+  (top/front)
+--doc1--++--doc2--+  (back, invisible)

I press meta key, go to overview, and select doc1 window to bring it to front (or, more likely, I press Alt+Tab). What happens is:
+--doc1--++--doc2--+  (top/front)
+-----terminal-----+  (back, invisible)

but I wish that final result is
+--doc1--+            (top/front)
+-----terminal-----+  (middle, partially visible)
          +--doc2--+  (back, invisible)

How can I achieve this? I tried looking in dconf editor and tweak tools, but couldn't find anything related.


text:
Q: Desktop Program That Notifies When Web Cam Is Being Accessed I'm trying to find a developer to write a desktop program that has a pretty basic function. It will notify users, via some dialog (or alert) that some program is about to access the web cam. It could be skype or facetime, or whatever it is, the program should be aware of when the OS's camera is going to be accessed and notify the user. Yes, even if the user is initiating the camera themselves via Skype, the notification would still appear.
My question is this. If I need this program written in Java, is it possible? Obviously I am trying to get it done in Java so it would run on Windows and Mac.
If it is not possible, then it seems as though I'd have to write 2 separate programs on Windows and Mac.
I've come here to get suggestions so that I can connect with the right developers. If you have any suggestions, I'd be happy to hear them. Thanks!

A: No, you can't write this in Java. Whatever approach you take will be very system-specific (and will probably require enhanced privileges). You could write a JNI library and a Java interface, but it'd probably be about the same amount of trouble to write programs to the native UI libraries.


text:
Q: loop finding "bouncy" numbers Consider the following definitions of positive numbers:
A number is nondecreasing if its digits never get smaller as you go from left to right. For example, 12345
and 3388 are nondecreasing.
A number is nonincreasing if its digits never larger as you go from left to right. For example, 987542 and
881 are nonincreasing.
A number is bouncy if it is neither nondecreasing nor nonincreasing. For example, 12134 and 98462 are
bouncy.
Write a Python function bouncy that consumes a positive natural number (called n) and produces the
percentage of numbers between 1 and n, inclusive, which are bouncy. The result should be produced as a
natural number between 0 and 100, inclusive. Use round to convert the floating point percentage to an
integer.
def bouncy(input):
list1 = [0 for i in range(input)]
list1[0] = 0
for x in range(1, input-1):
    if x < 100:
        list1[x] = list1[x - 1]
    else:
        n=x
        a = [0 for i in range(x)]
        i = 0
        while n > 0:
            a[i]=n % 10
            n/= 10
            i+=1
        flag = 1
        for k in range(1, len(a) - 2):
            if not ((a[k - 1] < a[k] < a[k + 1]) or (a[k - 1] > a[k] > a[k + 1])):
                flag = 0
                break
        if flag == 0:
            list1[x]==list[x-1]+ 1
return list1[input-1]

when i ran my code, it displays builtins.IndexError: list assignment index out of range.
Anyone got an idea?

A: You don't have to do any of that. Just turn the number into a string. If it's sorted it's nondecreasing, if it's reverse sorted it's nonincreasing, otherwise it's bouncy.
def bouncy(n):
    return round(sum(list(i) not in (sorted(i), sorted(i, reverse=True)) for i in map(str, range(1, n+1)))/n*100)

This map()s each number in the range to a string, then checks whether a list() of that string is not found in a sorted() version of that string (either increasing or decreasing). Then it adds together how many numbers match that, divides by n, multiplies by 100, round()s that, and returns it.


text:
Q: Callback from chrome custom tabs I am implementing Fit-bit rest-client authorisation in my android application. I use custom tabs for opening fitbit authorization URL like "https://www.fitbit.com/oauth2/authorize?response_type=code&client_id=xxxx&scope=activity&redirect_uri=testing://callbackfitbit&prompt=login?time=time". What normally happens is I get Authorization code in my Activity class. But sometimes as fitbit URL is opened in custom tabs, my application is exited. I don't understand this behaviour.
No log is reported for this behaviour.
Any suggestion may help me understanding this behaviour.

A: If you are integrating with an OAuth2 / OpenID Connect compliant authorization server, I would recommend AppAuth. AppAuth provides a simpler interface for performing OAuth2 authorization and token requests, and handles all the specifics of using custom tabs and routing of responses to your app. There is also an iOS variant of the library. Both are maintained by Google and the OpenID Foudnation.
Full disclosure: I'm the lead maintainer of AppAuth.


text:
Q: How do I set a topic filter in a Firebase cloud functions handler? I've created a cloud function that listens to a pubsub topic. When deployed, this creates a subscription to the correct topic and functions how I would expect it to.
export const handler = functions.pubsub.topic("topicName").onPublish(( message, context ) => {
    // code that runs
});

The deploy command used was:
firebase deploy --only functions

My question: How do I set a subscription filter for the topic, so that (for example) I only run the cloud function if an attribute is a specific value?
I know how to do this in the console by manually creating a subscription and create the filters on the subscription creation, but I can't find any documentation on how to do it in a Firebase cloud function.

A: From my understanding of CF Pub/Sub triggers, once the Cloud Function gets deployed the subscription gets created as well and modifying the subscription after it has been created is not possible currently, thus I am not sure if what you want to achieve is possible, due to the back-end of Pub/Sub Cloud Functions.
I tried reproducing a potential workaround with an HTTP trigger CF instead, which would be triggered from a Subscription via Push on the Cloud Function Endpoint URL, only when the manually created filter would be fulfilled and it seems like it worked.
I followed these steps:

*

*Created HTTP function to obtain the function URL

*Create the Pub/Sub topic

*Create Subscription type PUSH to function URL and filter attributes.domain = example.com

*Then on the corresponding topic UI -> Publish message -> Add attribute Key = attributes.domain and Value=example.com

*When publishing, the function gets triggered.

However, you should keep in mind that, as it is an HTTP CF, further authentication processes would be necessary to maintain security.


text:
Q: Удаление дубликатов в двух файлах Собственно есть файл1 и файл2,  допустим обьем файла1 100кк строк, а файла2 20кк строк, нужно проверить вхождения файла2 в файл1, и записать в новые 2 файла строки которые либо есть в файле1 либо нету, по сколько обьемы строк очень большие есть ли какие то быстрые не ресурсоемкие решения на с++ или с#?

A: Смотрите, наивный алгоритм, который будет сравнивать каждую строчку с каждой, будет для вас слишком медленным. Поэтому сделаем алгоритм, который разделит данные за один проход.
Для начала отсортировать ваши файлы. Это на самом деле самая ресурсоёмкая операция. Для этого вам может понадобиться внешняя сортировка, если ваши файлы не влезают в память.
Теперь, когда файлы отсортированы, вы делаете так. Пусть у вас есть текущая строка из первого файла (назовём его словарём), и второго (назовём его вводом). Откроем оба файла, и считаем первую строку из каждого.
Далее в цикле пока ввод или словарь не окончился, делаем следующее в цикле:

*

*сравниваем текущую строку ввода и строку словаря

*если строка словаря больше строки ввода, то строки ввода нет в словаре, дописываем её во второй выходной файл, считываем следующую строку ввода, и переходим к следующей итерации

*если строка словаря равна строке ввода, то строка ввода есть в словаре, дописываем её в первый выходной файл, считываем следующую строку ввода, и переходим к следующей итерации

*если строка словаря меньше строки ввода, считываем следующую строку словаря

Если после окончания цикла ввод не окончился, все его строки тоже попадают во второй выходной файл.

Обратите внимание, что алгоритм довольно сильно напоминает сортировку слиянием, которая вам, судя по всему, понадобится для внешней сортировки.


text:
Q: Stack screen output into columns to make use of screen width and avoid scrolling I often use gridengine's qstat command on our HPC cluster but since I have many jobs running on the cluster the output is too long to fit on my screen and I end up doing a lot of scrolling to see the upper section of the output. My terminal has enough space for two columns so it would be nice if they output could flow into columns and shown side-by-side.
Example using simple data file:
Obviously this should be general to any screen output so to illustrate here is a simpler example:
My file data1.txt contains 100 lines of "This is a test".
>> cat data1.txt
This is a test
This is a test
This is a test
This is a test
This is a test
This is a test
This is a test
This is a test
This is a test
This is a test
This is a test
This is a test
This is a test
This is a test
This is a test
This is a test
This is a test
This is a test
This is a test
This is a test
(etc. until 100th line)
>>

Desired output:
>> cat data1.txt | something | something_else -n 2
This is a test  This is a test
This is a test  This is a test
This is a test  This is a test
This is a test  This is a test
This is a test  This is a test
This is a test  This is a test
This is a test  This is a test
This is a test  This is a test
This is a test  This is a test
This is a test  This is a test
This is a test  This is a test
This is a test  This is a test
This is a test  This is a test
This is a test  This is a test
This is a test  This is a test
This is a test  This is a test
This is a test  This is a test
This is a test  This is a test
This is a test  This is a test
This is a test  This is a test
This is a test  This is a test
This is a test  This is a test
This is a test  This is a test
This is a test  This is a test
This is a test  This is a test
This is a test  This is a test
This is a test  This is a test
(etc. until 50 rows)

Of course, it would be nice to specify any arbitrary number of columns.
The only similar question/answer that I found was this one but I'm hoping there is a simpler way to do this in one line using pipes and no script files.

A: I just found a solution; pipe it to pr.
For the example data file:
cat data1.txt | pr -2 -l 60

And for gridengine's qstat:
qstat -f -u "*" | pr -2 -w 270 -l 130

The -2 flag simply specifies 2 columns.
You can adjust the width parameter -w to better accomodate the original columnar width and the length parameter -l to adjust the number of pages that the output is split across. For a longer output you probably want a higher -l value.


text:
Q: Coordinate transformation of basis vectors The question
Let $e_a$ be the coordinate basis vectors in a manifold described by coordinate system $x^a$. The vector displacement between two nearby points is given by
\begin{equation}
ds=dx^ae_a=dx'^ae'_a
\end{equation}
where a prime denotes the same quantity measured in a different reference frame.
Using the relationship $dx^a=\frac{\partial x^a}{\partial x'^b}dx'^b$, it is easy to see that
\begin{equation}
e'_a=\frac{\partial x^b}{\partial x'^a}e_b
\end{equation}
However, my textbook (General Relativity An Introduction for Physicists by Hobson Lasenby and Efsthathiou, pg 60-61) says that the following must obviously be true as well:
\begin{equation}
e'^a=\frac{\partial x'^a}{\partial x^b}e^b
\end{equation}
My question is how do I prove this?
Attempt at a solution
I can see that this would follow if we assume that $dx_a$ transforms as \begin{equation}
dx'_a=\frac{\partial x^a}{\partial x'^b}dx_b
\end{equation}
And the proof goes as:
\begin{eqnarray}
dx_ae^a&=&dx'_ae'^a\\
&=&\frac{\partial x^a}{\partial x'^b}dx_b e'^a
\end{eqnarray}
Switching the dummy index to b on the left side we get:
\begin{equation}
dx_be^b=\frac{\partial x^a}{\partial x'^b}dx_b e'^a
\end{equation}
which gives:
\begin{equation}
e^b=\frac{\partial x^a}{\partial x'^b} e'^a
\end{equation}
Interchanging primed and unprimed variables as well as a and b we get
\begin{equation}
e'^a=\frac{\partial x'^b}{\partial x^a} e^b
\end{equation}
This proof seems a bit clumsy to me, AND I am unable to prove my starting equation (my text uses the transformation rule for $e'^a$ to prove it later). Is there a better way of deriving this result WITHOUT using the equation I started with?

A: I do not know what you mean by the "coordinate basis vectors" with their upstairs  indices.  The basis vectors of the tangent space ${\rm TM}_p$ at a point $p$ are usually written with downstairs indices as
$$
{\bf e}_\mu= \frac{\partial}{\partial x^\mu}.
$$
The basis vectors with upstairs indices are
$$
{\bf e}^{*\mu}=  dx^\mu
$$
and they are the basis vectors of the dual space $({\rm TM}_p)^*$.
If we insert a displacement vector
$$
\delta {\bf x}= \delta x^\mu \frac{\partial}{\partial x^\mu}
$$
into the dual basis element $dx^\nu$ we use the definition of the dual basis
$$
dx^\nu(\partial_\mu)= \delta^\nu_\mu
$$
  to  get
$$
dx^\nu( \delta {\bf x})= \delta x^\nu
$$
Thus $dx^\nu$ is a machine into which we drop a vector a get back the numerical components of the vector.
If we change coordinates to $x'^\mu$ we have
$$
{\bf e}'^{*\nu}= dx'^\mu= \frac{\partial x'^\mu}{\partial x^\nu} dx^\nu=  \frac{\partial x'^\mu}{\partial x^\nu}{\bf e}^{*\nu}
$$
and
$$
{\bf e}'_\mu= \frac{\partial}{\partial x'^\mu}= \frac{\partial x^\nu }{\partial x'^\mu }\frac{\partial}{\partial x^\nu}= \frac{\partial x^\nu }{\partial x'^\mu }{\bf e}_\nu
$$


text:
Q: System.Exception when I try to send email I am trying to send an email with c#. Everything seems to be ok no errors but when  the programms tries to send the mail I get an exception : "System.Exception - Exception was not treated"
here is the code:
public void sendMail()
    {
        SmtpClient client = new SmtpClient();
        client.Port = 587;
        client.Host = "smtp.gmail.com";
        client.EnableSsl = true;
        client.Timeout = 100;
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.UseDefaultCredentials = false;
        client.Credentials = new System.Net.NetworkCredential("mymailaddress@googlemail.com", "mypassword");

        MailMessage mm = new MailMessage("mymailaddress@googlemail.com", "receiveremailaddress", "test", "test");
        mm.BodyEncoding = UTF8Encoding.UTF8;
        mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

         client.Send(mm); // HERE I GET THE EXCEPTION !!!!!

    }

A: The issue is your timeout is far too short try:
client.Timeout = 5000;

The default value is 100,000 (100 seconds), but smtp.gmail.com is fast enough that if you want to use 5000 it should be fine.
Also as per the above comment to your post; handle your exception (this is a very basic way of doing so).
try
{
...
}
catch(Exception ex)
{
Console.Writeline(ex);
}


text:
Q: Getting error whence I used Endpoint.publish I am trying to get wsdl from this. Getting this error

Exception occurred executing command line. Cannot run program
  "C:\Program Files\Java\jdk1.8.0_171\bin\javaw.exe" (in directory
  "C:\Users\EMUKTAT\Project1\TestMart"): CreateProcess error=206, The
  filename or extension is too long

Here is the code:
public class TestMartpublisher {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Endpoint.publish("http://localhost:58065/prod", new ProductCatalog());

    }

A: This issue is likely that your classpath is now very long:
The error message might not quite correct. It could be that the command line length has exceeded Windows limits.
Windows command-lines are restricted to 32,768 characters. An immediate workaround might be to put your workspace / checkout in your disk's root (e.g., c:\ws) to try to shorten pathnames as much as possible.
refer to : https://github.com/GoogleCloudPlatform/google-cloud-eclipse/issues/2912
Regards,


text:
Q: CSS How to make image fluid extending only to one side of browser, aligned with centered content? I currently don't have code to show as an example because I been trying to make this work but not even coming close to making it work as expected. I can't show the images because of an NDA. So will describe the best I can.
Basically:

*

*I have a logo image inside of a div. The div has margin:0 auto; so it is centered in the browser.

*I have a "Arrow" png image with transparent background that needs to be flushed against the right side of the browser.

*The catch is, No matter how wide you make the browser window, I need the arrow tip to stay next to right side of the logo with the tail of the arrow still being flushed against the right side of the browser.

*The content of the page will be centered as well. Just in case this info was needed.
Basically I need the arrow to resize to the browser width, but make sure the arrow tip is always pointing at the logo.
All my attempts makes the div too big, causing the logo to just be flushed all the way to the left and not centered.
I understanding that may consist of the arrow being sliced into two images, but even then I am still confused on to how I can make this actually work. Starting to think it isn't something that is possible.
Here is an image to explain, I am sure once I figure out how to do the top arrow arrow I can get the bottom arrow. The bottom arrow is slightly different because the arrow tip may be at different places depending on the page.

FINAL Update: Using the Advice from Max
Note: I only tested it on chrome, firefox and safari, all recent versions as of this post. Not sure what issues I will run into with other versions or IE.
HTML

CSS Code
.header-wrapper{
    position:relative;
    width:100%;
    overflow:hidden;
}

.header {

   position: relative;
    z-index: 10;
    height: 69px;
    margin: 0 auto;
}

.arrow-wrapper {
    z-index: 5;
    background:url(../images/arrow_tip.png) no-repeat top left;
    width: 50%;
    position: absolute;
    left: 50%;
    top: 18px;
    padding: 0 0 0 120px;
    height:23px;
    margin-left:140px;
}

.arrow-tail{
    background:url(../images/arrow_tail.png) repeat-x top left;
    height:23px;
    width:100%;
}

A: If I got you right, this could a be a solution:
http://jsfiddle.net/WazcT/3/
HTML:

←‐‐

CSS:
.main{
    position: relative;
    width: 100%;
    overflow: hidden;
}

.header{
    position: relative;
    opacity: 0.5;
    z-index: 10;
    width : 400px;
    height: 100px;
    margin: 0 auto;
    background: #ccc;
}

.arrow_container {
    z-index: 5;
    background: #88b7d5;
    width: 50%;
    position: absolute;
    left: 50%;
    top: 10px;
    padding: 10px 0 10px 200px;
}

.arrow{
    padding: 10px;
    background: #eee;
    font-size: 32px;
}


text:
Q: render the html contents of a controller's action inside a div I would like to render the contents of an action (e.g new_sub_batch) inside a div.
I tried

<%= render :template => 'new_sub_batch.html.erb' %>

but nothing is displayed.
I even tried  <%= render :action => 'new_sub_batch' %>..still nothing.
Any suggestion??
Thanks a lot

A: What you want are partials. Distil the common markup that both views will use into a single file, and prefix its name with an underscore. Then call render :partial => 'filename', where filename is the name of the partial without the underscore.
In your case, the code you pull out of new_sub_batch.html.erb might go in a _batch.html.erb partial, in the same directory as your other sub_batch views. You would render this partial with:
render :partial => 'batch'

In Rails3, you can simply use render 'batch'.
If you want to pass a variable to the partial, you can do so via :locals. Assuming you have a @sub_batch variable you want to pass, your call would look something like this:
render :partial => 'batch', :locals => { :sub_batch => @sub_batch }

While this doesn't strictly answer your question, I believe within the ruby-on-rails tag it's more important to explain the Rails Way, rather than help you do it the wrong way.

A: Try file render:

<%= render :file => 'directory/new_sub_batch.html.erb' %>


text:
Q: Allow user to edit tableview cell label when doing a long press I got a tableView and tableView cell setup (default values).
At the moment I got a button for adding a cell and set the cell.textLabel.text.
Is there a way to edit the cell.textLabel.text property by letting the user do a long click on  the cell to start editing (without using UIAlert)?


text:
Q: Asignar modelo a variable de session en rails 4 Quisiera saber si es posible guardar en una variable de session un objeto artículo por ejemplo tengo este código pero me da este error:

undefined method `add_cesta' for "#":String

Esto es lo que intento hacer:
Este es mi controlador:
class TiendaController < ApplicationController

  def index
    @titulo = "Bienvenido a la Tienda"
    @articulos = Articulo.all.order("nombre").page(params[:page]).per_page(4)
  end

  def quienes_somos
    @titulo = "Bienvenido a la Tienda"
  end

  def contacto
    @titulo = "Bienvenido a la Tienda"
  end

  def anadir_producto
      @articulo = Articulo.find(params[:id])
      @carro = sesion_carrito
      @carro.add_cesta(@articulo)
      flash[:info] ="Producto añadido #{@articulo.nombre}"
      redirect_to inicio_url
  end

  def ver_carro
    if tenemos_sesion?
      @carro = session[:carro]
    else
      flash[:info] = "Donde Vas! Compra antes"
      redirect_to inicio_url
    end
  end

  def vaciar_carrito
      session[:carro] = nil
      flash[:info] = "Carrito vacio"
      redirect_to inicio_url
  end

  private

  def tenemos_sesion?
    session[:carro]
  end

  def sesion_carrito
      session[:carro] ||= Carro.new
  end
end

esta es mi clase carro.rb dentro de models:
class Carro
  attr_reader :cesta

  def initialize
    @cesta = []
  end

  def add_cesta(articulo)
    @cesta << articulo
  end

end

Teóricamente debería funcionar, no he conseguido algo que me indique que no se puede pero tampoco algo que lo sustente, alguien me puede indicar si es posible y en caso de que si se pueda que estoy haciendo mal.

A: Las buenas prácticas dicen que no es recomendable guardar modelos en variables de sesión. Lo que deberías hacer es guardar solamente un arreglo con los id de los artículos.
Algo así sería mejor:
session[:carrito] ||= []
session[:carrito] << @artículo.os

Y luego cuando deseas trabajar con los artículos puedes recuperarlos usando
@articulos_en_carrito = Artículo.where(id: session[:carrito])


text:
Q: Query performance issue - Not in The query below is created by someone else but is running long so need to improve the performance. Can you please suggest me a better way to do?
Select * from ps_vendor G where G.vendor_id NOT IN (SELECT vendor_id
                               FROM   ps_voucher_line
                               WHERE  vendor_id <> '70830'
                                      AND cntrct_id <> ' '
                                      AND vendor_id NOT IN (SELECT vendor_id
                                                            FROM   ps_cntrct_hdr
                                                            WHERE
                                          cntrct_type = 'AP'))

A: Please try with inner join condition like display below
Select G.* from ps_vendor G
       inner join ps_voucher_line  pvl
            on G.vendor_id = pvl.vendor_id and pvl.vendor_id  <> '70830'
        inner join ps_cntrct_hdr pch
            on  (pch.vendor_id <> pvl.vendor_id and pch.cntrct_type = 'AP')
    where pv.cntrct_id <> ' '

Try different variations in joining condition!!
Good is that you have sub query to verify results.


text:
Q: How have you ever interacted with a Nabaztag? The Nabaztag I ordered has arrived. I know there is an API to interact with the critter from your own software. Have also seen links to libraries in Perl and .NET among others, and have started work myself on a simple .NET Compact Framework 3.5 library for interacting with the bunny from my mobile phone.
I have seen at least one application claiming to interact with the Wifi bunny: the TFS Build Notification application by Rob Aquila. (Not related to this question, but this does look like a nice app to have running on a central monitor in a large TFS Team...)
I'm just curious to experiences by other people with the Nabaztag:

*

*Have you ever used the Nabaztag API to interact with wireless rabbits?

*What did you do? Is it freely available to try it out on my bunny?

*How did you like working with the API? Did you just use the HTTP API yourself or did you use a library? And if so, which library did you use?

*Even if you did nothing with the API yourself, what applications and/or websites do you know of that can interact with a Nabaztag?

*Any other tips?

A: This is a bit of a shameless plug for my employer, but someone wrote a quick and dirty Perl script to make a bunny read out log events from ZXTM (Zeus Extensible Traffic Manager).

*

*The Perl script (and further up that page, how to plug it into ZXTM)

*Video of the bunny

*VMware image of ZXTM suitable for use on a desktop to try this out

A: I extended the start on a python api wrapper that others had made, and have a few apps (ugly control panel, personal weather and traffic reader, Google calendar events of the day).  They are all available for download at www.mcgurrin.com/nabaztag.

A: I created a CruiseControl.net plugin with it. Had some issues with the default API because it is not that good documented, so needed a lot of experimenting. Furthermore it is not that easy to develop to the default API.
So i made an .net API (c#) which abstracts the violet api away and gives you more help while developing, specially while creating choreographys (pain in butt they are Yoda would say).
Currently both are not available to the general public but i am in the process of releasing.
Things that can be neath to implement on your bunny, i don't know, local traffic information (nice to have) new releases for music you like, interfacing with your phone? (send command from phone to bunny)

A: Hey peSHIr, congrats for getting a rabbit. Now as violet got bought by Mindscape, it's sure it'll continue living...
I would like to develop funny stuff for the rabbit as well, but it seems like a big fuss and it's hard to get started - I checked out several APIs and proxys to get a grip on it - found many projects but either useless or outdated. Although it's written in PHP, the OpenNab Project seems to be one the fewer active around. Maybe worth to check it out?
http://opennab.sourceforge.net/
I hope Mindscape will provide a better API, or even better, open source the rabbit!


text:
Q: getting error 404 while passing an array through ajax to the controller i have a loop like this in my view that generates the list of student`s names

    name
    grade
    remove

    @foreach (string item in Model)
    {

            @item
            <input type="text" id="txtGrade_@item" onclick="" style="width: 40px;border-left: thin" />
            <input type="checkbox" id="chkStudent_@item" value="@item" />

    }

i use the script below to get the text for the first cell of each row :
$('#btnDone')
          .click(function() {
        //get studentslist
        function getFirstCellTextList(tableElement) {
            if (tableElement instanceof jQuery) {
                // Create an array
                var textList = [];
                // Iterate over each table row
                tableElement.find('tbody tr').each(function () {
                    // Get the first cells's text and push it inside the array
                    var row = $(this);
                    if (row.children('td').length > 0) {
                        textList.push(row.children('td').eq(0).text());
                    }
                });
                return textList;
            }
            return null;
        }
        // Get the array
        var lststudents = getFirstCellTextList($('#your_table'));
        var result = [];
        $(lststudents).each(function(index, item) {
            result.push(item);
        });

       alert(result);
       $.ajax('/TeacherPages/GetGrades/' + result).done(function () {
           alert("done");
       });
    });

the problem is. when i want to send the created array to the controller i get error 404. there is something wrong with this array. because when i manually add values to the array the ajax works without any problems
this is my action:
[AttributeRouting.Web.Mvc.GET("/TeacherPages/GetGrades/{result}")]
    public PartialViewResult GetGrades(string[] result)
    {
        return PartialView();
    }

A: You cannot just append a javascript array to your url. It just converts the values in the array to a comma separated string whereas you need to generate a url which is
/TeacherPages/GetGrades?result=someValue&result=anotherValue&result=etc...

Change your script to
$.ajax({
    url: '@Url.Action("GetGrades", "TeacherPages")', // don't hardcode your url's
    type: 'POST',
    traditional: true,
    data: { result: result },
    success: function (response) {
        ....
    }
});

As a side note, your getFirstCellTextList() function is returning the array you want and its pointless to create another identical array from it. You just need
var result = getFirstCellTextList($('#your_table'));


text:
Q: What is the best Magento reward point system? I'm looking for the best reward point system that allow the customer to sign up for it and start collecting point and spend it with his order. I need it to be compatible with Magento 2.4.5p1

A: you have to buy an extension for reward points please check the below link:- https://mirasvit.com/magento-2-extensions/reward-points-referral-program.html


text:
Q: How to stop Rails (close DB connection) with Apache still running Rails 3 on Apache with Passenger: I need to take down Rails so that the DB connection(s) are closed -- this is necessary to perform some regular database maintenance -- but I want Apache up so that it can respond to requests with a static maintenance page.
I am using Capistrano and have seen the threads on how to invoke maintenance mode, but I need to know where to hook my DB tasks, and cannot figure out where.
Any links, or even pointers to where to look in the Capistrano code would be greatly appreciated.
TIA

A: You can use capistrano's deploy:web:disable task to block access to your site, allowing you to do database maintenance, etc:
cap deploy:web:disable REASON="a Database Upgrade" UNTIL="in a few minutes"

Then, once you're done:
cap deploy:web:enable


text:
Q: 8GB RAM installed, free only shows 4GB I've installed 8GB of RAM (2x4GB) in my computer. Before I have only 4GB (1x4GB), and I've installed the new cards one where the oldest was and the other in the other slot of the same type. But if I check my Ubuntu's details or htop, it only shows 4GB (3'8GB). My motherboard is Asus P7H55-M. In windows it detects 8GB but it says that it only can use 4GB, don't know why.
This are my outputs. (there are in spanish)
free -h:
             total       usado       libre     compart.    búffers
    almac.
Mem:          3,8G       2,2G       1,6G        18M       119M       869M
-/+ buffers/cache:       1,2G       2,6G
Intercambio:       4,5G         0B       4,5G

sudo dmidecode --type memory:
SMBIOS 2.6 present.

Handle 0x0008, DMI type 5, 24 bytes
Memory Controller Information
    Error Detecting Method: 64-bit ECC
    Error Correcting Capabilities:
        None
    Supported Interleave: One-way Interleave
    Current Interleave: One-way Interleave
    Maximum Memory Module Size: 2048 MB
    Maximum Total Memory Size: 8192 MB
    Supported Speeds:
        Other
    Supported Memory Types:
        DIMM
        SDRAM
    Memory Module Voltage: 3.3 V
    Associated Memory Slots: 4
        0x0009
        0x000A
        0x000B
        0x000C
    Enabled Error Correcting Capabilities:
        None

Handle 0x0009, DMI type 6, 12 bytes
Memory Module Information
    Socket Designation: DIMM0
    Bank Connections: 0 1
    Current Speed: Unknown
    Type: DIMM SDRAM
    Installed Size: 4096 MB (Double-bank Connection)
    Enabled Size: 4096 MB (Double-bank Connection)
    Error Status: OK

Handle 0x000A, DMI type 6, 12 bytes
Memory Module Information
    Socket Designation: DIMM1
    Bank Connections: 2 3
    Current Speed: Unknown
    Type: DIMM SDRAM
    Installed Size: Not Installed
    Enabled Size: Not Installed
    Error Status: OK

Handle 0x000B, DMI type 6, 12 bytes
Memory Module Information
    Socket Designation: DIMM2
    Bank Connections: 4 5
    Current Speed: Unknown
    Type: DIMM SDRAM
    Installed Size: 4096 MB (Double-bank Connection)
    Enabled Size: 4096 MB (Double-bank Connection)
    Error Status: OK

Handle 0x000C, DMI type 6, 12 bytes
Memory Module Information
    Socket Designation: DIMM3
    Bank Connections: 6 7
    Current Speed: Unknown
    Type: DIMM SDRAM
    Installed Size: Not Installed
    Enabled Size: Not Installed
    Error Status: OK

Handle 0x0036, DMI type 16, 15 bytes
Physical Memory Array
    Location: System Board Or Motherboard
    Use: System Memory
    Error Correction Type: None
    Maximum Capacity: 16 GB
    Error Information Handle: Not Provided
    Number Of Devices: 4

Handle 0x0038, DMI type 17, 28 bytes
Memory Device
    Array Handle: 0x0036
    Error Information Handle: Not Provided
    Total Width: 64 bits
    Data Width: 64 bits
    Size: 4096 MB
    Form Factor: DIMM
    Set: None
    Locator: DIMM0
    Bank Locator: BANK0
    Type: DDR
    Type Detail: Synchronous
    Speed: 1333 MHz
    Manufacturer: Manufacturer0
    Serial Number: SerNum0
    Asset Tag: AssetTagNum0
    Part Number: PartNum0
    Rank: Unknown

Handle 0x003A, DMI type 17, 28 bytes
Memory Device
    Array Handle: 0x0036
    Error Information Handle: Not Provided
    Total Width: Unknown
    Data Width: Unknown
    Size: No Module Installed
    Form Factor: DIMM
    Set: None
    Locator: DIMM1
    Bank Locator: BANK1
    Type: Unknown
    Type Detail: Unknown
    Speed: Unknown
    Manufacturer: Manufacturer1
    Serial Number: SerNum1
    Asset Tag: AssetTagNum1
    Part Number: PartNum1
    Rank: Unknown

Handle 0x003C, DMI type 17, 28 bytes
Memory Device
    Array Handle: 0x0036
    Error Information Handle: Not Provided
    Total Width: 64 bits
    Data Width: 64 bits
    Size: 4096 MB
    Form Factor: DIMM
    Set: None
    Locator: DIMM2
    Bank Locator: BANK2
    Type: DDR
    Type Detail: Synchronous
    Speed: 1333 MHz
    Manufacturer: Manufacturer2
    Serial Number: SerNum2
    Asset Tag: AssetTagNum2
    Part Number: PartNum2
    Rank: Unknown

Handle 0x003E, DMI type 17, 28 bytes
Memory Device
    Array Handle: 0x0036
    Error Information Handle: Not Provided
    Total Width: Unknown
    Data Width: Unknown
    Size: No Module Installed
    Form Factor: DIMM
    Set: None
    Locator: DIMM3
    Bank Locator: BANK3
    Type: Unknown
    Type Detail: Unknown
    Speed: Unknown
    Manufacturer: Manufacturer3
    Serial Number: SerNum3
    Asset Tag: AssetTagNum3
    Part Number: PartNum3
    Rank: Unknown

With dmicoded it shows that there are two RAMs of 4GB.
And, obviously I'm using a 64bits kernel:
Linux m0skva 3.13.0-53-generic #89-Ubuntu SMP Wed May 20 10:34:39 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux

The BIOS memory remaping is enabled. I don't know what more to do.

A:
Memory Controller Information
     Maximum Memory Module Size: 2048 MB

This part of the output from above would explain what you are seeing.
Can you confirm the motherboard used, or check the maximum capacity it will accept for each individual DIMM?

A: Sharing my experience: I struggled with this issue all day. In my case, I realized the blue and white slots in my gigabyte motherboard were the issue. Once I put my 4gb ram sticks in the same colored slot(blue) it all worked out :)

A: Try to match your slots so that the pairs reflects the same speed and manufacturer of the sticks.
Check your CPU speed.  Go in the bios and slow it down to accommodate the slowest memory.  You might have to test by going slower than the specification to get to a point where the full memory is working.
After you have a working configuration, of course if it works as a results of slowing down the process speed, invest into changing the slowest sticks will faster sticks.


text:
Q: Align the text to center in headerlabel in iphone I am new to iphone development.I have displayed the text in the header label.Now i want to align the text to center. I using the following code
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{

UIView* customView = [[UIView alloc] initWithFrame:CGRectMake(10.0, 0.0,300.0,44.0)];

UILabel * headerLabel = [[UILabel alloc] initWithFrame:CGRectZero];
headerLabel.backgroundColor = [UIColor brownColor];

headerLabel.textColor = [UIColor whiteColor];
headerLabel.highlightedTextColor = [UIColor whiteColor];
headerLabel.font = [UIFont boldSystemFontOfSize:15];
headerLabel.frame = CGRectMake(0.0, 0.0, 500.0, 22.0);
headerLabel.text = @"Hello"; //
[customView addSubview:headerLabel];
return customView;
}

"hello" should be displayed at the center of the header label.Please help me out.Thanks.

A: Try this:
headerLabel.textAlignment = UITextAlignmentCenter;


text:
Q: Android layout is missing elements when debugging on phone I am experiencing some strange behaviour with my layouts. As you can see from the screenshot below (of the layout in eclipse) the 'register' button appears just fine at the bottom of the screen.
Before
However, if you now take a look at the following screenshot taken on my phone (HTC ONE X) whilst debugging, the button is completely cut off with plenty of space.
After
The code for the register page is as follows (where the button is contained within the relative layout)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    android:gravity="center"
    android:text="Register"
    android:textSize="18sp" />

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="25dp"
    android:orientation="horizontal" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_weight="0.25"
        android:text="Title:" />

    <EditText
        android:id="@+id/txtTitle"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginRight="20dp"
        android:layout_weight="0.75"
        android:ems="10"
        android:text="" />
</LinearLayout>

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_weight="0.25"
        android:text="First Name:" />

    <EditText
        android:id="@+id/txtFirstName"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginRight="20dp"
        android:layout_weight="0.75"
        android:ems="10"
        android:text="" />
</LinearLayout>

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_weight="0.25"
        android:text="Surname:" />

    <EditText
        android:id="@+id/txtSurname"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginRight="20dp"
        android:layout_weight="0.75"
        android:ems="10"
        android:text="" />
</LinearLayout>

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_weight="0.25"
        android:text="Email:" />

    <EditText
        android:id="@+id/txtEmail"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginRight="20dp"
        android:layout_weight="0.75"
        android:ems="10"
        android:text="" />
</LinearLayout>

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_weight="0.25"
        android:text="Age:" />

    <EditText
        android:id="@+id/txtAge"
        android:layout_width="10dp"
        android:layout_height="wrap_content"
        android:layout_marginRight="20dp"
        android:layout_weight="0.75"
        android:ems="10"
        android:text="" />
</LinearLayout>

<TableLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_marginTop="10dp"
    android:orientation="vertical"
    android:stretchColumns="*"
    android:weightSum="4" >

    <TableRow
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1" >

        <TextView
            android:id="@+id/txtGender"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_weight="0.25"
            android:text="Gender" />

        <TextView
            android:id="@+id/txtTypeOfUser"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_weight="0.25"
            android:text="Type of User" />
    </TableRow>

    <TableRow
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1" >

        <RadioGroup
            android:id="@+id/radioSex"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <RadioButton
                android:id="@+id/radioMale"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="true"
                android:text="Male" />

            <RadioButton
                android:id="@+id/radioFemale"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Female" />
        </RadioGroup>

        <RadioGroup
            android:id="@+id/radioTypeOfUser"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <RadioButton
                android:id="@+id/radioUser"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="true"
                android:text="User" />

            <RadioButton
                android:id="@+id/radioDoctor"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Doctor" />
        </RadioGroup>
    </TableRow>
</TableLayout>

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <Button
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="20dp"
        android:layout_marginRight="20dp"
        android:text="Register" />
</RelativeLayout>

</LinearLayout>

A: Your TableLayout has layout_height set to fill_parent, change it to wrap_content.
<TableLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:orientation="vertical"
    android:stretchColumns="*"
    android:weightSum="4" >


text:
Q: ¿Como saco una cuenta de correo que tenga cualquier numero, letra o caracteres especiales? Para encontrar cuentas con cualquier número de letras he usado el código que se muestra, pero de esta forma no puedo sacar cuentas que tengan números y caracteres especiales.
email <- str_extract_all(mail, "[a-z]+\\\\\@[a-z]+\\\\.[a-z]+")

A: Puedes filtrar tambien con str_extract() del mismo package stringr
   #R version 3.3.2
library(stringr)
a <- c('patricio.vega12345@gmail.com','tuejemplo999@gmail.com','email@outlook.es','stack_overflow_es@email.com')
b <- str_extract(a, '\\S+@\\S+|\\{(?:\\w+, *)+\\w+\\}@[\\w.-]+')
b

Respuesta
[1] "patricio.vega12345@gmail.com" "tuejemplo999@gmail.com"
[3] "email@outlook.es"             "stack_overflow_es@email.com"

El ejemplo usando str_extract_all()
#R version 3.3.2
library(stringr)
a <- c('patricio.vega12345@gmail.com','tuejemplo999@gmail.com','email@outlook.es','stack_overflow_es@email.com')
b <- str_extract_all(a, '\\S+@\\S+|\\{(?:\\w+, *)+\\w+\\}@[\\w.-]+')
b

imprime lo siguiente
[[1]]
[1] "patricio.vega12345@gmail.com"

[[2]]
[1] "tuejemplo999@gmail.com"

[[3]]
[1] "email@outlook.es"

[[4]]
[1] "stack_overflow_es@email.com"


text:
Q: Tool to find and replace numbers based on range in Unicode text file I've been seaching all over and am out of ideas, so I'll try my luck here.
What I need to do is simple... or so I thought.
I need to process a lot of Unicode files that all follow the same structure in a Windows environment. In these files are lines that contain "valuexxx" where xxx is a three digit number. I need to be able to replace valuexxx with a string, depending on what value xxx is. A crude way of explaining what I need to do is

*

*if xxx >= 270 and xxx < 310 then replace valuexxx with some text.

*if xxx >= 311 and xxx < 350 then replace valuexxx with some other text.

The ranges may need to be fine tuned later.
First I thought I'd use Notepad++ or FNR.exe as they use regular expressions, but as I have found out regular expressions can not do numeric value comparing. I did find that I could possibly solve it by testing for valid character combinations, but this will not work as the range may need to change and re-editing all character combinations will be too much of a hassle for the people who I need to solve this for.
So I moved on to Gawk, it seems to be able to do the comparisons I need, but it appears it can't process Unicode text files. I'd prefer not to have to convert from Unicode to something else as these files can contain multiple languages like Chinese, Japanese, Thai etc etc.
I can't program these kind of things myself so I need some sort of tool that can do the above. Any suggestions?

A: I don't think a ready-made tool exists for that, but you can do something like this very simply, for example in a Python script.
I'm assuming that by Unicode you mean UTF-8-encoded files. Then (in Python 3), you'd just have to do this to define your replacement texts:
import re
repl = {(270,310): "some text",
        (311,350): "some other text",
        # etc., add more here
       }
regex = re.compile(r"value(\d{3})")

def replace(match):
    value = int(match.group(1))
    for item in repl:
        if item[0] <= value < item[1]:
            return repl[item]

Then you could read the files, for example all files ending in .txt:
import glob
for filename in glob.glob("*.txt"):
    with open(filename, encoding="utf-8") as f:
        content = f.read()

and then write the corrected file:
    with open(filename + ".new", "w", encoding="utf-8") as f:
        f.write(regex.sub(replace, content))

That's it. There's no error checking done (for example if the three-digit number is not found in repl), but I think this should get you started.


text:
Q: How to interpret this output of lsof command? root@host [/home2]# lsof /home2
COMMAND     PID     USER   FD   TYPE DEVICE SIZE/OFF     NODE NAME
php        3182 ctxmortg  cwd    DIR   8,17     4096 32858196 /home2/ctxmortg/public_html/hello
php        3182 ctxmortg    3r   REG   8,17    46404 55781766 /home2/ctxmortg/public_html/hello/cache/subprimemortgagemorgage.com/cache-zch-8284-cache.txt
php        3185 ctxmortg  cwd    DIR   8,17     4096 32858196 /home2/ctxmortg/public_html/hello
php        3185 ctxmortg    3r   REG   8,17     4185 35962154 /home2/ctxmortg/public_html/hello/cache/curl/http%3A%2F%2Fimage.yahoo.cn%2Fs%3Fq%3DNudity%26c%3D0%26s%3D%26page%3D277
php        3187 ctxmortg  cwd    DIR   8,17     4096 32858196 /home2/ctxmortg/public_html/hello
php        3187 ctxmortg    3r   REG   8,17    54640 69699731 /home2/ctxmortg/public_html/hello/cache/newdatingfriends.com/cache-zch-1545-cache.txt
php        3188 ctxmortg  cwd    DIR   8,17     4096 32858196 /home2/ctxmortg/public_html/hello
php        3188 ctxmortg    3r   REG   8,17    54640 21557063 /home2/ctxmortg/public_html/hello/cache/customersdeals.com/cache-zch-5715-cache.txt
php        3189 ctxmortg  cwd    DIR   8,17     4096 32858196 /home2/ctxmortg/public_html/hello
php        3189 ctxmortg    3r   REG   8,17     4185 36028071 /home2/ctxmortg/public_html/hello/cache/curl/http%3A%2F%2Fimage.yahoo.cn%2Fs%3Fq%3DVideos%26c%3D0%26s%3D%26page%3D329
php        3200 ctxmortg  cwd    DIR   8,17     4096 32858196 /home2/ctxmortg/public_html/hello
php        3200 ctxmortg    3r   REG   8,17    21036  9155614 /home2/ctxmortg/public_html/hello/cache/indorealestates.com/cache-zch-8562-cache.txt
lsof       3201     root  cwd    DIR   8,17     4096        2 /home2
lsof       3202     root  cwd    DIR   8,17     4096        2 /home2
webalizer 32342 ctxmortg  cwd    DIR   8,17     4096 32890953 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com
webalizer 32342 ctxmortg    5uW  REG   8,17    12288 32890954 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com/dns_cache.db
webalizer 32360 ctxmortg  cwd    DIR   8,17     4096 32890953 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com
webalizer 32360 ctxmortg    5u   REG   8,17    12288 32890954 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com/dns_cache.db
webalizer 32361 ctxmortg  cwd    DIR   8,17     4096 32890953 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com
webalizer 32361 ctxmortg    5u   REG   8,17    12288 32890954 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com/dns_cache.db
webalizer 32362 ctxmortg  cwd    DIR   8,17     4096 32890953 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com
webalizer 32362 ctxmortg    5u   REG   8,17    12288 32890954 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com/dns_cache.db
webalizer 32363 ctxmortg  cwd    DIR   8,17     4096 32890953 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com
webalizer 32363 ctxmortg    5u   REG   8,17    12288 32890954 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com/dns_cache.db
webalizer 32364 ctxmortg  cwd    DIR   8,17     4096 32890953 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com
webalizer 32364 ctxmortg    5u   REG   8,17    12288 32890954 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com/dns_cache.db
webalizer 32365 ctxmortg  cwd    DIR   8,17     4096 32890953 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com
webalizer 32365 ctxmortg    5u   REG   8,17    12288 32890954 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com/dns_cache.db
webalizer 32366 ctxmortg  cwd    DIR   8,17     4096 32890953 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com
webalizer 32366 ctxmortg    5u   REG   8,17    12288 32890954 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com/dns_cache.db
webalizer 32367 ctxmortg  cwd    DIR   8,17     4096 32890953 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com
webalizer 32367 ctxmortg    5u   REG   8,17    12288 32890954 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com/dns_cache.db
webalizer 32368 ctxmortg  cwd    DIR   8,17     4096 32890953 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com
webalizer 32368 ctxmortg    5u   REG   8,17    12288 32890954 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com/dns_cache.db
webalizer 32369 ctxmortg  cwd    DIR   8,17     4096 32890953 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com
webalizer 32369 ctxmortg    5u   REG   8,17    12288 32890954 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com/dns_cache.db
bash      32409     root  cwd    DIR   8,17     4096        2 /home2

I want to umount a drive but cannot.
So, what does cwd, 3r dir, and reg mean anyway?

A: Information on the meanings of the columns can be found in the lsof(8) manpage. I will address  the ones you are asking about specifically.
cwd => current working directory
3r  => file descriptor 3 opened for reading
DIR => directory
REG => regular file

In order to unmount the drive, you will likely need to stop your webserver, and kill the webalizer process (since it's usually a batch job ran from cron).

A: COMMAND     PID     USER   FD   TYPE DEVICE SIZE/OFF     NODE NAME
webalizer 32342 ctxmortg    5uW  REG   8,17    12288 32890954 /home2/ctxmortg/tmp/webalizer/eyebestdatedotcomauph.ctxmortgagemortgagerefi.com/dns_cache.db

FD - File Descriptor
If you are looking for file being written, look for following flag
# - The number in front of flag(s) is the file descriptor number of used by the process to associated with the file
u - File open with Read and Write permission
r - File open with Read permission
w - File open with Write permission
W - File open with Write permission and with Write Lock on entire file
mem - Memory mapped file, usually for share library

So 3r means webalizer has a descriptor number 3 associated with ...dns_cache.db, with read permission.
TYPE - File Type
In Linux, almost everything are files, but with different type.
REG - REGgular file, file that show up in directory
DIR - Directory

NODE
inode number in filesystem
You can find complete details in the man page.

A: In this scenario I usually use lsof in combination with ps to find out who is holding the device busy.
Let's take a example with a usb stick that was mounted as /media/disk-1
$> sudo umount /media/disk-1
[sudo] password for cj:
umount: /media/disk-1: device is busy.
        (In some cases useful info about processes that use
         the device is found by lsof(8) or fuser(1))

So I then try to find out who is holding the device with lsof.
$> lsof | grep disk-1
bash       7822         cj  cwd       DIR       8,33      16384          1 /media/disk-1

And since column 2 is the pid holding we can get the name of that process with ps.
$> ps -A | grep 7822
7822 pts/1    00:00:00 bash

Now that bash comes from a terminal that was open in a dir on the device, so at this point I could either close or kill that terminal so the device would be free again.

Update I don't think I answered the question, but maybe it could be helpful for someone else so I leave it anyway.


text:
Q: Can't create a form for comments in a post RAILS I'm trying to create a comment box/form under my article in rails, but it keeps raising an error saying unknown attribute: post_id
My form code
<%= form_for ([@post, @post.comments.build]) do |f| %>

<%= f.label :commenter %>

<%= f.text_field :commenter %>

<%= f.label :body %>

<%= f.text_area :body %>

<%= f.submit %>

<% end %>

For my comment create action
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.build(comment_params)
redirect_to post_path(@post)

respond_to do |format|
  if @comment.save
    format.html { redirect_to @comment, notice: 'Comment was successfully created.' }
    format.json { render action: 'show', status: :created, location: @comment }
  else
    format.html { render action: 'new' }
    format.json { render json: @comment.errors, status: :unprocessable_entity }
  end
end
end

It raises an error for
<%= form_for ([@post, @post.comments.build]) do |f| %>

saying unknown attribute: post_id
Thanks all!
Updated Error : undefined method `posts'

       <%= comment.commenter %>
       <%= comment.body %>
       <%= comment.posts %>
       <%= link_to 'Show', comment %>
       <%= link_to 'Edit', edit_comment_path(comment) %>
       <%= link_to 'Destroy', comment, method: :delete, data: { confirm: 'Are you sure?' } %>

A: It seems like you don't have a post_id column in comments table which is causing the error.
Looking at your code, I am guessing that you want a 1-M relationship between Post and Comment model.
Make sure the relationship is setup correctly in the models as below:
class Post < ActiveRecord::Base
  has_many :comments
  ## ...
end

class Comment < ActiveRecord::Base
  belongs_to :post
  ## ...
end

After this, you must make a post_id column in comments table as a reference to posts table. This should resolve your unknown attribute: post_id error.
You can create post_id column in comments table by generating a migration:
rails generate migration AddPostRefToComments post:references

After this run rake db:migrate
UPDATE

I'm getting undefined method `post_comments_path'

In order to fix the above issue, you should have nested routes in routes.rb
resources :posts do
  resources :comments
end

UPDATE 2
Change
<%= comment.posts %>

To
<%= comment.post %>

Note singular post and not plural posts.


text:
Q: Filezilla stopped showing hidden files all of a sudden Recently my filezilla stopped displaying hidden files (.htaccess, .env, etc). I have the "Force showing hidden files" option selected. I thought this might be a change at the server level, but that's not it either as I downloaded winscp and am able to connect and view hidden files. Anyone had this happen before? Know of a solution?

A: To resolve this issue I went to View -> Directory listing filters, and under Remote filters unchecked Configuration files. I'm not sure how this was suddenly enabled, but unchecking it resolved the issue.


text:
Q: Select primary dropdown and force other dropdowns to select the option with the same value When the Primary dropdown changes, I want the other dropdown to change accordingly.
But I dont know why only the 1st Other dropdown is working while the 2nd fails to change its value accordingly. I
m aware that if I change the name of the 2nd dropdown to the same as the 1st dropdown it will work.
But as they are different fields that are to be saved in the db, so the names have to be different.
Any solution would be appreciated. Many thanks.

function setDropDown() {
  var index_name =
    document.getElementsByName('ForceSelection')[0].selectedIndex;
  var others = document.getElementsByName('Qualifications');
  for (i = 0; i < others.length; i++)
    others[i].selectedIndex = index_name;

  var others2 = document.getElementsByName('Qualifications2');
  for (i = 0; i < others2.length; i++)
    others2[i].selectedIndex = index_name2;
}
Primary dropdown<select name="ForceSelection" id="ForceSelection" onChange="javascript:return setDropDown();">
<option value="" selected>Select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select> other dropdown
<select id="Qualifications" name="Qualifications">
    <option value="select">select</option>
    <option value="treatmentid1">treatmentname1</option>
    <option value="treatmentid2">treatmentname2</option>
</select> other dropdown2
<select id="Qualifications2" name="Qualifications2">
    <option value="select">select</option>
    <option value="treatmentid1">treatmentname1</option>
    <option value="treatmentid2">treatmentname2</option>
</select>

A: Add a css class to your secondary drop downs and use document.querySelectorAll to get them all at once.
Then you can use a single loop to update their selectedIndex.

function setDropDown() {
  var index_name =
    document.getElementsByName('ForceSelection')[0].selectedIndex;
  var others = document.querySelectorAll('.secondary');
  for (var i = 0; i < others.length; i++) {
    others[i].selectedIndex = index_name;
  }

}
div {
  padding: 15px;
}

Primary dropdown:
  <select name="ForceSelection" id="ForceSelection" onChange="javascript:return setDropDown();">
<option value="" selected>Select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select>

  Other dropdown 1:
  <select class='secondary' id="Qualifications" name="Qualifications">
    <option value="select">select</option>
    <option value="treatmentid1">treatmentname1</option>
    <option value="treatmentid2">treatmentname2</option>
</select>

 Other dropdown 1:
  <select class='secondary' id="Qualifications2" name="Qualifications2">
    <option value="select">select</option>
    <option value="treatmentid1">treatmentname1</option>
    <option value="treatmentid2">treatmentname2</option>
</select>

A: So it turns out i haven't defined sth in my code, thanks for pointing that out  @Tiny Giant

function setDropDown() {
  var index_name =
    document.getElementsByName('ForceSelection')[0].selectedIndex;

    var index_name2 =
    document.getElementsByName('ForceSelection')[0].selectedIndex;

  var others = document.getElementsByName('Qualifications');
  for (i = 0; i < others.length; i++)
    others[i].selectedIndex = index_name;

  var others2 = document.getElementsByName('Qualifications2');
  for (j = 0; j < others2.length; j++)
    others2[j].selectedIndex = index_name2;
}
Primary dropdown<select name="ForceSelection" id="ForceSelection" onChange="javascript:return setDropDown();">
<option value="" selected>Select</option>
<option value="treatmentid1">treatmentname1</option>
<option value="treatmentid2">treatmentname2</option>
</select> other dropdown
<select id="Qualifications" name="Qualifications">
    <option value="select">select</option>
    <option value="treatmentid1">treatmentname1</option>
    <option value="treatmentid2">treatmentname2</option>
</select> other dropdown2
<select id="Qualifications2" name="Qualifications2">
    <option value="select">select</option>
    <option value="treatmentid1">treatmentname1</option>
    <option value="treatmentid2">treatmentname2</option>
</select>


text:
Q: BIT:Using a binary indexed tree? A binary indexed tree has very few or relatively no theory to study as compared to other data structures. The only place where it is taught succinctly is the topcoder tutorial. Although the tutorial is complete in all the explanations, I cannot understand that what is the intuition behind such a tree? And how to prove it's correctness?
I presume that the proof is to complex to explain. So when using BIT, what approach do you follow?

A: I found this answer by @templatetypedef very clearly explain about the intuition and proof of a binary indexed tree:
The answer....
Intuitively, you can think of a binary indexed tree as a compressed representation of a binary tree that is itself an optimization of a standard array representation.  This answer goes into one possible derivation.
Let's suppose, for example, that you want to store cumulative frequencies for a total of 7 different elements.  You could start off by writing out seven buckets into which the numbers will be distributed:
[   ] [   ] [   ] [   ] [   ] [   ] [   ]
  1     2     3     4     5     6     7

Now, let's suppose that the cumulative frequencies look something like this:
[ 5 ] [ 6 ] [14 ] [25 ] [77 ] [105] [105]
  1     2     3     4     5     6     7

Using this version of the array, you can increment the cumulative frequency of any element by increasing the value of the number stored at that spot, then incrementing the frequencies of everything that come afterwards.  For example, to increase the cumulative frequency of 3 by 7, we could add 7 to each element in the array at or after position 3, as shown here:
[ 5 ] [ 6 ] [21 ] [32 ] [84 ] [112] [112]
  1     2     3     4     5     6     7

The problem with this is that it takes O(n) time to do this, which is pretty slow if n is large.
One way that we can think about improving this operation would be to change what we store in the buckets.  Rather than storing the cumulative frequency up to the given point, you can instead think of just storing the amount that the current frequency has increased relative to the previous bucket.  For example, in our case, we would rewrite the above buckets as follows:
Before:
[ 5 ] [ 6 ] [21 ] [32 ] [84 ] [112] [112]
  1     2     3     4     5     6     7

After:
[ +5] [ +1] [+15] [+11] [+52] [+28] [ +0]
  1     2     3     4     5     6     7

Now, we can increment the frequency within a bucket in time O(1) by just adding the appropriate amount to that bucket.  However, the total cost of doing a lookup now becomes O(n), since we have to recompute the total in the bucket by summing up the values in all smaller buckets.
The first major insight we need to get from here to a binary indexed tree is the following: rather than continuously recomputing the sum of the array elements that precede a particular element, what if we were to precompute the total sum of all the elements before specific points in the sequence?  If we could do that, then we could figure out the cumulative sum at a point by just summing up the right combination of these precomputed sums.
One way to do this is to change the representation from being an array of buckets to being a binary tree of nodes.  Each node will be annotated with a value that represents the cumulative sum of all the nodes to the left of that given node.  For example, suppose we construct the following binary tree from these nodes:
             4
          /     \
         2       6
        / \     / \
       1   3   5   7

Now, we can augment each node by storing the cumulative sum of all the values including that node and its left subtree.  For example, given our values, we would store the following:
Before:
[ +5] [ +1] [+15] [+11] [+52] [+28] [ +0]
  1     2     3     4     5     6     7

After:
                 4
               [+32]
              /     \
           2           6
         [ +6]       [+80]
         /   \       /   \
        1     3     5     7
      [ +5] [+15] [+52] [ +0]

Given this tree structure, it's easy to determine the cumulative sum up to a point.  The idea is the following: we maintain a counter, initially 0, then do a normal binary search up until we find the node in question.  As we do so, we also the following: any time that we move right, we also add in the current value to the counter.
For example, suppose we want to look up the sum for 3.  To do so, we do the following:

*

*Start at the root (4).  Counter is 0.

*Go left to node (2).  Counter is 0.

*Go right to node (3).  Counter is 0 + 6 = 6.

*Find node (3).  Counter is 6 + 15 = 21.

You could imagine also running this process in reverse: starting at a given node, initialize the counter to that node's value, then walk up the tree to the root.  Any time you follow a right child link upward, add in the value at the node you arrive at.  For example, to find the frequency for 3, we could do the following:

*

*Start at node (3).  Counter is 15.

*Go upward to node (2).  Counter is 15 + 6 = 21.

*Go upward to node (1).  Counter is 21.

To increment the frequency of a node (and, implicitly, the frequencies of all nodes that come after it), we need to update the set of nodes in the tree that include that node in its left subtree.  To do this, we do the following: increment the frequency for that node, then start walking up to the root of the tree.  Any time you follow a link that takes you up as a left child, increment the frequency of the node you encounter by adding in the current value.
For example, to increment the frequency of node 1 by five, we would do the following:
                 4
               [+32]
              /     \
           2           6
         [ +6]       [+80]
         /   \       /   \
      > 1     3     5     7
      [ +5] [+15] [+52] [ +0]

Starting at node 1, increment its frequency by 5 to get
                 4
               [+32]
              /     \
           2           6
         [ +6]       [+80]
         /   \       /   \
      > 1     3     5     7
      [+10] [+15] [+52] [ +0]

Now, go to its parent:
                 4
               [+32]
              /     \
         > 2           6
         [ +6]       [+80]
         /   \       /   \
        1     3     5     7
      [+10] [+15] [+52] [ +0]

We followed a left child link upward, so we increment this node's frequency as well:
                 4
               [+32]
              /     \
         > 2           6
         [+11]       [+80]
         /   \       /   \
        1     3     5     7
      [+10] [+15] [+52] [ +0]

We now go to its parent:
               > 4
               [+32]
              /     \
           2           6
         [+11]       [+80]
         /   \       /   \
        1     3     5     7
      [+10] [+15] [+52] [ +0]

That was a left child link, so we increment this node as well:
                 4
               [+37]
              /     \
           2           6
         [+11]       [+80]
         /   \       /   \
        1     3     5     7
      [+10] [+15] [+52] [ +0]

And now we're done!
The final step is to convert from this to a binary indexed tree, and this is where we get to do some fun things with binary numbers.  Let's rewrite each bucket index in this tree in binary:
                100
               [+37]
              /     \
          010         110
         [+11]       [+80]
         /   \       /   \
       001   011   101   111
      [+10] [+15] [+52] [ +0]

Here, we can make a very, very cool observation.  Take any of these binary numbers and find the very last 1 that was set in the number, then drop that bit off, along with all the bits that come after it.  You are now left with the following:
              (empty)
               [+37]
              /     \
           0           1
         [+11]       [+80]
         /   \       /   \
        00   01     10   11
      [+10] [+15] [+52] [ +0]

Here is a really, really cool observation: if you treat 0 to mean "left" and 1 to mean "right," the remaining bits on each number spell out exactly how to start at the root and then walk down to that number.  For example, node 5 has binary pattern 101.  The last 1 is the final bit, so we drop that to get 10.  Indeed, if you start at the root, go right (1), then go left (0), you end up at node 5!
The reason that this is significant is that our lookup and update operations depend on the access path from the node back up to the root and whether we're following left or right child links.  For example, during a lookup, we just care about the left links we follow.  During an update, we just care about the right links we follow.  This binary indexed tree does all of this super efficiently by just using the bits in the index.
The key trick is the following property of this perfect binary tree:

Given node n, the next node on the access path back up to the root in which we go right is given by taking the binary representation of n and removing the last 1.

For example, take a look at the access path for node 7, which is 111.  The nodes on the access path to the root that we take that involve following a right pointer upward is

*

*Node 7: 111

*Node 6: 110

*Node 4: 100

All of these are right links.  If we take the access path for node 3, which is 011, and look at the nodes where we go right, we get

*

*Node 3: 011

*Node 2: 010

*(Node 4: 100, which follows a left link)
This means that we can very, very efficiently compute the cumulative sum up to a node as follows:

*

*Write out node n in binary.

*Set the counter to 0.

*Repeat the following while n ≠ 0:

*

*Add in the value at node n.

*Remove the leftmost 1 bit from n.

Similarly, let's think about how we would do an update step.  To do this, we would want to follow the access path back up to the root, updating all nodes where we followed a left link upward.  We can do this by essentially doing the above algorithm, but switching all 1's to 0's and 0's to 1's.
The final step in the binary indexed tree is to note that because of this bitwise trickery, we don't even need to have the tree stored explicitly anymore.  We can just store all the nodes in an array of length n, then use the bitwise twiddling techniques to navigate the tree implicitly.  In fact, that's exactly what the bitwise indexed tree does - it stores the nodes in an array, then uses these bitwise tricks to efficiently simulate walking upward in this tree.
Hope this helps!


text:
Q: Mysql calculation result in where clause? I'm working on a vBulletin forum. The idea is to create a webpage where admins can query all the latest posts and "read" them so they get marked as "checked".
The webpage works perfectly fine, however, the query is a bit slow because we get thousends of new posts every single day and right now it's pulling all posts from the past 24 hours.
To solve the issue, I want it to only pull the posts that aren't checked yet.
The original query is as follows:
SELECT
thread.forumid, thread.firstpostid, thread.lastpost, thread.lastposter, thread.lastpostid, thread.replycount,
thread.threadid, thread.title, thread.open, thread.views, post.pagetext AS preview, post.userid AS lastpuserid, threadread.readtime AS readtime, threadread.userid AS userid
FROM thread AS thread
LEFT JOIN deletionlog AS deletionlog ON (thread.threadid = deletionlog.primaryid AND deletionlog.type = 'thread')
LEFT JOIN post AS post ON (post.postid = thread.lastpostid)
LEFT JOIN threadread AS threadread ON (threadread.threadid = thread.threadid AND threadread.userid = 90122)
WHERE open <> 10
AND thread.lastpost >=  1494100000
AND thread.forumid NOT IN(0013482730313233343537)
AND thread.visible = '1'
AND post.visible = 1
AND deletionlog.primaryid IS NULL

GROUP BY thread.threadid
ORDER BY thread.lastpost DESC

To only get the unchecked posts, I need to calculate
thread.lastpost-threadread.readtime > 0
My first solution was to just add
AND thread.lastpost-threadread.readtime > 0 to the where clause. However, this caused
LEFT JOIN threadread AS threadread ON (threadread.threadid = thread.threadid AND threadread.userid = 90122)
to only select the threadread.userid = 90122 and not threadread.threadid = thread.threadid
So my idea was to do
SELECT ... thread.lastpost-threadread.readtime AS isread
and then AND isread > 0. This returned the error

Unknown column 'isread'

I'm most likely trying to do something very stupid or simply don't understand how this entiry query is working, but I'm out of ideas on how to solve my problem. So now I'm asking you guys :)

A: If you are going to use table aliases, then shorten the names so the query is easier to write and to read.
Then, you need to fix the JOINs.  The WHERE clause is turning some outer joins to inner joins.  Then, move the condition to the appropriate ON clause.
I think this is what you want:
SELECT t.forumid, t.firstpostid, t.lastpost, t.lastposter, t.lastpostid, t.replycount,
       t.threadid, t.title, t.open, t.views, p.pagetext AS preview, p.userid AS lastpuserid, tr.readtime AS readtime, tr.userid AS userid
FROM thread t JOIN
     post p
     ON p.postid = t.lastpostid LEFT JOIN
     deletionlog dl
     ON t.threadid = dl.primaryid AND dl.type = 'thread' LEFT JOIN
     threadread tr
     ON tr.threadid = t.threadid AND tr.userid = 90122 AND
        t.lastpost > tr.readtime
WHERE open <> 10 AND
      t.lastpost >=  1494100000 AND
      t.forumid NOT IN (0013482730313233343537) AND
      t.visible = 1 AND
      p.visible = 1 AND
      dl.primaryid IS NULL
GROUP BY t.threadid
ORDER BY t.lastpost DESC;

I'm not sure what the GROUP BY is supposed to be doing.  Using GROUP BY with no aggregation functions on the unaggregated columns is usually a really bad idea.  In this case, t.threadid is probably the primary key for the table, so the other columns from that table are fine.  But what if there are duplicates generated by joins to other tables?


text:
Q: How to use other variables from other definitions using buttons? I want to be able to receive the name that is set from pressing the button from startgame() and have it stored in getName(). But I don't know how to receive variables from another definition in doing so. I tried my best, but no luck? Any suggestions?
from tkinter import *
root = Tk()

root.wm_title("HangMan")

canvas = Canvas(root, height=400, width=800)
canvas.pack()

def titlescreen():
    title = canvas.create_text(400, 100, font=("Times New Roman", 50), tags="title")
    canvas.itemconfig(title, text="HANGMAN: THE GAME")

    startButton = Button(canvas, text="Start Game", width=10, command=startgame)
    canvas.create_window(400, 200, window = startButton)

    creditsButton = Button(canvas, text="Credits", width=10, command=displaycredits)
    canvas.create_window(400, 250, window = creditsButton)

def startgame():
    canvas.delete(ALL)
    welcome = canvas.create_text(400,100,font=("Times New Roman",50),text="WELCOME!")
    welcome2 = canvas.create_text(400,150,font=("Times New Roman", 30),text="PLEASE ENTER YOUR NAME")

    nameEntry = Entry(canvas)
    enterName = Button(canvas, text="Enter", width=10,command=getName)

    canvas.create_window(350, 200, window = nameEntry)
    canvas.create_window(490, 200, window = enterName)

    nameEntry.delete(0,END)
    nameEntry.insert(0, "Enter Player Name")

    name = nameEntry.get()

    return name

def getName():
    name2 = startgame()
    print (name)
    return name2

def displaycredits():
    canvas.delete(ALL)
    created = canvas.create_text(400,100,font=("Times New Roman",50),text="CREATED BY")
    credit1 = canvas.create_text(400,150,text="Patrick Tsui & Ricardo Perez")
    credit2 = canvas.create_text(400,170,text="Montclair State University Students")
    backButton = Button(canvas,text="Back to Title Screen",width=30,command=backtotitle)
    canvas.create_window(400, 200, window=backButton)

def backtotitle():
    canvas.delete(ALL)
    titlescreen()

def drawPole():
    canvas.delete(ALL)
    a = canvas.create_rectangle(550,50,550,350,fill = "black")
    b = canvas.create_rectangle(350,50,550,50,fill = "black")
    c = canvas.create_rectangle(350,50,350,90,fill = "black")

titlescreen()

root.mainloop()

A: ...
canvas.pack()
name = '' # initialize a 'name' variable

def startgame():
    def getName(): # define this inside startgame, so we don't need to pass widgets
        global name # tell the program that we're referring to the global variable 'name'
        name = nameEntry.get() # assign the contents of nameEntry to 'name'
        backtotitle() # do something

    canvas.delete(ALL)
    welcome = canvas.create_text(400,100,font=("Times New Roman", 50),
    text="WELCOME!")
    welcome2 = canvas.create_text(400,150,font=("Times New Roman", 30),
    text="PLEASE ENTER YOUR NAME")

    nameEntry = Entry(canvas)
    enterName = Button(canvas, text="Enter", width=10,
    command=getName) # does not pass widget

    canvas.create_window(350, 200, window = nameEntry)
    canvas.create_window(490, 200, window = enterName)

    nameEntry.delete(0,END)
    nameEntry.insert(0, "Enter Player Name")

    print(name) # for testing, to see the current name


text:
Q: How to change the color of subgraph using pyvis? I want to visualize the graph using pyviz.
I'm working on the code to extract a subgraph from a graph.
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt

def RWS(G, vs, r=0.5, S=4):
    #initialize subgraph
    Gk = nx.DiGraph()
    #initialize nodes
    Vk = []

    #add vs to Gk
    Gk.add_node(vs)
    Vk.append(vs)

    while len(Vk) < S:
        #get neighbor nodes set of Vk (step 4) (Also appending j just for the purpose of adding edge)
        NS = [(n, j) for j in Vk for n in G.neighbors(j) if n not in Vk]
        print("{} {} {} {}".format('length of NS is', len(NS), 'and vs =', vs))
        # randomly select r of nodes in NS, add them into the Vk
        if not len(NS) == 0:
            for node, j in NS:
                if np.random.uniform() < r:
                    Vk.append(node)
                    Gk.add_edge(j, node)
                    if len(Vk) == S or len(NS) < S:
                        break
        else:
            break
    return Gk

if __name__ == '__main__':

    m = np.matrix([
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [1, 0, 0, 0, 0, 1, 0, 0, 0, 0],
    [0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 1, 0, 1, 1, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 1, 0, 0]])

    # G = nx.from_numpy_matrix(m, create_using=nx.MultiDiGraph())
    G =  nx.from_numpy_matrix(m, create_using=nx.DiGraph)
    #expansion ratio
    r  = 0.5
    #subgraph size
    S  = 4
    # randomly select the node from G
    vs = np.random.randint(0, G.size())
    print(vs)

    Gk = RWS(G, vs, r, S)

    # VISUALIZATION
    pos = nx.spring_layout(G)
    nx.draw_networkx_nodes(G, pos)
    nx.draw_networkx_nodes(G, pos, nodelist=list(Gk.nodes()), node_color='r')
    nx.draw_networkx_labels(G, pos)
    nx.draw_networkx_edges(G, pos, edge_color='b', width=0.5)
    nx.draw_networkx_edges(G, pos, edgelist=list(Gk.edges()), edge_color='g', width=1, arrowstyle='->')

    plt.axis('off')
    plt.show()

Here I have the graph in networkx format, and extract the subgraph from it, then visualize with networkx. To make it easier to see, subgraph is colored green.
However, this visualization does not work well for large scaled graph.
So I want to recreate the visualization of this using pyvis. Can someone help me tto complete this?

A: In order to visualize this graph in pyvis, you can write the following function:
from pyvis.network import Network

def visualize(G, SG):
    N = Network(height='100%', width='100%', bgcolor='#222222', font_color='white', directed=True)
    # uncomment the following if the graph is large
    # N.barnes_hut(spring_strength=0.006)

    for n in G:
        if n in SG:  # if the node is part of the sub-graph
            color = 'green'
        else:
            color = 'red'
        N.add_node(n, label=n, color=color)

    for e in G.edges:
        if e in SG.edges:  # if the edge is part of sub-graph
            color = 'green'
            width = 2
        else:
            color = 'red'
            width = 0.5
        N.add_edge(int(e[0]), int(e[1]), color=color, width=width)

    N.write_html('subgraph.html')  # save a html file in current dir

Make sure that the graph and the sub-graph are both of the same type:
G = nx.from_numpy_matrix(m, create_using=nx.MultiDiGraph())
Gk = nx.MultiDiGraph()  # changed the graph type to MultiDiGraph

and finally you will have:
# VISUALIZATION
visualize(G, Gk)


text:
Q: Connecting 2 monitors and peripherals to a 2017 MacBook Pro I have a 2017 MacBook Pro (13 inch with two Thunderbolt 3 ports). I wanted to connect 2 monitors as well as a mouse and keyboard to it for work. I was wondering if this would be too much of a workload for the Mac  or if this is a normal thing to do with such a device.
I was looking at either buying a Henge dock or a cheaper option such as this 14 in one USB C hub  I found on Amazon.
Does the adapter make a difference for this too?

A:
I was wondering if this would be too much of a workload for the Mac  or if this is a normal thing to do with such a device.

What is "normal" is very subjective. What you actually intend to do with your Mac is what determines if it's capable of handling the processing load.
This model is capable of handling two external displays up to 4K each but that doesn't mean you're going to be driving high intensity graphics apps like gaming or video production with this configuration.

*

*There's no discrete GPU meaning it utilizes your CPU display chipset and up to 1.5GB of system RAM for video memory

*There's only one Thunderbolt chip so, your video bandwidth is limited.

Also, just because a computer can do something (it has the capability) doesn't mean it's sized appropriately for doing that thing long term.  Example:  just because you have the ability to plug in two display's to your MacBook Pro without a discrete GPU doesn't mean you that you've sized it right - you probably should have purchased the 15" with 4 Thunderbolt port model with Radeon GPU.  It's even possible you should have gone with a desktop.

*

*External Monitor Blurry text and Sluggy Mouse on MBP 2020

*A1398 2015 - inadequate fan behaviour/noise

*Adjusting graphics cards settings in Mojoave to reduce overheating with external monitor (MacBookPro2018)

I was looking at either buying a Henge dock or a cheaper option [USB Hub] .... Does the adapter make a difference for this too?

Yes! That device you linked to is a USB Hub.  Meaning, all the benefits of Thunderbolt will go unused.  If you want to get the best possible performance out of your machine, you need to use the components that will make the best possible use out of the resources you have.  Get a proper Thunderbolt Dock instead.
The Henge dock, does nothing more than take your TB ports and move them so you can have the Mac "in an upright and closed position."  Other than being slick, it gives you no audio, video, Ethernet, USB...nothing. IMO, it's a waste of money.


text:
Q: How load Partial View with JavaScript In my view I have JavaScript to load a partial view.

@using (Html.BeginForm(@MyChoise, "Corr_Exit"))
{
    @Html.AntiForgeryToken()

                    etc...........

I'd load this partial between
 tag

But my code doesn't work. Why?
Someone can help me please?

A: I have used load ajax for this
$('#AREA_PARTIAL_VIEW').load('@Url.Action("Insert_Partial_View","Customers")');


text:
Q: Delete Row button from List of record not working in Visualforce page I am writing a VF page where I have to show list records with Add/Delete button. when I click Delete (X) button it is deleting the record and removing that particular row. But if I am adding a row with clicking Add button and deleting the same row it is throwing error. It should delete that row which was added that moment. Added my code piece below.
public Pagereference removeRow() {

    String SelectedRowId = ApexPages.CurrentPage().getParameters().get('rowid');

    for (Integer i = 0; i < subConfigurationList.size(); i++) {
        Sub_Task_Configuration__c a = subConfigurationList[i];
        if (a.Id == SelectedRowId) {
            delete a;
            subConfigurationList.remove(i);
            break;
        }
    }

return null;

}

For 1st remove button as shown in pic it is working fine but where there is no record if I click remove(X) button it throwing error.
Error below:
Invalid id:
Error is in expression '{!removeRow}' in page task_con: Class.Task_con.removeRow: line 63, column 1
An unexpected error has occurred. Your development organization has been notified.
Please Help me in this!

A: Change
delete a;

to
Database.delete(a, false);

Which will ignore errors instead of throwing an exception.
Please note that you should probably validate why the deletion failed, in case you need to surface an error to the user (e.g. it's okay if it failed because the record does not exist or was deleted, but not if there was a validation or security error).


text:
Q: Change of subsite address and now points to an error I've managed to change the subsites address to 'Home.aspx' by mistake and need to change it back to something, what's the best way to do this? doesnt let me access the subsite anymore

A: Open the site in designer and then open any site page. Then set it as the home page.
Alternatively you can directly open the Site Settings page using URL
http://site/subsite/_layouts/settings.aspx

A: change the folder that it looks onto in SPDesigner on the subsite's details/home screen


text:
Q: Tweepy Error: Your credentials do not allow access to this resource I am using Tweepy to build a Telegram-based twitter client and when I try to post a tweet, I receive the following error message:
"TweepError occurred, args=([{'code': 220, 'message': 'Your credentials do not allow access to this resource.'}],)

I've managed to overcome this once, when I logged out and logged back in to my Twitter account (I'm using oauth with PIN verifier). But after some time posting stops working again and this error reoccurs.
How do I avoid this error with a single authentication?
I save access token and secret to a separate file and the application permissions are set to Write, Read, Access direct messages.


text:
Q: Example of a non-splitting exact sequence $0\rightarrow M\rightarrow M\oplus N\rightarrow N\rightarrow 0$, question This is question related to following link:
Example of a non-splitting exact sequence $0 → M → M\oplus N → N → 0$
$M$ and $N$ as in the linked post, that is, $M=\mathbb{Z}$ an $N=\bigoplus_{\mathbb{N}}\mathbb{Z}/2\mathbb{Z}$.
So you constructed an ses $S_1: 0\longrightarrow M\stackrel{\alpha}\longrightarrow M\oplus N\stackrel{\beta}\longrightarrow M\longrightarrow 0$ that is not split. Thus $S_1$ cannot be equivalent with $S_0: 0\longrightarrow M\stackrel{i}\longrightarrow M\oplus N\stackrel{\pi}\longrightarrow M\longrightarrow 0$ in which $i$ and $\pi$ are the natural injection and natural projection, respectively. Therefore, there cannot be an isomorphism $\phi : M\oplus N \longrightarrow M\oplus N$ such that $\phi \circ \alpha = i$.
Is it possible to prove that the identity is the only isomorphism $M\oplus N \longrightarrow M\oplus N$ ? I will be grateful if you / someone can prove that for me.

A: Your question is whether the $\mathbb{Z}$-module $\mathbb{Z}\oplus \bigoplus_{\mathbb{N}} \mathbb{Z}/2\mathbb{Z}$ admits automorphisms other that the identity.
As Hagen von Eitzen says in a comment, any non-trivial automorphism of $\mathbb{Z}$ or of $\bigoplus_{\mathbb{N}} \mathbb{Z}/2\mathbb{Z}$ will give rise to such an automorphism.  Since $\mathbb{Z}$ has a non-trivial automorphism (given by multiplication by $-1$), this answers your question.
Note that $\bigoplus_{\mathbb{N}} \mathbb{Z}/2\mathbb{Z}$ has even more non-trivial automorphisms.