text:
Q: How can I dynamically add input fields in visual force on a button click? I want to add a button "ADD NEW RECORD". When the button is clicked, a new row for input fields of accounts should be added along with the checkbox wrapped with it.
How can this be done?
EDIT:
Also, is there a way by which only selected accounts get updated and not the whole data? Thanks in advance.
VF PAGE
<apex:page controller="wrapAccountAndCheckbox" tabStyle="Account" >

    <apex:form id="frm">
        <apex:pageBlock title="Account Records">

                     Name
                     Fax
                     Phone

                <apex:repeat value="{!wrapClassList}" var="accountTable" id="Acnt_Table">

                         <apex:inputField value="{!accountTable.actWrap.Name}"/>
                         <apex:inputField value="{!accountTable.actWrap.fax}"/>
                         <apex:inputField value="{!accountTable.actWrap.phone}"/>
                         <apex:inputCheckbox value="{!accountTable.flag}"/>

                </apex:repeat>

            <apex:pageBlockButtons >
                <apex:commandButton value="SAVE" action="{!save}" />
                 <apex:commandButton value="DELETE" action="{!deleteAcc}" />
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>

CONTROLLER WITH WRAPPER CLASS
public class wrapAccountAndCheckbox {

    public List<wrapperClass> wrapClassList{get;set;}
    public List<Account> actList;
    public wrapperClass wc{get;set;}
    List<account> wcList=new List<account>();

    public wrapAccountAndCheckbox(){
        wrapClassList = new List<wrapperClass>();
        actList = new List<Account>();
        actList = [SELECT Id, Name, Fax, Phone FROM Account];
        For(Account ac : actList){
            wc = new wrapperClass();
            wc.flag = false;
            wc.actWrap = ac;
            wrapClassList.add(wc);
        }
    }
    public class wrapperClass{
        public boolean flag{get;set;}
        public Account actWrap{get;set;}

    }

    public void updateDetails()
    {
        if(wrapClassList!=null)
        {   wcList.clear();
            for(wrapperClass wc: wrapClassList)
            {   if(wc.flag==true)
            {wcList.add(wc.actWrap);
            }
            }
        }
    }
    public pageReference save()
    {updateDetails();
     update wcList;
     PageReference pageRef = new PageReference('https://cunning-badger-419701-dev-ed--c.ap4.visual.force.com/apex/AccountActions');
     return pageRef;
    }

    public pageReference deleteAcc()
    {
        updateDetails();
        try{
            for(Account a:actList)
            {   if(wcList.contains(a))
                delete a;}
        }
        catch(Exception e){
            system.debug('Exception in Delete>>>>'+e);
        }
        PageReference pageRef = new PageReference('https://cunning-badger-419701-dev-ed--c.ap4.visual.force.com/apex/AccountActions');
        return pageRef;
    }

}

A: This is a very common requirement.  First add a Add row button with ypur table
<apex:commandButton value="Add More" action="{!addNewRow}" rerender="frm" Status="status" immediate="true" />

and then in your controller add row in existing list
public void addNewRow() {
    wrapperClass wc = new wrapperClass();
    wc.flag = false;
    wc.actWrap = new Account();
    wrapClassList.add(wc);
}


text:
Q: Xcode shows wrong behaviour fir signing certificate Hy,
I am using Xcode 8.2.1. Bundle identifier belongs to distribution. I correctly chose the Team. I have downloaded all provisioning profile from Xcode > Preferences > Apple IDs > Team etc etc.
Why Xcode always show 'iPhone developer' instead of 'iPhone distribution'? Please see both images below.
More info: My system Keychain Access exactly have 4 certificates. Two of them, are for developer and distribution, other two are for push - development and distribution.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Check for a character in a list of strings Python's in doesn't work on whole columns:
> dfTrain['name'][22]
  'McGowan, Miss. Anna "Annie"'

> "\"" in dfTrain['name'][22]
  True

> "\"" in dfTrain['name']
False

How can I check if a character is present in a list of strings?

A: "\"" in dfTrain['name'][22] is 'McGowan, Miss. Anna "Annie"' which contains "\"
while dfTrain['name'] is a list and you dont have a "\" as element in list
Similar example as yours:
>>> nested_list_example = ["abhishek","ralesh","wr'"]
>>> "wr'" in nested_list_example
True
>>> "'" in nested_list_example
False
>>> "'" in nested_list_example[2]
True

A: There can be several ways of doing this:
1) One of the things you can do is
"\"" in dfTrain['name'].to_string()

This returns True if any of the names in the df contain a ".
2) The other way could be not dfTrain[dfTrain['name'].str.contains('"')].empty
This is because, I am finding all columns that contain ".
If there are no columns that contain " it means the dataframe returned will be empty.
If the dataframe returned is empty(True) then none of the columns contain a " for which you want the output 'False' (hence the 'not' statement')

A: you can join() elements in each row into one string and use contains() in order to check whether it contains ":
In [11]: df
Out[11]:
                                      name
0                           [test1, test2]
1                           [another test]
2                      [yet, another test]
3  [McGowan, Miss. Anna "Annie", aaa, bbb]

In [12]: df['name'].str.join('').str.contains('"')
Out[12]:
0    False
1    False
2    False
3     True
Name: name, dtype: bool


text:
Q: Prevent Fortran_MODULE_DIRECTORY creating empty directories When I use Fortran_MODULE_DIRECTORY in my CMakeLists.txt file for a target, an empty directory is automatically created, even if there are no module files there.
Can I prevent it, or at least remove the empty directories after building? This is no big deal, especially for an out-of-source build, but since I have many targets, I'd prefer not having many empty directories (and it would also let me see which targets create module files).
(I think the same happens with EXECUTABLE_OUTPUT_PATH, but I usually don't have it empty.)


text:
Q: Mongoid Rails 5 convert string with multiple arguments to symbolized value for order_by method I have a controller method where I'm trying to pass a string with multiple order_by arguments to return a sorted collection.
The order_by syntax works with one stringified argument,
i.e.
order_param = "image_fize_size DESC"

query.order_by(order_param)

>> #<Mongoid::Criteria
selector: {...},
options: {:sort => {"image_file_size"=> -1}}
class: ...>

Due to mongoid transforming the string behind the scenes
Is there a certain syntax I can use to pass multiple arguments as one string to the order_by method without any complex string manipulation required?
i.e.
order_param = "image_file_size DESC created_at DESC"

query.order_by(order_param)
# to hopefully yield a criteria that looks like:
>> #<Mongoid::Criteria
selector: {...},
options: {:sort => {"image_file_size"=> -1, "created_at" => -1 }}
class: ...>

A: There are many ways to affect multiple sorts using order_by!
irb(main):001:0> query.order_by("image_file_size DESC, created_at DESC")

Some other ways:
irb(main):002:0> query.order_by(image_file_size: :desc, created_at: :desc)

irb(main):003:0> query.order_by(image_file_size: "desc", created_at: "desc")

irb(main):004:0> query.order_by(image_file_size: -1, created_at: -1)

irb(main):006:0> query.order_by([:image_file_size, -1], [:created_at, -1])
(This also accepts "desc", :desc)

irb(main):007:0> query.order_by(:image_file_size.desc, :created_at.desc)
=>
#<Mongoid::Criteria
  selector: {}
  options:  {:sort=>{"image_file_size"=>-1, "created_at"=>-1}}
  class:    ...
  embedded: ...>

EDIT: Check out the API docs for more details.


text:
Q: Electron.js quick start guide: Errors on "npm start" I am new to electron and followed the quick start guide here: https://www.electronjs.org/docs/tutorial/quick-start
My package.json has this:
"scripts": {
    "start": "electron ."
}

When I run npm start the app starts but the versions are not printed and I get these errors in the js console:
Uncaught ReferenceError: process is not defined at index.html:11
Uncaught ReferenceError: process is not defined at index.html:12
Uncaught ReferenceError: process is not defined at index.html:13

Seems like process is not defined in index.html. But when I directly run electron . everything works correctly.
Why?
My versions:

Manjaro 20.2.1, Kernel 5.10.18-1-MANJARO
Node.js 15.10.0
npm 7.6.1
electron 12.0.0

A: You should use contextIsolation: false along with nodeIntegration: true
Try the following:
const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    }
  })

This is being discussed here: https://github.com/electron/electron/issues/18139
What is context Isolation?

Context Isolation is a feature that ensures that both your preload
scripts and Electron's internal logic run in a separate context to the
website you load in a webContents. This is important for security
purposes as it helps prevent the website from accessing Electron
internals or the powerful APIs your preload script has access to.
This means that the window object that your preload script has access
to is actually a different object than the website would have access
to. For example, if you set window.hello = 'wave' in your preload
script and context isolation is enabled window.hello will be undefined
if the website tries to access it.

A: Make sure you have nodeIntegration set to true.
main.js
const { BrowserWindow } = require('electron')
let win = new BrowserWindow({
  webPreferences: {
    nodeIntegration: true
  }
})


text:
Q: Date returns 00 00 0000 values after submiting edit form in php Date returns null values after submiting edit form in php
HTML CODE IS
<form  class="form-horizontal"  action="" method="post" >
    Start Date

     <input type="text" name="coupon_strt_date" id="datepicker"  value="<?php echo $cats_rows['coupon_strt_date'];  ?>" class='datepick'>
    Exp Date
    <input type="text" name="coupon_exp_date"  value="<?php echo $cats_rows['coupon_exp_date'];  ?>" id="datepicker" class='datepick'>

    <input type="submit" name="submit" value="submit">
    </form>

    <?php
include("config.php");

$tbl_name = "coupons";
if (isset($_POST['submit'])){
$id=$_POST['id'];
    $coupon_strt_date = $_POST['coupon_strt_date'];
    $coupon_exp_date = $_POST['coupon_exp_date'];

$sql="update $tbl_name set coupon_strt_date = STR_TO_DATE('$_POST[coupon_strt_date]', '%m/%d/%Y'), coupon_exp_date = STR_TO_DATE('$_POST[coupon_exp_date]', '%m/%d/%Y') where id='$id'";
if (!mysql_query($sql))
  {
 echo "Error Accured";
  }
  else {
 echo " Successfull";
  }
}

While iam saving data.. Dates are getting null value after chaning the date..add form is working fine..but edit form is dates are getting null value.. please sugguest me with correct code..

A: Try this:
<?php
    $coupon_strt_date = date('Y-m-d', strtotime($_POST['coupon_strt_date']));
    $coupon_exp_date = date('Y-m-d', strtotime($_POST['coupon_exp_date']));

    $sql="update $tbl_name set coupon_strt_date = '$coupon_strt_date', coupon_exp_date = '$coupon_exp_date' where id='$id'";
?>

A: Dates needs to be stored in YYYY-MM-DD format in your database.


text:
Q: Can not trigger any javascript events inside popover in bootstrap Ok, I've been dealing with this issue for a couple of days and I just found out that I can't trigger any events inside a bootstrap popover. I even tried to trigger an alert() and it does nothing.
I have a popover with a button in it. When you click the button the text on it change. Any help? Fiddle here. Thanks.

A: As Michael pointed out in his answer, the popover element does not exist in the HTML until the link is clicked. So the click handler can't attach to it until after the link is clicked.  So you can either move the click handler into the popover call, or use the jquery on delegate, like this:
$('.location').on('click','.text-btn',function () {
    alert('What\'s going on!');
    //$('.text-btn').toggle();
});

See this work in the fiddle
What this does is the following:  It attaches a click handler to the element with the location class. When anything inside this element gets clicked (such as the text-btn element), the event bubbles up and triggers this handler.  However, the on handler listens only to events that are triggered by specific elements (in this case elements that have the text-btn class).  Since the the handler is attached to the .location element and this element is non-dynamic, it will always be available.

A: The problem is that you are assigning an event listen on a node that does not exist yet. If you look at the HTML that is generated when you click on Fire popover the following HTML is generated:
<div class="popover-content">
     <button class="btn text-btn">Toggle me!</button>
     <button class="btn text-btn toggle-text">Un-Tobble me</button>
</div>

The problem is that this was generated after your listener code ran on the document - therefore there is no listener on your button.
Hopefully someone else can tell you how to add the listener as I can't figure it out.


text:
Q: In Userform how to link the value of a textbox dynamically to that of another thing like Spinbutton or checkboxes I am curious how to make the value of a text box dynamically change when you select a different option button or toggle with a spin button. What I have tried so far is
    Userform1.textbox1.value = spinbutton1
Is there a better way to do this??
Thanks.

A: Well, you are on the right track, but it would be:
 Userform1.textbox1.value = spinbutton1.value

And, you'd want to have that code inside of the spinbutton1's change event handler.


text:
Q: Get all records based on Date Range I want to query below table data based on Date Range.
Id      | DateFrom    |  DateTo
--------+-------------+-------------
1       | 2019-09-15  |  2019-09-17
2       | 2019-09-20  |  2019-09-20
3       | 2019-09-21  |  2019-09-21
4       | 2019-09-22  |  2019-09-22
5       | 2019-09-20  |  2019-09-22

I wrote this query to filter data and I'm not getting any data.
DECLARE @StartDate DateTime = '09/02/2019' -- MM/DD/YYYY
DECLARE @EndDate DateTime = '09/20/2019'

SELECT *
FROM MyTable
WHERE (@StartDate BETWEEN DateFrom AND DateTo)
   OR (@EndDate BETWEEN DateFrom AND DateTo)

The output should be 1, 4, 5 records.
If @StartDate and @EndDate are '09/21/2019', then the output should be 3, 5.

A: You are relying on database session settings here. Is '09/02/2019' February 2 or September 9? Does the setting allow '/' to be a date part separator? Better use an unambiguous format. That is 'YYYYMMDD'  for all SQL Server versions (or 'YYYY-MM-DD' for newer ones).
Then, what type are your date columns? If they are datetimes actually, there may be time parts you don't see. You can cast to date to play safe.
DECLARE @StartDate DateTime = '2019-09-02'
DECLARE @EndDate DateTime = '2019-09-20'

SELECT *
FROM MyTable
WHERE (@StartDate BETWEEN CAST(DateFrom AS DATE) AND CAST(DateTo AS DATE))
   OR (@EndDate BETWEEN CAST(DateFrom AS DATE) AND CAST(DateTo AS DATE));

A: Below query serve my purpose. However, below query returns duplicates.. and handled distinct in c#.

SELECT *
FROM MyTable
WHERE (DateFrom BETWEEN ''' + @DateFrom + ''' AND ''' + @DateTo + ''')
  OR (DateTo BETWEEN ''' + @DateFrom + ''' AND ''' + @DateTo + ''')
  OR (''' + @DateFrom + ''' BETWEEN DateFrom AND DateTo)
  OR (''' + @DateTo + ''' BETWEEN DateFrom AND DateTo)

A: Since date formats can be different on each machine, I suggest you to use DATEFROMPARTS(year, month, day) instead of a literal string.
Use it like this:
DECLARE @StartDate DateTime = DATEFROMPARTS(2019, 2, 9) ;
DECLARE @EndDate DateTime = DATEFROMPARTS(2019, 9, 20) ;


text:
Q: How do I make use of the Criteria API to find a specific person based on different criterias? I love all the help I've gotten in the past simply by reading your topics, however I've now stumbled onto something I literally have no idea how to implement at all.
Edit: Forgot a big portion -> My framework: I'm running this on Netbeans, using Glassfish server with EJB and the DB being run on a MySQL server. Also I'm making use of JPA.
I have a database which contains several tables, but there's 3 that I need to use a join on, to get people that match the criterias out of it.
My database:

I'll try to simplify what I'm trying to do, might actually help me get some insight in this while I'm typing.
I'm trying to

*

*Find all pid in Availability where the dates that a user sends in is inbetween. Example:
User sends in Period 2010-10-10 to 2011-01-01, I'm trying to find all pid where, in Availability, the from_date is "higher than" or past 2010-10-10 and the to_date is lower than or not past 2011-01-01.

*Find all pid in Competence_profile where competence_name is the name sent in by the user, and the years_of_experience is at least equals to or greater than the years of experience that the user sends in.

*Join them somehow so that I get Person p from the Person-table, that matches the pid that remained from the join (meaning, the pid existed in both Availability and Competence_profile for the criterias).
How do I do something like this based on the Criteria API? I played around with it awhile and read quite a lot of tutorials and topisc, but none were able to actually answer my question as to how I combine it in this form.
Any help is very much appreciated!

A: This is with Hibernate Criteria API.
     // First set up a subquery to get the ids of Persons who are available
     // (assuming that the Person must be available for the entire duration)
     DetachedCriteria dc = DetachedCriteria.forClass(Person.class)
         .setProjections(Projections.id())
         .createAlias("availability", "a")
         .add(Restrictions.le("a.to", endDate)
         .add(Restrictions.ge("a.from", startDate);

     Criteria crit = session.createCriteria(Person.class)
          .createAlias("competence", "c")
          .add(Restrictions.eq("c.name", competenceName)
          .add(Subqueries.in(dc,"id");

     List<Person> people = crit.list();


text:
Q: NSImage vs. CIImage vs. CGImage? When should I use each?

A: NSImage is an abstract data type that can represent many different types of images, as well as multiple representations of an image. It is often useful when the actual type of image is not important for what you're trying to do. It is also the only image class that AppKit will accept in its APIs (NSImageView and so forth).
CGImage can only represent bitmaps. If you need to get down and dirty with the actual bitmap data, CGImage is an appropriate type to use. The operations in CoreGraphics, such as blend modes and masking, require CGImageRefs. CGImageRefs can be used to create NSBitmapImageRefs, which can then added to an NSImage.
I think the documentation describes a CIImage best:

Although a CIImage object has image data associated with it, it is not an image. You can think of a CIImage object as an image "recipe." A CIImage object has all the information necessary to produce an image, but Core Image doesn't actually render an image until it is told to do so. This "lazy evaluation" method allows Core Image to operate as efficiently as possible.

CIImages are the type required to use the various GPU-optimized Core Image filters that come with Mac OS X, but, like CGImageRefs, they can also be converted to NSBitmapImageReps.


text:
Q: How do people figure out what goes where? Okay so I recently started my career as a Jr. Software Engineer, and after training for a couple of months I feel baffled.
So far I have been following coding tutorials and books to make a web application, but whenever I imagine making something from scratch, it makes me anxious. How do developers know what goes where? How does that guy in the tutorial know exactly which files to update and exactly what property or component to change when he adds a functionality?
I have a computer science degree and I was fairly good in my class when it came to solving problems and writing simple 2-5 files of code to accomplish a task. But real world coding is very different! There are generators for everything,frameworks for every language. My university did not teach me any of that. I feel like all those years of formal education are wasted because real world software development is very different.
Is there any website that burns it into memory about what goes where? I want to be proficient at this like I was while solving coding problems in uni.

A: Above all, know that it is normal to feel this way. Today there are many technologies, languages and ways of doing things. The advice I can give you is to choose a technology, to read the documentation carefully. If you encounter a problem, search on google, the forums... And finally, take a project that you really want to do, try to carry it out with this technology, this is how you will learn and progress. Courage, developing complex projects can be intimidating!


text:
Q: communicate a .exe with a service c# I have a windows service that uses a FileSystemWatcher to see if there are pdf files moved to a folder, and then, when a user moves a pdf file into that folder, the service executes  MyProcess. The pdf filename is like this:   name_doctorcode.pdf.
code:
Private static void MyProcess(string pdfname)
{
  string sDoctorCode= getdoctorcode(pdfname); //brings doctor code from filename
  bool foundDoctorCode= FindDoctorCode(sDoctorCode); //searchs  into a data container (database, txt,etc..) to see if the doctor code is found
  if(foundDoctorCode==false)
  {
    // HELP to call exe file to prompt user to enter a correct doctorcode
    //pass the doctorcode to a variable
   string sNewDoctorCode = doctorCodeFromExe;
  }
}

Can you help me to do this?
Any guide,tutorial or code?
Thanks


text:
Q: Multiple AND OR logic in the where clause Consider the following scenario
I want to select all columns from table A where

*

*SubscribeDate is between 2016-01-01 and now() and clubid=2

*timesbilled>0 and clubid=2
I am trying the following (The sample is big enough to have the sample)
Select *

From Table A

Where
SubscribeDate between '2016-01-01' and now()
and clubid=2
OR
timesbilled>0

Will the query meet my requirement?

A: I would phrase your query as:
SELECT *
FROM TableA
WHERE (SubscribeDate BETWEEN '2016-01-01' AND NOW() OR timesbilled > 0) AND
      clubid = 2

Both of your listed conditions require a clubid of 2.  The other requirement is that the date condition or billing condition be true.

A: Try the following
Select *

From Table A

Where
(SubscribeDate between '2016-01-01' and now()
and clubid=2)
OR
(timesbilled>0 and clubid=2);


text:
Q: Anaconda + Apache + mod_wsgi + Ubuntu I'm running a server with Ubuntu and Apache. Now I'm trying to get Anaconda working with mod_wsgi but just can't get it to work.
First off. It is working if I use mod_wsgi-express. By following the instruction at https://anaconda.org/pypi/mod_wsgi in section Installing into Python I can get it working by first setting PYTHONHOME=/opt/anaconda and then /opt/anaconda3/bin/mod_wsgi-express start-server.
I want to use Apache so I load the mod_wsgi module from anaconda into apache. And then I have a VirtualHost looking like this:
WSGIPythonHome /opt/anaconda3
WSGIPythonPath /opt/anaconda3/lib/python3.6/site-packages:/path/to/application
<VirtualHost *:8080>
ServerName example.com
WSGIDaemonProcess example python-home=/opt/anaconda3 python-path=path/to/application:/opt/anaconda3/lib/python3.6/site-packages
WSGIProcessGroup example

WSGIScriptAlias / /path/to/application/wsgi.py

<Directory /path/to/application/static>
    Require all granted
</Directory>

<Directory /path/to/application>
<Files wsgi.py>
    Require all granted
</Files>
</Directory>

</VirtualHost>

Now to the problem. I get this error in my apache error log. I get the same error if I don't specify PYTHONHOME=/opt/anaconda with mod_wsgi_express.
[Wed Mar 01 09:31:17.159233 2017] [core:trace4] [pid 16941] mpm_common.c(530): mpm child 19356 (gen 0/slot 1) started
[Wed Mar 01 09:31:17.159638 2017] [core:trace4] [pid 16941] mpm_common.c(530): mpm child 19357 (gen 0/slot 2) started
[Wed Mar 01 09:31:17.160049 2017] [core:trace4] [pid 16941] mpm_common.c(530): mpm child 19358 (gen 0/slot 6) started
[Wed Mar 01 09:31:17.160467 2017] [core:trace4] [pid 16941] mpm_common.c(530): mpm child 19359 (gen 0/slot 7) started
[Wed Mar 01 09:31:17.160967 2017] [core:trace4] [pid 16941] mpm_common.c(530): mpm child 19360 (gen 0/slot 8) started
[Wed Mar 01 09:31:17.161421 2017] [core:trace4] [pid 16941] mpm_common.c(530): mpm child 19361 (gen 0/slot 9) started
[Wed Mar 01 09:31:17.161877 2017] [core:trace4] [pid 16941] mpm_common.c(530): mpm child 19362 (gen 0/slot 10) started
[Wed Mar 01 09:31:17.162345 2017] [core:trace4] [pid 16941] mpm_common.c(530): mpm child 19363 (gen 0/slot 11) started
[Wed Mar 01 09:31:17.162792 2017] [wsgi:info] [pid 19361] mod_wsgi (pid=19361): Python home /opt/anaconda3.
[Wed Mar 01 09:31:17.162817 2017] [wsgi:info] [pid 19361] mod_wsgi (pid=19361): Initializing Python.
[Wed Mar 01 09:31:17.166761 2017] [wsgi:info] [pid 19362] mod_wsgi (pid=19362): Python home /opt/anaconda3.
[Wed Mar 01 09:31:17.166806 2017] [wsgi:info] [pid 19362] mod_wsgi (pid=19362): Initializing Python.
[Wed Mar 01 09:31:17.170927 2017] [wsgi:info] [pid 19360] mod_wsgi (pid=19360): Python home /opt/anaconda3.
[Wed Mar 01 09:31:17.170967 2017] [wsgi:info] [pid 19360] mod_wsgi (pid=19360): Initializing Python.
[Wed Mar 01 09:31:17.174897 2017] [wsgi:info] [pid 19359] mod_wsgi (pid=19359): Python home /opt/anaconda3.
[Wed Mar 01 09:31:17.174921 2017] [wsgi:info] [pid 19359] mod_wsgi (pid=19359): Initializing Python.
[Wed Mar 01 09:31:17.178746 2017] [wsgi:info] [pid 19363] mod_wsgi (pid=19363): Python home /opt/anaconda3.
[Wed Mar 01 09:31:17.178769 2017] [wsgi:info] [pid 19363] mod_wsgi (pid=19363): Initializing Python.
[Wed Mar 01 09:31:17.182570 2017] [core:notice] [pid 16941] AH00052: child pid 19317 exit signal Aborted (6)
[Wed Mar 01 09:31:17.182582 2017] [core:trace4] [pid 16941] mpm_common.c(530): mpm child 19317 (gen 0/slot 0) exited
[Wed Mar 01 09:31:17.182594 2017] [core:notice] [pid 16941] AH00052: child pid 19318 exit signal Aborted (6)
[Wed Mar 01 09:31:17.182597 2017] [core:trace4] [pid 16941] mpm_common.c(530): mpm child 19318 (gen 0/slot 3) exited
[Wed Mar 01 09:31:17.182605 2017] [core:notice] [pid 16941] AH00052: child pid 19319 exit signal Aborted (6)
[Wed Mar 01 09:31:17.182608 2017] [core:trace4] [pid 16941] mpm_common.c(530): mpm child 19319 (gen 0/slot 4) exited
[Wed Mar 01 09:31:17.182615 2017] [core:notice] [pid 16941] AH00052: child pid 19320 exit signal Aborted (6)
[Wed Mar 01 09:31:17.182618 2017] [core:trace4] [pid 16941] mpm_common.c(530): mpm child 19320 (gen 0/slot 5) exited
[Wed Mar 01 09:31:17.182636 2017] [wsgi:info] [pid 16941] mod_wsgi (pid=19321): Process 'store-test' has died but server is being stopped, deregister it.
[Wed Mar 01 09:31:17.182646 2017] [wsgi:info] [pid 16941] mod_wsgi (pid=19321): Process 'store-test' has been deregistered and will no longer be monitored.
[Wed Mar 01 09:31:17.182934 2017] [wsgi:info] [pid 19358] mod_wsgi (pid=19358): Python home /opt/anaconda3.
[Wed Mar 01 09:31:17.182954 2017] [wsgi:info] [pid 19358] mod_wsgi (pid=19358): Initializing Python.
[Wed Mar 01 09:31:17.186756 2017] [wsgi:info] [pid 19357] mod_wsgi (pid=19357): Python home /opt/anaconda3.
[Wed Mar 01 09:31:17.186781 2017] [wsgi:info] [pid 19357] mod_wsgi (pid=19357): Initializing Python.
[Wed Mar 01 09:31:17.190807 2017] [wsgi:info] [pid 19356] mod_wsgi (pid=19356): Python home /opt/anaconda3.
[Wed Mar 01 09:31:17.190840 2017] [wsgi:info] [pid 19356] mod_wsgi (pid=19356): Initializing Python.
Could not find platform independent libraries <prefix>
Could not find platform dependent libraries <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ModuleNotFoundError: No module named 'encodings'
Current thread 0x00007f4ad9333780 (most recent call first):

Anyone know what I can do to get it working?

A: You cannot use any system package for mod_wsgi if you are wanting to use Anaconda Python. So first step is to uninstall any system mod_wsgi package.
Then use pip install mod_wsgi to install mod_wsgi-express into your Anaconda Python installation or virtual environment.
Then run:
mod_wsgi-express module-config

Take the output of that and put it into your Apache configuration file to load mod_wsgi.
Then add to Apache the mod_wsgi configuration for your specific WSGI application.
Show the configuration you are using after doing that if have issues.


text:
Q: Recursive sum function, How do i limit the sum? The goal is to code this sum into a recursive function.
Sum
I have tried so far to code it like this.
def under(u: Int): Int = {
    var i1 = u/2
    var i = i1+1
    if (  u/2 == 1 ) then u + 1 - 2 * 1
    else   (u + 1 - 2 * i) + under(u-1)
}

It seems like i am running into an issue with the recursive part but i am not able to figure out what goes wrong.
In theory, under(5) should produce 10.

A: Your logic is wrong. It should iterate (whether through loop, recursion or collection is irrelevant) from i=1 to i=n/2. But using n and current i as they are.
(1 to (n/2)).map(i => n + 1 - 2 * i).sum

You are (more or less) running computations from i=1 to i=n (or rather n down to 1) but instead of n you use i/2 and instead of i you use i/2+1. (sum from i=1 to i=n of (n/2 + 1 - 2 * i)).
// actually what you do is more like (1 to n).toList.reverse
// rather than (1 to n)
(1 to n).map(i => i/2 + 1 - 2 * (i/2 + 1)).sum

It's a different formula. It has twice the elements to sum, and a part of each of them is changing instead of being constant while another part has a wrong value.
To implement the same logic with recursion you would have to do something like:
// as one function with default args

// tail recursive version
def under(n: Int, i: Int = 1, sum: Int = 0): Int =
  if (i > n/2) sum
  else under(n, i+1, sum + (n + 2 - 2 * i))

// not tail recursive
def under(n: Int, i: Int = 1): Int =
  if (i > n/2) 0
  else (n + 2 - 2 * i) + under(n, i + 1)

// with nested functions without default args

def under(n: Int): Int = {
  // tail recursive
  def helper(i: Int, sum: Int): Int =
    if (i > n/2) sum
    else helper(i + 1, sum + (n + 2 - 2 * i))
  helper(1, 0)
}

def under(n: Int): Int = {
  // not tail recursive
  def helper(i: Int): Int =
    if (i > n/2) 0
    else (n + 2 - 2 * i) + helper(i + 1)
  helper(1)
}

A: As a side note: there is no need to use any iteration / recursion at all. Here is an explicit formula:
def g(n: Int) = n / 2 * (n - n / 2)

that gives the same results as
def h(n: Int) = (1 to n / 2).map(i => n + 1 - 2 * i).sum

Both assume that you want floored n / 2 in the case that n is odd, i.e. both of the functions above behave the same as
def j(n: Int) = (math.ceil(n / 2.0) * math.floor(n / 2.0)).toInt

(at least until rounding errors kick in).


text:
Q: How to find sequence of numbers in list I am trying to find if some sequences of numbers are in a list. If so, this tuple should be removed from the list. Numbers must be contiguous to one another.
Example:
list of tuples:
list_1 =  [(), (1,), (3,), (2,), (4,), (1, 3), (1, 2), (1, 4), (3, 2), (3, 4), (2, 4), (1, 3, 2), (1, 3, 4), (1, 2, 4), (3, 2, 4), (1, 3, 2, 4)]

and a second list:
list_2 = [1,3,2,4]

In this case the elements (1, 3), (3, 2), (2, 4), (1, 3, 2), (3, 2, 4), (1, 3, 2, 4), (1, 3, 4), (1, 2, 4) in list_1 should be removed, because they contain numbers (not necessarily all of them!)that are contiguous in list_2.
I want to check if the elements in list
I tried something like this:
for i in range(len(lista)):
    teste = []
    for j in range(len(lista[i])):
        for k in stuff:
            if len(lista[i]) >= 2:
                if lista[i][j] == k:
                    teste.append(k)
                    if len(teste) == 2:
                        lista.remove(lista[i])
                        teste=[]

            else:
                pass

With this output:
if len(lista[i]) >= 2:
IndexError: list index out of range

I was trying to check a number, append it to a list check the next one and if it was appended too i would remove the corresponding tuple.

A: Here you go, I think this works.
If you want to delete the blank set, just delete it, it's however you define a match.  I added commented code to do that.
Fixed based on your comment
print("List 1:", list_1)
print("List 2:", list_2)
removeElements = []
for k in range(len(list_1)):
    #if len(list_1[k]) == 0:
    #    removeElements.append(k)
    count = 0
    for i in range(0, len(list_2)):
        for j in range(0, len(list_1[k])):
            if len(list_2) <= i + j:
                break
            count = count + 1
            if list_1[k][j] != list_2[i + j]:
                count = 0
            if count == 2:
                print("removing", list_1[k])
                removeElements.append(k)

removeElements = sorted(set(removeElements))
for i in range(len(removeElements)):
    list_1.pop(removeElements[i] - i)

print("List_1:", list_1)

A: If you grab the window recipe from an old python example this becomes easy:
from itertools import islice

def window(seq, n=2):
    "Returns a sliding window (of width n) over data from the iterable"
    "   s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...                   "
    it = iter(seq)
    result = tuple(islice(it, n))
    if len(result) == n:
        yield result
    for elem in it:
        result = result[1:] + (elem,)
        yield result

Then you can just keep the elements that don't appear in any window from list_2
[t for t in list_1 if t not in window(list_2, len(t))]

However, you seem to have special cased tuples of zero or one element, so you'd need to change the filter
[t for t in list_1 if len(t) < 2 or t not in window(list_2, len(t))]

A: This is one way to do it:
list_1 = [(), (1,), (1,2), (1,4)]
y = [list(i) for i in list_1]

list_2=[3,1,2,4]
x = [list_2[0:2], list_2[1:3], list_2[2:4]]

new_list_1 = [tuple(i) for i in y if i not in x[0:]]

Output:
[(), (1,), (1, 4)]


text:
Q: How to define DB functions in MySQL Docker? When using a SQL file placed inside /docker-entrypoint-initdb.d/ defining functions fails with the following error:
ERROR 1064 (42000) at line 6: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 3

This is the content of the SQL file:
CREATE DATABASE alpha;
USE alpha;

SET GLOBAL log_bin_trust_function_creators = 1;

create function addit(a int, b int) returns int
begin
    return a+b;
end

The above code works perfectly well when I connect to the instance after creation and run it.
Is it not allowed to define functions in db init scripts? How do I get around this?


text:
Q: WinAPI получить время создания pagefile.sys Как получить время создания файла pagefile.sys с помощью WinAPI?
Из MSDN:

BOOL WINAPI GetFileTime(_In_ HANDLE hFile,......
   The handle must have
  been created using the CreateFile function with the GENERIC_READ
  access right.

Но попытка HANDLE WINAPI CreateFile возвращает:

GetLastError 0x20 - The process cannot access the file because it is
  being used by another process.

A: FindFirstFile() и поле WIN32_FIND_DATA.ftCreationTime попробуйте...


text:
Q: Python will access external config file unless script is open from root directory of script I am new to python and linux. Below is the issue I am having.
If I open terminal window and go to directory that has my .py file and run the script everything works fine.
If I try running the script from any other directory using path to the .py file I get an error saying it couldnt find the external config.py file my script uses.
example:
My a.py script and config.py are in /home/pi/m
If I am in directory pi@raspberrypi:/home/pi/m and call my .py file everything works
If I am in directory pi@raspberrypi:/ and run command python /home/pi/m/a.py the script doesn't execute and states it can't find my config.py file
What causes this behavior and how do I fix it?

A: I tried what you are speaking of.It works on my system.Assuming you are doing import config.
[raa@raa ~]$ python ./Desktop/test.py
Ok
[raa@raa ~]$ python ./Desktop/test.py
Config
Ok
[raa@raa ~]$ python /Desktop/test.py
python: can't open file '/Desktop/test.py': [Errno 2] No such file or directory
[raa@raa ~]$

I am doing this in test.py
#!/usr/bin/env python3
import config

print('Ok')

And this in config.py:
#!/usr/bin/env python3

print('Config')

A: Add this to the top of a.py:
import os, sys
sys.path.append(os.path.realpath(__file__))

This will extend the search for modules to be imported to the local folder of a.py.


text:
Q: Can you implement arithmetic operator as variables in C? I'm trying to program a reverse polish calculator and I didn't wanted to write switches for every single arithmetic operator inputted. Is it possible to input an arithmetic operator and use it as such inside the language itself?
For example, the program could prompt the user for an arithmetic operator, for:
a = b [whatever operator here] c;
and some variable would store the operator. Let's say it's +, we get:
a = b + c;
Is this possible or should I just suck it up and write the switches for the operators?

A: It is possible. See an example below
RPN calculator implies in some sort of stack. On identifying an operand you pop up two operands and does the operation.
I want to let a short example so I will shortcut some things...
our "stack"
I will assume integer operands only, but I think it is not hard to make it generic, by using the usual suspects, void*
This is the stack in the example
// stack
int pop()
{
    int val = 1 + rand()%1000 / (-1)*(rand()%2);
    printf("pop(): operand %d from stack\n", val);
    return val;
}

It just gets a random number in [-998,999] inclusive :)
the operations
// operations
int divd(int A, int B) { return A / B; };
int mult(int A, int B) { return A * B; };
int sub(int A, int B)  { return A - B; };
int sum(int A, int B)  { return A + B; };

So we have something to test.
the syntax glue
Assuming the operator is a single char we can build a lookup-table indexed by the operator and put the functions there.
C was created precisely to write this kind of things.
    int (*the_fs[256])(int,int) = {0};
    the_fs['+'] = sum;
    the_fs['-'] = sub;
    the_fs['*'] = mult;
    the_fs['/'] = divd;

a test
    // test for some cases
    const char oper[] = "+-*/";
    const int N = 8;
    for (int i = 0; i < N; i += 1)
    {
        // do one test
        int ix = rand() % 4;
        printf("using '%c'\n", oper[ix]);
        a = pop();
        b = pop();
        printf("%d %c %d = %d\n", a, oper[ix], b,
            the_fs[oper[ix]](a,b));
    }

It is just a matter of calling the_fs[X] where X is the operand. No need for if, no need for switch(). It can the used alo for unary operators, just PUSHing back the second operator in the function.
output for a random test with random numbers and random operations
using '+'
pop(): operand -624 from stack
pop(): operand -906 from stack
-624 + -906 = -1530
using '*'
pop(): operand -724 from stack
pop(): operand 1 from stack
-724 * 1 = -724
using '*'
pop(): operand -733 from stack
pop(): operand -807 from stack
-733 * -807 = 591531
using '-'
pop(): operand -938 from stack
pop(): operand 1 from stack
-938 - 1 = -939
using '*'
pop(): operand 0 from stack
pop(): operand -121 from stack
0 * -121 = 0
using '*'
pop(): operand 1 from stack
pop(): operand 1 from stack
1 * 1 = 1
using '-'
pop(): operand 1 from stack
pop(): operand -396 from stack
1 - -396 = 397
using '+'
pop(): operand -130 from stack
pop(): operand -372 from stack
-130 + -372 = -502

the complete test program
#include <stdio.h>
#include <stdlib.h>

int pop(); // stack simulator :)

int sum(int,int);
int sub(int,int);
int mult(int,int);
int divd(int,int);

int main(void)
{
    int        a      = 0;
    int        b      = 0; // the operands
    srand(210907);
    int (*the_fs[256])(int,int) = {0};
    the_fs['+'] = sum;
    the_fs['-'] = sub;
    the_fs['*'] = mult;
    the_fs['/'] = divd;

    // so you have an operator, and it is RPN
    // the stack must have 2 operands

    // test for some cases
    const char oper[] = "+-*/";
    const int N = 8;
    for (int i = 0; i < N; i += 1)
    {
        // do one test
        int ix = rand() % 4;
        printf("using '%c'\n", oper[ix]);
        a = pop();
        b = pop();
        printf("%d %c %d = %d\n", a, oper[ix], b,
            the_fs[oper[ix]](a,b));
    }
    return 0;
}

// stack
int pop()
{
    int val = 1 + rand()%1000 / (-1)*(rand()%2);
    printf("pop(): operand %d from stack\n", val);
    return val;
}

// operations
int divd(int A, int B)  { return A / B; };
int mult(int A, int B) { return A * B; };
int sub(int A, int B)  { return A - B; };
int sum(int A, int B)  { return A + B; };

/*
https: //stackoverflow.com/questions/69080130/
can-you-implement-arithmetic-operator-as-variables-in-c
*/

A: Short answer:
No, it's not possible. At least not the way you want.
Long answer:
No, you cannot. C simply does not support things like the eval function in Python. For those who does not know what it is, this will print "Hello":
s = "print('Hello')" # A string with the code we want to execute
eval(s)              # Evaluate the string s as python code and execute it

If you want to do something like that in C, well just forget it. It's not possible.
You can achieve something similar with function pointers. It will look really awkward if you're not used to function pointers, but it mimics what you're talking about. Although quite badly.
int add(int a, int b) { return a+b; }
int sub(int a, int b) { return a-b; }

// Function taking two int and returning int
typedef int (operation)(int, int);

int main(void) {
    operation *ops[UCHAR_MAX+1];
    ops['+'] = add;
    ops['-'] = sub;
    printf("Sum:  %d\nDiff: %d\n", ops['+'](5,3), ops['-'](5,3));
}

This prints:
Sum:  8
Diff: 2

ops is an array of function pointers. More precisely, an "array 256 of pointer to function (int, int) returning int". So we're using a single character directly to index it.
One thing to look out for here is to make sure that no negative values are passed to ops. This could happen on a machine where char is signed as default.
If you want some safety in form of error handling, you could do something like this:
int error(int a, int b) {
    fprintf(stderr, "Function not implemented");
    exit(EXIT_FAILURE);
}

and then do:
operation *ops[UCHAR_MAX+1];
for(int i=0; i < sizeof ops/sizeof *ops; i++)
    ops[i] = error;

ops['+'] = add;
ops['-'] = sub;

This method is not worth all this extra hassle if you only want to support four operations, but it can actually come in quite handy if you're writing an emulator. I watched a very interesting youtube playlist about writing a NES emulator. It's in C++, but very oldschool so if you know C, it's not hard to follow. He talks about function pointers in part 2.
https://youtu.be/F8kx56OZQhg
Note: Not my channel. I have absolutely nothing to do with it. Was hesitating because it could look like spam, but those videos are really interesting for a coder.

A: Q: Does C support operator overloading?
A: No: only C++
Q: I want to branch on different operators ("+", "-", "/", etc.).  Do I absolutely need a switch()/case block?
A: No.  You can always use if/else equivalents.  But a switch/case block is arguably "cleaner".
FINALLY:
What you're really trying to do is parse an input string into "tokens", then process the tokens.  There are many different tools you could use (everything from calling "strtok()" to using lexx/yacc); there are many different algorithms.  SUGGESTION: Google for "C parsing", look at Shunting Yard algorithm.


text:
Q: Passing data from my razor view to my js file I'm searching for the best way to pass data from my razor view to my js file. For example, lets say we have a jquery dialog configured in the js file. For buttons text on this dialog, I would like to localize it (through resource files FR/NL/UK). The translations are available with @UserResource.ButtonDelete + @UserResource.ButtonCancel
Below are the different solutions I see:

*

*Using the nice RazorJS nuget package to allows razor code inside my javascript file. It works pretty well. But the question is: is it a bad practice to compile js files in order to use razor syntax inside the scripts?

*Declaring global variables in the js script file and assign value from the view like this:
In the view:
<script>
        var labelButtonDelete = @UserResource.ButtonDelete;
</script>

In the js file:
alert('The text for my button is ' + labelButtonDelete);

What is the best way to pass data from razor to js file? Do you have another alternative?
Thanks anyway.

A: I've been using something like your second approach for some time without any issues. The only difference is that I'm using a singleton in my JS file to avoid polluting the global javascript namespace.
But if you will be doing more serious client side stuff, your Javascript code will follow a more object oriented structure, and from there you almost automatically get a single initialization/constructor path where you can pass your localized values.
That RazorJS looks nice, but I'm not sure if I'm comfortable mixing Javascript with Razor. Might do it for a small project, but I can see it becoming really messy if you have lots of Javascript files.
After all, I still consider the resources/localization code to be related to the view. The Javascript should only implement functionality in my opinion.


text:
Q: UITableView.automaticDimension height is coming -1 I am implementing uitableview, where I have 5 cells in total (each is having webview in it with dynamic text).
I am implementing 2 xib in this tableview.
But I am having problems with adjusting the height of tableview
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
       return UITableView.automaticDimension . // is returning a -1 value
    }

I have already set these properties before reloading my tableview
self.myTableview.rowHeight = UITableView.automaticDimension
self.myTableview.estimatedRowHeight = 300

But not able to calculate the height dynamically.
I have cross-checked the constraints in xib file and attaching the constraints which I have applied to tableview.
Any suggestions on how I can solve this?

A: UITableView.automaticDimension is a CGFloat with a value of -1.0, so that's as intended. You can therefore not use UITableView.automaticDimension in calculations.
If each cell can have different heights, depending on the text length in each webview, my suggestion is that you add a height constraint to each cell (or to the webview in each cell), and then calculate the height of the text, setting the height constraint to this value.
To calculate the height of your webview, have a look at How to determine the content size of a WKWebView?


text:
Q: Unable to Import BACPAC Local Server SSMS I have installed SSMS 18 and SQL Server 2019.
I get this error when trying to import a .bacpac file:

Could not load type 'Microsoft.SqlServer.TransactSql.ScriptDom.DropExternalStreamStatement' from assembly 'Microsoft.SqlServer.TransactSql.ScriptDom, Version=15.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91'. (Microsoft.Data.Tools.Schema.Sql)

A: I just ran into this issue and wasted a couple of hours trying to figure it out. I found the eventual answer here: SQL Server bacpac fails on local import in latest update (Online index operations can only be performed in Enterprise edition of SQL Server)
The problem is SSMS 18.8. Some have said that downgrading to 18.7.1 should work, but I had to go to 18.6 in order for it to work correctly.


text:
Q: How do I put a height limit within a canvas game? Right so I'm a bit new to JS and I wanted to know how to put a roof or height limit within this small canvas game. It's practically W3's code but the teacher told us to just model after it. I wanted to fix the annoying issue of just jumping over the map to avoid obstacles.
I don't really know what to try since the height is set by canvas. I tried to make a new function based of hitBottom() which failed.
Just wanted to put the roof or height limit. Here's the original source: Here. Everything is literally the same except colors.

A: What you want to do is see if the current y-position is lower than 0, since that would be the 'roof' of the room. If the player y position is lower than 0, reset it back to 0, and stop the acceleration.
    this.hitTop = function() {
        if (this.y < 0) {
            this.y = 0;
            this.gravitySpeed = 0;
        }
    }

And to the newpos function, you want to call this function, so add this:
this.hitTop();

A: Check for y position in newPos method after increasing the y position. If it is less than 0 then make it 0. Code should look like below;
this.newPos = function() {
    this.gravitySpeed += this.gravity;
    this.x += this.speedX;
    this.y += this.speedY + this.gravitySpeed;

    /* Add below 4 lines */
    if (this.y <= 0) {
        this.y = 0;
        this.gravitySpeed = 0;
    }
    /* Add above 4 lines */

    this.hitBottom();
}

Happy coding ;)


text:
Q: C++ Trying to implement a Matrix Firstly, I'm new to C++. I'm trying to implement a Matrix in C++.
I saw this:
https://www.quantstart.com/articles/Matrix-Classes-in-C-The-Source-File/
And i was trying to implement a construtor that would allow the user to create a matrix by using, as arguments, the vector of vectors. (IDK if that is possible).
template <typename T> class Matrix
{
private:
    vector<vector<T>> content;
    unsigned _rows;
    unsigned _columns;

public:
    Matrix(unsigned rows, unsigned columns)
.
.
.
    Matrix(vector <vector<T>> a) {
        this->content = a;
    }
.
.
.
};

The goal was to create the matrix through this:
Matrix<double> m({ {1,2,3},{4,5,6} });

As I said, I don't know if it is possible or even correct. Any help would be truly appreaciated, even if it is just a good practise advise. Thank you in advance.
Edited:
I clearly had a mistake on the constructor, but now when i try to display it:
 Matrix<double> m3({ { 1, 2, 3 }, { 4, 5, 6 } });
    m3.display();

It returns nothing

A: you could just assign a to Matrix.content, if you want it in a constructor it would be:
template <typename T>
class Matrix
{
private:
    vector<vector<T>> content;
    unsigned _rows;
    unsigned _columns;

public:
    Matrix(vector<vector<T>> a)
    {
        this->content = a;
    }
};

A: Problem solve. Bassicaly i was implementing the construtor in a bad way and displaying was not working it that after.
void display() {
    for (int i = 0; i < content.size(); i++) {
        for (int j = 0; j < content[i].size(); j++)
            cout << content[i][j] << " ";
        cout << endl;
    }
};


text:
Q: Trying to help but ending up causing more harm than good I'm writing a paper on Romeo and Juliet and how Frair Lawrence and the Nurse are to blame for Romeo and Juliet's deaths and I'm looking for a word. I've looked at other posts but I just see the same few answers. I'm more looking for one word rather than a statement. I saw things like 'hindering rather than helping' and the slang term 'Verschlimmbesserung' but I feel like they just aren't cutting it.

A: A potential option -
bungle

a task carried out in a clumsy or incompetent way.

It doesn't quite have the exact meaning you're requesting insofar as there's no requirement for the bungler to have good intentions; one could, for instance, bungle something evil.
Nevertheless, it's the best I can come up with.


text:
Q: Cannot install eclipse adt plugin I am trying this for the past two days but don't seem to get a right direction to the solution. I have been trying to install the ADT plugin for eclipse Juno but while doing so though the install new software option in help, and providing the url, it starts calculating the dependencies in downloading for a longer time but doesn't complete the calculation.
Previously, when i tried downloading any eclipse package, it gave me a weird time remaining for downloading the software packages (2 hrs, 4 hrs, 1 day etc.). I don't know if this is a problem with the eclipse server or some other technical issue.
Please note, this is not the first time i am using eclipse so I have been trying to follow the same methods like i used to do. I also tried doing it on a friend's PC and on a different network as well, but same issue existed.
Please guide me accordingly people. I appreciate it.
Thank you

A: You might want to try downloading the new Android SDK at http://developer.android.com/sdk/index.html
As I explained in a post on my blog:

It is basically Eclipse 3.8 + Android Developer Tools (ADT) 21, pre-installed in a single downloadable package. Previously, Android programmers had to go through a multi-step process to locate the ADT update site, accept licenses, etc. This should save time for new installs.


text:
Q: Active Directory Access Token expire detection I am using this singleton pattern on accessToken. For preventing unnecessary token call to login.windows service.
As you see if I have access token, I am serving existing token to my Code.
My problem is when I retrieve token first time. There is no Expire Time or any information.
This Expire on information always same as request date :

private static string accessToken_;

private static string AccessToken
{
    get
    {
        if (accessToken_ == null)
        {
            accessToken_ = GetAccessToken();
        }
        return accessToken_;
    }
}

private static string GetAccessToken()
{
    string AadInstance = "https://login.windows.net/{0}";

    AuthenticationContext authenticationContext = new AuthenticationContext(string.Format(AadInstance, aadTenantId));
    ClientCredential clientCredential = new ClientCredential(clientId, clientSecretKey);

    AuthenticationResult authenticationResult = authenticationContext.AcquireTokenAsync(ResourceId, clientCredential).Result;

    return authenticationResult.AccessToken;
}

And then really I cannot know when my token will expire?!
For fixing this problem I have this code block on Exception Catch.
And I think it is not correct design. Do you have another information with suitable design? :
private static CellSet ExecuteOlapCellSet(string mdxQuery)
{
try
{
.... method codes here...
}
catch (Exception e)
{
    //25 November: unauthorized, probably token expired.
    if (e.InnerException != null && e.InnerException.Message.Contains("(401)"))
    {
        accessToken_ = GetAccessToken();
        //call same method Again here
        ExecuteOlapCellSet(mdxQuery);
    }

    Utils.LogError(ErrorVariables.Error105, e.InnerException ?? e);
    throw new AnalystServiceException(ErrorVariables.Error105, e);
}
}


text:
Q: Javascript object with jQuery event scope issue I've got a draggable within my Pointer object in which I want to refer back to a method within my Pointer from the drag stop. However I run into a scope issue. Now I suppose I can use $.proxy(). But I still need the $(this) inside the drag stop to get the width and height(right?)
Can anyone tell me how I can call this.snapToClosestTile()(one of last rows in code) within my draggable.stop()?
function Pointer (obj) {
    this.element = obj;

     this.getSnapX = function () {
        var newOffsetX  = null;
        for (var i in board.tiles) {
            var tile = board.tiles[i];

            var offsetX = tile.offset().left;

            //Compensate a quarter of the width of the object. If the pointer overlaps with 25% or less; it snaps closer to where the pointers' center is.
            var objOffsetX = this.element.offset().left - (this.element.width()*0.25);

            if (lastOffsetX != null) {
                if (objOffsetX >= lastOffsetX && objOffsetX < offsetX) {
                    newOffsetX = tile.offset().left;
                    return newOffsetX;
                }
            }

            //Save a last offset to determine that the object is between the last known offset and the current offset.
            this.lastOffsetX = offsetX;
        }

        return newOffsetX;
    }

     this.getSnapY = function () {
        var newOffsetY  = null;
        for (var i in board.tiles) {
            var tile = board.tiles[i];

            var offsetY = tile.offset().top;
            //Compensate a quarter of the height of the object. If the pointer overlaps with 25% or less; it snaps closer to where the pointers' center is.
            var objOffsetY = this.element.offset().top - (this.element.height()*0.25);

            if (lastOffsetY != null) {
                if (objOffsetY >= lastOffsetY && objOffsetY < offsetY) {
                    newOffsetY = tile.offset().top;
                    return newOffsetY;
                }
            }

            //Save a last offset to determine that the object is between the last known offset and the current offset.
            this.lastOffsetY = offsetY;
        }

        return lastOffsetY;
    }

    this.lastOffsetY = null;
    this.lastOffsetX = null;
    this.snapToClosestTile = function (obj) {
        var newOffsetX = this.getSnapX();
        var newOffsetY = this.getSnapY();

        //When snap positions are found, set the object to those positions. If not, use the drag-start data to reset the pointer to the initial drag-position
        if (newOffsetX != null && newOffsetY != null) {
            this.element.offset({left: newOffsetX, top: newOffsetY});
        } else {
            this.element.offset({left: jQuery(this).data('startX'), top: jQuery(this).data('startY')});
        }
    }

    this.element.draggable({
        containment: '.board_container',
        start: function () {
            //Set all pointers to z-index 1, than higher the current to 2 to always be on top
            jQuery('.pointer').css('z-index', 1);
            jQuery(this).css('z-index', 2);

            //Set a start position in the data of the element to reset it to that place when the stop is out of bounds
            jQuery(this).data('startX', jQuery(this).offset().left);
            jQuery(this).data('startY', jQuery(this).offset().top);
        },
        stop: function (e, obj) {
            //The dragged item is contained to the parent. The parent is as high as the board
            //However; the container is wider than the board(because of the pointer list)
            //Therefore there should be a check to verify that the dragged item was dragged inside the #board div's perimeter.
            //If not; Reset it to its startX and startY defined in the start above.

            //And while we're at it; check the top aswell. It never hurts i suppose.

            var objectMaxPositionLeft = board.offset.maxPosX - jQuery(this).width();
            var currentPositionLeft = obj.offset.left;

            var objectMaxPositionTop = board.offset.maxPosX - jQuery(this).height();
            var currentPositionTop = obj.offset.top;

            if (currentPositionLeft > objectMaxPositionLeft || currentPositionTop > objectMaxPositionTop) {
                jQuery(this).offset({left: jQuery(this).data('startX'), top: jQuery(this).data('startY')});
            }

            this.snapToClosestTile(jQuery(this));
        }
    });
}

A: In most cases you define a variable with a copy of this:
function Pointer()
{
    var that = this;

    this.blah = function()
    {
        ...snip...
        that.foo();  // that represents 'this' inside Pointer()
        ...snip...
    };

    this.element.draggable({
        stop: function()
        {
             ...snip...
             that.foo();   // also works here
             ...snip...
        }
    });

    this.foo  = function()
    {
        ...snip...
    };
}

This is assuming Pointer() is a valid constructor, of course... otherwise this may not mean what you think inside of Pointer().

Update to answer the question about prototype:
function Pointer()
{
}

Pointer.prototype.blah = function() { ... };

Pointer.prototype.foo = function() { ... };

...

Then you can create an instance of the Pointer declaration with:
var ptr = new Pointer();

The advantage, if you need 10 different Pointer objects, is that all those prototype functions do not get duplicated. If you have really large objects, that can become important. It also allows you to inherit an object from another.
I have a working example in the file named editor.js here:
https://sourceforge.net/p/snapcpp/code/ci/master/tree/snapwebsites/plugins/editor/
If you scroll down a bit, you'll see the tree of classes that I use. And also I verify my code with the Google Closure Compiler. It helps a lot avoid many basic mistakes.


text:
Q: How to protect ServeStaticModule module in NestJS with a Guard I have a folder with static files that I want to serve with Nest's ServeStaticModule but I want to protect it with one of the guards that I have.
Is it possible with NestJS style, or the only option is to hang an express middleware with app.use() in the bootstrap() function?


text:
Q: Rails use multiple query in single query for importing csv file data How to pass araay data in IN operator query.
data = ["055226", "000879", "069889", "078720", "078764"] //use array data in query statements IN operator

file_data = ActiveRecord::Base.connection.execute("SELECT t1.user_id, t2.dept_id, t1.price,
t3.first_name, t3.last_name
      FROM price_table t1
      INNER JOIN user_branch_table t2
        on t1.user_id = t2.user_id
      INNER JOIN user_deatils_table t3
        on t1.user_id = t3.user_id
      where t1.user_id in (#{data}) and now() between t2.start_dt and t2.end_dt").first

I have tried with different ways, but didn't get proper.

A: The below should work:
    file_data = ActiveRecord::Base.connection.execute("SELECT t1.user_id, t2.dept_id, t1.price,
t3.first_name, t3.last_name
      FROM price_table t1
      INNER JOIN user_branch_table t2
        on t1.user_id = t2.user_id
      INNER JOIN user_deatils_table t3
        on t1.user_id = t3.user_id
      where t1.user_id in (#{data.join(',')}) and now() between t2.start_dt and t2.end_dt").first

The above won't work for the string inputs, The below should work for string inputs

    ActiveRecord::Base.connection.execute(
      ActiveRecord::Base.send(:sanitize_sql_array, ["SELECT
        t1.user_id, t2.dept_id, t1.price,
        t3.first_name, t3.last_name
        FROM price_table t1
        INNER JOIN user_branch_table t2
        on t1.user_id = t2.user_id
        INNER JOIN user_deatils_table t3
        on t1.user_id = t3.user_id
        where t1.user_id in (?) and now() between t2.start_dt and t2.end_dt", data])).first


text:
Q: How to evaluate multiple rows based on a column Table ActualTO(60000+ records daily increment) have columns rid, caid & consent .rid is primary key.there will be multiple unique caid's corresponding to each rid.consent Column contains either consented or not-consented. How to add a new column which contains list caid's which are not-consented corresponding to each rid.
Rid caid  consent new_col.
1001 qc101 consented qc102;qc111
1001 qc102 notconsented qc102;qc111
1001 qc111 notconsented qc102;qc111
1221 qc244 notconsented qc244;qc201
1221 qc202 consented qc244;qc201
1221 qc201 notconsented qc244;qc201


text:
Q: How to configure Angular secondary route? I am trying to configure secondary routes within a component where the content of the routes are displayed in tabs
In app.component.html
Projected VM
In variation-margin.routing.module.ts
I am trying to configure secondary routes within a component where the content of the routes are displayed in tabs
In app.component.html
Projected VM
In variation-margin.routing.module.ts
const routes: Routes = [{
    path: 'variationMargin',
    component: VariationMarginComponent,
    canActivate: [AuthGuard],
}, {
    path: 'futuresMargin,
    component: FuturesMarginComponent,
    canActivate: [AuthGuard],
    outlet: 'futuresMargin'
}];

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class VariationMarginRoutingModule { }

Within the template for VariationMarginComponent I have tabs
tab1 -> the primary route i.e. the VariationMarginComponent
tab2 -> <router-outlet name='futuresMargin'></router-outlet>

In futures-margin.routing.module.ts. I am not using this component as a standalone route so not sure if this matters.
const routes: Routes = [{
    path: AppSettings.FuturesMarginRoute,
    component: FuturesMarginComponent,
    canActivate: [AuthGuard],
    outlet: 'futuresMargin'
}];

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class FuturesMarginRoutingModule { }

However nothing is showing up for futuresMargin in tab2. I see just he the blank tab.
How should I configure the route for it to show up in the tab2?

A: Turns out the solution is far simpler and the router link needs to be as if it does not even know about the secondary route
Projected VM


text:
Q: GC problems in ES 1.4.4 Frequent full GC even if the memory utilization is 30-40%. We have not changed the default JVM settings
Cluster details

*

*A master node

*Two data nodes

All the replicas are allocated on one node and all the primaries are on the other node. It should not be a problem, right? Also frequent full GC is observed on one of the 2 data nodes.
Shards -
We have around 75 shards with replication as 1. I guess the problem is because of shard over allocation.
Most of the queries we hit are aggregation queries.


text:
Q: Integrate elastic search with Logrus (golang logging) I am using logrus to do all the logging my golang application. However, I also want to integrate this with Elastic Search such that all the logs are also flushed to elastic search when I create a logrus log entry. Currently all logs are created in a file as shown in the snippet below. How could I integrate with elastic search?
type LoggerConfig struct {
    Filename string `validate:regexp=.log$`
    AppName  string `validate:regexp=^[a-zA-Z]$`
}

type AppLogger struct {
    Err    error
    Logger logrus.Entry
}

func Logger(loggerConfig LoggerConfig) AppLogger {
    response := new(AppLogger)
    // validate the schema of the logger_config
    if errs := validator.Validate(loggerConfig); errs != nil {
        response.Err = errs
        // this sets up the error on the the response struct
    }

    logrus.SetFormatter(&logrus.JSONFormatter{})
    f, err := os.OpenFile(loggerConfig.Filename, os.O_WRONLY|os.O_CREATE, 0755)
    if err != nil {
        response.Err = err
    }
    multipleWriter := io.MultiWriter(os.Stdout, f)
    logrus.SetOutput(multipleWriter)

    contextLogger := logrus.WithFields(logrus.Fields{
        "app": loggerConfig.AppName,
    })

    //logrus.AddHook(hook)
    response.Logger = *contextLogger

    //response.Logger.Info("adele")
    return *response

}

I had tried elogrus which adds a hook but I am not sure how to use it. Here is the method which attempts to create elastic search client. How could I integrate this with logrus instance?
func prepareElasticSearchClient() *elastic.Client {
    indexName := "my-server"

    client, _ := elastic.NewClientFromConfig(&config.Config{
        URL:      os.Getenv("ELASTIC_SEARCH_URL_LOGS") + ":" + os.Getenv("ELASTIC_SEARCH_PORT_LOGS"),
        Index:    indexName,
        Username: os.Getenv("ELASTIC_SEARCH_USERNAME_LOGS"),
        Password: os.Getenv("ELASTIC_SEARCH_PASSWORD_LOGS"),
    })

    return client
}

Earlier I have used modules like Winston where it was super easy to setup elastic search logging but somehow, I find little documentation with golang on how to integrate Golang logging with elastic search

A: With elogrus you first create Elastic client and pass it to elogrus hook when creating it with elogrus.NewAsyncElasticHook(). Hook just wraps sending message to Elastic. Then you add this hook to logrus log. Every time you log message using log it will fire your hook and send message (if log level filter passes) to Elastic.
log := logrus.New()
client, err := elastic.NewClient(elastic.SetURL("http://localhost:9200"))
// ... handle err
hook, err := elogrus.NewAsyncElasticHook(client, "localhost", logrus.DebugLevel, "testlog")
// ... handle err
log.Hooks.Add(hook)

Signature of NewAsyncElasticHook is (client *elastic.Client, host string, level logrus.Level, index string) where:

*

*client is pointer to Elastic.Client you obtained before using elastic

*host is string that denotes from which host you are sending the log trace (it's a string - hostname of host where program that logs is running)

*level is the maximum logrus log level you want messages to be sent (e.g. if you want to see DEBUG messages locally but only send only ERROR and below to Elastic)

*index is name of Elastic Search index you want to add messages from log to

From here you can use log normally as you would do with logrus and all messages will get passed to Elastic.
Another part of issue was a bit more tricky and rooted in (not only) Golang elastic client node sniffing behavior. We debugged it in chat and summary was posted as my answer to OP's another question regarding that: Cannot connect to elastic search : no active connection found: no Elasticsearch node available


text:
Q: How to find button created by Ajax outside Ajax I am creating table rows with delete button in it, but the problem is I am not able to find that delete button outside Ajax. So I use Ajax inside Ajax logic but I have to do it again and again. I want to use the button created by Ajax to call separate Ajax call.
My script is:
 $.ajax({
      url : "{{url('addtocart')}}",
      type : "POST",
      data : {_token: CSRF_TOKEN, username:username, userType:userType,
            table_no:table_no, order_no:order_no, cname:cname,
            tname:tname, dname:dname, dish_qty:dish_qty,
            chefnote:chefnote
              },
      success : function(data){
        //console.log(data);
        $('#cartOrder').empty();
        for(var i = 0; i < data.length; i++) {
              drawRow(data[i]);
            }
        function drawRow(rowData) {
                var row = $("
")
                row.empty();
                $("#cartOrder").append(row);
                row.append($("" + rowData.dish + "	"));
                row.append($("" + rowData.dish_qty + "	"));
                row.append($("" + rowData.chefnote + "	"));
                row.append($(""+"<button class='btn btn-primary' value='"+rowData.ord_id+"'>" +"Edit"+"</button>"+" | " +"<button class='btn btn-primary' id='deletecart' value='"+rowData.ord_id+"'>" +"Delete"+"</button>" + "	"));
            }

      //delete cart order
            $('tBody #deletecart').click(function(e){
              e.preventDefault();
              $.get("{{url('deletecart')}}",{id:$(this).val()},function(data){
               // console.log(data);
                 $.ajax({
                      url : "{{url('getcart')}}",
                      type : 'GET',
                      data : {table_no:table_no},
                      success : function(data){
                        console.log(data);
                        $('#cartOrder').empty();
                          for(var i = 0; i < data.length; i++) {
                                drawRow(data[i]);
                              }
                          function drawRow(rowData) {
                            var row = $("
")
                            row.empty();
                            $("#cartOrder").append(row);
                            row.append($("" + rowData.dish + "	"));
                            row.append($("" + rowData.dish_qty + "	"));
                            row.append($("" + rowData.chefnote + "	"));
                            row.append($(""+"<button class='btn btn-primary' value='"+rowData.ord_id+"'>" +"Edit"+"</button>"+" | " +"<button class='btn btn-primary' id='deletecart' value='"+rowData.ord_id+"'>" +"Delete"+"</button>" + "	"));
                          }
                      }
                });
              });
            });
          }
    });
  });

As you can see, first time I use Ajax to load data into table. But when I click delete, the row gets deleted from database but not from the view. So I load that table data on delete button in second Ajax. But it is not working the second time I click the delete button. It is may be because I am calling parent delete function. How can I do this?

A: The problem is with ID. You can not use same id at multiple places in same page. In your case, you need to use class instead of id.
Replace this :
<button class='btn btn-primary' id='deletecart' value='"+rowData.ord_id+"'>" +"Delete"+"</button>

with ?
<button class='btn btn-primary' class='deletecart' value='"+rowData.ord_id+"'>" +"Delete"+"</button>

As you are creating this html in loop so id is repeating. So use class and override your delete function :
 $('tBody .deletecart').click(function(e){


text:
Q: lambda and filter in a list I am trying to understand this code, it gives me a list of all the words that start with s.
What I don't understand is how simply using x [0] == 's', it only evaluates the first letter of the word in the list and not the whole word, that is, x [0] would correspond to soup not only the first letter.
Thanks
seq = ['soup','dog','salad','cat','great']
result = list(filter(lambda x: (x[0] == 's'), seq))
print(result)


text:
Q: How do i query values of an enum in postgresql Hi i want to use an enum in postgresql as an alternative to making a table, because the values my never change, but i want to be able to retrieve these values for an application that might check just in case they do, is there any way the query it to get the values?

A: SELECT unnest(enum_range(NULL::your_enum))::text AS your_column

This will return a single column result set of the contents of the enum "your_enum" with a column named "your_column" of type text.

A: See the manual: Functions and Operators / Enum Support Functions
You probably want the enum_range(...) function.
Alternatively, you could look in the system catalogues: pg_enum


text:
Q: What does it mean that $X_T$ is a solution to a Brownian Motion driven SDE ($dX_t = ....$)? Please consider the
$$
X_t = X_0 + \int^t_of(X_s,s)ds+\int^t_og(X_s,s)dB_s
$$ where $B_t$ is Brownian Motion. This can also be expressed as:
$$dX_t=f()dt+g()dB_t$$
What does it mean that $X_T$ is a solution to the above stochastic differential equation?
I can't seem to intuitive explain this. The way I will put it is:
For a given Brownian motion realization it $X_T$ is a solution to the SDE above.. Is this correct or is there more it?

A: There's actually two definitions of solution to SDE. Strong and weak.

Strong solution. Given a probability space $
(\Omega, \mathcal F, \mathcal F_t,P)$ and a Brownian motion $B(t)$ on that space adapted to $\mathcal F_t$, a solution to $dX=fdt+g~dB(t)$ with initial condition $x\in \mathbb R$ is a continuous process adapted to $\mathcal F_t$ such that $X(t)=x+\int_0^t fdt+\int_0^t g~dB(t)$.

There is also

Weak solution. A process $X(t)$ is called a weak solution to $dX=fdt+g~dB(t)$ if there exists a probability space $
(\Omega, \mathcal F, \mathcal F_t,P)$ and a Brownian motion $B(t)$ on that space adapted to $\mathcal F_t$ such that $X(t)=x+\int_0^t fdt+\int_0^t g~dB(t)$.

Note that strong solution implies weak solution.
As an example of something that has weak but not strong solution, consider Tanaka's equation
$$dX(t)=\text{sign}(X(t))dB(t)$$
It can be shown that this has no strong solution by considering local times. However let $X(t)$ be a Brownian motion and then $X(t)$ is a weak solution. Note that $\int_0^t\text{sign}^2(s)ds=t<\infty$ so the Ito integral $\int_0^t\frac{1}{\text{sign}(s)}dX(s)=\int_0^t \text{sign}(s) dX(s)$ exists. Noting that the quadratic variation of this integral is $t$, and Ito integrals are continuous martingales, so we know $\int_0^t\frac{1}{\text{sign}(s)}dX(s)=\tilde{B}(t)$ is a Brownian motion.
Thus, $dX(t)=\text{sign}(t)d\tilde{B}(t)$.
The difference here is that the Brownian motion is constructed in terms of our solution not the other way around.


text:
Q: get dynamic radiobutton using id in javascript? In my view i create a dynamic radio button the sample code of this is as follows..
 @for (int i = 0; i < Model.ChManufacturer.Count(); i++)
  {
     if (@Model.ChManufacturer[i].Text == "Select ...")
     {
     }
     else
     {
          <input id="manufacturer:@Model.ChManufacturer[i].Text" type="radio" name="Manu_rbgrp" value="@Model.ChManufacturer[i].Text"> @Model.ChManufacturer[i].Text

     }
   }

but i am in need of get the selected radiobutton value. How to get the values of a checked radiobutton.. For Ex:
   O abc , O bbc, O ccc. So if i select the 2nd option means ithe value is bbc. Any answer???
i got the following output at the runtime

<input id="manufacturer:GLI-List" type="radio" value="GLI-List" name="Manu_rbgrp">
 GLI-List

<input id="manufacturer:Latham-List" type="radio" value="Latham-List" name="Manu_rbgrp">
 Latham-List

<input id="manufacturer:Loop-Loc-List" type="radio" value="Loop-Loc-List" name="Manu_rbgrp">
 Loop-Loc-List

<input id="manufacturer:Merlin-List" type="radio" value="Merlin-List" name="Manu_rbgrp">
 Merlin-List

A: Use the onclick event and store selected values in a JS object or array.
Example using of the onclick and getting the id of a radio: http://jsfiddle.net/coshmos/CBk5d/
Code of the examle:

<input id="SomeId" type="radio" onclick="alert(this.id);"/> Radio


text:
Q: How do I build a 2 mH inductor coil (with air gap) from a microwave oven transformer? I am converting the voltage on a kiln from AC to DC. The kiln (48 A, 240 V) holds two crucibles for melting colored glass. When I gather glass using a steel pipe for glassblowing, I receive a strong shock if I am simultaneously grounded.
I theorize that the AC current is causing changes in the glass chemistry. Glass formulas which should be deeply purple (MnO2 addition) are pale and a silver opal glass acts reduced without addition of otherwise essential reducing agents.
I have installed a full-wave bridge rectifier and even tried to add a pair of capacitors (200 V, 20000 μF) running in parallel. This promptly blew my superconductive fuses above the SCR due to a surge current to charge the capacitors. At this point, the schematic below was submitted by member @PSTechPaul to help me realize this idea:

His answer is to run my capacitors in series (400 V, 10000 μF) and add a custom built 2 mH induction coil (choke) made from a microwave oven transformer, or MOT, to filter the flow of ripple current.

I have stripped down a microwave oven transformer to a bare laminated iron core. I plan on winding the coil with 10 AWG insulated, stranded wire.

The part needs an air gap as well and I'm not sure how to construct one. Lots of YouTube videos exist to build custom transformer power supplies from MOTs, but I can't find one for building a choke. I have an LCR meter on order and a small oscilloscope/signal generator as well. I think I know how to test for inductance but any tips would be greatly appreciated. Is this a proper location for an air gap (see below) or could it be slotted anywhere through the laminated iron?
I'll be limited on the ability to size the gap to a saw blade's width so hoping that works. This website looks like a great resource for this project, but I wonder if I'll be better off determining the specs on my coil as I wind it?

This question is the result of advice I received in this post: 240V (North America) bridge rectifier with parallel filter capacitors is blowing fuses above the bridge

A: Making the air gap you propose is difficult, you need to grind or otherwise remove 2 mm off the centre leg.
There is a much easier way to make the same effective length air gap, and that's to put 1 mm in both centre and outer legs. Magnetically, the two gaps are in series, giving you exactly the same effect on inductance.
Identify the welds that hold the Es to the Is, and carefully, with a hand-held hack saw, saw through the middle of the weld. It takes a little time and patience, but this retains the weld that holds each stack of laminations together. Then simply sandwich the Es and Is back together again, with a 1 mm shim of non-magnetic material between them. It can be anything, a stack of 10 sheets of printer paper, a sheet of plastic, maybe even a wood ply.
Using gaps in the external legs results in a larger external field than the internal-only gap would give you, but that should not be an issue in your application.


text:
Q: Can onDestroy() be called without onHandleWork() in JobIntentService? I am using JobIntentService.enqueueWork()
I would like to know if it's ever possible for the onDestroy() to be called even without onHandleWork() called in a JobIntentService.
Basically, what's the lifecycle of a JobIntentService. Is onHandleWork() guaranteed to be called at least once before onDestroy() gets invoked?

A: The behaviour of JobIntentService is different depending on the version of Android running on the target device (prior to API level 26, or API level 26 or higher).
However, generally you can assume that onHandleWork() is called at least once before onDestroy(). There would be no reason to start the Service if there was no work for it. Generally the Service would only be started when there is work in the queue, in which case onHandleWork() would be called immediately after the Service is started.


text:
Q: Read and parse files with go templating Context
I am looking for a nice way to loop through a json array file to populate a video gallery in a Hugo project. Here is the general idea of what I have in mind:
content/
    some_section/
        index.md  (uses {{<iframe_gallery>}})
        videos.json
    ...

videos.json
[
    {
        "title": "some video",
        "url": "https://www.youtube.com/embed/kjkdskdck"
    },
    {
        "title": "some other video",
        "url": "https://www.youtube.com/embed/kjzflzjan"
    }
]

I found a lot of valuable resources about how to load and parse json files in go like this one
Issue
Go and go templating are quite new for me. I don't understand how to transpose what I read about realizing this in plain go to go-templates. I naively started with
iframe_gallery.html
<section class="flex-ns flex-wrap justify-around center">
    {{ $jsonFile, $err := os.Open("./videos.json") }}

and got
Process: loading templates: "/home/zar3bski/Documents/Code/Sites/melainya/layouts/shortcodes/iframe_gallery.html:2:1": parse failed: template: shortcodes/iframe_gallery.html:2: too many declarations in command

I feel like I am missing an important difference but fail to understand it in a synthetic way. How would you load, parse and loop through this json array? Is there a more direct way to achieve this goal?


text:
Q: Show/Hide content in a Gmail email body Our organization is completely on Gmail (Google Apps), and we are trying to figure out a way to show/hide content in the body of the email and have the recipient decide whether to show the content or collapse it to hide it.
The reason why we need to do this is because we send out generic emails in various languages, so we want the recipient to simply click on their language and have the email show the text in that language.
Things we want to avoid:

*

*Sending multiple emails out in different language (and have to manage email recipients languages and multiple emails).

*Display the content for all the languages one after another in the body of the email and have the user scroll down to their language.

One way I thought of doing this is by using Javascript to show/hide a div in the email that would hold the content for each language.  For example, I would have an "English" hyperlink, a "Spanish" hyperlink, a "Chinese" hyperlink, etc and on click, the JS would show the div associated to the language that was clicked.
However, I was not able to get Javascript to run in Gmail when I sent a HTML email from an email client (Thunderbird).
The solution I'm looking for should ideally only require Gmail as some of the users do not have access to browse any other site outside of Gmail from their Chrome browser.

A: The simple solution would just be an HTML (no javascript) email with a "table of contents" at the top showing the various languages. Clicking a language in the table of contents would jump to that language's anchor in the HTML (and thus, the correct language message body).
The hard way to do this would be to write a Gmail contextual gadget:
https://developers.google.com/google-apps/gmail/contextual_gadgets

A: Options that don't work:

*

*JavaScript doesn't work in Gmail

*Pseudo-selectors aren't supported, so you can't do anything like :active td { height:100px }

*display:none and visibility:invisible aren't supported

Ideas that might work

*

*Point the image to your server, and get the HTTP headers. With a combination of HTTP_ACCEPT_LANGUAGE and the IP address, you should be able to serve up the appropriate image.

*In Gmail labs, there is an option to add apps by XML. You could write an app that lets you do more advanced stuff, and tell your users to install that.

Personally, I wouldn't worry about just displaying the content one after the other. Put an index of the languages at the top of the email, with anchor links to the relevant language.


text:
Q: Perl Unicode internals - mess with utf8 Before anyone will tells me to RTFM, I must say - I have digged through:

*

*Why does modern Perl avoid UTF-8 by default?

*Checklist for going the Unicode way with Perl

*How to match string with diacritic in perl?

*How to make "use My::defaults" with modern perl & utf8 defaults?

*and many others (like perluniintro and others) - but - sure, missed something

So, the basic code:
use 5.014;           #getting 'unicode_strings' feature
use uni::perl;       #turning on many utf8 things
use Unicode::Normalize  qw(NFD NFC);
use warnings;
while(<>) {
    chomp;
    my $data = NFD($_);
    say "OK" if utf8::is_utf8($data);
}

At this point, from the utf8 encoded STDIN I got a correct unicode string in $data, e.g. "\w" will match multibyte [\p{Alphabetic}\p{Decimal_Number}\p{Letter_Number}] (maybe something more). That's ok and works.
AFAIK $data does not contain utf8, but a string in perl's internal Unicode format.
Now the questions:

*

*HOW can I ensure (test it), that any $other_data contains valid Unicode string?

*For what purpose is the utf8::is_utf8($data)? The whole utf8 pragma is a mystery for me.

I understand that the use utf8; is only for the purpose of telling Perl that my source code is in utf8 (so do similar things as when my script starts with BOM flag - for BigEndian) - from Perl's point of view, my source code is like an external file - and Perl should know in what encoding it is...
In the above example utf8::is_utf8($data) will print OK - but I don't understand WHY.
Internally Perl does not use utf8, so my utf8 data-file is converted into Perl's internal Unicode, so why does the utf8::is_utf8($data) return true for $data, which is not in utf8 format? Or it is misnamed and the function should be named as uni::is_unicode($data)???
Thanks in advance for clarification.
Ps: @brian d foy - yes, I still don't have the Effective Perl Programming book - I will get it - I promise :) /joking/

A: is_utf8 returns information about which internal storage format was used, period.

*

*It's not related to the value of the string (though certain strings can only be stored in one of the two formats).

*It's not related to whether the string has been decoded or not.

*It's not related to whether the string contains something that has been encoded using UTF-8 or not.

*It's not a validity check of any kind.

Now on to your questions.

The whole utf8 pragma is a mystery for me.
use utf8; tells perl your source code is encoded using UTF-8. If you don't tell it so, perl effectively assumes it's iso-8859-1 (as a side-effect of internal mechanisms).
The functions in the utf8:: namespace are unrelated to the pragma, and they serve a variety of purposes.

*

*utf8::encode and utf8::decode: Useful encoding and decoding functions. Similar to Encode's encode_utf8 and decode_utf8, but they work in-place.

*utf8::upgrade and utf8::downgrade: Rarely used, but useful for working around bugs in XS modules. More on this below.

*utf8::is_utf8: I don't know why someone would ever use that.

HOW i can ensure (test it), than any $other_data contains valid unicode string?
What does "valid Unicode string" mean to you? Unicode has different definitions of valid for different circumstances.

for what purpose is the utf8::is_utf8($data)?
Debugging. It peeks at Perl guts.

In the above example utf8::is_utf8($data) will print OK - but don't understand WHY.
Because NFD happens to have chosen to return a scalar containing a string in the UTF8=1 format.
Perl has two formats for storing strings:

*

*UTF8=0 can store a sequence of 8-bit values.

*UTF8=1 can store a sequence of 72-bit values (although practically limited to 32 or 64 bits.)

The first format uses less memory and is faster when it comes to access a specific position in the string, but it's limited in what it can contain. (For example, it can't store Unicode code points since they require 21 bits.) Perl can freely switch between the two.
use utf8;
use feature qw( say );

my $d = my $u = "abcdé";
utf8::downgrade($d);  # Switch to using the UTF8=0 format for $d.
utf8::upgrade($u);    # Switch to using the UTF8=1 format for $u.

say utf8::is_utf8($d) ?1:0;   # 0
say utf8::is_utf8($u) ?1:0;   # 1
say $d eq $u          ?1:0;   # 1

One normally doesn't have to worry about this, but there are buggy modules. There are even buggy corners of Perl remaining despite use feature qw( unicode_strings );. One can use utf8::upgrade and utf8::downgrade for changing the format of a scalar to that expected by the XS function.

Or it is miss-named and the function should be named as uni::is_unicode($data)???
That's no better. Perl has no way to know whether a string is a Unicode string or not. If you need to track that, you need to track it yourself.
Strings in the UTF8=0 format may contain Unicode code points.
my $s = "abc";  # U+0041,0042,0043

Strings in the UTF8=1 format may contain values that aren't Unicode code points.
my $s = pack('W*', @temperature_measurements);

A:
HOW i can ensure (test it), than any $other_data contains valid unicode string?

You cannot determine ex post facto whether a string has character semantics or byte semantics. Perl does not track this for you. You have to track it by careful programming: encode and decode at the boundaries; :raw layer for byte semantics, :encoding(foo) for character semantics. Employ naming conventions for your variables and functions to clearly differentiate between the semantics and make wrong code look wrong.

for what purpose is the utf8::is_utf8($data)?

It tells you the presence of the SvUTF8 flag, nothing more. This is almost entirely useless for most developers, because it is an internals thing. The flag does not mean that a string has character semantics, its absence does not mean that a string has byte semantics.

The whole utf8 pragma is a mystery for me.

Probably because it is overdocumented, and therefore confusing. Most developers can stop reading after the part where is says that its purpose is to enable Unicode literals in the source code.

In the above example utf8::is_utf8($data) will print OK - but don't understand WHY.

Because of uni::perl which enables use open qw(:utf8 :std);. Any input read from STDIN with <> will be decoded. The normalisation step afterwards does not change that.


text:
Q: Expect method calls from non-instantiated variable with OCMock I'm not sure if that was the best title, but basically I know that a variable will become instantiated upon running a function. I want to do a partial mock of this variable and expect certain method calls before the variable is instantiated. Here's an example of what I'm trying to do.
-(void)testMethod {
    id mockVar = [OCMock partialMockForObject:self.controller.variable];
    [[mockVar expect] someMethod];

    [self.controller method];
    [mockVar verify];
}

The method inside the controller will look something like:
-(void)method {
    self.variable = [[Class alloc]init];
    [self.variable someMethod];
}

I'm receiving a message like 'doesNotRecognizeSelector'. Is this possible?

A: It feels like a weird test, but it's possible if you mock the accessor:
-(void)testMethod {
    id mockVar = [OCMock mockForClass:[Class class]];
    id mockController = [OCMock partialMockForObject:controller];
    [[[mockController stub] andReturn:mockVar] variable];
    [[mockVar expect] someMethod];

    [self.controller method];
    [mockVar verify];
}

If you provide a more concrete example of what you're trying to achieve, I could give you a better answer.

A: If stubbing the property accessor is a possibility, I would go with that.  But if you need to partial mock the instance actually created by the real code, it's possible provided it gets stored on the property -- the setter method becomes the hook -- but it's definitely ugly.
The basic idea is to use OCMArg's checkWithBlock: functionality to intercept the argument to the set method, and create the partial mock at that point.  You can assign it to a variable outside the block for verification later on.  It would look something like this:
-(void)testMethod
{
    id mockController = [OCMockObject partialMockForObject:self.controller];
    __block id mockVar;

    [[[mockController stub] andForwardToRealObject] setVariable:[OCMArg checkWithBlock:^BOOL(id param) {
        mockVar = [OCMockObject partialMockForObject:param];
        [[mockVar expect] someMethod];
        return YES;
    }]];

    [self.controller method];  // mockVar will be created and assigned during this call
    [mockVar verify];
}

If your real code creates an object and only stores it temporarily in a local variable (not an instance variable), there is really nothing you can do, aside from restructuring your real code to make it easier to test (such as moving the code which creates the object into a new method, which makes it much easier to stub).


text:
Q: Automatically update the repositories , when install an application As you know when we are use apt-get update , it updates packages list .
So when we want to install an application or upgrade the older ones, it's better to run apt-get update command to install the Latest application or upgrade to the Latest one .
And here is the question :
What can I do to run apt-get update command automatically, when I run apt-get install Application or apt-get upgrade commands ?
Update : I'm using Ubuntu 16.04 distribution .

A: You could make aliases that you run instead of the real commands, like this:
alias apt-upgrade='sudo apt update && sudo apt upgrade'
alias apt-install='sudo apt update && sudo apt install'

To test, you can simply define the aliases for your current session only  by running the two lines above directly in your terminal. If you are happy with them, make the definitions persistent for your user account by either appending them to the end of your ~/.bashrc file or your ~/.bash_aliases file (which you have to create first in case it doesn't exist yet).
After the aliases are defined one way or the other, you can use them like this:

*

*running apt-upgrade will be equivalent to typing
sudo apt update && sudo apt upgrade

*running apt-install SOME PACKAGES will be equivalent to typing
sudo apt update && sudo apt install SOME PACKAGES


text:
Q: How to find out the file offset of an opened file? My problem is that with
lsof -p pid
I can find out the list of opened file of a process whose process id is pid. But is there a way to find out the file offset of each accessed file ?
Please give me some suggestions ?

A: On linux, you can find the position of the file descriptor number N of process PID in /proc/$PID/fdinfo/$N. Example:
$ cat /proc/687705/fdinfo/36
pos:    26088
flags:  0100001

The same file can be opened several times with different positions using several file descriptors, so you'll have to choose the relevant one in the case there are more than one. Use:
$ readlink /proc/$PID/fd/$N

to know what is the file to which the corresponding file descriptor is attached (it might not be a file, in this case the symlink is dangling).

A: lsof can do this, with the -o option.
Under Linux, it gets its information from /proc, so you can get it there as well.


text:
Q: Patterns between YouTube m. and normal site urls My site is not able to show uploaded youtube videos when the url is a mobile (m.) site, but it works for the normal youtube site. It seems to me that the mobile and normal urls differ in a pattern, as shown below:
http://www.youtube.com/watch?v=5ILbPFSc4_4
http://m.youtube.com/#/watch?v=5ILbPFSc4_4&desktop_uri=%2Fwatch%3Fv%3D5ILbPFSc4_4
obviously, the m. is added, as is the /#, and all the &desktop_uri... stuff.
and again:
http://www.youtube.com/watch?v=8To-6VIJZRE
http://m.youtube.com/#/watch?v=9To-6VIJZRE&desktop_uri=%2Fwatch%3Fv%3D8To-6VIJZRE
What we hope to do is check to see if the url is mobile site, and if it is, parse it so it shows as the normal site.
Does any one know if all youtube urls work this way--if this similar pattern works for all the same videos on mobile and normal sites?

A: In general, any time you attempt to parse URLs for sites (as opposed to web APIs) by hand, you're leaving yourself open to breakage. There's no "contract" in place that states that a common format will always be used for watch page URLs on the mobile site, or on the desktop site.
The oEmbed service is what you should use whenever you want to take a YouTube watch page URL as input and get information about the underlying video resource as output in a programmatic fashion. That being said, the oEmbed response doesn't include a canonical link to the desktop YouTube watch page, so it's not going to give you exactly what you want in this case. For many use cases, such as when you want to get the embed code for a video given its watch page URL, it's the right choice.
If you do code something by hand, please ensure that your code is deployed somewhere where it would be easy to update if the format of the watch pages ever do change.