text:
Q: Why wont my pipeline work? I am trying to make a bash script that will find all the mp3s in my Downloads folder and move them into a music folder.  Why won't this line work?
find ./ -type f -name \*.mp3 | mv *.mp3 /home/mitch/Desktop/Music/$ARTIST

I tried using a pipeline to have the information from the first command translate to the second, but I have never used a pipeline before and don't know if I'm doing it wrong or if I have the wrong idea of what they are used for.

A: The mv command do not use its stdin, so you have to translate the stdin to a parameter, and for this can be used xargs:
find ./ -type f -name '*.mp3' | xargs mv -t /home/mitch/Desktop/Music/$ARTIST

Also, you can directly use the -exec action of find:
find ./ -type f -name '*.mp3' -exec mv {} /home/mitch/Desktop/Music/$ARTIST ';'

Edit
As pointed out by @geirha, the first command do not work if you have filenames containing spaces. In such a case it should be as follows
find ./ -type f -name '*.mp3' -print0 | xargs -0 mv -t /home/mitch/Desktop/Music/$ARTIST

A: The advantage of xargs is that command line expansion.  If you had a command that returned a very large amount of text (or many files all on one command) the you would need xargs.
If you had several thousand files in a directory and wanted to run some script on that list, you might try "./myprogram *", but if your program has any limits on the size of a parameter you might blow the buffer by expanding *.  Also, the command line itself has limits so the command may fails because the command line buffer is overrun.  The use of xargs will avoid the problem.
lastly, the -print0 on find will put null delimiters for spaces in the returned file names, and the -0 option on xargs will interpret those nulls.  Read man xargs.


text:
Q: merge xml elements in one element using xslt-3     <?xml version="1.0" encoding="UTF-8" ?>
<mr:collection
    xmlns:mr="http://www.lc.gov/mr2/slim"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.lc.gov/mr2/slim http://www.lc.gov/standards/mrxml/schema/mr21slim.xsd">
    <mr:rc>
    <mr:dtf tg="2000" i1="1" i2=" ">
        <mr:sbf cd="a">Christoph Kolumbus</mr:sbf>
        <mr:sbf cd="d">John Diter</mr:sbf>
        <mr:sbf cd="b">Julie Nat</mr:sbf>
        <mr:sbf cd="f">Darius Milhaud</mr:sbf>
        <mr:sbf cd="g">Erich kleiber</mr:sbf>
        <mr:sbf cd="g">Franz Ludwig Horth</mr:sbf>
    </mr:dtf>
    <mr:dtf tg="3000" i1="1" i2=" ">
        <mr:sbf cd="a">Christoph Kolumbus</mr:sbf>
        <mr:sbf cd="d">Serg</mr:sbf>
        <mr:sbf cd="b">Mak</mr:sbf>
        <mr:sbf cd="f">DarMil</mr:sbf>
        <mr:sbf cd="g">Erikl</mr:sbf>
        <mr:sbf cd="g">LudHorth</mr:sbf>
    </mr:dtf>
</mr:rc>
<mr:rc>
<mr:dtf tg="2000" i1="1" i2="0">
    <mr:sbf cd="a">Chris Prante</mr:sbf>
    <mr:sbf cd="e">"Chris Dietz"</mr:sbf>
</mr:dtf>
</mr:rc>
</mr:collection>

i need to create a new xml file, by merging the elements that have the value <mr:dtf tg="2000" (irrelevant of what follows in i1 and i2 values),and of course there are other elements in the input xmlfiles with different values,ie <mr:dtf tg="3000" in the following way: the new value of the new single element that will be created will consist of the value of cd a, then a space character and the value of cd b, then a space character, the : character,again a space character, then the value of cd e, then a space character, the / character,again a space character, then the value of cd f, then a space character, the ; character,again a space character, then the value of cd g,only if the above cd elements exist.
Desired output:
<O-PM xsi:schemaLocation="http://www.op.org/O/2.0/ http://www.op.org/O/2.0/O-PM.xsd">
<ListRcs>
    <rc>
        <mtdt>
            <e:rc>
                <d:title xml:lang="el">Christoph Kolumbus Julie Nat / Darius Milhaud ; Erich kleiber ; Franz Ludwig Horth</d:title>
            </e:rc>
        </mtdt>
    </rc>
    <rc>
        <mtdt>
            <e:rc>
                <d:title xml:lang="el">Chris Prante : "Chris Dietz"</d:title>
            </e:rc>
        </mtdt>
    </rc>
</ListRcs>

I have tried only with xsl:value-of select, getting not the result i need... is there a more clever - efficient way to do this? Thank you

A: It is kind of hard to cater for all options of missing or existing items, perhaps the following helps as it outputs certain separators only if the item itself exists; nevertheless I haven't got the exact output, hopefully you can adjust the code to your needs:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xpath-default-namespace="http://www.lc.gov/mr2/slim"
    exclude-result-prefixes="#all"
    expand-text="yes"
    version="3.0">

  <xsl:mode on-no-match="shallow-copy"/>

  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="collection">
    <O-PM>
        <ListRcs>
            <xsl:apply-templates/>
        </ListRcs>
    </O-PM>
  </xsl:template>

  <xsl:template match="rc">
      <rc>
          <xsl:apply-templates/>
      </rc>
  </xsl:template>

  <xsl:template match="dtf[@tg = 2000]">
      <mdtd>
          <rc>
              <title xml:lang="el">{sbf[@cd = 'a']} {sbf[@cd = 'b']}{sbf[@cd = 'e']!(':', .)} {sbf[@cd = 'f']!('/', .)}{(sbf[@cd = 'g'] => string-join(' ; '))!('', .)}</title>
          </rc>
      </mdtd>
  </xsl:template>

  <xsl:template match="dtf[@tg != 2000]"/>

</xsl:stylesheet>

Namespaces for the output were not declared so I have put everything in no namespace.
Example at https://xsltfiddle.liberty-development.net/pNEj9dR.

redpajama_set_name: RedPajamaStackExchange


text:
Q: EdgeDriver - Cannot change window size in Edge I am using the EdgeDriver for running automation tests on my browser (Edge 38.14393.0.0). My tests are in C#, so I am using the .NET driver:
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Edge;

var options = new EdgeOptions();
options.PageLoadStrategy = EdgePageLoadStrategy.Normal;

RemoteWebDriver driver = return new EdgeDriver(Environment.CurrentDirectory, options, TimeSpan.FromSeconds(60));

driver.SetDocumentSize(new Size(800, 600)); // HERE!

The error
This code is the one I run at the beginning of the test. And it fails at the last line with:

Class Initialization method
  Web.TestSuite.UIRendering.RenderingTestSuiteEdge.TestClassInitialize
  threw exception. System.InvalidOperationException:
  System.InvalidOperationException: A window size operation failed
  because the window is not currently available.

With this stack trace:
OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse) in c:\Projects\webdriver\dotnet\src\webdriver\Remote\RemoteWebDriver.cs: line 1126
OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters) in c:\Projects\webdriver\dotnet\src\webdriver\Remote\RemoteWebDriver.cs: line 920
OpenQA.Selenium.Remote.RemoteWindow.set_Size(Size value) in ...

FYI Be aware that I have other tests running on Chrome and IE11 using their respective drivers. When I call SetDocumentSize on those, I get no errors.
Open issues
I could find some open issues related to this problem:

*

*https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/9340417/

*https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8778306/
Questions
So, these are my questions:

*

*Has anybody succeeded in setting the window size in Edge?

*Is this problem I am hitting a known issue? If so, is it fixed? The referenced issues (which look similar) are still open and no status provided.

*Is there any workaround?

A: Try one of those for C#:
driver.Manage().Window.Size = new Size(1920, 1080);
driver.Manage().Window.Maximize();

Although I encounter that error for different reason (like the one here -> https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/10319887/).
Now I kill all process of the driver & edge before each test so hopefully it will be resolved like that:
try
{
     foreach (var process in Process.GetProcessesByName("MicrosoftWebDriver"))
     {
           process.Kill();
     }

     foreach (var process in Process.GetProcessesByName("MicrosoftEdge"))
     {
           process.Kill();
     }
}
catch (Exception)
{
}

Also if you run them on remote machine via RDP for example it will make the same error when you close the RDP. This is the current workaround that I found for it:
Create a batch file with this code:

for /f "skip=1 tokens=3" %%s in ('query user %USERNAME%') do (
  %windir%\System32\tscon.exe %%s /dest:console
)

Create a desktop shortcut to this file. To do this, right-click the batch
file and select Send to | Desktop (create shortcut).

In the shortcut properties, click Advanced and select Run as administrator.

Now, when you need to disconnect from Remote Desktop, double-click this shortcut on the remote computer (in the Remote Desktop window).
Thanks to https://support.smartbear.com/testcomplete/docs/testing-with/running/via-rdp/keeping-computer-unlocked.html for the script.

A: This works for me:
driver.manage().window().setSize(new Dimension(1250, 720));


text:
Q: HTML5 video elements loading time I just want to figure out why my website is serving video files without coherence.
First of all, I have created my website on ODROID-XU4 and OS is Ubuntu. Also, using Django and Apache2 as Framework
Anyway, here is my problem.
Videos won't start instantly when I click the play button
But, funny thing is some video files with big size do play instantly.
For example, when I upload 3GB of video(mkv) and click play button, it plays instantly.
However, another video file which is only 1.8GB uploaded won't be played before fully loaded.
Please, I am waiting for answer from someone who had similar experience
Below, I add my HTML Source Code
{%extends 'base.html'%}

{%block title%}video_detail.html{%endblock%}

{%load staticfiles%}
{%block extrastyle%}{%static 'photo/photo.css'%}{%endblock%}

{%block content%}

{{object.title}}

                <video width="960" height="540" preload="none" controls>
                        <source src="{{object.video.url}}" type="video/mp4; codecs="avc1.4D401E, mp4a.40.2""/>
                        <source src="{{object.video.url}}" type="video/webm; codecs="vp8.0, vorbis""/>
                        <source src="{{object.video.url}}" type="video/oggi; codecs="theora, vorbis""/>
                        Your browser does not support the video element.
                </video>

Video Description

                {%if object.description%}
    {{object.description|linebreaks}}

                {%else%}
(blank)
{%endif%}

Upload Date

{{object.upload_date}}

Album Name

    {{object.album.name}}

Download

{{object.title}}

A: If you use the html5-Video-Tag you've set this parameter in the Video-TAG: preload="none"


text:
Q: Infinite Nested Square Root, Prove or disprove that there is at least one real number  satisfy $$\sqrt{x+\sqrt{x+\sqrt{x+\sqrt{x+...}}}} = 4$$
If I let $X_1=\sqrt x$, $X_2= \sqrt {x+X_1}$, then $X_{n+1}= \sqrt{x+X_n}$
It is a increasing sequence since $X_n<X_{n+1}$ for all $n$.
However, is there any way to say it is bounded?
If yes, is my next step to prove the limit to the infinity of the sequence will converge to $4$.
And finally try to figure out the $x$ value?
In addition, I saw in Wiki that this infinite square can be represent by a function $$\frac 1 2 (1 + \sqrt {1 + 4n})$$
I am able to follow the logic that when x in side the infinite the square is 2, then $x=\sqrt{2+x}$
However, I don't really understand how it can be generalized to the function shown above.

A: When you are dealing with this nested radicals. the first thing you get is that $x$ should be positive. Now to say that the sequence is bounded, an observation would come in hand, if $x \geq 1$ then by induction each term is less than $2x$. For $x <1$ then this sequence is obviously ,term by term, less than the sequence obtained by $x=1$. So in this case it is again bounded. Now for a sequence which is increasing an bounded in $\Bbb R$ then it shoudld its $\sup$. so the limit exists and if it is eqaul to $L$m then you should solve the quadratic eqaution $ L = \sqrt{x+L}$

A: A way to find an upper bound for the function is to try to anticipate the limit of the sequence,  setting $x_n=x_{n+1}=l$..then by induction you can prove that $l$ is an upper bound....


text:
Q: How to disable displaying "New version of Jenkins (2.62) is available for download (changelog)"? seems jenkins is getting updated very frequently. I dont want to see those message where jenkins is popping with red button saying "New version of Jenkins (2.62) is available for download (changelog)".
any one know how to disable this feature in jenkins? Thanks in advance

A: To manually disable it
Manage Jenkins => Configure System => Administrative monitors configuration

UnCheck "Jenkins Update Notification" and apply


text:
Q: EF multiple relationships between entities I'm using the Code First approach to build the database in this problem. I have the following (partial) entity:
public class Tournament {
    public int TournamentID { get; set; }
    public String Name { get; set; }
    public DateTime? StartDate { get; set; }
    public DateTime? EndDate { get; set; }
    public int? SportID { get; set; }

    public virtual Sport Sport { get; set; }

    public virtual ICollection<Official> Officials { get; set; }
}

In the Official Entity I have this:
public class Official {
    public int OfficialID { get; set; }
    public String Surname { get; set; }
    public String FirstName { get; set; }
    public int? TournamentID { get; set; }

    public virtual Tournament Tournament { get; set; }

    public virtual ICollection<Match> Matches { get; set; }
}

Using some sample data and checking the SQL Server database, this works as I would expect it to. The tournament has a one-to-many relationship with officials.
The problem I'm having is that I would like the tournament to hold the primary key of an official as the head official. So I would add to the Tournament entity:
public int? OfficialID { get; set; } // foreign key to official table
public virtual Official HeadOfficial { get; set; } // navigation property

If I do this I get an attribute OfficialID and HeadOfficial_OfficialID in my Tournament table and I get TournamentID, Tournament_TournamentID and Tournament_TournamentID1 in my Officials table. I realise I now not only have a one-to-many relationship between Tournament and Official (seeing as a tournament can have many officials), but I also have a one-to-one relationship (seeing as a tournament can only have one head official).
How can I fix this problem?

A: You can fix the problem by giving EF a hint which navigation properties belong together. EF conventions cannot decide this anymore when you have two navigation properties in a class which refer to the same target class:
public class Tournament {
    public int TournamentID { get; set; }
    //...

    public int? OfficialID { get; set; }
    [ForeignKey("OfficialID")]
    public virtual Official HeadOfficial { get; set; }

    [InverseProperty("Tournament")] // the navigation property in Official class
    public virtual ICollection<Official> Officials { get; set; }
}

It's also possible with Fluent API if you prefer that:
modelBuilder.Entity<Tournament>()
    .HasOptional(t => t.HeadOfficial)
    .WithMany()
    .HasForeignKey(t => t.OfficialID);

modelBuilder.Entity<Tournament>()
    .HasMany(t => t.Officials)
    .WithOptional(o => o.Tournament)
    .HasForeignKey(o => o.TournamentID);


text:
Q: vi/vim repeat :bw with one keystroke? I am manually processing a very large number of files and so I use vim *.txt to open a batch of files and then :bw to close a file and move to the next one in the buffer. This works, but I would like to have a way to repeat :bw with one keystroke, the same way that you can use . to repeat the last command. (If I use ., it repeats the command that I had done before :bw, which was dd.)

A: If you don't use any ex command in the meantime you can use @: to repeat the last ex command.
Anyway, I recommend a quick mapping like:
nnoremap <key> :bwipeout<CR>

A: It is possible to get this down to two keystrokes by recording a macro: qa:bw<enter>q. The macro is then called with @a (or @@ if it was the last macro used). Especially if you are passing over many consecutive files, @@ is much faster/easier to type than :bw.


text:
Q: Multiple post IDs from array in Wordpress I want to display 3 specifics posts.
Problem : My posts IDs are from a previous array.
Result : It displays only the first one.
Function :
foreach($fav_author_list as $i => $item) {
  $insert = get_user_favorites($item);
  if (!is_array($insert[0])) {
    $result = array_merge($result, $insert);
  }
}
$algoid = implode(",", $result);

Result from $algoid (Post ID) = 865, 866, 877
I want to display the three posts.
$myarray = array($algoid);
$args = array(
   'post__in'      => $myarray,
);
// The Query
$the_query = new WP_Query( $args );

A: You don't have to implode your $algoid for the post__in. Since you're using implode, you're actually passing an array with a string for your query:
array('865, 866, 877'); // Items: 1

However, WP_Query is expecting an array with the ids, not as a string:
array(865, 866, 877); // Items: 3

Here's how it should be:
// Use your function to generate the array with the IDs
$algoid = array(865, 866, 877);

$args = array(
    'post__in' => $algoid
);

For more information about WP_Query: https://codex.wordpress.org/Class_Reference/WP_Query

post__in (array) - use post ids. Specify posts to retrieve. ATTENTION If you use sticky posts, they will be included (prepended!) in the posts you retrieve whether you want it or not. To suppress this behaviour use ignore_sticky_posts.


text:
Q: Uniquely Identy Wordpress Installation I am working on an API for wordpress and I am looking for a way to uniquely identify a wordpress installation that is requesting the API. Does anyone know of a install id or unique wordpress blog id? Is that even a thing?

A: I have written 2 APIs and have worked with several, I stumbled upon this question long time back...
I like to keep the stuff simple... so I use site_url() as identity of the blog, since I'm sure no other installation would run on the same site url so whenever there is an issue to debug, I know site ID is the url.
Saved one extra field in my DB ( If I had ID different, I'd need another field for site url ).
You can also go for complex solutions like using md5 of site_url along with some random generated strings to name a few.

Update
This will generate an ID on activation and save it in the database.
function generate_password($length = 12) {
  $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';

  $password = '';
  for ($i = 0; $i < $length; $i++) {
    $password. = substr($chars, rand(0, strlen($chars) - 1), 1);
  }

  return $password;
}

function my_plugin_activated() {
  $id = generate_password();
  add_option('my_plugin_installation_id', $id);
}
register_activation_hook( __FILE__, 'my_plugin_activated' );

Code in my_plugin_activated() is executed only once on activation of plugin ( you can do the same for theme  ), you can, in activation hook itself, make a call to your api and get the site registered in your db.
Hope that helps.


text:
Q: https.onRequest() vs onWrite() firebase using nodejs for Stripe Currently the open sourced cloud function provided by Firebase/Stripe uses onwrite to Firebase database to trigger the charge to Stripe:
https://github.com/firebase/functions-samples/tree/master/stripe
It seems that it would be more direct and faster to just call Stripe using https trigger instead of writing to Firebase local database which syncs/writes to Firebase server database, which then triggers the cloud function call to Stripe.
Will there be any problems using Https call to trigger Stripe call?  What advantages are there for using onwrite trigger instead of https?

A: Beginner to beginner, this is my understanding:
Let's say you have an app where a you need to
(1) sign users up for a subscription using Stripe, and then
(2) when users use the app, check to make sure their subscription is still valid.
For (1),
you'd only do this once(ish) per user, and you need to tell Stripe "make a new subscription for this user," so it makes sense to use an https.onRequest or https.onCall function.
For (2),
you'd be checking to see whether the user is subscribed many times, and you're not telling Stripe something, you're asking it about stored information: "is this user's subscription still valid?"
If you're asking about stored information, it's a lot faster to check your own database rather than to wait for a response from Stripe.  You just need to make sure the information in your database (e.g. Firestore) is up to date with Stripe.
So what you can do is create a Stripe webhook that will trigger an https.onRequest function whenever there is a change to a user's subscription status.  Then, your function writes the change to your database.
So, rather than ask Stripe over and over, "is this user subscribed," and wait for a slow response, you just check your own database, knowing that it's kept up to date by the Stripe webhook.


text:
Q: Create a list of Spatial Polygon dataframe from a list of dataframe I want Create a list of Spatial Polygon dataframe from a list of dataframe. The list of Spatial polygons is called list_sp_Tanzania and the list of dataframe is called list_df_Tanzania_Modis500. Each list contains 61 objects and each objects contains several polygons.
str(list_df_Tanzania_Modis500)
$ :'data.frame':    30 obs. of  11 variables:
  ..$ ID        : int [1:30] 296 298 321 323 324 330 331 361 419 453 ...
  ..$ LU_1990   : int [1:30] 11 11 11 11 11 11 11 11 11 11 ...
  ..$ LU_2000   : num [1:30] 12 12 12 12 12 12 12 12 12 12 ...
  ..$ CHLU_90_00: chr [1:30] "1112" "1112" "1112" "1112" ...
  ..$ LU_2005   : num [1:30] 12 12 12 12 12 12 12 12 12 15 ...
  ..$ CHLU_00_05: chr [1:30] "1212" "1212" "1212" "1212" ...
  ..$ Tile      : Factor w/ 1 level "S11_E039": 1 1 1 1 1 1 1 1 1 1 ...
  ..$ UNIQ_ID   : Factor w/ 30 levels "S11_E039_296",..: 1 2 3 4 5 6 7 8 9 10 ...
  ..$ AREA      : num [1:30] 219337 347133 393961 181875 105137 ...
  ..$ Sour_90_00: chr [1:30] "Modis500_2000" "Modis500_2000" "Modis500_2000" "Modis500_2000" ...
  ..$ Sour_00_05: chr [1:30] "Modis500_2005" "Modis500_2005" "Modis500_2005" "Modis500_2005" ...

str(list_sp_Tanzania)
[[61]]
class       : SpatialPolygons
features    : 30
extent      : 38.95413, 39.04577, -11.04522, -10.95469  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0

Unfortunately, I cannot provide the data with dput because they are s4 objects and I could not find similar examples. Hope someone can help me somehow though.

A: Here is the solution.
fun <- function(x, y) {
  SpatialPolygonsDataFrame(x, y, match.ID = F)
}

list_Spdf_Tanzania_Modis500 <- mapply(FUN = fun,
                                      x = list_sp_Tanzania,
                                      y = list_df_Tanzania_Modis500)


text:
Q: Two different servers (with one tied to SAP), with different login id's. Can they all sync? Forgive me in advance:  I USED to be a network admin many moons ago, but moved to management and my skills have weakened over time.  So I might use wrong terms... background first, then question:
Background
My company uses a standard windows AD login for the network on Server SERVER01 and uses firstname.middleinital.lastname for the usernames.
Our company also has SERVER02 which uses a firstinital.lastname (F.Last) which also ties into our SAP logins (and it seems we only use it to login to SAP).
We had no self-help portal for SERVER01.  We had to call IT and wait on hold forever (Because passwords would expire in waves), to have them change it to something like SPRING17, and then when we logged in, it would force us to change it.  We used to be able to go to PORTAL.SERVER02.COM and login with the old password (Even if expired), and then click a little key icon and change the password.
Then our company made an announcement that there was a NEW portal site that would change both of them for us, and promptly deep-sixed the PORTAL.SERVER02.COM site.
The new site has a dropdown for the domain you wish to fix your password for, but that dropdown only showed SERVER01.
But, we were told by IT, when you changed that password it would also change the SERVER02 password.
I was immediately suspect about that because of the nomenclature of the usernames.  And sure enough, it doesn't do diddly squat to SERVER02 (to be more exact, it does NOT change the password on SAP.. I've never tested logging in to the SERVER02 account itself since the change, but again, there's no need to).
So NOW, we have to call IT for that password reset, but the bigger security risk there is that YOU CAN'T change the password they give you!  So you're stuck with a simple-to-brute-force password for the next 90 days.
Finally, my question
Before I go all ape-sh*t crazy on the IT team, I need to know: Can you link two different server user id's and have a change on one affect the other? AND, have that change also trickle down to an SAP login (I have no idea how they do that, TBH.  I would GUESS LDAP??)?
Sorry for the long story.  But as an old IT guy, the more knowledge, the less troubleshooting/probing questions the expert needs :)

A: In theory your IT guys could have taken care of it by linking the user entries in the two user-management servers with some attribute referencing the foreign user entry. Ideally this should be done based on a unique employee ID or similar which never changes and never gets reused. (Choosing usernames based on person names is bad practice because person names changes.)
So being in your situation I would

*

*test the functionality from your point of view

*ask how they achieved keeping the passwords in sync

I've often seen strange things done in the wild. So chances are quite high that they messed up things though and that your questions reveal that pretty quickly.


text:
Q: ERROR:unknown field '..' While working with Solr, I get this error:
 ERROR:unknown field 'name'

But, I have defined this field in my schema.xml :
<field name="name" type="string" indexed="false"
       stored="true" required="true" elementForm="INPUTHIDDEN" />

I get this error when I try to add the field to the documment which is going to be commited:
doc.addField("name", getName());
solrClient.addDocument(doc);

Any ideas? Thanks in advance.

A: If you want to verify your index configuration within Solr, you can use the /admin/luke handler commonly defined in the solrconfig.xml. The output will give you information about the fields that are defined in the schema that Solr has loaded.
If you don't see your name field in there, you should double check that you've updated your schema.xml in the correct location for your index, and that the appropriate Solr core (or Solr itself) has since been restarted to load the changes.

A: i had the same issue, and i found a solution
i did this
i got the error unknown field
so i looked up in the schema of solr (schema.xml) and i found
i used store that is specified in the schema. you do the same. you should look for a field declared the same way as yours or use commands to add your field ( i don't know very much these, but you gonna find it ;)
)


text:
Q: sign of loglikelihood during parameter estimation I need to optimize parameters of a Gaussian shaped function to best fit my data points using maximum likelihood.
I first make an initial estimate for the parameters (mu, sigma and peak) and apply a gradient descent (fmincon in Matlab) algorithm to optimize these parameters.
The cost function is the sum of the negative log values of probabilities of observing each data point given the model parameters and the model noise parameter.
sum(-log( normpdf( Y - model( X, params) ,0,error_sigma) ));

where,
Y: observations
normpdf : normal probability densitiy function.
model:  a function that takes the x values and parameters to be optimized
params : parameters of the model
error_sigma : noise of the data
I optimize the model parameters and the noise parameter simultaneously to obtain highest -loglikelihood values.
I am puzzled by obtaining negative likelihood values. I would have estimated that -log of probabilities should always evaluate in positive values. However, the matlab function normpdf, especially for small spread values, returns probability values which are bigger than 1.
This is because the integral of the normpdf function does nearly never sums up to 1. Therefore I am thinking that I should be using the normal cumulative function for optimization, instead of normpdf in order to get valid loglikelihood values. However, the parameters never converges as good as the normpdf case, when I use normcdf.
I hope I am clear.


text:
Q: intersection multiplicity from kirwan's book I'm working on F. Kirwan's Complex Algebraic Curves. To define intersection multiplicity, Kirwan choose some special projective coordinates and calculate the resultant. She claims before the definition that "In order to show that the definition is independent of the choice of coordinates we show that it is uniquely determined by the properties listed in the following theorem". That's Theorem 3.18.
However, I can't see why this definition is independent of the choice of coordinates. I can't even agree with the proof for Theorem 3.18. For example, in the existence part of the proof, she tries to prove $I_p(C,D)=I_p(D,C)$ using $\mathcal R_{P,Q}(y,z)=\pm\mathcal R_{Q,P}(y,z)$. However, if I use different projective coordinates to define $I_p(C,D)$ and $I_p(D,C)$, $\mathcal R_{P,Q}(y,z)$ and $\mathcal R_{Q,P}(y,z)$ are not simply determinants with some rows interchanged. So where am I wrong and how should I understand this independence of choice of coordinates?
P.S. I have to presume that you have this book because the proof for Theorem 3.18 is too long to type.


text:
Q: Why wp_update_post strip slashes? I'm trying to update the post_content:
<?php
$something = '<a class=\"class_name\" href=\"#\">';
$my_post = array(
      'ID'           => 1,
      'post_content' => $something,
  );
  wp_update_post( $my_post );
?>

Could anyone tell me why this always strips slashes from the $something?
What can I do to avoid this situation and update it just as it's in $something?

A: @miken32
I've looked into database and it's stripped there :-) I need this because I want to update data that's been stored by another plugin which needs specifically this format in order to work properly.
I already fixed this by replacing wp_update_post with wpdb->update. It seems that this one updates exactly as I wanted.


text:
Q: Buildout installs django but can't import Here's my buildout.cfg:
[buildout]
parts =
    django

[versions]
djangorecipe = 1.5
django = 1.7

[django]
recipe = djangorecipe
project = timetable
eggs =

Here's my routine for setting up project in a new environment:
virtualenv .
source bin/activate
easy_install -U setuptools
python bootstrap.py
bin/buildout -v
python manage.py migrate

When I run bin/buildout, it says django is installed, and django binary is in the bin folder. But when I run manage.py, it can't import django:
(timetable)mick88@s59gr2dmmd:~/timetable$ python manage.py migrate
Traceback (most recent call last):
  File "manage.py", line 8, in <module>
    from django.core.management import execute_from_command_line
ImportError: No module named django.core.management

But it works when I install django using pip. Why doesn't buildout install django in my virualenv? How can I fix this?

A: Buildout doesn't install anything in a virtualenv. Buildout collects python packages and adds programs to the bin/ directory that have the correct python packages added to their sys.path.
So:

*

*virtualenv/pip installs everything into the virtualenv. You have to activate the virtualenv so that it can modify your PYTHONPATH environment variable (and the PATH variable). This way the python from your virtualenv's bin/ directory is used and the python packages from the lib/ dir.

*Buildout adds the necessary "pythonpath" changes to scripts in bin/, modifying the sys.path setting directly instead of through the environment variable.
The one thing you need to know is that you should run bin/django instead of python manage.py. The effect is the same, only bin/django already has the right sys.path setting.
As an example, just look at the contents of the bin/django script. It should look something like this:
#!/usr/bin/python

import sys
sys.path[0:0] = [
  '/vagrant',
  '/vagrant/eggs/djangorecipe-1.10-py2.7.egg',
  '/vagrant/eggs/Django-1.6.6-py2.7.egg',
  '/vagrant/eggs/zc.recipe.egg-2.0.1-py2.7.egg',
  '/vagrant/eggs/zc.buildout-2.2.1-py2.7.egg',
  '/vagrant/eggs/South-1.0-py2.7.egg',
  ...
  ]

import djangorecipe.manage

if __name__ == '__main__':
    sys.exit(djangorecipe.manage.main('yoursite.settings'))


text:
Q: Make a function execute only in Kotlin interfaces? If I have an interface, is there any easy way I can declare a function to make it a public member, but non-overridable? Meaning, it would be exclusively callable and could not be set or overridden by its descendants
interface IFoo {
    fun ExecuteOnly(){
       // Do Something
    }
}

A: I read a book recently by CommonsWare where this situation was described.
and I quote it from there:
"... As a result, anything in an interface hierarchy is permanently open , until you start
implementing the interfaces in classes. If that is a problem — if you have some
function that you really want to mark as final — use abstract classes, not interfaces..."

A: You can define an extension function on the interface.
fun IFoo.executeOnly() {

}

It will still be possible for someone to define a member function with that name in a class implementing IFoo but the intention is quite clear. And anyway when using an object via a IFoo reference the IFoo extension will be chosen.

A: No, you cannot. That's not how Kotlin's interface is implemented.
You can use an abstract class instead
abstract class Foo {
    fun executeOnly(){
       // Do Something
    }
}

A: Ofcourse You Can... Actually there is not much difference bw kotlin interfaces and abstract classes... simply add a body and a private modifier..
interface MyInterface {

    fun triggerTakeMe(){
        takeMe()
    }

   private fun takeMe(){
        println("Taken")
    }
}

class MyClass : MyInterface

fun main() {

    val obj = MyClass()
    obj.triggerTakeMe()

}


text:
Q: How to solve predicate tableaux I can't figure out how to solve this particular tableaux. Especially I don't know how to treat the existence operator which comes first. I can't find a solution neither online or on books, so I don't know if my bet is right.
¬∃x ( ∃y P(x,y) → ∀z P(x,z) )
How I would procede:
( ∃y ¬P(a,y) → ∀z ¬P(a,z) )
now I split into two different fields:
∃y P(a,y) ------------------------------------------- ∀z ¬P(a,z)
P(a,b) --------------------------------------------- ¬P(a,c)
Is this right?
Thanks very much to anyone who will help.

A: No. On the left branch you should get $\neg \exists y P(a,y)$
Also, I wonder what happened to the negation from the very first statement in your post ... Or is that the statement you want to prove valid, i.e. have to negate at the start of the tableaux?
Oh, I see what is going on.  Ok, no, that step you take in the beginning isn't right either. OK, then forget that first comment, and let's start from the very beginning:
$\neg \exists x (\exists y P(x,y) \rightarrow \forall z P(x,z))$
First step (assuming you have this as a separate rule... Some systems go straight to my second step)
$\forall x \neg (\exists y P(x,y) \rightarrow \forall z P(x,z))$
Now instantiate universal:
$\neg (\exists y P(a,y) \rightarrow \forall z P(a,z))$
Use negation of conditional rule:
$\exists y P(a,y)$
$\neg \forall z P(a,z)$
Instantiate existential:
$P(a,b)$
Bring negation in:
$\exists z \neg P(a,z)$
Instantiate existential
$\neg P(a,c)$
... And now you need to instantiate the universal with $b$ and $c$ ... which gives you $d$, and $e$, and $f$, ... and this will just continue without end ...


text:
Q: How do you obtain the fluctuation spectrum of a tubular membrane? I am reading through a paper. A tubular membrane, submitted to tension $\sigma$ acting as a Lagrange multiplier to conserve area, fluctuates around a cylindrical shape of length L and radius R. Parametrisation is as follows,
\begin{equation}
\mathbf{r}(\phi,\zeta)= (x,y,z) = R([1+u(\phi,\zeta)]\cos{(\phi)}, [1+u(\phi,\zeta)]\sin{(\phi)}, \zeta)
\end{equation}
where $0 \leq \phi \leq 2\pi$, $0 \leq \zeta \leq L/R$ and $u(\phi,\zeta)$ is the deformation field.
Using the Canham-Helfrich Hamiltonian, $F= \int dS\left( \frac{1}{2} \kappa H^2 + \sigma \right)$ one can obtain expressions, to second order, for the excess energy.
Long story short, the excess energy can be represented in Fourier modes from which you obtain the mean squared amplitude using the equipartition of energy:
\begin{equation}
\langle \lvert u_{m,n} \rvert ^2 \rangle = \frac{k_B T}{\kappa} \frac{1}{(m^2 -1)^2 + \bar{q}^2 (\bar{q}^2 + 2m^2)}
\end{equation}
The correlation function can also be found:
\begin{align}
C((\phi - \phi '),( \zeta - \zeta')) &= \langle u(\phi,\zeta)u(\phi ', \zeta ') \rangle \\
&= \frac{k_B T R}{2 \pi \kappa L} \sum_{m,\bar{q}} \frac{\cos(m(\phi - \phi '))cos(\bar{q}(\zeta - \zeta '))}{(m^2 -1)^2 + \bar{q}^2 (\bar{q}^2 + 2m^2)}
\end{align}
So my questions are:
1) What is the meaning of the mean squared amplitude and the correlation function?
2) How can I obtain a fluctuation spectrum from them?
The paper can be found here: http://journals.aps.org/prl/pdf/10.1103/PhysRevLett.98.018103
Many thanks in advance.


text:
Q: How to retrieve child data from firebase realtime database on Swift 5 I am facing with firebase problem for 2 days and couldn't handle it.
Here is my realtime database

I am getting content, publishdate, source etc. but tags.
I want to get "0:100"  value that child of tags.  Here is my code:
Could you please help me ?
databaseRef.child("posts").queryOrderedByKey().observe(.childAdded, with: { (snapshot) in
  if let valueDictionary = snapshot.value as? [AnyHashable:String] {
    let newsTitle = valueDictionary["title"]
    let newsImage = valueDictionary["imageUrl"]
    let publishData = valueDictionary["publishData"]
    let content = valueDictionary["content"]
    let tags = valueDictionary["tags"]

    self.news.insert(newsStruct(newsTitle: newsTitle, newsImage: newsImage, publishData: publishData, content: content, tags: tags), at: 0)

    self.tableView.reloadData()
    self.tableViewTagsNews.reloadData()
 }
})

A: Assuming you have multiple posts like this
posts
   0
      tags
         0: 100
         1: 200
   1
      tags
         0: 100
         1: 200

Here's the code that will iterate over each post, one at a time, read the content and then read the tags and output them to the console.
func readPostTags() {
    let postsRef = self.ref.child("posts")
    postsRef.observe(.childAdded, with: { snapshot in
        let content = snapshot.childSnapshot(forPath: "creation_date").value as! String
        let tagsSnap = snapshot.childSnapshot(forPath: "tags")
        let allChildTagsSnap = tagsSnap.children.allObjects as! [DataSnapshot]
        for tagChildSnap in allChildTagsSnap {
            let key = tagChildSnap.key
            let value = tagChildSnap.value as! Int
            print(content, key, value)
        }
    })
}

and the output
0 100
1 200
0 100
1 200

Keep in mind that .childAdded will leave an observer on that node and notify you of further additions.

A: I think it's because you're casting the dictionary so its values are Strings only: if let valueDictionary = snapshot.value as? [AnyHashable:String] so the key value pair that does not have a string as its value gets lost in the conversion.
Instead, cast snapshot.value as [String: Any] and then get the tags like this: let tags: Int = valueDictionary["tags"] ?? 0.


text:
Q: How to apply style to Chrome without affecting Edge I'm trying to apply a style for chrome to fix a bug. I'm able to get it working, but when I check it in Edge I get now edge looks off. How can I apply my style to just Chrome (I'm using version 60), without affecting any other browsers?
@media (min-width: 860px) and (-webkit-min-device-pixel-ratio: 0) {
    table.content tbody tr td { min-width: 90px; }
}

@media (min-width: 711px) and (max-width: 860px) and (-webkit-min-device-pixel-ratio: 0) {
    table.content tbody tr td { min-width: 60px; }
}

A: To target specific browser you can use @supports and combine supported and/or unsupported CSS properties by particular browser. Also you can exclude other browsers this way.
If you care only about Chrome on Windows, you should know that it doesn't support hyphens: auto even with -webkit prefix (but Chrome for Mac and Android supports -webkit-hyphens: auto) so to target Chrome for Windows with media query use
@supports not ((-webkit-hyphens: auto) or (-ms-hyphens: auto) or (hyphens: auto)) {
/* Your styles here */
}

Example

@supports not ((-webkit-hyphens: auto) or (-ms-hyphens: auto) or (hyphens: auto)) {
  * {
    color: red;
  }
}
This is red, but only in Chrome for Windows


text:
Q: Swift UITableView delete selected row and any rows above it My TableView contains cells that represent a mileage log. I need to allow users that ability to delete any mistakes. The tableview lists the logs in descending order. Deleting the top row is OK. Deleting any other row I need to issue a warning as an alert and if confirmed then delete the selected row + all rows above it. Is this possible? Is there any example code anywhere?
UPDATE
Based on the two answers I have had so far I have done the following....
import UIKit
import CoreData

class MileageLogsTableViewController: UITableViewController, NSFetchedResultsControllerDelegate {

    @IBOutlet var milageLogTableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        do {
            try fetchedResultsController.performFetch()
        } catch {
            let fetchError = error as NSError
            print("Unable to fetch MileageLog")
            print("\(fetchError), \(fetchError.localizedDescription)")
        }

        // Display an Edit button in the navigation bar for this view controller.
        self.navigationItem.leftBarButtonItem = self.editButtonItem()
    }

    // MARK: - Table view data source

    private lazy var fetchedResultsController: NSFetchedResultsController = {
        // Initialize Fetch Request
        let fetchRequest = NSFetchRequest(entityName: "MileageLog")

        // Add Sort Descriptors
        let dateSort = NSSortDescriptor(key: "tripDate", ascending: false)
        let mileSort = NSSortDescriptor(key: "startMileage", ascending: false)
        fetchRequest.sortDescriptors = [dateSort, mileSort]

        let delegate = UIApplication.sharedApplication().delegate as! AppDelegate
        let managedObjectContext = delegate.managedObjectContext

        // Initialize Fetched Results Controller
        let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: "rootCache")

        //ADDED AS PER ANSWER FROM SANDEEP
    fetchedResultsController.delegate = self

        return fetchedResultsController

    }()

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        if let sections = fetchedResultsController.sections {
            return sections.count
        }

        return 0
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let sections = fetchedResultsController.sections {
            let sectionInfo = sections[section]
            return sectionInfo.numberOfObjects
        }

        return 0
    }

     override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("MileageLogCell") as! MileageTableViewCell

        // Fetch MileageLog
        if let mileageLog = fetchedResultsController.objectAtIndexPath(indexPath) as? MileageLog {
            //format date as medium style date
            let formatter = NSDateFormatter()
            formatter.dateStyle = .MediumStyle
            let logDateString = formatter.stringFromDate(mileageLog.tripDate!)
            //format NSNumber mileage to string
            let mileageInt:NSNumber = mileageLog.startMileage!
            let mileageString = String(mileageInt)

            cell.lb_LogDate.text = logDateString
            cell.lb_LogMileage.text = mileageString
            cell.lb_LogStartLocation.text = mileageLog.startLocation
            cell.lb_LogDestination.text = mileageLog.endLocation
        }
        return cell
     }

    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        return true
    }

    // MARK: Fetched Results Controller Delegate Methods
    func controllerWillChangeContent(fetchedResultsController: NSFetchedResultsController) {
        tableView.beginUpdates()
    }

    func controllerDidChangeContent(fetchedResultsController: NSFetchedResultsController) {
        tableView.endUpdates()
    }

    func controller(fetchedResultsController: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
        switch (type) {
            case .Insert:
                break;
            case .Delete:

                let context = fetchedResultsController.managedObjectContext
                if let indexPath = indexPath {

                    if indexPath.row == 0 {
                        //this is the top (first row)
                        // Deleting without warning
                        let objectToDelete = fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject
                        context.deleteObject(objectToDelete)

                        do {
                            try context.save()
                            self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)

                        } catch {
                            print(error)
                        }
                        self.tableView.reloadData();

                    } else {
                        //we are deleted a row that is not the top row
                        // we need to give a warning and if acknowledged then delele all rows from the selected row and all rows above it

                        let alertController = UIAlertController(title: nil, message: "Are you sure? This will remove this and all logs above it.", preferredStyle: .Alert)
                        let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in

                        }
                        alertController.addAction(cancelAction)
                        let deleteAction = UIAlertAction(title: "Delete", style: .Default) { (action) in

                            for deleteindex in 0 ... indexPath.row {
                                let deleteIndexPath = NSIndexPath(forRow: deleteindex, inSection: 0)
                                let objectToDelete = self.fetchedResultsController.objectAtIndexPath(deleteIndexPath) as! NSManagedObject
                                context.deleteObject(objectToDelete)

                                do {
                                    try context.save()
                                    self.tableView.deleteRowsAtIndexPaths([deleteIndexPath], withRowAnimation: .Fade)

                                } catch {
                                    print(error)
                                }
                            }
                            self.tableView.reloadData();
                        }
                        alertController.addAction(deleteAction)

                        // Dispatch on the main thread
                        dispatch_async(dispatch_get_main_queue()) {
                            self.presentViewController(alertController, animated: true, completion:nil)
                        }

                    }
                }
                break;
            case .Update:
                break;
            case .Move:
                break;
        }
    }

}

Now my problem is that the touching Delete does nothing. The treeview is correctly populated. The Edit button is in the navbar. Click Edit and the 'no entry' icon appear on each row... slide a row and the Delete block appears. Click delete and nothing...! What have I missed out?
FINAL WORKING FIX
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

    switch editingStyle {

     case .Delete:
        let context = fetchedResultsController.managedObjectContext
            if indexPath.row == 0 {
                //this is the top (first row)
                // Deleting without warning
                let indexPathToDelete = NSIndexPath(forRow: 0, inSection: 0)
                let objectToDelete = fetchedResultsController.objectAtIndexPath(indexPathToDelete) as! NSManagedObject
                context.deleteObject(objectToDelete)

                do {
                    try context.save()
                    //self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)

                } catch {
                    print(error)
                }
                //self.tableView.reloadData();

            } else {
                //we are deleted a row that is not the top row
                // we need to give a warning and if acknowledged then delele all rows from the selected row and all rows above it

                let alertController = UIAlertController(title: nil, message: "Are you sure? This will remove this and all logs above it.", preferredStyle: .Alert)
                let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in

                }
                alertController.addAction(cancelAction)
                let deleteAction = UIAlertAction(title: "Delete", style: .Default) { (action) in

                    for deleteindex in 0 ... indexPath.row {
                        let deleteIndexPath = NSIndexPath(forRow: deleteindex, inSection: 0)
                        let objectToDelete = self.fetchedResultsController.objectAtIndexPath(deleteIndexPath) as! NSManagedObject
                        context.deleteObject(objectToDelete)

                    }

                    do {
                        try context.save()

                    } catch {
                        print(error)
                    }
                }
                alertController.addAction(deleteAction)

                // Dispatch on the main thread
                dispatch_async(dispatch_get_main_queue()) {
                    self.presentViewController(alertController, animated: true, completion:nil)
                }

            }
        break;

    default :
        return
    }

}

// MARK: Fetched Results Controller Delegate Methods
func controllerWillChangeContent(controller: NSFetchedResultsController) {
    tableView.beginUpdates()
}

func controllerDidChangeContent(controller: NSFetchedResultsController) {
    tableView.endUpdates()
}

func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
    switch type {
    case .Insert:
        break;
    case .Delete:
        tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
    case .Update:
        break;
    case .Move:
        break;
    }
}

A: Apart from the enhancement to use edit actions this is the easy solution.
First of all do not touch the delegate method didChangeObject.
Leave it as it is. It is called after making changes in the managed object context and works like the view in the MVC pattern.
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
    switch type {
        case .insert:
            tableView.insertRows(at: [newIndexPath!], with: .fade)
        case .delete:
            tableView.deleteRows(at: [indexPath!], with: .fade)
        case .update:
            self.configureCell(tableView.cellForRow(at: indexPath!)!, atIndexPath: indexPath!)
        case .move:
            tableView.deleteRows(at: [indexPath!], with: .fade)
            tableView.insertRows(at: [newIndexPath!], with: .fade)
    }
}

Insert the code to delete the rows in commitEditingStyle which works like the model in the MVC pattern. The code deletes all rows from the selected row above in the current section.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    switch editingStyle {
    case .delete:
      let context = fetchedResultsController.managedObjectContext
      let section = indexPath.section
      let currentRow = indexPath.row
      for index in 0...currentRow {
          let indexPathToDelete = IndexPath(row: index, section: section)
          let objectToDelete = fetchedResultsController.object(at: indexPathToDelete) as! NSManagedObject
          context.delete(objectToDelete)
      }
      do {
        try context.save()
      } catch {
        print(error)
      }

    case .insert, .none: break
    }
  }

A: Here is what I believe what you can do :)
Knowing that you have already sorted your data using fetchedResultsController sort predicate :) now all you have to do is to delete all the rows from 0 to row the user has selected :)
Because you have only one section and all cell will have section as "0" in their index path :) all you have to do is to iterate from 0 to row number of the cell selected :)
create a indexpath with iterated value as row and "0" as section :) fetch the object from fetchedResultsController and delete it in a loop :)
Once done reload the tableView :)
Refering to your previous question :)
case .Delete:
        // Delete the row from the data source

        let context = fetchedResultsController.managedObjectContext
        for deleteindex in 0 ... indexPath.row {
                var deleteIndexPath = NSIndexPath(forRow: deleteindex, inSection: 0)
                let objectToDelete = fetchedResultsController.objectAtIndexPath(deleteIndexPath) as! NSManagedObject
               context.deleteObject(objectToDelete)
        }
        do {
          try context.save()
          self.tableView.reloadData();
        } catch {
           print(error)
        }

EDIT
As per your updated question, none of the fetchedResults controller delegates are getting called.
That's because, you haven't told fetchedResults controller whom to inform when something happens in DB. What I meant is you have not set the delegate of fetchedResults controller to self buddy :)
copy pasting your own code with modification and comment
private lazy var fetchedResultsController: NSFetchedResultsController = {
        // Initialize Fetch Request
        let fetchRequest = NSFetchRequest(entityName: "MileageLog")

        // Add Sort Descriptors
        let dateSort = NSSortDescriptor(key: "tripDate", ascending: false)
        let mileSort = NSSortDescriptor(key: "startMileage", ascending: false)
        fetchRequest.sortDescriptors = [dateSort, mileSort]

        let delegate = UIApplication.sharedApplication().delegate as! AppDelegate
        let managedObjectContext = delegate.managedObjectContext

        // Initialize Fetched Results Controller
        let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: "rootCache")

        //set the delegate to self here. You have confirmed the fetchedResultsController delegate in interface remember ??
        fetchedResultsController.delegate = self

        return fetchedResultsController

    }()

Hope I answerred your question :) Have a doubt ? Leave a comment below :) Happy coding buddy :)

A: You can do it using the editActionsForRowAtIndexPath method of UITableViewDelegate protocol, available since iOS 8.0.

Return Value
An array of UITableViewRowAction objects representing the actions for the row. Each action you provide is used to create a button that the user can tap.
Discussion
Use this method when you want to provide custom actions for one of your table rows. When the user swipes horizontally in a row, the table view moves the row content aside to reveal your actions. Tapping one of the action buttons executes the handler block stored with the action object.

Here is an example of implementation
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {

    if indexPath.row == 0 {
        // Deleting without warning

        // The closure will be called when tapping on the action
        let deleteClosure = { (action: UITableViewRowAction!, indexPath: NSIndexPath!) -> Void in

            // Delete the first object
            // you can animate it with the BeginUpdates... EndUpdates too
            self.dataSourceArray.removeAtIndex(0)
            self.tableView.reloadData()
        }

        // Default style is Destructive
        return [UITableViewRowAction(style: .Default, title: "Delete", handler: deleteClosure)]
    }
    else  {
        // Deleting with warning

        // The closure will be called when tapping on the action
        let deleteClosure = { (action: UITableViewRowAction!, indexPath: NSIndexPath!) -> Void in

            let alertController = UIAlertController(title: nil, message: Localization(kStr_NotifDisabled), preferredStyle: .Alert)
            let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in

            }
            alertController.addAction(cancelAction)
            let deleteAction = UIAlertAction(title: "Delete", style: .Default) { (action) in

                self.dataSourceArray(Range(start: 0, end: indexPath.row))
                self.tableView.reloadData()
            }
            alertController.addAction(deleteAction)

            // Dispatch on the main thread
            dispatch_async(dispatch_get_main_queue()) {
                self.presentViewController(alertController, animated: true, completion:nil)
            }
        }
        // Default style is Destructive
        return [UITableViewRowAction(style: .Default, title: "Delete", handler: deleteClosure)]
    }
}

A: override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true

}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
  arrRecordList.removeAtIndex(indexPath.row)
  tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)

}

}


text:
Q: using scheduleAtFixedRate and Schedule method for newSingleThreadScheduledExecutor I followed the following link to implement a single thread scheduled Executor
Link to example
I am a bit confused at why the schedule method is invoked after the scheduleAtFixedRate method.
What exactly is the reason for having the schedule method here?

A: It is used to cancel the periodic task after 1 hour


text:
Q: Why DbSet<> not works with asp.net core web application? I'm working on an ASP.Net Core Web Application. While trying to set the dbset<>, I get this error.
This line of code gives error:
 public DbSet<Person> Persons { get; set; }
Resharper suggests two options:

*

*System.Data.Entity.

*Microsoft.EntityFrameworkCore.

public System.Data.Entity.DbSet<Person> Persons { get; set; }
Can anyone please explain which one to chose: the first or second option?
I have included the necessary references.
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using Microsoft.EntityFrameworkCore;
using DbContext = System.Data.Entity.DbContext;

I see this error:

A: The using directive is a shortcut to allow you to write just DbSet instead of System.Data.Entity.DbSet, for example.
But both System.Data.Entity and Microsoft.EntityFrameworkCore have a DbSet class, so it doesn't know which one to use, and it's not going to choose for you. So you have to tell it.
That said, you shouldn't be using both. Entity Framework 6 and Entity Framework Core are two completely different things. System.Data.Entity is for EF 6, and Microsoft.EntityFrameworkCore is for EF Core.
You probably shouldn't be using System.Data.Entity.

A: The reason is Ambigous Reference:
that DbSet<> is defined in both System.Data.Entity and Microsoft.EntityFrameworkCore.
Since you are working with ASPNET Core, recommended is to use Microsoft.EntityFrameworkCore


text:
Q: How long/how much did it cost to develop iPhone SDK & App Store
Possible Duplicate:
How much does it cost to develop an iphone application?

Hope somebody can help. I have been googling trying to get an indication of how long it took apple to develop the AppStore & the iPhone SDK?
My Co. have had an idea to try and do a similar thing internally for our own apps and  massively underestimating the amount of work that will be required.
If anybody has any idea how long Apple spent developing the SDK & AppStore, links to any pages even better, I would be very grateful for the info so that I can use that for discussion about the plans.
Cheers

A: Well apple has hundreds of trained engineers working for them, even still at launch, Steve Jobs said the iPhone took around 6 years to create. Along this time frame they were creating the iPhone SDK which they used to create all the apps built in to the phone. Since then they have been constantly updating the SDK several times a year, expanding a lot. The App Store, my guess is that they used the robust iTunes base they already had for distribution, and then all the rest (legal and technical) things should have taken no time at all.
I'm not sure what your company wants to do but it seems without Apple's resources you'd be better off not.


text:
Q: Replace the values in the column of a dataframe a<-c('F','M','F','M','M','F')
b<-data.frame(a)
d<- c('1','2')

Expected result:
  a
1 1
2 2
3 1
4 2
5 2
6 1

A: Using factor method by specifying the labels as 'd'
b$a <- factor(b$a, levels = c('F', 'M'), labels = d))

Or with matching based on a named vector
setNames(d, c("F", "M"))[as.character(b$a)]


text:
Q: How to color the entire web page I am using simple HTML and CSS my background color is only filling a third of the page and I want it to fill the entkire page. I have tried using the html and body class for background color and this did not work. Here is my code below:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">
<meta name="viewport" content="initial-scale=1.0">

Web Page Blocked

Access to the web page you were trying to visit has been blocked in accordance with company policy.

Please contact The Support Desk if you believe this is in error.

User:

URL:

Category:

A: You should be used both tags also.

A: For me it worked properly:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">
<meta name="viewport" content="initial-scale=1.0">

Web Page Blocked

Access to the web page you were trying to visit has been blocked in accordance with company policy.

Please contact The Support Desk if you believe this is in error.

User:

URL:

Category:

But you should use this instead of bgcolor:

A: Instead of using BGColor on the body tag in HTML, try adding this to your CSS.
body {
    background-color:#f6f6f6; // you can choose any color
}

A: use;
body,html {
    background-color:#DBD7D6;
}

This will set the background color of your entire html file
`


text:
Q: How to replace comma separated different values with a particular value I've a string with the values - 'a','b','c','d,'e'. I need to convert each of the values to the text null - null,null,null,null,null. If there are 10 values in quotes and separated by comma, then 10 null will appear. I tried using REGEXP_REPLACE but failed to get the result.
declare
a varchar2(32767) := q'#'a','b','c'#';
c varchar2(32767);
begin
c := replace(REGEXP_REPLACE (a, <don't know what pattern should be here>, 'null'),'''');
dbms_output.put_line(c);
end;
/

A: There are many ways to do this. For example, you could use the regular expression '[^,]+' - which means any number (one or more) of consecutive non-comma characters. Then every occurrence of that pattern will be replaced with the replacement string (while the commas will stay in place).
declare
a varchar2(32767) := q'#'a','b','c'#';
c varchar2(32767);
begin
c := REGEXP_REPLACE (a, '[^,]+', 'null');    -- notice the regular expression
dbms_output.put_line(c);
end;
/

null,null,null

PL/SQL procedure successfully completed.


text:
Q: Mirth - Waiting for a message from server before querying for data I am new to Mirth (currently using version 2.2.1.56861)
I need to configure a client so that it does the following:

*

*Makes a connection to a server port

*Waits for a message (ORU^R01)

*Sends a QRY^R02 to the server

Is this possible in Mirth?
I have setup an LLP sender, but it appears the connection is made, the QRY^R02 is sent and then the connection is closed
Any help would be much appreciated.
Thanks

A: If I understand your question correctly, what you need is to set up a channel like this:
Source: LLP Listener

*

*Waits for server to connect to it and send an ORU^R01 message.

*Other message types may be filtered out based on Source Filter criteria.

*May use Transformer steps to pull data out of the ORU^R01 message for use in the QRY^R02 message.

Destination: LLP Sender

*

*When a ORU^R01 is received from Source, sends a related QRY^R02 message to a server.

*Constructs the QRY^R02 message using a series of Transformer steps operating on a Message Template.

*Does not need to send to the same port or even the same server as the ORU^R01 message was received on.


text:
Q: Shell scripting and using backslashes with back-ticks? I'm trying to do some manipulation with Wordpress and I'm trying to write a script for it...
# cat /usr/local/uftwf/_wr.sh
#!/bin/sh
# $Id$
#

table_prefix=`grep ^\$table_prefix wp-config.php | awk -F\' '{print $2}'`
echo $table_prefix
#

Yet I'm getting following output
# /usr/local/uftwf/_wr.sh
 ABSPATH ABSPATH wp-settings.php_KEY LOGGED_IN_KEY NONCE_KEY AUTH_SALT SECURE_AUTH_SALT LOGGED_IN_SALT NONCE_SALT wp_0zw2h5_ de_DE WPLANG WP_DEBUG s all, stop editing! Happy blogging. */
#

Running from command line, I get the correct output that I'm looking for:
# grep ^\$table_prefix wp-config.php | awk -F\' '{print $2}'
wp_0zw2h5_
#

What is going wrong in the script?

A: The problem is the grep command:
table_prefix=`grep ^\$table_prefix wp-config.php | awk -F\' '{print $2}'`

It either needs three backslashes - not one - or you need to use single quotes (which is much simpler):
table_prefix=$(grep '^$table_prefix' wp-config.php | awk -F"'" '{print $2}')

It's also worth using the $( ... ) notation in general.
The trouble is that the backquotes removes the backslash, so the shell variable is evaluated, and what's passed to grep is, most likely, just ^, and each line starts with a beginning of line.

A: You should try
#!/bin/sh

table_prefix=$(awk -F"'" '/^\$table_prefix/{print $2}' wp-config.php)
echo $table_prefix

A: Does this one work for you?
 awk -F\' '/^\$table_prefix/ {print $2}' wp-config.php

Update
If you are using shell scripting, there is no need to call up awk, grep:
#!/bin/sh
while read varName op varValue theRest
do
    if [ "_$varName" = "_\$table_prefix" ]
    then
        table_prefix=${varValue//\'/}   # Remove the single quotes
        table_prefix=${table_prefix/;/} # Remove the semicolon
        break
    fi
done < wp-config.php

echo "Found: $table_prefix"

A: This has all the appearance as though the grep is not omitting all the lines that are not matching, when you issue the echo $table_prefix without quotes it collapses all the white space into a single output line, if you issue an: echo "$table_prefix", you would see the match with all the other white-space that was output.
I'd recommend the following sed expression instead:
table_prefix=$(sed -n "s/^\$table_prefix.*'\([^']*\)'.*/\1/p" wp-config.php)


text:
Q: В чем разница пакетов javax и jakarta? Когда импортирую классы пакета jaсarta(когда создаю новый проект по умолчанию импортируются они), маппинг сервлета не работает и в браузере вылетает ошибка 404, а когда импортирую вместо них javax, работает.Подскажите пожалуйста в чем причина? Прикрепляю скрины:

A: jakarta и javax
Ранее Java состояла из:

*

*Java SE (Standart Edition)

*Java EE (Enterprise Edition)

В последнем содержались наборы спецификаций и документация для языка Java, описывающей архитектуру серверной платформы для разработки Enterprise приложений.
Соответственно реализации Java EE содержали и пакет javax.
После поглащения Sun Microsystems  корпорацией Oracle, последняя отказалась от поддержки Java EE.
Развитием и поддержкой последнего занялось сообщество с компании, использующие данные технологии.
Но так как Java является зарегистрированной торговой маркой - разработчикам, поддерживающим реализации Java EE, пришлось переименовать часть пакетов во избежания исков со стороны Oracle.
И jakarta - одна из реализаций Java EE
Вот и весь сказ.

*

*Старые пакеты и реализации  - javax.*

*Новые - jakarta.*, etc

Что подключать
С одной стороны кажется что все одно и тоже и нет разницы что именно подключать.
Но то не так!
У Вас должен быть подключен пакет, который совместим с версией вашего сервера приложений.
логика та же
Старые версии сервера приложений - javax
Новые - jakarta, etc
Чтобы не гадать - можете посмотреть зависимости сервера приложений и подключить ту же у себя в приложении.
(если приложите версию сервера приложений - могу предложить что именно подключать)


text:
Q: Cannot index decimal values from CSV I'm using SOLR 6.6.2 and im trying to update a core with a CSV file of vehicle data.
Each column of data consists of various datatypes such as ints, string, dates and decimal values.
The problem is with the decimal values. I have to update them to zero decimal places otherwise i get the following error:

PS C:\solr-6.6.2\example\exampledocs> java -Dtype=text/csv
  -Dc="vehicles" -jar post.jar vehicles.csv
using content-type text/csv... POSTing file vehicles.csv to [base]
  SimplePostTool: WARNING: Solr returned an error #400 (Bad Request) for
  url: http://localhost:8983/solr/vehicles/update SimplePostTool:
  WARNING: Response:
  400124org.apache.solr.common.SolrExceptionjava.lang.NumberFormatExceptionERROR: [doc=d90354e7-3d73-4718-aeb5-80b0ce8fccf9] Error
  adding field 'Price'='7950.01' msg=For input string:
  "7950.01"400
  SimplePostTool: WARNING: IOException while reading response:
  java.io.IOException: Server returned HTTP response code: 400 for URL:
  http://localhost:8983/solr/vehicles/update 1 files indexed. COMMITting
  Solr index changes to http://localhost:8983/solr/vehicles/update...
  Time spent: 0:00:01.363>  SimplePostTool version 5.0.0 Posting files to [base] url
  http://localhost:8983/solr/vehicles/update

What isn't helping is that im learning from the SOLR pluralsight videos which are using SOLR version 4 which uses the schema.xml to define the fields, but it appears this is deprecated in version 6 and from what I read there should be no need to modify a schema.

A: There still is a schema - and you should create / edit it explicitly to match your values.
When you're running in the schemaless mode, a guess is made when the first value for a field is encountered. This guess seems to be wrong for your dataset - i.e., the first value isn't considered a decimal number for some reason. You can see which type Solr guessed for your column under the schema browser in the Admin interface.
The best solution is to create an explicit schema - so you're sure that your columns are matched to a specific type.
You can edit the schema directly in the Admin interface, use the Schema API, or modify the schema.xml file as in previous versions.


text:
Q: server socket javascript and client android . Its possible? . Its possible to develop a server socket on javascript and client android.
If its possible how can i send message from socket server made in java script to client made in android.. help me plsss

A: Yes you can, using node.js...you can create websocket server. :-) In android devices, I only tested it in firefox mobile browser...maybe you can achieve your goal if you will use phonegap.


text:
Q: Symfony not serving concurrent requests My problem is that my Symfony application running on a remote machine with Apache/2.4.6 (CentOS) PHP/5.6.31 MySQL 5.7.19 does not handle concurrent requests. Meaning that when asking for two different pages at the same time. First one has to finish before second one can be rendered.
I have a another site on the same server written in plain Php which has no problem rendering as many pages as possible at the same time (it uses deprecated mysql connection not pdo like Doctrine).
That said I have done the following test:
I have inserted a sleep(3); at my DefaultController. I requested that page and simultaneously requested a different one. See the two profilers below:
Page with sleep (called 1st):

Page without sleep (called 2nd).

*

*Page 1 normal load time is 782ms

*Page 2 normal load time is 108ms
As you can see Symfony's Http Firewall is taking all of the time of the second page to load.
My guess (might be stupid) is that 1st action holds the database connection and only until it has finished with it does it let it go for other requests to use it. And especially something having to do with Doctrine's use of PDO connection.
By the way I have already read help and articles like:
 - What is the Symfony firewall doing that takes so long?
 - Why is constructing PDO connection slow?
 - https://www.drupal.org/node/1064342
P.S. I have tried using both app.php and app_dev.php in apache configs nothing changed. Sticked to app_dev.php so I can have the profiler. And local development using Symfony's build in server has the same result

A: You can not have 2 concurrent requests for the same open session in PHP. When you use a firewall, Symfony locks the user session and until you release it manually or the request is served.
To release the session lock use this:
$session->save();

Note there will be some drawbacks and iimplications. After you save the session, you will not be able to update it (change attributes) until the next request arrives.
Session management: https://symfony.com/doc/current/components/http_foundation/sessions.html
Session interface: http://api.symfony.com/4.0/Symfony/Component/HttpFoundation/Session/SessionInterface.html#method_save
Note 2. If you have multiple concurrent users with different sessions PHP will serve concurrently those requests.


text:
Q: How to extract all occurrences of a JSON object that share a duplicate key:value pair? I am writing a python script that reads a large JSON file containing data from an API, and iterates through all the objects. I want to extract all objects that have a specific matching/duplicate "key:value", and save it to a separate JSON file.
Currently, I have it almost doing this, however the one flaw in my code that I cannot fix is that it skips the first occurrence of the duplicate object, and does not add it to my dupObjects list. I have an OrderedDict keeping track of unique objects, and a regular list for duplicate objects. I know this means that when I add the second occurrence, I must add the first (unique) object, but how would I create a conditional statement that only does this once per unique object?
This is my code at the moment:
import collections import OrderedDict
import json

with open('input.json') as data:
    data = json.load(data)

uniqueObjects = OrderedDict()
dupObjects = list()

for d in data:
    value = d["key"]

    if value in uniqueObjects:
        # dupObjects.append(uniqueObjects[hostname])
        dupHostnames.append(d)

    if value not in uniqueObjects:
        uniqueObjects[value] = d

with open('duplicates.json', 'w') as g:
    json.dump(dupObjects, g, indent=4)

Where you see that one commented line is where I tried to just add the object from the OrderedList to my list, but that causes it to add it as many times as there are duplicates. I only want it to add it one time.
Edit:
There are several unique objects that have duplicates. I'm looking for some conditional statement that can add the first occurrence of an object that has duplicates, once per unique object.

A: You could group by key.
Using itertools:
def by_key(element):
    return ["key"]

grouped_by_key = itertools.groupby(data, key_func=by_key)

Then is just a matter of finding groups that have more than one element.
For details check: https://docs.python.org/3/howto/functional.html#grouping-elements

A: In this line you forgot .keys(), so you skip need values
if value in uniqueObjects.keys():

And this line
if value not in uniqueObjects.keys():

Edit #1
My mistake :)
You need to add first duplicate object from uniqueObjects in first if
if value in uniqueObjects:
    if uniqueObjects[value] != -1:
        dupObjects.append(uniqueObjects[value])
        uniqueObjects[value] = -1
    dupHostnames.append(d)

Edit #2
Try this option, it will write only the first occurrence in duplicates
if value in uniqueObjects:
    if uniqueObjects[value] != -1:
        dupObjects.append(uniqueObjects[value])
        uniqueObjects[value] = -1


text:
Q: Getting level values from PCM raw data using Core Audio I am trying to extract level data from a PCM audio file using core audio. I have gotten as far as (I believe) getting the raw data into a byte array (UInt8) but it is 16 bit PCM data and I am having trouble reading the data out. The input is from the iPhone microphone, which I have set as:
[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt:1] forKey:AVNumberOfChannelsKey];

[recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
[recordSetting setValue:[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
[recordSetting setValue:[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];

which is obviously 16 bits. I am then trying to just print out a few values to see if they look reasonable for debug purposes below, and they do not look reasonable (many 0's).
ExtAudioFileRef inputFile = NULL;
    ExtAudioFileOpenURL(track.location, &inputFile);
AudioStreamBasicDescription inputFileFormat;
UInt32 dataSize = (UInt32)sizeof(inputFileFormat);
ExtAudioFileGetProperty(inputFile, kExtAudioFileProperty_FileDataFormat, &dataSize, &inputFileFormat);

UInt8 *buffer = malloc(BUFFER_SIZE);
AudioBufferList bufferList;
bufferList.mNumberBuffers = 1;
bufferList.mBuffers[0].mNumberChannels = 1;
bufferList.mBuffers[0].mData = buffer; //pointer to buffer of audio data
bufferList.mBuffers[0].mDataByteSize = BUFFER_SIZE; //number of bytes in the buffer

while(true) {

    UInt32 frameCount = (bufferList.mBuffers[0].mDataByteSize / inputFileFormat.mBytesPerFrame);

    // Read a chunk of input
    OSStatus status = ExtAudioFileRead(inputFile, &frameCount, &bufferList);

    // If no frames were returned, conversion is finished
    if(0 == frameCount)
        break;

    NSLog(@"---");

    int16_t *bufferl = &buffer;
    for(int i=0;i<100;i++){
        //const int16_t *bufferl = bufferl[i];
        NSLog(@"%d",bufferl[i]);
    }

}

Not sure what I am doing wrong, I think it has to do with reading the byte array. Sorry for the long code post...

A: youre allocating a buffer of unsigned 8 bit ints and then casting the address of that to an unsigned 16 bit int. ka-boom.
what you want to do in your for loop is cast bufferList.mBuffers[0].mData to a SInt16 *, and then iterate thru that to print out your values.
you dont need your buffer var at all. (for this)

A: You could simplify a lot of things. I'm sure you can let the API allocate the buffer for you.
bufferList.mBuffers[0].mData = nil;
bufferList.mBuffers[0].mDataByteSize = 0;

Also you should use the values in the bufferList after the read call instead of assuming they're the same ones you passed in. So after you read,
SInt16 *buffer = (SInt16 *)bufferList.mBuffers[0].mData;
for (UInt32 i=0; i< frameCount; i++) {
    NSLog (@"%d", buffer[i]);
}


text:
Q: How to use Automatic type registration? I bag your pardon but Automatic type registration is gone amiss for me. I've already installed LoadAssembliesOnStartup.Fody from Nuget to my project but it is necessary to add some code in my apllication for correct work of LoadAssembliesOnStartup.Fody! If I want to use, for example, 'Automatic type registration using Naming Convention' then where I have to put this code:
var serviceLocator = new ServiceLocator();
serviceLocator.RegisterTypesUsingDefaultNamingConvention();

in my application? Because now when I run my app and try to execute the following code in button command method in MainWindowViewModel:
private void ShowCalibrationViewExecute()
{
    var viewModel = new CalibrationViewModel();
    var dependencyResolver = this.GetDependencyResolver();
    var uiCompositionService = dependencyResolver.Resolve<IUICompositionService>();
    uiCompositionService.Activate(viewModel, "MainRegion");
}

I again have Catel.IoC.TypeNotRegisteredException exception in Catel.Core.dll, letting me know that:

The specified type 'Catel.Services.IUICompositionService' is not registered or could not be constructed. Please register type before using it.

Please point me what I should do in this case. I'll appreciative your help very highly.


text:
Q: JBOSS JMS subscriber receiving messages with wrong selector we use the below pseudo implementation for message synchronization between nodes in our Jboss clusters.
Pseudo-code is as follows-
void someMethod() {
Topic topic = (Topic) context.lookup(topicName);

//create separate sessions for publisher and subscriber
this.publisher_session = this.connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
this.publisher = publisher_session.createPublisher(topic);
this.subscriber_session = this.connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
String selector = NAME_PROPERTY + "='" + getTestValue() + "'";
this.subscriber = subscriber_session.createSubscriber(topic,selector,true);

subscriber.setMessageListener(this);
connection.setExceptionListener(this);
this.connection.start();
}

protected void publish(Message message)
{
    try
    {
      synchronized (publisher_session)
      {
        ObjectMessage objMessage =
          getSession().createObjectMessage(message);
        objMessage.setStringProperty(NAME_PROPERTY, getTestValue());
        getPublisher().publish(objMessage);
      }
    }
    catch (JMSException e)
    {
      logger.error("Failed to publish message: " + message + " for "
                   + getTestValue(), e);
    }
}

 public void onMessage(Message message)
  {
    // Validate type
    if (!(message instanceof ObjectMessage))
    {
      throw new IllegalArgumentException
        ("message not instanceof ObjectMessage: " + message.getClass());
    }

    ObjectMessage objectMessage = (ObjectMessage) message;

    try
    {
      // Validate selector
      if (!objectMessage.getStringProperty
          (NAME_PROPERTY).equals(getTestValue()))
      {
        throw new IllegalArgumentException
          ("Selector mechanism failed: received message regarding "
           + objectMessage.getStringProperty(NAME_PROPERTY));    <========== THIS EXCEPTION GETS THROWN
      }
        // Further code
    }
    catch (JMSException ex)
    {
      logger.error("Problem getting message for " + getTestValue(), ex);
    }
  }

Expectation here is that since selector matches the value of objMessage.setStringProperty(NAME_PROPERTY, getTestValue()), respective messages will arrive for subscriber and then the validation will pass.
But this is not happening.
The onMessage() method keeps throwing exception for some time and after restart, starts behaving fine, till it misbehaves once again. Currently running in JBOSS EAP 6.0.1


text:
Q: CakePHP3 - creating multiple associations between same two records I have a many-to-many relationship between Invoices and Items. An Item can appear multiple times in the same Invoice, but with different amounts (e.g. when the same service is used several times during one month).
I was hoping I could create this association by including the following in the 'items' element of the invoice when saving (see https://book.cakephp.org/3/en/orm/saving-data.html#saving-belongstomany-associations):
Array
(
    [0] => Array
        (
            [id] => 1
            [_joinData] => Array
                (
                    [amount] => 5338.29
                )

        )

    [1] => Array
        (
            [id] => 1
            [_joinData] => Array
                (
                    [amount] => 5988.53
                )

        )

    [2] => Array
        (
            [id] => 1
            [_joinData] => Array
                (
                    [amount] => 6023.40
                )

        )
)

In the example above, the result I'm hoping for is that three rows are created in the join table invoices_items. The invoice is saved correctly, but only one row is created in the join table.
One both associations I tried setting saveStrategy to append (I wasn't sure what this does), but this didn't help:
  $this->belongsToMany('Invoices', [
    'saveStrategy' => 'append'
  ]);

Is it possible to achieve this behaviour out of the box, or do I need to create something more custom, like a new model to specifically keep track of these relationships? Please let me know if more code would help to clarify what I'm trying to achieve.
Thanks!

A: The answer seems to be that no, this type of mass assignment isn't possible.
The solution I arrived at is to loop through each item I want to associate with the freshly saved invoice and call link() for each. I don't know what the performance hit is for this but for my purposes it works as this operation in my case happens relatively rarely.
        // Build an array with an element per item
        ...
        $itemsJoinData[] = [
          'item' => $item,
          '_joinData' => [
            'amount' => $amount
          ]
        ];
        ...

Once the invoice is successfully saved I attach the items with their respective amount.
        // Join up the invoice with the items
        foreach($itemsJoinData as $itemToJoin)  {
          $itemToJoin['item']->_joinData =  new Entity(['amount' => $itemToJoin['_joinData']['amount']], ['markNew' => true]);
          $this->Invoices->Items->link( $invoice, [$itemToJoin['item']] );
        }


text:
Q: limiting ratio of two triangle areas At the end points and the midpoint of circular arc $AB$ tangent lines are drawn, and the points $A$ and $B$ are joined with a chord. Find the limit of the ratio of the areas of the two triangles thus formed, as the length of arc $AB$ decreases indefinitely, approaching a length of zero.

A: Without loss of generality, we can assume the circle has radius $1$.

Let $O$ be the center of the circle.

Let $C$ be the point where the tangent lines at $A$ and $B$ intersect.

Let $M$ be the midpoint of segment $AB$, and let $N$ be the midpoint of arc $AB$.

Since we are intending to force the length of arc $AB$ to approach zero, we can assume that angle $AOB$ is acute.

Let $A',B'$ be the points where the tangent line at $N$ meets $AC,BC$, respectively.

Let $\theta=\angle AOC$.

Then $\angle AOB = 2\theta$.

Our goal is to find the limit of the ratio
$$
{\frac
{\text{area}(\Delta A'B'C)}
{\text{area}(\Delta ABC)}
}
$$
as $2\theta$ approaches $0$, or equivalently, as $\theta$ approaches $0$.

By right triangle trigonometry, we get

*

*$CO=\sec(\theta)$, hence $CN=\sec(\theta)-1$.$\\[4pt]$

*$MO=\cos(\theta)$, hence $CM=\sec(\theta)-cos(\theta)$.

Since triangles $A'B'C$ and $ABC$ are similar, with corresponding altitudes $CN$ and $CM$, respectively, it follows that
$$
{\frac
{\text{area}(\Delta A'B'C)}
{\text{area}(\Delta ABC)}
}
=
\left(\!\frac{CN}{CM}\!\right)^{\!2}
=
\left(\!\frac{\sec(\theta)-1}{\sec(\theta)-\cos(\theta)}\!\right)^{\!2}
$$
which simplifies to
$$
\left(\!\frac{1}{1+\cos(\theta)}\!\right)^{\!2}
$$
hence the limit, as $\theta$ approaches $0$, is ${\large{\frac{1}{4}}}$.


text:
Q: Collections usable in a class denoted as a Fault Bean for a @WebFault All examples I've found of classes denoted as @WebFault for a SOAP web service contain an array of Fault Beans, and the class denoted as the fault bean contain an int, a String, and sometimes a List .
My webservice makes use of a build-step using java2ws to create the wsdl.
Question 1) can a SOAP webservice have more than one @WebFault? One would think so.
Question 2) can the fault bean class take a Set? and can the elements in the set be classes ie Set ?
The goal here is to propagate JSR-303 bean validation failures from the server back to the web service client where a form is waiting to be updated with 0,1, or >1 error messages.
TIA,
Still-learning Steve
Question 3) can the @WebFault class take a Set<> instead of an array?

A: 1)  Yes, a single operation can have multiple faults, just like in Java a method can throw more than one checked exception
2) Not sure exactly what you're asking.
Let me just show one quick example of what you can do..maybe it points you in a helpful direction:
// MyIntf.java
@WebService
public interface MyIntf {

@WebMethod
void myMethod() throws MyFault;

//...
}

// MyFault.java

@WebFault(faultBean="mypkg.MyFaultBean")
public class MyFault extends Exception {

private MyFaultBean bean;

public MyFault(MyFaultBean bean, String message) {
    super(message);
    this.bean = bean;
}

public MyFault(MyFaultBean bean, String message, Throwable cause) {
    super(message, cause);
    this.bean = bean;
}

public MyFaultBean getFaultInfo() {
    return bean;
}
}

// MyFaultBean.java
public class MyFaultBean {

    private Set mySet;

    public Set getMySet() {
        return mySet;
    }

    public void setMySet(Set mySet) {
        this.mySet = mySet;
    }
    //...
}

So you're trying to use JAXB and JAX-WS to map between Java exceptions and WSDL faults (putting it that way might help your searches).
One thing to consider is whether to approach this top-down (WSDL/XSD primary, Java secondary) or bottom-up (Java primary).
If you don't already have a fixed Java interface that you're trying to use (sounds like you may not, but maybe you do), you might be better off starting from WSDL/XSD, then using wsdl2java to generate the Java interface, then maybe customizing it a bit using JAXB customizations.
A couple more links on the subject here and here, (the latter mentions "SCA" but this uses JAX-WS and JAXB so is relevant).


text:
Q: Android Studio Shows error in everything suddenly See Images.Check Error Here!
I dont know what happened but every thing shows in error. while restarting sometimes it says something like "can not load settings from file android studio". As you can see my, java code turned in to XML code. I am new in Android studio so please someone help me. I cant even go back to my previous version since i forget commit last 24 hour work. Any suggestion and help will be highly appreciated. Thanks


text:
Q: Jinja convert string to integer I am trying to convert a string that has been parsed using a regex into a number so I can multiply it, using Jinja2. This file is a template to be used within an ansible script.
I have a series of items which all take the form of <word><number> such as aaa01, aaa141, bbb05.
The idea was to parse the word and number(ignoring leading zeros) and use them later in the template.
I wanted to manipulate the number by multiplication and use it. Below is what I have done so far
```
{% macro get_host_number() -%}
{{ item | regex_replace('^\D*[0]?(\d*)$', '\\1') }}
{%- endmacro %}

{% macro get_host_name() -%}
{{ item | regex_replace('^(\D*)\d*$', '\\1') }}
{%- endmacro %}

{% macro get_host_range(name, number) -%}
{% if name=='aaa' %}
{{ ((number*5)+100) | int | abs }}
{% elif name=='bbb' %}
{{ ((number*5)+200) | int | abs }}
{% else %}
{{ ((number*5)+300) | int | abs }}
{% endif %}
{%- endmacro %}

{% set number = get_host_number() %}
{% set name = get_host_name() %}
{% set value = get_host_range(name, number) %}

Name: {{ name }}
Number: {{ number }}
Type: {{ value }}

With the above template I am getting an error coercing to Unicode: need string or buffer, int found which i think is telling me it cannot convert the string to integer, however i do not understand why. I have seen examples doing this and working.

A: You need to cast string to int after regex'ing number:
{% set number = get_host_number() | int %}

And then there is no need in | int inside get_host_range macro.


text:
Q: Почему элементы в Relative Layout никак не хотят ставиться по центру горизонтально? Проблема заключается в том, что элементы в Relative Layout никак не хотят ставиться по центру горизонтально, даже если свойство layout center horizontal = true, Relative Layout вложен в Scroll View.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent"
    android:layout_width="match_parent">

    <RelativeLayout
        android:layout_height="wrap_content"
        android:layout_width="wrap_content">

        <ProgressBar
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:layout_centerHorizontal="true"/>

    </RelativeLayout>

</ScrollView>

A: Чтобы прогресс бар расположился по центру надо установить у RelativeLayout ширину match_parent
Вот работающий лейаут:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    <ProgressBar
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true" />

</RelativeLayout>

</ScrollView>