Q: addClass function working properly but removeClass function not working on input text field for form? Creating an Online form and I'd like only the field that the user is focused on to be notfaded so i decided to add some jQuery to my form but the remove class function is not working. addClass works when I click into a field it shows brightly and not faded as it adds the Focused class but as soon as I click away or am no longer focused on that field the Focused class remains.
I've seen some similar posts but the solutions on the other posts don't seem to pertain to my issue.
Below is my form
<form name="contactform" method="post">

Name *

Please provide your full name
<input type="text" maxlength="100" class="form-control discuss" name="projectname">

    <input type="submit" name="nameaction" value="SEND" class="btn btn-lg btn-success btn-block">

</form>

Below is my jQuery
$(document).ready(function(){
   $('input[type="text"]').on('focus', function() {
       $('.inputFaded').addClass('Focused');
   });

   $('input[type="text"]').off('focus', function() {
       $('.inputFaded').removeClass('Focused');
   });
});

Any help greatly appreciated!
Thanks,

A: You are misunderstanding .off()

Description: Remove an event handler.

So it seems that you need to listen focusin and focusout event.

$(document).ready(function(){
$('input[type="text"]').focusin(function() {
    $('.inputFaded').addClass('Focused');
});

$('input[type="text"]').focusout(function() {
    $('.inputFaded').removeClass('Focused');
});
});
.Focused{
    background-color: #FFFFCC;
}

<form name="contactform" method="post">

Name *

Please provide your full name
<input type="text" maxlength="100" class="form-control discuss" name="projectname">

    <input type="submit" name="nameaction" value="SEND" class="btn btn-lg btn-success btn-block">

</form>

Updated

$(document).ready(function(){
    $('input[type="text"]').focusin(function() {
        $(this).addClass('Focused');
    });

    $('input[type="text"]').focusout(function() {
        $(this).removeClass('Focused');
    });
});
.Focused{
   border-color: red;
}

<form name="contactform" method="post">

Name *

Please provide your full name
<input type="text" maxlength="100" class="form-control discuss" name="projectname">

    <input type="submit" name="nameaction" value="SEND" class="btn btn-lg btn-success btn-block">

</form>

A: The .off function is not used for running a function but for removing a function from an Event tied to an element, as already pointed out by @Phong. Instead use the .focusout() function or .on("focusout", ..)
Please note that if this is also quite simple in Vanilla JS:
// Vanilla JS solution
(function(){
  let input = document.querySelector("input[type='text']"),
      inputFaded = document.querySelector(".inputFaded");

  input.addEventListener('focus', function() {
    console.log("focused now!");
    inputFaded.classList.add('Focused');
  });

  input.addEventListener('focusout', function(){
    console.log("I will also be run! :)");
    inputFaded.classList.remove('Focused');
  })
})()

$(document).ready(function(){
    $('input[type="text"]').on('focus', function() {
        console.log("focused now!");
        $('.inputFaded').addClass('Focused');
    });

    // Removing function from focus event that does not exist as a function to an eventlistener
    $('input[type="text"]').off('focus', function() {
        console.log("I will never be run? :(");
        $('.inputFaded').removeClass('Focused');
    });

    // adding focusout eventlistener
    $('input[type="text"]').on('focusout', function() {
        console.log("I will be run! :)");
        $('.inputFaded').removeClass('Focused');
    });

    // alternative way of adding focusout eventlistener
    $('input[type="text"]').focusout( function() {
        console.log("I will also be run! :)");
        $('.inputFaded').removeClass('Focused');
    });

});

<form name="contactform" method="post">

Name *

Please provide your full name
<input type="text" maxlength="100" class="form-control discuss" name="projectname">

    <input type="submit" name="nameaction" value="SEND" class="btn btn-lg btn-success btn-block">

</form>

A: You can also try like this :
$(document).ready(function(){
  $("input").focus(function(){
    $('.inputFaded').addClass('Focused');
  });

   $("input").on('blur', function() {
    $('div').removeClass('Focused');
  });

});


Q: Trying to get Azimuth difference in a loop I have a micropython program on a ESP32 connected to a stepper motor via a driver board.
The software runs in a while true loop. I'm trying to get the azimuth difference between 30 second previous azimuth reading and the post 30 second azimuth reading, then send the difference to the stepper motor. Unfortunately they will not let me post all my code, so here is a small example.....
import math
import time
import Stepper
from machine import Pin
s1 = Stepper.create(Pin(26,Pin.OUT),Pin(25,Pin.OUT),Pin(33,Pin.OUT),Pin(32,Pin.OUT),
delay=2)

while True:

   xxxxx loop in here I have working code that updates the Azimuth of the sun in
   realtime every 30 seconds XXXXXXX

   s1.angle(azimuth, -1)

   time.sleep(30)


Q: Simple slopes test for merMod object with R package interactions (jtools) I'm trying to conduct a simple slopes analysis for a mixed effects model obtained with lmer.
The model is similar to the following:
data(Orthodont,package="nlme")
mod <- lme4::lmer(distance ~ age*Sex + (1|Subject), data=Orthodont)

When trying to conduct a simple slopes analysis with the function sim_slopes in the package interactions, I obtain the following error message.
interactions::sim_slopes(model=mod, pred=age, modx=Sex)

Error: One of the requested columns does not exist.
  Backtrace:
  1. interactions::sim_slopes(model = mod, pred = age, modx = Sex)
  5. jtools:::summ.merMod(...)
  6. jtools:::create_table(...)
  In addition: Warning message:
  Johnson-Neyman intervals are not available for factor moderators.

Would any one have any thoughts on what the problem might be?
Note that it works well with the package reghelper, but I need p values for these tests, which reghelper does not provide.
reghelper::simple_slopes(mod)

The output of sessionInfo() is:

R version 3.6.0 (2019-04-26)
  Platform: x86_64-pc-linux-gnu (64-bit) Running under: Ubuntu 18.04.2
  LTS
Matrix products: default BLAS:
  /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.7.1 LAPACK:
  /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.7.1
locale:  [1] LC_CTYPE=en_CA.UTF-8       LC_NUMERIC=C
  LC_TIME=en_CA.UTF-8         [4] LC_COLLATE=en_CA.UTF-8
  LC_MONETARY=en_CA.UTF-8    LC_MESSAGES=en_CA.UTF-8     [7]
  LC_PAPER=en_CA.UTF-8       LC_NAME=C                  LC_ADDRESS=C
  [10] LC_TELEPHONE=C             LC_MEASUREMENT=en_CA.UTF-8
  LC_IDENTIFICATION=C
attached base packages: [1] stats     graphics  grDevices utils
  datasets  methods   base
loaded via a namespace (and not attached):
  [1] Rcpp_1.0.1        magrittr_1.5       splines_3.6.0      MASS_7.3-51.1
  [5] munsell_0.5.0      colorspace_1.4-1   lattice_0.20-38    rlang_0.3.4
  [9] minqa_1.2.4        plyr_1.8.4         tools_3.6.0       grid_3.6.0
  [13] gtable_0.3.0       nlme_3.1-140       cli_1.1.0          assertthat_0.2.1
  [17] digest_0.6.19      lme4_1.1-21        lazyeval_0.2.2     tibble_2.1.2
  [21] crayon_1.3.4       Matrix_1.2-17      reghelper_0.3.4    nloptr_1.2.1
[25] ggplot2_3.1.1      interactions_1.1.0 jtools_2.0.1       pander_0.6.3
  [29] compiler_3.6.0     pillar_1.4.1       scales_1.0.0       boot_1.3-20
  [33] pkgconfig_2.0.2

A: (Not an answer but way too long for a comment.  Will delete later if appropriate.)
In a clean R session, this works for me:
data(Orthodont,package="nlme")
mod <- lme4::lmer(distance ~ age*Sex + (1|Subject), data=Orthodont)
interactions::sim_slopes(model=mod, pred=age, modx=Sex)
sessionInfo()

SIMPLE SLOPES ANALYSIS
  Slope of age when Sex = Female:
   Est.   S.E.    t val.      p
  ------ ------ -------- ------
   0.48   0.09     5.13   0.00
  Slope of age when Sex = Male:
   Est.   S.E.   t val.      p
  ------ ------ -------- ------
    0.78   0.08    10.12   0.00
  Warning message:
  Johnson-Neyman intervals are not available for factor moderators.

Here is my sessionInfo(): the important stuff looks the same as yours (lme4 1.1-21, interactions 1.1.0, jtools 2.0.1), but it's certainly not identical ... ??
R Under development (unstable) (2019-05-21 r76566)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 16.04.6 LTS

[matrix product and locale info deleted]

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.1         magrittr_1.5       splines_3.7.0      MASS_7.3-51.4
 [5] tidyselect_0.2.5   munsell_0.5.0      colorspace_1.4-1   lattice_0.20-38
 [9] R6_2.4.0           rlang_0.3.4        minqa_1.2.4        plyr_1.8.4
[13] dplyr_0.8.1        tools_3.7.0        grid_3.7.0         gtable_0.3.0
[17] nlme_3.1-140       cli_1.1.0          digest_0.6.19      assertthat_0.2.1
[21] lme4_1.1-21        lazyeval_0.2.2     tibble_2.1.2       numDeriv_2016.8-1
[25] crayon_1.3.4       Matrix_1.2-17      purrr_0.3.2        nloptr_1.2.1
[29] ggplot2_3.1.1      jtools_2.0.1       interactions_1.1.0 glue_1.3.1
[33] pander_0.6.3       compiler_3.7.0     pillar_1.4.1       scales_1.0.0
[37] lmerTest_3.1-0     boot_1.3-22        pkgconfig_2.0.2

A: I solved the problem by detaching lmerTest.


Q: Next Js - Providers/getProviders() - FetchError - next build I am trying to build my application next js.
I use providers with next-auth.
It works fine when I use npm run dev.
But when I use npm run build I get this:

However, I use the variable NEXTAUTH_URL = localhost: 3000 in a .env.local
The error appears when I have "getProviders ()" in a file like this:

import {getProviders, useSession} from 'next-auth/client'
import Layout from "../components/layout";

export default function Page({providers}) {
    const [session, loading] = useSession()

    return (
        <Layout providers={providers}>Page index</Layout>
    )
}

export async function getStaticProps() {
    const providers = await getProviders()

    return {
        props: {providers}
    }
}

A: I think same probrem this.
ECONNREFUSED during 'next build'. Works fine with 'next dev'
It is working.
import {getProviders, useSession} from 'next-auth/client'
import Layout from "../components/layout";

export default function Page() {
    const [session, loading] = useSession()
    const [providers, setProviders] = useState({});

    useEffect(() => {
      (async () => {
        const res = await getProviders();
        setProviders(res);
      })();
    }, []);

    return (
        <Layout providers={providers}>Page index</Layout>
    )
}


Q: How to set radio button selected value using jquery How to set radio button selected value in javascript:
HTML Code :
<input type="radio" name="RBLExperienceApplicable" class="radio" value="1" >
<input type="radio" name="RBLExperienceApplicable" class="radio" value="0" >

<input type="radio" name="RBLExperienceApplicable2" class="radio" value="1" >
<input type="radio" name="RBLExperienceApplicable2" class="radio" value="0" >

ASPX Code
     <asp:RadioButtonList ID="RBLExperienceApplicable" runat="server" class="radio"    RepeatDirection="Horizontal" EnableViewState="false">
            <asp:ListItem Value="1" Text="Yes   "></asp:ListItem>
                <asp:ListItem Value="0" Text="No"></asp:ListItem>
        </asp:RadioButtonList>

     <asp:RadioButtonList ID="RBLExperienceApplicable2" runat="server" class="radio"  RepeatDirection="Horizontal" EnableViewState="false">
            <asp:ListItem Value="1" Text="Yes   "></asp:ListItem>
                <asp:ListItem Value="0" Text="No"></asp:ListItem>
        </asp:RadioButtonList>

// Some Code Fetch from db
// Based on db value script block will execute
 <script type="text/javascript">
        RadionButtonSelectedValueSet('1');
 </script>

Script Block :
function RadionButtonSelectedValueSet(SelectdValue) {
    $('#RBLExperienceApplicable').val(SelectdValue);
        //$("input[name='RBLExperienceApplicable']:checked").val(SelectdValue);
}

A: Try
function RadionButtonSelectedValueSet(name, SelectdValue) {
    $('input[name="' + name+ '"][value="' + SelectdValue + '"]').prop('checked', true);
}

also call the method on dom ready
<script type="text/javascript">
jQuery(function(){
    RadionButtonSelectedValueSet('RBLExperienceApplicable', '1');
})
</script>

A: You can try this also
function SetRadiobuttonValue(selectedValue)
{
  $(':radio[value="' + selectedValue + '"]').attr('checked', 'checked');
}

A: You can do more elegantly.
function RadionButtonSelectedValueSet(name, SelectedValue) {
    $('input[name="' + name+ '"]').val([SelectedValue]);
}

A: Below script works fine in all browser:
function RadionButtonSelectedValueSet(name, SelectdValue) {
     $('input[name="' + name + '"][value="' + SelectdValue + '"]').attr('checked',true);
}

A: $('input[name="RBLExperienceApplicable"]').prop('checked',true);

Thanks dude...

A: If the selection changes, make sure to clear the other checks first. al la...

$('input[name="' + value.id + '"]').attr('checked', false);
$('input[name="' + value.id + '"][value="' + thing[value.prop] + '"]').attr('checked',  true);

A: for multiple dropdowns
$('[id^=RBLExperienceApplicable][value='+ SelectedVAlue +']').attr("checked","checked");

here RBLExperienceApplicable is the matching part of the radio button groups input tag ids.
and [id^=RBLExperienceApplicable] matches all the radio button whose id start with RBLExperienceApplicable

A:   <input type="radio" name="RBLExperienceApplicable" class="radio" value="1" checked >
 //       For Example it is checked
 <input type="radio" name="RBLExperienceApplicable" class="radio" value="0" >

<input type="radio" name="RBLExperienceApplicable2" class="radio" value="1" >
<input type="radio" name="RBLExperienceApplicable2" class="radio" value="0" >

      $( "input[type='radio']" ).change(function() //on change radio buttons
   {

    alert('Test');
   if($('input[name=RBLExperienceApplicable]:checked').val() != '') //Testing value
 {

$('input[name=RBLExperienceApplicable]:checked').val('Your value Without Quotes');

}
    });

http://jsfiddle.net/6d6FJ/1/
Demo

A:   <asp:RadioButtonList ID="rblRequestType">
        <asp:ListItem Selected="True" Value="value1">Value1</asp:ListItem>
        <asp:ListItem Value="Value2">Value2</asp:ListItem>
  </asp:RadioButtonList>

You can set checked like this.
var radio0 = $("#rblRequestType_0");
var radio1 = $("#rblRequestType_1");

radio0.checked = true;
radio1.checked = true;

A: A clean approach I find is by giving an ID for each radio button and then setting it by using the following statement:
document.getElementById('publicedit').checked = true;

A: Can be done using the id of the element
example
<label><input type="radio" name="travel_mode"  value="Flight" id="Flight"> Flight </label>
<label><input type="radio" name="travel_mode"  value="Train" id="Train"> Train </label>
<label><input type="radio" name="travel_mode"  value="Bus" id="Bus"> Bus </label>
<label><input type="radio" name="travel_mode"  value="Road" id="Road"> Other </label>

js:
$('#' + selected).prop('checked',true);

A: This is the only syntax that worked for me
$('input[name="assReq"][value="' + obj["AssociationReq"] + '"]').prop('checked', 'checked');

A: document.getElementById("TestToggleRadioButtonList").rows[0].cells[0].childNodes[0].checked = true;

where TestToggleRadioButtonList is the id of the RadioButtonList.


Q: Spring service periodic task Lets suppose there is spring boot web app with 2 classes mapped as @Controller and @Service. Service is injected into controller's field. I need my service to run task once a second to update some external data. Is there something wrong with this code?
@Component
public class MyService implements Runnable{
    public MyService() {
        new Thread(this).start();
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
                // operations here
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

A: Though there are a lot of ways of creating a task, using job or spring task scheduler, below is one straightforward way.
Below task will run every second.
Timer timer = new Timer();
    timer.schedule(new TimerTask() {

        @Override
        public void run() {
            System.out.println("hello");
        }
    }, 0, 1000); // o is delay time after which it starts, 1000 is time interval

Or you may want to refer here to implement spring task scheduler .


Q: How to use a variable to pass a crop string argument to cpdf in bash This question is about how, in bash, one can (and cannot) pass a string—which is contained in a bash variable—as an argument to a binary executable. I am using a particular binary executable, but the question is broader, because we may want to pass string arguments to all kinds of binary executables.
I understand that the behavior described below may turn out to be very special to the binary executable I am calling. But I suspect that what I am describing is a reflection of something basic in how bash works, in which case it could be of interest to a border range of people.
Background
This question arose in the course of me writing a bash script that uses cpdf (link), which is a binary executable. The program cpdf is open source; the source code (in OCaml) is available here.
Basic usage of the binary executable in question
Suppose, in a bash terminal, the working directory contains a one-page pdf file called in.pdf.
Then the following command produces a pdf file called out.pdf containing a cropped window from in.pdf:
cpdf -crop "10pt 10pt 200pt 500pt" in.pdf -o out.pdf

The size of the crop is specified by the string "10pt 10pt 200pt 500pt" (For completeness: if the crop window has its lower-left corner at (x1,y1) and upper-right corner ar (x2,y2), then the string format is x1 y1 x2 y2—plus the units, all enclosed in quote marks.)
Using a variable to pass the crop string
The following will work:
cropstring="10pt 10pt 200pt 500pt"
cpdf -crop "$cropstring"  $filein -o out1.pdf

But the following will not:
cropstring="\"10pt 10pt 200pt 500pt\""
cpdf -crop $cropstring  $filein -o out2.pdf

If you execute the latter, it returns the error message
Bad rectangle specification "10pt

The difference is that in the first case, the enclosing quote marks are not part of the string which is contained in the variable cropstring, while in the second case, they are part of it.
Questions
Is this behavior likely to be very specific to cpdf, or is it reflective of some general properties of bash? If the latter, then two more questions: why doesn't the second way work? Is there a way to define the variable cropstring so that the second way (meaning, all required quote marks are somehow included in the content of the variable) does work?

A: The problem you have here is that cpdf is not a string interpreter like echo or printf and so on. In your case cpdf doesn't know how to interpret your escaped string and when you pass this "so called" variable (cropstring) to cpdf binary you actually tell to bash like this: pass to cpdf script this argument in which you close double-quote and after \"10pt you have a space which means cpdf jump to next argument (input file) and leave away this part of string 10pt 200pt 500pt\" (that means that your script will take 10pt as a single argument and that is unfortunate because your binary script expect other 3 arguments). This is why your binary raise an error because it cannot crop a window having just one argument 10pt. It expects yet 3 arguments in a string.
This is how your binary script will exit (with an error) and tell you that there is a Bad rectangle specification "10pt.
The arguments that you pass to cpdf are good in first example but in the second example are wrong. I described earlier how bash interpret parameters. In the first example your binary script treat cropstring as a string variable and in the second example it will pass only the first argument which is 10pt.
To respond to your answer, it is the way bash interpret strings and your script and not a problem of cpdf binary.
The line in which you write:
cropstring="\"10pt 10pt 200pt 500pt\""
can be interpreted well only by a text interpreter (you can play writing echo -e $cropstring) but NEVER in bash command line. When you pass your variable as an argument to some bash script, bash see your variable like cpdf -crop ""10pt. That's all because the rest of the string will be seen as file.in argument. The error occurs because your string parameter asked by crop argument is just 10pt and thus, the binary doesn't know how to crop that window.


Q: how to split one string in a column into two string pandas I have 2 STRING dataframe, each data is given name as dataset and colloquial.
dataframe colloquial:
|**wrong**  | **correct** |
|sheis      | she is      |
|taht       | that        |
|diedwhen   | died when   |

The second dataframe is dataset with specific column that I use that look like this:
dataframe dataset['review'] :
review
[shewas, wrong, but, her, intentions, are, good]
[is, taht, you]
[he, diedwhen, he, was, young]

I want to change the wrong word in the dataset['review'] into the correct word according to dataframe colloquial. I use this:
normalizad_word = pd.read_excel("colloquial.xlsx")

normalizad_word_dict = {}

for index, row in normalizad_word.iterrows():
    if row[0] not in normalizad_word_dict:
        normalizad_word_dict[row[0]] = row[1]

def normalized_term(document):
    return [normalizad_word_dict[term] if term in normalizad_word_dict else term for term in document]

dataset['review_normalized'] = dataset['review'].apply(normalized_term)

dataset['review_normalized']

BUT the result is like this:
review_normalized
[she was, wrong, but, her, intentions, are, good]
[is, that, you]
[he, died when, he, was, young]

I want it to be like this:
review_normalized
[she, was, wrong, but, her, intentions, are, good]
[is, that, you]
[he, died, when, he, was, young]

A: Change normalized_term function:
def normalized_term(document):
    result = []
    for term in document:
        if term in normalizad_word_dict:
            for word in normalizad_word_dict[term].split(' '):
                result.append(word)
        else:
            result.append(term)
    return result

Or if you want to use inline loop:
import itertools
def normalized_term(document):
    return list(itertools.chain(*[normalizad_word_dict[term].split() if term in normalizad_word_dict else term.split() for term in document]))


Q: resigning the keyboard swift 1.2 So I just updated to swift 1.2 and now my code to resign the keyboard wont work?
the code is:
override func touchesBegan(touches:NSSet, withEvent event: UIEvent) {
self.view.endEditing(true)

the error says Overriding method with selector "touchesBegan:withEvent:" has incompatible type

A: Try replacing NSSet with Set<NSObject>
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    self.view.endEditing(true)
}

The syntax has been edited in swift 1.2. The NSSet was replaced by Set<NSObject>
See the Blog Post and the Xcode 6.3 release notes


Q: PHP separate acces to some links I have a table in DB where I put all the admins and their rights. I am setting theri rights with letters A-Z and each letter has access to something else. The thing is I want to check where they have access and show links only to those areas. For now I got an idea to put all those letters in some aray with for loop and then when rendering the menu output only those items where they have access with if (in_array(letter, rights)) I think this would work but I would like to know whether there is another way

A: I wrote a PHP class that I use in all my projects that require different access for different roles.  I put a copy of the class out on paste bin: class_role_restrictions.php.
This class also requires another class I wrote, which can be obtained here: better_mysqli.php
The initial setup involves the creation of some database tables (The SQL create statements are found in comments at end of the class_role_restrictions.php file) and adding roles / user memberships via it's admin interface.
Detailed setup/usage can be obtained here: role_restrictions_detailed_example.php
Once it is setup you can use it like this:
<?php

  include_once('class_role_restrictions.php');
  include_once('better_mysqli.php');

  $mysqli = new better_mysqli('your_server', 'your_user', 'your_pass', 'your_db_name');
  if (mysqli_connect_errno()) {
     error_log(sprintf("Can't connect to MySQL Server. Errorcode: %s\n", mysqli_connect_error()));
     exit;
  }

  $role = new role_restrictions($mysqli, 'http://your_server.com/path/to/this/page/example.php');

  // == Restrict an entire page to authorized users only ==
    $role->restrict_to('role_name, to_restrict user_to', 'username_currently_logged_in');
  // .. now do stuff that only users in any of the roles listed are allowed to do

  // -- OR --

  // == Only do certain things if the username given is a member of any of the roles given ==
  if( $role->has_role('a_list, of_roles, allowed', 'username_currently_logged_in') ){
      // .. do stuff that only users in the given role(s) are allowed to do ..
  }

?>


Q: Duplicates removal from different excel files at a time I have 5 folders and each folder consists of around 20 excel sheets.
And these excel sheets contain duplicates within it. It is becoming very hectic to open every file and remove duplicates.
Is there anyother way to remove duplicates from all these files at once ?
All the files contain different set of duplicates and no common columns will be present.

A: XD I'm really understanding your situation but I think that the solution will be one of two :) :
1-make a program with any programming language you can use and try to load the files one by one to do what you want
2-(the easiest one)Try to find a good converter to convert all your files to SQL tables then come here to this site and ask how to delete duplicated rows from different SQL tables after doing that reconvert the SQL tables to EXCEL files again and it will be done (y) ;)


Q: Bash: using parameter expansion to add variables at front and end simultaneously How can i use parameter expansion to add strings at front and end at the same time.
Currently i'm doing this in two steps:
base_test_path=something
folder=anotherthing
test=(abc cde)

halfPaths=("${test[@]/#/$base_test_path}")
fullPath=("${halfPaths[@]/%//$folder/}")

can i eliminate one step here.


Q: Is JQuery namespace a good practice? Can anyone explain to me please that if using a namespace is a good coding practice. And why is it needed? If it was a good approach why JQuery didn't include it by default. There is a separate plugin to allow this functionality.
I saw this post that mentions few ways to do it. Someone mentioned about memory leak in the post that is worrisome.
Lastly, what is the best way to organize JQuery libraries?
thanks,

A: Re: best ways to organize jQuery libraries, you should start by reading the Plugins Authoring article on jquery.com:
http://docs.jquery.com/Plugins/Authoring

A: Notes:

*

*Namespacing is a good practice because you have less chance of having conflicting names with other scripts. This way, only your name-space has to be unique, but multiple name-spaces can have the same functions in them.

*jQuery DOES use namespacing, and you do not need the plug-in. The jQuery object itself is a name-space. . . Any function inside jQuery is 'name-spaced' in the jQuery object.  This is true for any JavaScript object.

In response to Amir's comment:
YUI achieves namespacing by adding a variable to the YUI object where the added variable is also an object.  Their namespace function just builds it for you.
var lib = {
    util:{},
    widget:{},
    tool:{}
};

//creates a function named reset in the lib.util namespace
lib.util.reset = function() {};

//creates a function named reset in the lib.widget namespace
lib.widget.reset = function() {};

In jQuery, you add it to the jQuery.fn (or $.fn if you use $ for jQuery() namespace.

A: require.js is a better practice because it doesn't require you to add objects onto the window object unnecessarily. It also doesn't mean you have to worry about the loading order of previous javascript files.


Q: Any ccTalk libraries available? I want to integrate a coin acceptor into one of our applications. This specific coin acceptor uses the ccTalk protocol (specs here).
I've been looking for a ccTalk library which I can use from C#, but until this point I've only found this open source project which seems not quite ready, and abandoned.
Any of you guys know of any ccTalk libraries out there? I can't believe this hasn't been done before. It doesn't necessarily has to be free.

A: Have you looked at cctalk-net? It's a rewrite of libcctalk and has been worked on up to August 2011 this year. It does not support everything in ccTalk but might just support enough for your needs.

A: I managed to come up with a solution based on the aforementioned cctalk-net project.
I hosted my project on github: https://github.com/Hitman666/nbCcTalkCoinAcceptor so I hope it will help someone. I made a full fledged documentation for an easy start (which can't be said for cctalk-net project).


Q: filter2D OpenCV function c++ I have noticed differences between the OpenCV implementation of filter2D in C++ and a direct implementation of the corresponding kernel. I have read the following question:
Opencv - how does the filter2D() method actually work?
The author of that question had tried to get a working implementation of the filter2D function. He claims that using a normalized version of filters yields correct results. I have tested his hypothesis and found that normalization gives the correct answer only when all the coefficients are positive. Thus an averaging filter can be successfully implemented using the filter2D function.[We must still normalize the kernel].
However this is not the case for filters with negative coefficients such as the Sobel,Laplacian and any edge detection filter. The author of that question has encountered the same problems as me.
https://stackoverflow.com/users/2669614/bovaz
The user mentioned above replied to the linked question. He claimed that filter2D might modify its implementation if the sum of the coefficients of  the kernel equals zero. Is that the case? Why does the implementation of filter2D in C+ give different results from a direct implementation? I have checked that filter2D in Python and a direct implementation of the corresponding kernel in C++ yield the same results.

A: It is mainly because of scaling and overflow issues.
The documentation for filter2D does not mention(atleast i did not find) whether the overflowed values are clipped or scaled appropriately to the min-max range.
This is more important in the case of directional filters, where the co-efficients are positive and negative and after the algebraic
The function 'myfilter2D' presented on the link above does not scale to the min-max range which should be the case.
If you could post the sample code then it would be easier to help.
My suggestion would be to convert the matrices to float(with scaling) and perform algebraic operations because this tends to preserve the resulting values and values are not lost due to overflow or saturation.
im2double()->"perform algebraic operations"->im2uchar() for displaying
void im2uchar( Mat & src, Mat  & dest){
  double minVal, maxVal;
  minMaxLoc(src, &minVal, &maxVal); //find minimum and maximum intensities
  src.convertTo(dest, CV_8U, 255.0/(maxVal - minVal), -minVal * 255.0/(maxVal - minVal));
  }

void im2float( Mat  & src, Mat  & dest){
  double minVal, maxVal;
  minMaxLoc(src, &minVal, &maxVal); //find minimum and maximum intensities
  src.convertTo(dest, CV_32F, 1.0/(maxVal - minVal), -minVal * 1.0/(maxVal - minVal));
  }


Q: API $http delete returns 405 when calling from factory in angular This is what I have in my factory. This was working fine when I was running it in regular ajax syntax from the controller.
function endAgentSession(sessionData, tokenData) {

            var sessionId = sessionData.data.sessionId,
                access_token = tokenData.access_token,
                baseURI = tokenData.resource_server_base_uri,
                endAgentSessionPayload = {
                    'sessionId': sessionId,
                    'forceLogOff': true,
                    'endContacts': true,
                    'ignorePersonalQueue': false
                    };

            console.log(sessionId, "sessID");

            return $http({
                'url': baseURI + 'services/v6.0/agent-sessions/' + sessionId,
                'type': 'DELETE',
                'headers': {
                    //Use access_token previously retrieved from inContact token service
                    'Authorization': 'bearer ' + access_token,
                    'content-Type': 'application/json'
                },
                'data': endAgentSessionPayload
            }).then(function(res){
               return res })};
        }

This is my controller. When I call the endAgentSession function from the controller with an ng-click, it errors out to a 405..
 $scope.endAgentSession = function(){
    agentFactory.endAgentSession($scope.sessionData, $scope.tokenData);
};

What am I doing wrong? It was working w/ ajax in the controller, then seemed to break when I moved it to the factory and used a promise.
it's actually showing it' requesting a GET request in Network..
[![enter image description here][1]][1]
full controller:
csMgmtApp.controller('launchedController', ['$scope', '$http', '$document', '$resource', 'agentFactory', '$timeout', function ($scope, $http, $document, $resource, agentFactory, $timeout) {

$scope.agentStatePayload = {};
$scope.sessionData = {};
$scope.tokenData = {};
$scope.startSessionPayload = {
    'stationPhoneNumber': '2223222222',
    'inactivityTimeout': 0,
    'inactivityForceLogout': 'false'
};

$document.ready(function () {
    $scope.tokenData = agentFactory.getToken();
    console.log($scope.tokenData);
});

agentFactory.startSession($scope.startSessionPayload, $scope.tokenData).then(function(res){
    console.log("sessionId", res);
    $scope.sessionData = res;
});

$scope.endAgentSession = function(){
    agentFactory.endAgentSession($scope.sessionData, $scope.tokenData);
};

}]);

It all seems to be working, except for the endSession, now..

A: I should have guessed that every time you said

regular ajax syntax from the controller

you meant you were using jQuery $.ajax previously.
The difference is that the property that sets the request method in Angular's $http is method, not type.
You can simplify it further using
return $http.delete(baseURI + 'services/v6.0/agent-sessions/' + sessionId, {
    headers: {
        Authorization: 'Bearer ' + access_token,
    },
    data: endAgentSessionPayload
});


Q: Declare explicit types for a dynamically created class function Say I've got this class:
class Foo {
  bar = this.createDynamicFunction((param: string) => {
    return "string" + param;
  });

  baz = this.createDynamicFunction((param: number) => {
    return 1 + param;
  });

  createDynamicFunction(fn: (param: any) => any) {
    return (param) => fn(param);
  }
}

const foo = new Foo()
foo.bar('baz') // => barbaz
foo.baz(2) // => 3

How do I declare types for the functions Foo.prototype.bar and Foo.prototype.baz? I want to explicitly say that bar and baz accept and return string and number respectively.
I realize that this is a contrived example. For some context, I'm in the final stages of rewriting one of my message queue client libraries and a lot of the class functions are dynamically created. These functions share a lot of functionality, but their inputs/outputs differ.

A: Generics are made for this:
class Foo {
  bar = this.createDynamicFunction((param: string) => {
    return "string" + param;
  });

  baz = this.createDynamicFunction((param: number) => {
    return 1 + param;
  });

  createDynamicFunction<Type>(fn: (param: Type) => Type) {
    return (param : Type) => fn(param);
  }
}

const foo = new Foo()
//console.log(foo.baz(2)) // => 3
console.log(foo.bar('baz')) // => barbaz
console.log(foo.baz(2)) // => 3

You create a generic function, for which the type can be anything. And you can define your overall function type based on that type
Playground Link


Q: ipa extraction after you download an app from iTunes We are currently providing ios app via Itunes. The main function of the app is to verify `app integrity' and it is done by checking hash value (sha256) of the execution file in .ipa once we download it.
With the 32bit app we downloaded from iTunes, we can extract .ipa file to get execution file without problems. However, it does not seem to be possible with 64bit ios apps. (maybe there is a way and we couldn't find it. if this is the case please enlighten us.) Since we are planning provide our service both with 32 and 64bit, we do need to extract execution file from 64bit app.
So there are two questions we would like to ask regarding on this ipa extraction.
1. The hash value(sha256) of the app before we upload to iTunes and the value after we download it from iTunes is different. Why is that?
2. Is there any way we can extract .ipa (32/64 bit both) after we download the app from iTunes?


Q: lock/prevent close of menu reactjs I have a side menu that opens when an icon is clicked and closes when the either the page is clicked or an item on the menu is clicked. I am trying to implement a lock so when the lock icon is clicked, the menu will not close even if you click on a menu item or on the page.
I was able to setup the icon changing from a locked one to an unlocked one but I am having trouble with the functionality of stopping the close. Any help/suggestions would be awesome. Below are the 2 components that (the parent and the menu with the lock button) here is the code sandbox for a full look: https://codesandbox.io/s/pw6q46jp20

class SideBar extends Component {
  constructor(props) {
    super(props);
    this.state = {
      category: props.category,
      currentPage: {
        backgroundColor: '#383838',
        color: '#A9A9A9',
      },
      menuLocked: false,
      menuOpen: false,
      selectedIcon: null,
    };
  }
  handleIconClick = (category) => {
    this.setState({
      category,
      menuOpen: true,
      selectedIcon: category,
    });
  };
  handleMenuItemClick = (category) => {
    this.setState({
      menuOpen: false,
      selectedIcon: '',
      currentPage: category,
    });
  }
  handlePageClick = () => {
    this.setState({
      menuOpen: false,
    });
  }
  handleMenuLock = () => {
    this.setState({ menuLocked: !this.state.menuLocked });
  }
  render() {
    return (

        <TopBar {...this.props} />
        <Container>
          <SideNav>
            <ListWrapper>
              <IconList
                currentPage={this.state.currentPage}
                openMenu={this.handleIconClick}
                selectedIcon={this.state.selectedIcon}
                visible={this.state.menuOpen}
              />
            </ListWrapper>
          </SideNav>
          <PageContentWrapper>
            <Sidebar.Pushable>
              <PushMenu
                category={this.state.category}
                closeOnItemClick={this.handleMenuItemClick}
                handleMenuLock={this.handleMenuLock}
                menuLocked={this.state.menuLocked}
                params={this.props.params}
                visible={this.state.menuOpen}
              />
              <Sidebar.Pusher
                onClick={this.handlePageClick}>
                <Segment basic>
                  {this.props.children || <Home />}
                </Segment>
              </Sidebar.Pusher>
            </Sidebar.Pushable>
          </PageContentWrapper>
        </Container>

    );
  }
}

SideBar.propTypes = {
  children: PropTypes.any,
  params: PropTypes.any,
  category: PropTypes.any,
};

export default SideBar;

class PushMenu extends React.Component {
  render() {
    const category = sideNavData.lookupCategory(this.props.category);
    const menuLockButton = !this.props.menuLocked
      ? <Icon
        link={true}
        name='unlock'
        size='big'
      />
      : <Icon
        link={true}
        name='lock'
        size='big'
      />;
    return (
      <Sidebar
        className='Push-menu'
        animation='push'
        width='thin'
        visible={this.props.visible}
      >
        {this.props.category}
        <Linebreak />
        {
          Object.keys(category).map((subCategory, index) => {
            return (

                <SubcategoryHeader>{subCategory}</SubcategoryHeader>
                <List>
                  {
                    Object.keys(category[subCategory]).map((item, index) => (

                        <ListLink>
                          <Link
                            to={`/${this.props.category}/${subCategory}/${category[subCategory][item].name}`}
                            activeStyle={{ color: '#FFFFFF' }}
                            onClick={() => {
                              this.props.closeOnItemClick(this.props.category);
                            }}
                          >
                            {category[subCategory][item].name}
                          </Link>
                        </ListLink>

                    ))
                  }
                </List>
                <LockButtonWrapper onClick={this.props.handleMenuLock}>
                  {menuLockButton}
                </LockButtonWrapper>

            );
          })
        }
      </Sidebar>
    );
  }
}

PushMenu.propTypes = {
  category: PropTypes.any,
  closeOnItemClick: PropTypes.func,
  currentPage: PropTypes.func,
  handleMenuLock: PropTypes.func,
  menuLocked: PropTypes.bool,
  visible: PropTypes.bool,
};

export default PushMenu;

A: You can change your handlePageClick method to setState only when this.state.menuLocked is false.

  handlePageClick = () => {
    if (!this.state.menuLocked) {
      this.setState({
        menuOpen: false,
      });
    }
  }

A: Inside of handlePageClick() you should do a check to see if this.state.menuLocked is true. If so, don't change the value of menuOpen in state.
handlePageClick = () => {
  if (!this.state.menuLocked) {
    this.setState({
      menuOpen: false,
    });
  }
}

As a side note, in handleMenuLock() you are using the previous value of menuLocked to set the new value. Since setState is asynchronous, it's entirely possible that the value of menuLocked has changed by the time it actually saves and so you may not get the desired result. As such, you should pass it a function like this:
handleMenuLock = () => {
  this.setState((prevState) => ({ menuLocked: !prevState.menuLocked }))
}

This ensures that the value is actually toggled. Docs on using setState in this manner can be found here.


Q: Google Apps Script refresh sheet while function is running I have some script in my Google Sheets/ It can take a lot of time to finish all this script (up to 5 minutes I think). And I want to show some message that user should just wait a little. So I have some code like:
function test(){
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var cell = sheet.getRange("A1");
  sheet.clear();
  cell.setValue('WAIT!!!!');
  DATA = UrlFetchApp.fetch(url);
  // And some action that takes a lot of time ....
  cell.setValue('DONE!!!!');

But it doesn't show "WAIT" it only shows me "DONE" when everything is ok. It can only show me "WAIT" if there was any error and function crashed. It looks like I need to refresh it somehow.

A: Call the flush()method after you set the cell value to wait.
SpreadsheetApp.flush(); //Applies all pending Spreadsheet changes.


Q: IE11 moves cursor to beginning of input when editing value I have a really odd problem on a project.  Long Story Short, I have input fields that record interest rate, so a % is appended on blur and removed on focus.  It works fine on every browser except for IE11.  For some reason, it moves the cursor to the beginning of the input, which is annoying for people tabbing through and typing in values quickly.
Here is a simplified example in:

$('#test').val('default');

$('#test').focus(function() {
    var value = $(this).val().slice(0, -1);
    $(this).val(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test" />

Again, this only happens in IE11 (works fine in older versions of IE).  Has anyone run into this issue before?  I tried forcing focus again after the value is reassigned, but that didn't solve the issue.  Any tips are appreciated.

A: You could try to set caret position manually when appending/removing % mark, using those two functions (those are pretty generic and should work for every browser if you need setting caret positions for all browsers some other time):
function getCaretPosition(element) {
  var caretPos = 0;
  if (element.type === 'text' || element.type === 'tel') {
    if (document.selection) { // IE Support
      element.focus();
      var Sel = document.selection.createRange();
      Sel.moveStart('character', -element.value.length);
      caretPos = Sel.text.length;
    } else if (element.selectionStart || element.selectionStart === '0') {// Firefox support
      caretPos = element.selectionStart;
    }
  }

  return caretPos;
}

function setCaretPosition(element, position) {
  if (element.type === 'text' || element.type === 'tel') {
    if (element.setSelectionRange) {
      element.focus();
      element.setSelectionRange(position, position);
    } else if (element.createTextRange) {
      var range = element.createTextRange();
      range.collapse(true);
      range.moveEnd('character', position);
      range.moveStart('character', position);
      range.select();
    }
  }
}

And call them only when using IE11 :) Also, if you want, you could make those functions more specific, removing parts for FF :)

A: This issue can be solved by:

*

*getting a reference to the input element

*adding an onfocus event handler

Then setting the selection range in the onfocus handler to the end of the input value, like so:
const onFocus = (el) => {
  const { value } = el.value
  el.setSelectionRange(value.length, value.length);
}

<input type='text' onfocus='onFocus(this)'  />

If you are using ReactJS, here is that solution.


Q: How to get the constructor name in Node.js from super class I have a "super" module in my Node.js application with a constructor and some prototype functions.
var parser = function(options, util, cache, url) {

    this.options        = options;
    this.util           = util;
    this.cache          = cache;
    this.url            = url;
}

parser.prototype.start = function() {
    console.log("I am a default start function");
    console.log(this.constructor.name);
}

module.exports = parser;

I have a handful of other modules that inherit from this module. Now, when i invoke the start function i would like to get the name of that module's constructor. For some reason this is not working for me.
var parser = require('../parser');
var util   = require('util');

var DKAN = function(options, util, cache, url) {

    parser.apply(this,arguments);

}

util.inherits(DKAN, parser);

DKAN.prototype.check = function($) {
    var DKANParser = this;
    if ($('meta[content*="Drupal"]').length !== 0 ) {
        DKANParser.start();
        return true;
    } else return false;
}

module.exports = DKAN;

When invoking the DKANParser.start() i only get the first console.log with "I am a default start function" and cannot get the name of constructor whih is supposed to be DKAN


Q: Overwriting HDFS file/directory through Spark Problem
I have a file saved in HDFS and all I want to do is to run my spark application, calculate a result javaRDD and use saveAsTextFile() in order to store the new "file" in HDFS.
However Spark's saveAsTextFile() does not work if the file already exists. It does not overwrite it.
What I tried
So I searched for a solution to this and I found that a possible way to make it work could be deleting the file through the HDFS API before trying to save the new one.
I added the Code:
FileSystem hdfs = FileSystem.get(new Configuration());
Path newFolderPath = new Path("hdfs://node1:50050/hdfs/" +filename);

if(hdfs.exists(newFolderPath)){
    System.out.println("EXISTS");
    hdfs.delete(newFolderPath, true);
}

filerdd.saveAsTextFile("/hdfs/" + filename);

When I tried to run my Spark application, the file was deleted but I get a FileNotFoundException.
Considering the fact, that this exception occurs when someone is trying to read a file from a path and the file does not exist, this makes no sense because after deleting the file, there is no code that tries to read it.
Part of my code
 JavaRDD<String> filerdd = sc.textFile("/hdfs/" + filename)    // load the file here
 ...
 ...
 // Transformations here
 filerdd = filerdd.map(....);
 ...
 ...

 // Delete old file here
 FileSystem hdfs = FileSystem.get(new Configuration());
 Path newFolderPath = new Path("hdfs://node1:50050/hdfs/" +filename);

 if(hdfs.exists(newFolderPath)){
    System.out.println("EXISTS");
    hdfs.delete(newFolderPath, true);
 }

 // Write new file here
 filerdd.saveAsTextFile("/hdfs/" + filename);

I am trying to do the simplest thing here but I have no idea why this does not work. Maybe the filerdd is somehow connected to the path??

A: The problem is you use the same path for input and output. Spark's RDD will be executed lazily. It runs when you call saveAsTextFile. At this point, you have already deleted the newFolderPath. So filerdd will complain.
Anyway, you should not use the same path for input and output.


Q: lambda function does not update the reference array I have a method which basically updates each value of the passed reference array by 5.
Initially I tried the below options but it wouldn't update the reference array.
Option 1:
void Int_Array_Update(std::vector<int>& param)
{
    auto f1 = [](int n) { return n + 5; };
    std::for_each(param.begin(), param.end(), f1);
}

Option 2:
void Int_Array_Update(std::vector<int>& param)
{
    auto f1 = [&](int n) { return n + 5; };
    std::for_each(param.begin(), param.end(), f1);
}

Option 3:
void Int_Array_Update(std::vector<int>& param)
{
    auto f1 = [&param](int n) { return n + 5; };
    std::for_each(param.begin(), param.end(), f1);
}

The workaround I have currently is as below:
void Int_Array_Update(std::vector<int>& param)
{
    for (int i = 0; i < param.size(); ++i)
        param[i] = param[i] + 5;
}

I am not able to find any answers why the lambda function is not updating the reference vector or maybe I am doing something wrong. Any help is appreciated.

A: std:.for_each does not update the elements in the range the way you expect. std::for_each applies the lambda to each element, but does not care about the return value from the lambda.
You want std::transform for that:
std::transform(param.begin(), param.end(), param.begin(), f1);
//                                         ^^^^^^^^^^^^^
//                                              |
//                it starts writing the result here

To work with std::for_each you would need to receive the argument by-reference in the lambda and make the update to the argument directly instead of returning it:
auto f1 = [](int& n) { n += 5; }; // int& and add to n directly
std::for_each(param.begin(), param.end(), f1);


Q: phpseclib - Parse mysql query to array I do a mysql select query over ssh2 with phpseclib.
I get my result back. If I add nl2br(), it's kind of readable (every row is on a seperate line). But I still can't access the columns of the rows.
How can I properly parse the output of a phpseclib ssh2 mysql query into a recursive array?
This is how I do my query:
$output = $ssh->exec('mysql -uMyUser -pMyPassword MyTable -e "SELECT * FROM users LIMIT"');

A: Doing str_replace("\t", ',', $output) would probably work.
Here's how you'd get it into an associative array (not what you asked but it could prove useful to helping you understanding how the output is formatted):
$output = $ssh->exec('mysql -uMyUser -pMyPassword MyTable -e "SELECT * FROM users LIMIT"');
$output = explode("\n", $output);
$colNames = explode("\t", $output[0]);
$colValues = explode("\t", $output[1]);

$cols = array_combine($colNames, $colValues);


Q: AWS EBS volume attachement using snapshot I am trying with AWS EBS volume. I created an EC2 Server using the AMI rancheros-v0.7.1-hvm-1. Then I attached volume and mounted to /var/lib/docker folder. Then I run few docker images on that server and I am able to access those applications also.
Later I created a snapshot of the volume. and launched another server using the same AMI and attached an EBS volume from the snapshot I created earlier and mounted to /var/lib/docker folder.
After that I ssh to the second server and did docker PS. But no docker Images are running there.
When I do df -kh command on first server the output was:
Filesystem                Size      Used Available Use% Mounted on
/dev/xvdb                29.4G      1.2G     26.7G   4% /var/lib/docker
/dev/xvdb                29.4G      1.2G     26.7G   4% /var/lib/docker/overlay
overlay                  29.4G      1.2G     26.7G   4% /var/lib/docker/overlay
.........

And followed by the docker images running.
But when I did the same command on the second server I got the output like this:
Filesystem                Size      Used Available Use% Mounted on

/dev/xvdb                29.4G     44.1M     27.8G   0% /var/lib/docker
/dev/xvdb                29.4G     44.1M     27.8G   0% /var/lib/docker/overlay

No docker images running also.
In both servers the use% are different.
Can any one tell me how can I check both are similar, and the snapshot contains all the data in the EBS volume? If the snapshot contains the similar data in the volume, then the second server should contain the docker images. But in my case its not happening.
This is the user data I gave while creating the EC2 server.
#!/bin/sh

sudo mkfs.ext4 /dev/xvdb

mkdir -p /var/lib/docker
echo "/dev/xvdb /var/lib/docker ext4 defaults 0 0" >> /etc/fstab
mount /dev/xvdb /var/lib/docker -t ext4

chown -R 1000 /var/lib/docker

Can anyone tell me a solution for this?

A: It worked now.
the server which I created from snapshot I should not create the file system. I have to remove this command
sudo mkfs.ext4 /dev/xvdb
from the user data. just create the folder and mount it. then it worked.


Q: How to add text into along the object using three.js I have added text into my object (a shirt model) using a text geometry. Here is my code:
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
ctx.font = 'italic 18px Arial';
ctx.textAlign = 'center';
ctx. textBaseline = 'middle';
ctx.fillStyle = 'red';
ctx.fillText('Your Text', 150, 50);`

My output looks like this:

The text does not fit into the shirt model. If I rotate the shirt model means text showing irrelevant view. I want to fit the text into the shirt model like this:

How can I fit my dynamic text into the shirt model using three.js.

A: if you are searching for " How to fit a 3D text in a 3D object" I will explain how to do this, lets begin with the theory,
Imagine having a flag with the form of the flag given sin(2*pi) if your camera is watching from y axis (three js axes) then you gonna add a text that exactly fits the function sin(2*pi), right?

so,
as you can see the idea of this is trying to get some tangets of sin(x) function, the secret of this is to cut the text in the number of tangents that will fit your text...
for the text, "Montiel Software" it will be now ["Mon","tiel","Soft","Ware"]
Flag:
function flag(u,v,vector)
{
var x = 10*u;
var y = 10*v;
var z = Math.sin(2*Math.PI*u) ;
vector.set(x,y,z);}

Create the Geometry:
var geometry_sin = new THREE.ParametricGeometry(flag, 100, 100);
var material_sin = new THREE.MeshPhongMaterial({map:groundTexture,side:THREE.DoubleSide, color:0x000000} );
var flag = new THREE.Mesh( geometry_sin, material_sin );

Now add the text to flag (choose your tangents here) then the flag to scene:
var loader = new THREE.FontLoader();
loader.load('js/examples/fonts/helvetiker_regular.typeface.json',function(font){
var geometry = new THREE.TextGeometry( 'Mon', {
        font: font,
        size: 1,
        height: 0.5,
        curveSegments: 12,
        bevelEnabled: false,
        bevelThickness: 0.1,
        bevelSize: 0.1,
        bevelSegments: 0.1
    } );
    var txt_mat = new THREE.MeshPhongMaterial({color:0xffffff});
    var txt_mesh = new THREE.Mesh(geometry, txt_mat);
    txt_mesh.position.z = 0.2;
    txt_mesh.position.y = 5;
    txt_mesh.rotation.y = -Math.PI/8;
    flag.add(txt_mesh);
    var geometry = new THREE.TextGeometry( 'tiel', {
        font: font,
        size: 1,
        height: 0.5,
        curveSegments: 12,
        bevelEnabled: false,
        bevelThickness: 0.1,
        bevelSize: 0.1,
        bevelSegments: 0.1
    } );
    var txt_mat = new THREE.MeshPhongMaterial({color:0xffffff});
    var txt_mesh = new THREE.Mesh(geometry, txt_mat);
    txt_mesh.position.z = 1.2;
    txt_mesh.position.x = 2.5;
    txt_mesh.position.y = 5;
    txt_mesh.rotation.y = Math.PI/12;
    flag.add(txt_mesh);
    var geometry = new THREE.TextGeometry( '$oft', {
        font: font,
        size: 1,
        height: 0.5,
        curveSegments: 12,
        bevelEnabled: false,
        bevelThickness: 0.1,
        bevelSize: 0.1,
        bevelSegments: 0.1
    } );
    var txt_mat = new THREE.MeshPhongMaterial({color:0xffffff});
    var txt_mesh = new THREE.Mesh(geometry, txt_mat);
    txt_mesh.position.z = 0.28;
    txt_mesh.position.x = 4.5;
    txt_mesh.position.y = 5;
    txt_mesh.rotation.y = Math.PI/7;
    flag.add(txt_mesh);
    var geometry = new THREE.TextGeometry( 'Ware', {
        font: font,
        size: 1,
        height: 0.5,
        curveSegments: 12,
        bevelEnabled: false,
        bevelThickness: 0.1,
        bevelSize: 0.1,
        bevelSegments: 0.1
    } );
    var txt_mat = new THREE.MeshPhongMaterial({color:0xffffff});
    var txt_mesh = new THREE.Mesh(geometry, txt_mat);
    txt_mesh.position.z = -1;
    txt_mesh.position.x = 7;
    txt_mesh.position.y = 5;
    txt_mesh.rotation.y = -Math.PI/8;
    flag.add(txt_mesh);

} );
scene.add(flag);

that's the only way I can imagine to do this in three JS, if you are just searching to make a 3D objet, I suggest you to install 3D builder and try options there then load the object to THREE js.

A: Simply drawing the text to your 2D canvas will most likely never give you a satisfactory result. You have three possibilities to tackle this issue.

*

*Using textures loaded with a THREE.TextureLoader.

*

*several examples here: http://threejs.org/examples

*tutorial: http://www.johannes-raida.de/tutorials/three.js/tutorial06/tutorial06.htm

*Using THREE.TextGeometry:

*

*an example: https://threejs.org/docs/index.html?q=textgeo#api/en/geometries/TextGeometry

*Using a CSS3D solution.

*

*a nice blog post on this topic: http://learningthreejs.com/blog/2013/04/30/closing-the-gap-between-html-and-webgl/

Check also the UI example on the THREE.TextGeometry documentation page:


Q: Git deployment of October CMS site I set up Git deployment for most of my sites and it work really well. I have recently started to work with October, and for main pages which I create myself, I would like to work locally and then use Git to deploy new and updated pages to the live server.
It is my understanding that (apart from blog plugins for instance) October uses flat files for it's content. If I create files locally within my local install of October, can I safely Git push only the files I have worked on (html, css, js etc.) up to the site along with front matter and have them work on the remote deployment server? Will October just integrate them?

A: Yes, you can use git to deploy your site content and manage it via version control.
You can set your .gitignore to the following folders
.DS_Store
*.log
/vendor
/storage
/plugins/october
/modules/**/*
/config
/bootstrap
/themes/demo
artisan
index.php
.htaccess

And it will upload the text/theme files you add/commit.
After the git pull you might wish to do a cache refresh
php artisan cache:clear

or install the cache clear widget(https://octobercms.com/plugin/romanov-clearcachewidget)


Q: How to shrink the storage size limit of IPFS? I am using IPFS and trying to understand its structure.
ISSUE: 1
The issue I am facing is that when I am trying to shrink the storage size of IPFS (for testing it is taking so long time, hence I just want to shrink File System for a while) but is unable to shrink.
I tried to configure the config file by changing the StorageMax limit
using this command

ipfs config Datastore.StorageMax 1GB

but still it does not work, it accepting (ipfs add ) the files after the 1GB also, why he is not limiting the file-storage?
anyone, please suggest me How to reduce file-system size?
ISSUE: 2
Even in case of IPFS's default storage limit (Which is 10 GB), I saw when I am adding the files on IPFS it is not stopping to store files after crosses 10GB (which was limit).
It should not be cross after the limit ends, for this what to do?
below is the config file
{
  "API": {
    "HTTPHeaders": {}
  },
  "Addresses": {
    "API": "/ip4/0.0.0.0/tcp/5001",
    "Announce": [],
    "Gateway": "/ip4/0.0.0.0/tcp/8080",
    "NoAnnounce": [],
    "Swarm": [
      "/ip4/0.0.0.0/tcp/4001",
      "/ip6/::/tcp/4001"
    ]
  },
  "Bootstrap": [
    "/dnsaddr/bootstrap.libp2p.io/ipfs/QmNnooDu7bfjPFoTZYxMWUQJyrVwtbZg5gBMjTezGAJN",
    "/dnsaddr/bootstrap.libp2p.io/ipfs/QmQCU2EcMqAqQPR2i9bChGNJchTbq5TbXJJ16u19uLTa",
    "/dnsaddr/bootstrap.libp2p.io/ipfs/QmbLHAnMoJPWSCR5Zhtx6BX9KiKNN6tpvbUcqanj75Nb",
    "/dnsaddr/bootstrap.libp2p.io/ipfs/QmcZf59bWwK5XFi76CZX8cbBhTzzA3gU1ZjYZcYW3dwt",
    "/ip4/104.131.131.82/tcp/4001/ipfs/QmaCpDMGvV2BGHeYERUEQAwe3N8SzbUtfsmvsqQLuvuJ",
    "/ip4/104.236.179.241/tcp/4001/ipfs/QmSoLPppuBtQSGwKDZT2MULpjvfd3aZ6ha4oFGL1KrGM",
    "/ip4/128.199.219.111/tcp/4001/ipfs/QmSoLSafTMBsPKadTEgaXDQVcqN88CNLHXMkTNwMKPnu",
    "/ip4/104.236.76.40/tcp/4001/ipfs/QmSoLV4Bbm51jM9C4gDYZCy3U6aXMJDAbzgu2fzaDs64",
    "/ip4/178.62.158.247/tcp/4001/ipfs/QmSoLer265NRgSp2LA3dPakiS1J6DifTC88f5uVQKNAd",
    "/ip6/2604:a880:1:20::203:d001/tcp/4001/ipfs/QmSoLPppuBtQSGwKDZT2M7Lpjvfd3aZ6ha4oFGL1KrGM",
    "/ip6/2400:6180:0:d0::151:6001/tcp/4001/ipfs/QmSoLSafTMBsPKadTEgaXctVcqN88CNLHXMkTNwMKPnu",
    "/ip6/2604:a880:800:10::4a:5001/tcp/4001/ipfs/QmSoLV4Bbm51jM9C4gDYZQ9Cy3U6aXMJDAbzgu2fzaDs64",
    "/ip6/2a03:b0c0:0:1010::23:1001/tcp/4001/ipfs/QmSoLer265NRgSp2LA3dPaeykiS1J6DifTC88f5uVQKNAd"
  ],
  "Datastore": {
    "BloomFilterSize": 0,
    "GCPeriod": "1h",
    "HashOnRead": false,
    "Spec": {
      "mounts": [
        {
          "child": {
            "path": "blocks",
            "shardFunc": "/repo/flatfs/shard/v1/next-to-last/2",
            "sync": true,
            "type": "flatfs"
          },
          "mountpoint": "/blocks",
          "prefix": "flatfs.datastore",
          "type": "measure"
        },
        {
          "child": {
            "compression": "none",
            "path": "datastore",
            "type": "levelds"
          },
          "mountpoint": "/",
          "prefix": "leveldb.datastore",
          "type": "measure"
        }
      ],
      "type": "mount"
    },
    "StorageGCWatermark": 0,
    "StorageMax": "1GB"
  },
  "Discovery": {
    "MDNS": {
      "Enabled": true,
      "Interval": 10
    }
  },
  "Experimental": {
    "FilestoreEnabled": false,
    "Libp2pStreamMounting": false,
    "P2pHttpProxy": false,
    "QUIC": false,
    "ShardingEnabled": false,
    "UrlstoreEnabled": false
  },
  "Gateway": {
    "APICommands": [],
    "HTTPHeaders": {
      "Access-Control-Allow-Headers": [
        "X-Requested-With",
        "Range"
      ],
      "Access-Control-Allow-Methods": [
        "GET"
      ],
      "Access-Control-Allow-Origin": [
        "*"
      ]
    },
    "PathPrefixes": [],
    "RootRedirect": "",
    "Writable": false
  },
  "Identity": {
    "PeerID": "QmfB8xVzjndgMWHuxszYADGrwBo1Zx6zjBQQCsqARDupsW"
  },
  "Ipns": {
    "RecordLifetime": "",
    "RepublishPeriod": "",
    "ResolveCacheSize": 128
  },
  "Mounts": {
    "FuseAllowOther": false,
    "IPFS": "/ipfs",
    "IPNS": "/ipns"
  },
  "Pubsub": {
    "DisableSigning": false,
    "Router": "",
    "StrictSignatureVerification": false
  },
  "Reprovider": {
    "Interval": "12h",
    "Strategy": "all"
  },
  "Routing": {
    "Type": "dht"
  },
  "Swarm": {
    "AddrFilters": null,
    "ConnMgr": {
      "GracePeriod": "20s",
      "HighWater": 900,
      "LowWater": 600,
      "Type": "basic"
    },
    "DisableBandwidthMetrics": false,
    "DisableNatPortMap": false,
    "DisableRelay": false,
    "EnableRelayHop": false
  }
}

A: It looks like StorageMax does not actually limit the size of the IPFS node, instead it's used to determine whether or not to run garbage collection. IPFS will write until the disk is full.


Q: Loading data into json file How can i update json file from model in sap ui5?
    var oModel  = new sap.ui.model.json.JSONModel();
    oModel.loadData("json/Product.json");

I have to update my product.json file.
Please give me your suggestion...
Thank you very much in advance.

A: You cannot update a JSON file stored on your server with UI5 or any client side library. You will need a server-side script with some file writing code to do it. You should use an OData service and perform any read/write operations to it.


Q: How to fix Signal Handler assignment For Linux C programming, I have this handler and main method:
void handler(int number, signinfo_t, void *ignore){
    printf("Signaling %d\n", si->si_pid);
}

int main(){
    struct sigaction sig;
    sig.sa_flags = SA_SIGINFO;
    sigemptyset(&sig.sa_mask);
    sig.sa_handler = handler // This line has error

If I make the handler with just 1 parameter void handler(int num)
it works fine; however, I will not be able to use si->si_pid. The warning I am getting is :
 warning: assignment to __sighandler_t from an incompatible pointer type
 -Wincompatible-pointer-types
 sig.sa_handler = handler;

Do I make it sig.sa_action instead? I want to fix the warning

A: You're assigning the handler function to the wrong member of sig. The declaration of struct sigaction is:
struct sigaction {
    void     (*sa_handler)(int);
    void     (*sa_sigaction)(int, siginfo_t *, void *);
    sigset_t   sa_mask;
    int        sa_flags;
    void     (*sa_restorer)(void);
};

sig.sa_handler is a function with only one argument, the signal number. When you use the SA_SIGINFO flag, you need to assign the 3-argument function to sig.sa_sigaction instead.
int main(){
    struct sigaction sig;
    sig.sa_flags = SA_SIGINFO;
    sigemptyset(&sig.sa_mask);
    sig.sa_sigaction = handler;


Q: loading div only visible on referrer I've got a minor problem I'm trying to resolve on my website. I have it currently so that a loading screen div appears above the page when the user visits and then fades away after a set time/the page is loaded, whichever comes latest. I want this div only to appear on first visit and would prefer to avoid cookies or anything server side. From what I understand I want to utilize session storage or referrer but have not had success with implementing that. Also, subsequent pages have a less prominent and faster loading screen that will have to go away only when each individual page has been visited once during the session. The applicable code is:
css:
.js div#preloader {
    position: fixed;
    left: 0;
    top: 0;
    z-index: 1000;
    width: 100%;
    height: 100%;
    overflow: visible;
    background-color: #202020;}

#preloader {
    z-index: 1000; }

js:
 jQuery(document).ready(function ($) {
 $(window).load(function () {
    setTimeout(function(){
        $('#preloader').fadeOut(1500, function () {
        });

    },5000);

   });
});

So it's likely obvious that I'm not well informed; I'm teaching myself as I go and needless to say I have a lot to learn about javascript. If I've done something horribly wrong here, which is entirely plausible, or a working demo is required, please let me know.
Thanks!

A: You can probably accomplish what you want using the sessionStorage object. In that object, you can track which pages have been visited in the current session.
The issue you can run into with JavaScript (and the reason I said it may not be the best approach) is that, when using a library, there is always a finite amount of time that passes while the library is loaded, parsed, and executed. This makes your "only appear on the first visit" requirement somewhat difficult to accomplish in JavaScript. If you show it by default and hide it with library code, it will show briefly each time you go to the page. If you hide it by default and show it with library code, it will be briefly hidden the first time you go to the page.
One way to handle this is to use embedded JavaScript that is executed immediately after the DOM for the preloader is defined. The downside to this is that you have to know how to write cross-browser JavaScript without assistance from a library like jQuery. In your case, the JavaScript required to simply hide the preloader is simple enough that it shouldn't have any cross-browser issues.
I created a simple page that demonstrates the technique. The source for this page is:

Preloader

This is the text of the body

I also created a fiddle for it: http://jsfiddle.net/cdvhvwmm/


Q: How to upgrade to mysql 5.6 in ubuntu 12.04 I was needed to upgrade mysql 5.5 to 5.6, to avoid some issues on importing sql files.

ERROR 1293 (HY000) at line 231: Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause

How do you upgrade it?

A: Just run the following commands:
apt-get -y remove mysql-server
apt-get -y autoremove
apt-get -y install software-properties-common
add-apt-repository -y ppa:ondrej/mysql-5.6
apt-get update
apt-get -y install mysql-server


Q: Sorting string value in a case-insensitive manner in Java 8 How do I sort string values in case-insensitive order in the following?
List<Employee> listofEmployees = Arrays.asList(
    new Employee(1, "aaa", Arrays.asList(123, 345, 678)),
    new Employee(1, "bbb", Arrays.asList(91011, 121314, 1516117)),
    new Employee(2, "ccc", Arrays.asList(181920, 212223, 242526)),
    new Employee(3, "ddd", Arrays.asList(272829, 303132, 333435)),
    new Employee(4, "BBB", Arrays.asList(29, 332, 33))
);

I wrote like this:
listofEmployees.stream().sorted(Comparator.comparing(Employee::getName).reversed())
        .forEach(s -> System.out.println(s.getName()));

How do I pass a string case insensitive option here?

A: This is one of many ways:
listofEmployees.stream()
    .sorted((o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName()))
    .forEach(s -> System.out.println(s.getName()));

A: As @Tree suggested in comments, one can use the java.text.Collator for a case-insensitive and locale-sensitive String comparison. The following shows how both case and accents could be ignored for US English:
Collator collator = Collator.getInstance(Locale.US);
collator.setStrength(Collator.PRIMARY);
listOfEmployees.sort(Comparator.comparing(Employee::getName, collator.reversed()));

When collator strength is set to PRIMARY, then only PRIMARY differences are considered significant during comparison. Therefore, the following Strings are considered equivalent:
if (collator.compare("abc", "ABC") == 0) {
    System.out.println("Strings are equivalent");
}

A: You can specify it as the second argument to ignore cases:
Comparator.comparing(Employee::getName, String::compareToIgnoreCase).reversed()

A: Try this
Comparator.comparing(Employee::getName, String.CASE_INSENSITIVE_ORDER)

A: It looks like there is a Comparator that orders String objects as by compareToIgnoreCase, you can read the documentation here: https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#CASE_INSENSITIVE_ORDER

A: You can lowercase or uppercase it like this:
listofEmployees.stream()
               .sorted(Comparator.comparing((Employee e) -> e.getName()
                                 .toLowerCase()) // or toUpperCase
                                 .reversed())
               .forEach(s -> System.out.println(s.getName()));


Q: installing libjpeg for pil and Google app engine on mac Mountain Lion I'm sure there's a duplicate of this somewhere out there but I looked and am about at the end of my rope.  I'm trying get PIL working on my mac OS X 10.8 so that I can use dev_appserver.py to test an imaging feature.  First I had trouble installing PIL until I got Homebrew and installed it using brew install pil.  I was under the opinion that brew installed all the necessary dependencies but when I tried to resize a jpeg in my app, it says IOError: decoder jpeg is not available.  So I looked online and most places said I needed to (1) uninstall PIL, (2) install libjpeg from source and (3) reinstall PIL.  So, I brew uninstall PIL, and then
curl -O www.ijg.org/files/jpegsrc.v7.tar.gz
tar zxvf jpegsrc.v7.tar.gz
cd jpeg-7d/
./configure
make
make install

and finally brew install pil.  I restart dev_appserver.py and reload the page on localhost, but same error.  I tested pil out from the python command-line with
>>> from PIL.Image import Image
>>> f = open("someimagefile", "rb")
>>> i = Image()
>>> i.fromstring(f.read(), decoder_name="jpeg")
Traceback blah blah blah
IOError: decoder jpeg not available

I don't have much experience installing utilities from command-line, so I probably missed something obvious.  Again, sorry if there are duplicates, but like I said, I looked and couldn't find anything that seemed to work.

A: Finally got it working!  Thanks to @zgoda and this link.  Here are the steps I ended up with for those of you who have the same problem:
First make sure PIL is not installed.  Download libjpeg from http://www.ijg.org/files/jpegsrc.v8c.tar.gz, unpacked it, ./configure, and make.  When I tried to make install it couldn't find the directory to store the man pages so installation failed.  I looked at the information on the above link and decided to
cp -r ~/Downloads/jpeg-6d/ /usr/local/jpeg
I suspect if the installation goes fine than that line isn't necessary.
Then edit the following line in PIL's setup.py:
JPEG_ROOT = None

to
JPEG_ROOT = "/usr/local/jpeg"

finally:
$ python setup.py build
$ python setup.py install

A: PIL did not found libjpeg headers during compilation. Consult your build system documentation on how to specify headers ("includes") location, eg. as environment variables.


Q: Using Boost asio to receive commands and execute them I'm trying to make a boost server, which will receive commands and do certain things. Now I would like to create a function, that will receive a file and save it to a specific location. The problem is with serialization. I don't know how can I recognize a command in a stream in an efficint way. I tried with boost::asio::read_until. And actually my code works. First file is being sent and received perfectly. But I am getting an error (The file handle supplied is not valid) when client sends second file. I would be very grateful for every advice. Thanks in an advance!
    bool Sync::start_server() {

    boost::asio::streambuf request_buf;
    std::istream request_stream(&request_buf);
    boost::system::error_code error;

    try {

        tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), conf->def_port));
        acceptor.accept(socket); //socket is a member of class Sync
        while (true)
        {

            error.clear();

            size_t siz = boost::asio::read_until(socket, request_buf, "\n\n");

            std::cout << "request size:" << request_buf.size() << "\n";

            string command;
            string parameter;
            size_t data_size = 0;

            request_stream >> command;
            request_stream >> parameter;
            request_stream >> data_size;

            request_buf.consume(siz);//And also this

            //cut filename from path below
            size_t pos = parameter.find_last_of('\\');
            if (pos != std::string::npos)
                parameter = parameter.substr(pos + 1);
            //cut filename from path above
            //command = "save";// constant until I make up other functions
             //execute(command, parameter, data_size);

            save(parameter,data_size);//parameter is filename

        }

    }
    catch (std::exception& e)
    {
        std::cerr << e.what() << std::endl;
    }
}

And function to save file to a hard drive:
bool Sync::save(string filename, size_t filesize) {
    boost::array<char, 1024> buf;
    cout << "filesize is" << filesize;
    size_t data_size = 0;
    boost::system::error_code error;
    std::ofstream output_file(filename.c_str(), std::ios_base::binary);
    if (!output_file)
    {
        std::cout << "failed to open " << filename << std::endl;
        return __LINE__;
    }
    while (true) {

        size_t len = socket.read_some(boost::asio::buffer(buf), error);

        if (len>0)
            output_file.write(buf.c_array(), (std::streamsize)len);
        if (output_file.tellp() == (std::fstream::pos_type)(std::streamsize)filesize)
        {

            output_file.close();
            buf.empty();
            break; // file was received
        }

        if (error)
        {
            socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, error);
            socket.close(error);
            output_file.close();
            buf.empty();
            break;//an error occured
        }

    }

}

A: *

*read_until might read beyond the delimiter (therefore request_buf.size() can be more than siz). This is a conceptual problem when you implement save because you read data_size bytes from the socket, which ignores any data already in request_buf

*These things are code smells:
if (output_file.tellp() == (std::fstream::pos_type)(std::streamsize)filesize) {

(never use C-style casts). And
return __LINE__; // huh? just `true` then

And
    buf.empty();

(That has no effect whatsoever).
I present here three versions:

*

*First Cleanup

*Simplify (using tcp::iostream)

*Simplify! (assuming more things about the request format)

First Cleanup
Here's a reasonable cleanup:
Live On Coliru
#include <boost/asio.hpp>
#include <boost/array.hpp>
#include <iostream>
#include <fstream>
namespace ba = boost::asio;
using ba::ip::tcp;

struct Conf {
    int def_port = 6767;
} s_config;

struct Request {
    std::string command;
    std::string parameter;
    std::size_t data_size = 0;

    std::string get_filename() const {
        // cut filename from path - TODO use boost::filesystem::path instead
        return parameter.substr(parameter.find_last_of('\\') + 1);
    }

    friend std::istream& operator>>(std::istream& is, Request& req) {
        return is >> req.command >> req.parameter >> req.data_size;
    }
};

struct Sync {
    bool start_server();
    bool save(Request const& req, boost::asio::streambuf& request_buf);

    ba::io_service& io_service;
    tcp::socket socket{ io_service };
    Conf const *conf = &s_config;
};

bool Sync::start_server() {

    boost::asio::streambuf request_buf;
    boost::system::error_code error;

    try {

        tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), conf->def_port));
        acceptor.accept(socket); // socket is a member of class Sync
        while (true) {

            error.clear();

            std::string req_txt;

            {
                char const* delim = "\n\n";
                size_t siz = boost::asio::read_until(socket, request_buf, delim, error);

                // correct for actual request siz
                auto b = buffers_begin(request_buf.data()),
                     e = buffers_end(request_buf.data());

                auto where = std::search(b, e, delim, delim+strlen(delim));
                siz = where==e
                    ? std::distance(b,e)
                    : std::distance(b,where)+strlen(delim);

                std::copy_n(b, siz, back_inserter(req_txt));
                request_buf.consume(siz); // consume only the request text bits from the buffer
            }

            std::cout << "request size:" << req_txt.size() << "\n";
            std::cout << "Request text: '" << req_txt << "'\n";
            Request req;

            {
                std::istringstream request_stream(req_txt);
                request_stream.exceptions(std::ios::failbit);
                request_stream >> req;
            }

            save(req, request_buf); // parameter is filename
        }

    } catch (std::exception &e) {
        std::cerr << "Error parsing request: " << e.what() << std::endl;
    }

    return false;
}

bool Sync::save(Request const& req, boost::asio::streambuf& request_buf) {
    auto filesize = req.data_size;
    std::cout << "filesize is: " << filesize << "\n";

    {
        std::ofstream output_file(req.get_filename(), std::ios::binary);
        if (!output_file) {
            std::cout << "failed to open " << req.get_filename() << std::endl;
            return true;
        }

        // deplete request_buf
        if (request_buf.size()) {
            if (request_buf.size() < filesize)
            {
                filesize -= request_buf.size();
                output_file << &request_buf;
            }
            else {
                // copy only filesize already available bytes
                std::copy_n(std::istreambuf_iterator<char>(&request_buf), filesize,
                        std::ostreambuf_iterator<char>(output_file));
                filesize = 0;
            }
        }

        while (filesize) {
            boost::array<char, 1024> buf;
            boost::system::error_code error;

            std::streamsize len = socket.read_some(boost::asio::buffer(buf), error);

            if (len > 0)
            {
                output_file.write(buf.c_array(), len);
                filesize -= len;
            }

            if (error) {
                socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, error); // ignore error
                socket.close(error);
                break; // an error occured
            }
        }
    } // closes output_file

    return false;
}

int main() {
    ba::io_service svc;

    Sync s{svc};
    s.start_server();

    svc.run();
}

Prints with a client like echo -ne "save test.txt 12\n\nHello world\n" | netcat 127.0.0.1 6767:
request size:18
Request text: 'save test.txt 12

'
filesize is: 12
request size:1
Request text: '
'
Error parsing request: basic_ios::clear: iostream error

SIMPLIFY
However, since everything is synchronous, why not just use tcp::iostream socket;. That would make start_server look like this:
tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), conf->def_port));
acceptor.accept(*socket.rdbuf());

while (socket) {
    std::string req_txt, line;

    while (getline(socket, line) && !line.empty()) {
        req_txt += line + "\n";
    }

    std::cout << "request size:" << req_txt.size() << "\n";
    std::cout << "Request text: '" << req_txt << "'\n";

    Request req;
    if (std::istringstream(req_txt) >> req)
        save(req);
}

And save even simpler:
void Sync::save(Request const& req) {
    char buf[1024];
    size_t remain = req.data_size, n = 0;

    for (std::ofstream of(req.get_filename(), std::ios::binary);
        socket.read(buf, std::min(sizeof(buf), remain)), (n = socket.gcount());
        remain -= n)
    {
        if (!of.write(buf, n))
            break;
    }
}

See it Live On Coliru
When tested with
for f in test{a..z}.txt; do (echo -ne "save $f 12\n\nHello world\n"); done | netcat 127.0.0.1 6767

that prints:
request size:18
Request text: 'save testa.txt 12
'
request size:18
Request text: 'save testb.txt 12
'
[... snip ...]
request size:18
Request text: 'save testz.txt 12
'
request size:0
Request text: ''

Even Simpler
If you know that the request is a single line, or whitespace is not significant:
struct Sync {
    void run_server();
    void save(Request const& req);

  private:
    Conf const *conf = &s_config;
    tcp::iostream socket;
};

void Sync::run_server() {
    ba::io_service io_service;
    tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), conf->def_port));
    acceptor.accept(*socket.rdbuf());

    for (Request req; socket >> std::noskipws >> req; std::cout << req << " handled\n")
        save(req);
}

void Sync::save(Request const& req) {
    char buf[1024];
    size_t remain = req.data_size, n = 0;

    for (std::ofstream of(req.get_filename(), std::ios::binary);
        socket.read(buf, std::min(sizeof(buf), remain)), (n = socket.gcount());
        remain -= n)
    {
        if (!of.write(buf, n)) break;
    }
}

int main() {
    Sync().run_server();
}

That's the entire program in ~33 lines of code. See it Live On Coliru, printing:
Request {"save" "testa.txt"} handled
Request {"save" "testb.txt"} handled
Request {"save" "testc.txt"} handled
[... snip ...]
Request {"save" "testy.txt"} handled
Request {"save" "testz.txt"} handled


Q: change directory with python I coincidentally found out that I cannot change the actual directory from within a python-code. My Test-Program is as follows:
from os import system

def sh(script):
    system("bash -c '%s'" % script)

sh("cd /home")
sh("pwd")

The output of pwd is not /home, but the directory where the code above lives.
Can someone explain why this happens?

A: The problem is that you execute shell commands instead of actually changing the directory using os.chdir()
Each os.system() call executes the given command in a new shell - so the script's working directory is not affected at all.

A: The directory actually is changed, but in another process, the child of your script. There's one simple rule to remember: a child can never affect the environment (PATH, CWD etc) of its parent.

A: sh("cd /home")
sh("pwd")

^ this spawns 2 separate shells, try:
sh("cd /home; pwd")

A: When you run sh function you spawn a new bash process which then changes current directory and exits.  Then you spawn a new process which knows nothing about what happened to the first bash process.  Its current directory is, again, set to the home directory of the current user.
To change Python process' current working directory use
os.chdir("blah")`

A: Each sh( ) call is generating a different shell, so you are affecting the shell's working directory, not python's.  To change pythons working directory, use chdir()


Q: Delete link for user isn't showing up I am new to web development (I have been coding for about 6/7 months now) in hopes of building my own app. I have been reading and working of the Ruby on Rails tutorial by Michael Hartl.  I am on the chapter 9 section deleting users and am stuck. Everything works for the most part  except that the user link. It just doesn't show on the display page. The users and their avatars fine. I just can't figure out a way to get the user delete link to show.  Below is the code for the user model, the user controller, the session controller where the code current user lives and the view.
Also, when ever i take out the if statement from the user partial the delete link shows. I am not sure whats wrong since I already defined admin, and the current_user.
I would be entirely grateful for any kind of guidance. My project is also on github if the information below isn't sufficient enough
https://github.com/krischery2150/Try2150-master/tree/updating-users
class UsersController < ApplicationController
  before_action :logged_in_user, only: [:index, :edit, :update, :destroy]
  before_action :correct_user,   only: [:edit, :update]
  before_action :admin_user,     only: :destroy

  def new
    @user = User.new
  end

  def show
    @user = User.find(params[:id])
  end

  def create
    @user = User.new(user_params)
    if @user.save
      log_in @user
      flash[:success] = "Welcome to the Sample App!"
      redirect_to @user
    else
      render 'new'
    end
  end

  def edit
    @user = User.find(params[:id])
  end

  def update
    @user = User.find(params[:id])
    if @user.update_attributes(user_params)
      flash[:success] = "Profile Updated"
      redirect_to @user
    else
      render 'edit'
    end
  end

  def index
    @users = User.paginate(page: params[:page])
  end

  def destroy
    User.find(params[:id]).destroy
    flash[:success] = "Your profile was deleted"
    redirect_to users_url
  end

  private

  def user_params
      params.require(:user).permit(:username, :email, :password,
                                  :password_confirmation, :user_about_me,
                                  :birthday, :avatar, :gender)

  end

  ##Before filters method
  # Confirms that a given user is logged in. Only when these conditions are met the user will
  # be able to update or edit their page

  def logged_in_user
    unless logged_in?
      store_location
      flash[:danger]= "Please Log In"
      redirect_to login_url
    end
  end

# Confirms the correct user.
  def correct_user
    @user = User.find(params[:id])
    redirect_to(root_url) unless current_user?(@user)
  end

  # Confirms an admin user.
  def admin_user
    redirect_to(root_url) unless current_user.admin?
  end

end

.
class User < ActiveRecord::Base
    before_save {self.email = email.downcase}
    attr_accessor :remember_token

    has_attached_file :avatar, styles: { medium: "300x300>", thumb: "50x50>" }, default_url: "/images/:thumb/missing.png"
    validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\Z/
    # this before_save is a callback method. What it does is before it saves the email
    #address it calls back and transforms all the letters into lower case. Had to do the indexing
    #in active record in order for the method to work
    validates :username , presence: true, length: {maximum: 250}
      VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
      #code that ensures that a user  puts the right format for emails in signup
      #fields
    validates :email, presence: true, length:{maximum: 50},
                                      format:{with: VALID_EMAIL_REGEX },
                                      uniqueness:{ case_sensitive: false }
                                      #rails still assumes that uniquess is true
                                      #whether the user types CAMELcase or lowercase
    validates :password, presence: true, length:{maximum: 50}, allow_nil: true
    validates :user_about_me, presence: true
    validates :birthday, presence:true
    has_secure_password

    # Returns the hash digest of the given string.
    def User.digest(string)
      cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
                                                    BCrypt::Engine.cost
      BCrypt::Password.create(string, cost: cost)
    end

    ## returns a random user token
    def User.new_token
      SecureRandom.urlsafe_base64
    end

    # Remember a given user to the database for use of persistent sessions

    def remember
      self.remember_token = User.new_token
      update_attribute(:remember_digest, User.digest(remember_token))
    end

    ##returns true if given token matches the digest
    def authenticated?(remember_token)
      return false if remember_digest.nil?
      BCrypt::Password.new(remember_digest).is_password?(remember_token)
    end

    def forget
      update_attribute(:remember_digest, nil)
    end

    def log_out
      forget(current_user)
      session.delete(:user_id)
      @current_user = nil
    end
  end

This is the code in the partial rendering on the index page where all users show up.

      <%= image_tag user.avatar.url %>

    <%= link_to user.username, user %>
    <% if current_user.admin? && !current_user?(user) %>
     | <%= link_to "delete", user, method: :delete,
                                   data: { confirm: "You sure?" } %>
      <% end %>

A: The delete link in your partial has two conditions that are required to be true. The user must be an admin, and the profile must not be their own profile. So if the admin user is the only user, then no delete link will show up.
Try creating a second user and see if the delete link shows up for that user.


Q: What's the best way to update some properties of an object immutably in JavaScript? Say we have an object like:
const obj = {
  foo: {
    a: { type: 'foo', baz: 1 },
    b: { type: 'bar', baz: 2 },
    c: { type: 'foo', baz: 3 }
  }
}

Now I want to update all properties' baz to 5 if the type of the property in foo is foo. And I would like to modify it in an immutable way, that means it would not modify the origin object but returns a new object.

A: I normally write Object.create() for shallow copy ,but deep copy (nested object) I do with JSON.parse(JSON.stringify(nestedObject))
const obj = {
  foo: {
    a: { type: 'foo', baz: 1 },
    b: { type: 'bar', baz: 2 },
    c: { type: 'foo', baz: 3 }
  }
}
var temp = JSON.parse(JSON.stringify(obj))

for(var i in temp.foo) {
  if(temp.foo[i].type == "foo") {
    temp.foo[i].baz = 5;
  }
}
console.log(temp);
console.log(obj);

A: Object.assign is perfect for this, from the docs:

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

And you can use it like this :
Object.assign(
    {},
    obj,
    {
        foo: {
            a: {
                baz: obj.foo.a.type === 'foo' ? 5 : obj.foo.a
            }
        }
    }
);

A: You can use Object.entries(), Array.prototype.map(), spread element, computed property, Object.assign()

const obj = {
  foo: {
    a: { type: 'foo', baz: 1 },
    b: { type: 'bar', baz: 2 },
    c: { type: 'foo', baz: 3 }
  }
}

let key = Object.keys(obj).pop();

let res = {[key]: Object.assign({},
          ...Object.entries(obj[key])
          .map(([prop, {type,baz}]) =>
            ({[prop]: {type,baz:type === "foo" ? 5 : baz}})
          ))};

console.log(res, obj);


Q: How do certain variables/equations affect lists? def list(a, b):
  for k in range(len(a)):
    a[k] = a[k] + b[len(b)-1-k]
  return a

When it comes to manipulating lists, how does python execute a function like this one from a line by line basis. Specifically when i'm presented with an len() or [k] in this code how does it affect a list presented by a user? An example could be
when a = [1,3,5,7,9], b = [1,4,9,8,6] the returned (a) value is [7, 11, 14, 11, 10] I'm unsure how this process is completed in Python.

A:
I am mostly confused by the introduction of [k] in the equation as I don't know how it changes the list.

someList[k] is an item accessor for the kth item of the list. So for a list a = [2, 3, 5, 7], a[k] will return the kth number. For example:
>>> a = [2, 3, 5, 7]
>>> a[0]
2
>>> a[1]
3
>>> k = 3
>>> a[k]
7

Using the accessor alone will just read the value without affecting the list. Python however does allow you to also assign a value to it. Doing so will change the list’s item at that index:
>>> a = [2, 3, 5, 7]
>>> a[2]
5
>>> a[2] = 13 # we change the value
>>> a[2]
13
>>> a # the original list was modified
[2, 3, 13, 7]

So in your loop, when you have a[k] = a[k] + something, you get the value at the kth index, add something to it, and then update the original list at the same index. Since function parameters are passed by references, this updates your original list (and you later return the identical list object from your function).
As for the “something” part, you are doing this: b[len(b)-1-k]. Again, you are using an index to access a single item of the list b. But this time, the index is not a constant or a single variable, but a more complex expression: len(b) - 1 - k. len(b) will return the length of the list b, so ultimaltely, as you iterate through the a list from the beginning, you are iterating b from the end (assuming the same length for both lists). Python will execute the expression first, so in the end it will access b’s item at the index that results from that expression.


Q: How to write numeric expressions in Makefile? I want to write statements about Podman in Makefile. A UID mapping is used here.  But I found that I was always unable to do numerical calculations.
Below is my Makefile. But here ${uid}+1 and similar operations will become empty strings. How should I solve this problem?
Thanks!
HOST_GEM5 := /mnt/disk/cuiyujie/workspace/workGem5/gem5
SIM := ${HOST_GEM5}/X86/gem5.opt
SHELL := /bin/bash
DOCKER_GEM5 := /usr/local/src/gem5

subuidSize=$(shell $(( $(podman info --format "{{ range .Host.IDMappings.UIDMap }}+{{.Size }}{{end }}" ) - 1 )))
subgidSize=$(shell $(( $(podman info --format "{{ range .Host.IDMappings.GIDMap }}+{{.Size }}{{end }}" ) - 1 )))
uid := $(shell id -u)
gid := $(shell id -g)

DOCKER_DIRS_MAP := \
    -v ${HOST_GEM5}/runScripts:${DOCKER_GEM5}/runScripts

MAP_CMD := \
    --user ${uid}:${gid} \
    --uidmap ${uid}:0:1 \
    --uidmap 0:1:${uid} \
    --uidmap $(($uid+1)):$(($uid+1)):$(($subuidSize-$uid)) \
    --gidmap ${gid}:0:1 \
    --gidmap 0:1:${gid} \
    --gidmap $(($gid+1)):$(($gid+1)):$(($subgidSize-$gid))

.PHONY: default clean run build

default: build

build:
    podman run  -it --rm  ${DOCKER_DIRS_MAP} --security-opt seccomp=unconfined  \
    ${MAP_CMD}  \
    gerrie/gem5:v1  "/bin/bash"

clean:
    rm -rf ${HOST_GEM5}/build/*

A: Make always uses /bin/sh as the shell it invokes, both for recipes and for $(shell ...) functions.  /bin/sh is a POSIX-conforming shell.  The syntax you're using is not POSIX shell syntax: it's special enhanced syntax that is only available in the bash shell.
You can either rewrite your scripting to work in POSIX shells (probably by using the expr program to do the math), or add this to your makefile to tell it you want to use bash instead of /bin/sh:
SHELL := /bin/bash

Note, of course, that your makefile will now no longer work on any system that doesn't have a /bin/bash shell.