text:
Q: Raspberry: Every binary : command not found When booted, my raspberry checks if the program called reader is running. If it is, it does nothing, but if not, it runs it.
After a bunch of time, a few hours (between 2 and 4 hours) the raspberry is completely lost. I can't connect with SSH, the program that ran is not running anymore, etc.
I tried to run a SSH client to get the error while i'm connected to it so I can watch what's in the dmesg and so on, but here is what I get :
pi@raspberrypi:~ $ tail -f /var/log/syslog
-bash: tail: command not found
pi@raspberrypi:~ $ sudo tail -f /var/log/syslog
-bash: /usr/bin/sudo: No such file or directory
pi@raspberrypi:~ $ ls
-bash: ls: command not found
pi@raspberrypi:~ $ /bin/ls
-bash: /bin/ls: No such file or directory
pi@raspberrypi:~ $
pi@raspberrypi:~ $ cd /bin/
pi@raspberrypi:/bin $ ./ls
-bash: ./ls: No such file or directory

If I stop the SSH session and try to connect again :
pi@raspberrypi:/bin $ logout
Connection to 10.25.168.59 closed.
root@me:/home/user# ssh pi@10.25.168.59
Read from socket failed: Connection reset by peer

I can ping the raspberry pi and NMAP says something hilarious :
Nmap scan report for 10.25.168.59
Host is up (-0.087s latency).
MAC Address: xx:xx:xx:xx:xx:xx (Raspberry Pi Foundation)

Then if I unplug the raspi and plug it back, I can connect back to it and here are the logs from syslog : http://sprunge.us/lSSnj7
We can see at 11:17:08 it's booting but nothing more.
And here's maybe a thing that can help : The pi has the red light constantly ON while the green one blinks following that pattern : on for 8s, off for 0.5s

For information, my program is written in C, it opens an USB port (it is a barcode scanner) and does nothing about shutdown or reboot the machine.
I've already checked for memory peaks, CPU peaks, zombies processes, but nothing. I use only 60 Mb of RAM on 1 Gb, CPU is used at less than 2%. 110 tasks and 0.03 load average.
Why does the raspberry freezes or reboots (without killing the SSH session) but does not completely reboot, because my reader is not launched again ?
Any help would be very much appreciated. Thanks

A: Maybe some hardware problems on the SD card ?
These "not found" look like when the system is in really bad shape after a hardware failure or a sudo rm -rf /*


text:
Q: Relationships of model How can I get all relationships for model. IE, I've got User model:
class User < AR::Base
  has_many :messages, :foreign_key => 'author'
  has_many :posts
  belongs_to :role
end

So how can I know which relationships User model has got? And foreign_keys if they are presented.

A: User.reflect_on_all_associations.each do |assoc|
  puts "#{assoc.macro} #{assoc.name}"
end

Outputs:
has_many messages
has_many posts
belongs_to role

The reflect_on_all_associations method return an array of MacroReflection objects.  They support other methods as well, for querying the options hash of each association and other useful stuff.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ARC with pointers created inside methods I have read about the concept of ARC and how we can use the @property to define strong or weakreferences. My question is how do a define or free pointers when they are inside methods and I would want the memory to be reclaimed as soon as the scope ends such as this
    - (void) SomeMethod {
     NSString* databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"contacts.db"]];
     ....
     ....
    }

My question is how do I free the string databasePath ?

A: When you declared a local variable, it marks as strong reference by default. And the memory will be freed, when all the strong references to var have become lost. So outside scope, your variables memory automatically is freed, because strong reference is inside scope.

A: Unless some of the .... code stores databasePath in an instance variable, the memory for the string will be reclaimed as soon as you assign nil to databasePath, or let the variable go out of scope. You do not need to do anything special for it, because you used alloc / init.
The story is slightly different with autoreleased objects, i.e.
NSString* databasePath = [NSString stringWithString: [docsDir stringByAppendingPathComponent: @"contacts.db"]];

This string would stay around until the run loop gets to decrementing its reference count, unless you create it inside a separate autorelease pool. Therefore, simply setting databasePath to nil is no longer sufficient to release the memory right away: you need to put an autorelease pool around your variable in order to achieve immediate freeing of memory.


text:
Q: unable to solve the routing error while using devise gem I am using devise gem, I had install the gem also but I am still getting error as below:
no route matches[Get] "/dhwani_app"

A: In your routes try adding
"devise_for :(whatever your model is)" but obviously don't put the quotations in


text:
Q: Галерея изображений Есть галерея изображений на jQuery (вот демо). Описание к изображениям выводится в той же рамке, что и изображение ( http://SSMaker.ru/25fd84e8/ ), а хотелось бы вывести описание снизу. То есть, сейчас так http://SSMaker.ru/669724d9/ + http://SSMaker.ru/9a06ccb4/ , а хотелось бы так http://SSMaker.ru/55af8d3a/ + http://SSMaker.ru/67d14454/ .
И удалить из галереи вот эту возможность http://SSMaker.ru/60b72b8b/ .Надеюсь найдутся те, кто сможет мне помочь или хотя бы что-нибудь подскажут. Заранее всем спасибо.
A: Описание выводится как вы сами видите в div с классом rg-caption-wrapper. Этот элемент как и другие некоторые добавляется из шаблона, который указан в начале страницы
 <script id="img-wrapper-tmpl" type="text/x-jquery-tmpl">
 ...

Измените там иерархию div'ов и получите ту иерархию какая вам нужна.
По поводу кнопок смотрите файл gallery.js. Там в функции init есть вызов добавления этих кнопок
// Добавляем опции
_addViewModes();

Закомментируйте этот вызов и их не будет.


text:
Q: Typescript: Convert For loop to Promise and wait to resolve all ISSUE: save.emit() runs before all the iterations are completed in the below "for" loop which shows incorrect values of the addUpdate call inside loop.
I am trying to convert a for loop to promise and then wait for each of those promise to resolve so that I can emit changes and close a popup.
Below, is a test code in which I want to print "console.log("Print Before")" first for each iteration and then at the end print "console.log("Print After")" once all iterations are done.
Any help on the syntax for this is really appreciated.
  convertForLoopToPromiseAndWait(someParameterOfTypeObject) {
    for (var test of someParameterOfTypeObject) {
      var testVariable = test.setValue;
      if (testVariable) {
          dataService.addUpdateEndpointCall();
          console.log("Print Before");
      }
    }
    console.log("Print After");
    save.emit();
  }

      async addUpdateEndpointCall() {
        const promise1 =  this.dataService.addCall().take(1).toPromise();
        const promise2 =  this.dataService.deleteCall().take(1).toPromise();

        await Promise.all([promise1, promise2])
          .then(_ => this.save.emit());
      }

A: Convert convertForLoopToPromiseAndWait to async method, then you can use await after for keyword and before dataService.addUpdateEndpointCall();
async convertForLoopToPromiseAndWait(someParameterOfTypeObject) {
  for await (var test of someParameterOfTypeObject) {
    var testVariable = test.setValue;
    if (testVariable) {
      await dataService.addUpdateEndpointCall();
      console.log("Print Before");
    }
  }
  console.log("Print After");
  await save.emit();
}

A: Another way is to make a list of promises and wait for them to resolve:
const promises = [];
        for await (your iterating condition) {
          promises.push(dataService.addUpdateEndpointCall());
        }

then use
await Promise.all(promises).then( this.save.emit());

A: I think that you have made a mistake here:
const promise1 = await this.dataService.addCall().take(1).toPromise();
const promise2 = await this.dataService.deleteCall().take(1).toPromise();

You await promises. The results put in the variables promise1 and promise2 will then not be promises.
Don't you mean the following?
      async addUpdateEndpointCall() {
        const promise1 = this.dataService.addCall().take(1).toPromise();
        const promise2 = this.dataService.deleteCall().take(1).toPromise();

        await Promise.all([promise1, promise2])
          .then(_ => this.save.emit());
      }


text:
Q: Generating a JSON schema from a Ruby on rails model (class) There are gems for generating json from Ruby instances (e.g., jbuilder) and gems for building Ruby models from json schemata. Is there one for doing the inverse? That is, for generating a json schema from an existing model?
I would like to go from a model:
class Example
  { firstName: string,
  lastName: string,
  id: integer }
end

to a schema
{
    "title": "Example Schema",
    "type": "object",
    "properties": {
        "firstName": {
            "type": "string"
        },
        "lastName": {
            "type": "string"
        },
        "id": {
            "type": "integer",
        }
    }
}

This question was asked 6 or so years ago, but never answered: How can I export a rails model to json schema?

A: I don't know if it's enough for your needs, but there is a gem that does something like that: https://github.com/salesking/json_schema_builder


text:
Q: How do I call a method on a WebBrowser inside an event handler? This is what I have:
public void initiate(WebBrowser browser)
{
   browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(refDocumentCompleted);
   // navigate browser to the referal Uri
   browser.Navigate(refreral);

   browser.DocumentCompleted -= refDocumentCompleted;
   //remove here so that it doesn't do this everytime a document is completed, i want it just in this method
}

private void refDocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    // want to call navigate method on browser here. but Its out of scope.
}

What I would like it to do is, navigating to referral, then once that is loaded navigate to another page stored as a global string in the class.
I'm sure my trouble here is from a poor understanding of how events work, I've tried to read up on it, but can't seem to get my head around it but don't think I need to create my own handler.

A: You already have the webbrowser object. You just need to cast it:
((WebBrowser)sender).Navigate(...);

etc.

A: Use lambdas, e.g.:
public void initiate(WebBrowser browser)
{

    browser.DocumentCompleted += (sender, e) => {
        browser.DoStuff(); // it's in scope via closure
    };

    // etc
}

EDIT: to add / remove it, assign the lambda to a variable:
public void initiate(WebBrowser browser)
{

    var doStuff = (sender, e) => {
        browser.DoStuff(); // it's in scope via closure
    };

    browser.DocumentCompleted += doStuff;

    // etc

    browser.DocumentCompleted -= doStuff;
}

A: In your initiate method store the WebBrowser in an instance field, then reference it from your event handler:
private WebBrowser _browser;

// inside initiate
_browser = browser;

// Inside event handler
_browser.Navigate(...);


text:
Q: four forms, Four buttons, four links, one page. Is there a better way? I have a page that will have multiple buttons, and I want each button to take the user to a different place. I've searched all over for tutorials, and can't figure out what to do. I have this in the body:
<form method="get" action="KFC.html">
    <input type="submit" value="KFC">
</form>

<form method="get" action="Pizza_Hut.html">
    <input type="submit" value="Pizza Hut">
</form>

<form method="get" action="Olive_Garden.html">
    <input type="submit" value="Olive Garden">
</form>

<form method="get" action="Create_Order.html">
    <input type="Submit" value="Create Your Own Order">
</form>

How do I make multiple buttons on one page that go to different places? Is this right? it works but I was told this is a really bad method.

A: Try to add standard browser independent anchor links and then use CSS to style them too look like the buttons you want.
 KFC
 Pizza hut

Etcetera...
Then CSS. In my example below I show one way of styling the links like buttons, Im sure you can find many other more suitable looks if you search for it.
a.button {
   display: inline-block;
   padding: 5px;
   border: 1px solid #999;
   background: #aaa;
   color: #333;
   text-decoration: none;
 }
 a.button:hover {
   background: #ccc;
 }

I added a class "button" so you only style certain links as buttons. This way you can add as many "buttons" you want without adding forms to your code, and without affecting other links on your page.

A: You are creating multiple forms which can cause lag and issues with validation as well. If you want your buttons to go some where in-particular there are a few methods.
You could use onclick attribute to catch the click event and select the correct location based on the button something like this could work.
<button type="button" id="1" onclick="window.location = newLocation1;">Click Me 1!</button>
<button type="button" id="2" onclick="window.location = newLocation2;">Click Me 2!</button>
<button type="button" id="3" onclick="window.location = newLocation3;">Click Me 3!</button>

A: Thank you. Turns out You would want something very similar to answers above. But for some reason I wasn't understanding.
here is my html code:

Deliveries

KFC  #This part -> >KFC gives you the text that appears on the button. The  will take you to the KFC_Menu page.

Create Your Own Order

To Style those links to look like buttons make a CSS file like this as an example:
stylesheet.css
a {
text-decoration: none;
font-size: 24px;
font-family: sans-serif, arial;
font-weight: bold;
background-color: blue;
color: #ffffff;
padding: 8px;
border: 2px solid grey;
border-radius: 10px;

}


text:
Q: Pass Parameter Using Lightning Navigation I am following this link  where Source Component passes parameters to Target and the parameters are visible in URL..
I am following the exact steps but its not passing parameters to mt Target Component, neither can I see any Parameters in URL.. Is there anything I am doing wrong?
I have added the component in Account Details Page.
Source.cmp
<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId" access="global" >
<lightning:navigation aura:id="navService"/>
<aura:attribute name="pageReference" type="Object"/>
<aura:attribute name="url" type="String"/>
<aura:handler name="init" value="{! this }" action="{! c.init }"/>
<lightning:button label="Open Lightning Component" onclick="{!c.handleClick}"/>

SourceController.js
({
init : function(cmp, event, helper) {
    var navService = cmp.find("navService");
    var pageReference = {

        "type": "standard__component",
        "attributes": {
            "componentName": "c__Target"
        },
        "state": {
            "firstName": "Test"  ,
            "lastName": "user"
        }
    };
    cmp.set("v.pageReference", pageReference);
    var defaultUrl = "#";
    navService.generateUrl(pageReference)
    .then($A.getCallback(function(url) {
        cmp.set("v.url", url ? url : defaultUrl);
    }), $A.getCallback(function(error) {
        cmp.set("v.url", defaultUrl);
    }));
},
handleClick: function(cmp, event, helper) {
    var navService = cmp.find("navService");
    // Uses the pageReference definition in the init handler
    var pageReference = cmp.get("v.pageReference");
    event.preventDefault();
    navService.navigate(pageReference);
}

})
Target.cmp
<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId,lightning:isUrlAddressable" access="global" >
<aura:handler name="init" value="{!this}" action="{!c.init}" />

<aura:attribute name="firstName" type="String" />
<aura:attribute name="lastName" type="String" />
<div>
    Full Name : {!v.firstName} + {!v.lastName}
</div>

({
init: function(cmp, event, helper) {
    var pageReference = cmp.get("v.pageReference");
    cmp.set("v.firstName", pageReference.state.firstName);
    cmp.set("v.lastName", pageReference.state.lastName);
}

})
When I click the button, URL is now showing any parameter.. Is there anything wrong?

A: From Summer'19 release, it is mandatory to prefix c__ to parameters (if without namespace) in state or else they will be ignored.

As mentioned in the Spring '19 release notes, this critical update
  addresses an issue with naming conflicts between package components. A
  namespace prefix distinguishes your package and its contents from
  other developers' packages. The namespace prefix prevents conflicts
  between components on the state or query parameter name. Query
  parameters and pageReference.state properties must have a namespace
  prefix. If they don't, this critical update removes them from the
  org's URLs. This critical update is enabled for Summer '19 on May 17,
  2019.

"state": {
        "c__firstName": "Test"  ,
        "c__lastName": "user"
    }


text:
Q: NHibernate query with restriction on child collection I've looked at plenty of examples on this site, but I'm still not sure how to do this:
For illustration, let's say I have persistent Venues, each of which has a collection of Events, where each Event has ReservationDate.  If I want to get all the Venues whose next Event is of type "Wedding", how would I go about it?  It requires selecting based on a value of a specific element (in this case the first ReservationDate > Today) in the child collection, that element being determined by a different restriction (Type == "Wedding").
I've looked at various queries using CreateCriteria, QueryOver, DetachedCriteria, JoinOver and the whole gamut of NH query options (I don't want to use HQL), but I'm still at a loss.
Your help is appreciated.
Michael

A: I've created very detailed example how to handle these situations. Please see all the details here:

*

*Query on HasMany reference
The point is to create few Subqueries represented as DetachedCriteria. Using aliasing we can communicate among them (passing the ID).
At the end, we can SELECT clean/flat structure of the ROOT entity... while having full power of filtering based on referenced collecitons.
This approach has the biggest advantage in the fact, that we can apply the paging (Take(), Skip()) because the final select is on top of the root table


text:
Q: Distributed systems, best framework? I am building a software program that follows the scenario:
I have many computers, and add each one of them to the a cluster.
Each computer in the cluster can add a file to a distributed table (dictionary,hashmap, should be fast enough).
So now I have a place where everyone can see what files does the group/cluster contains.
Now a computer from the group/cluster requests a file. He can access all the information about the file from the distributed table ( on what computer it can find the file etc...).
By some mechanism it should get the file from point B ( computer that has the file ) to point A ( the computer who requested the file ).
Basically it should do data replication. ( but for very large files )
So you probably wonder by now, what is this quy asking for, here it is :
The data replication should be as fast as possible. What would be the best approach ? I thought about something like flux networks.
What would be the best framework, to use for a software following the scenario ?
I AM SEARCHING FOR A JAVA FRAMEWORK :). (I NEEDED TO RUN CROSS-PLATFORM)
Thank you!

A: As I'm sure you have discovered there are a lot of libraries out there for java that allow you to implement this sort of disturbuted map.

*

*Hazelcast - new kid on the block, really simple to use and provides implmentations of standard java interfaces like ConcurrentMap

*JGroups - Really just library for group messaging, but includes a DisturbutedHashMap implementation

*jBoss Cache - built on top of jGroups provides a much more complete disturbuted caching system with optional persistence and transactions

*Terracotta - Big and quite popular, commercially supported

*Oracle Coherence - The daddy of them all, with a price tag to match

There are more (quite a lot more), my personal preference at the moment is Hazelcast it's insanely easy to get started. All of the caching frameworks I've listed (I think) rely on being able (at least temporarily) to be able to load the whole entry into memory, this may be an issue if you are attempting to put the contents of large files into them.
In your case I'd problably use the disturbuted map to store the location data, ie some data to tell any other node where a particalar file is, and then go directly to that node using some out of bound method such as HTTP.

A: JXTA is Sun's Java peer-to-peer framework, and most likely of use here.
Or check out Jini and it's capability for service leasing, dynamic discovery and protocol independent client/server communication. Using Jini you can publish each service with particular attributes (in this case your filename?), or perhaps use it with Javaspaces (I'm not sure about the appropriateness of spaces here, however)

A: It looks like you are searching for: Project Voldemort or other Key=>Value datastores which automatic failover, replication etc.

A: There are a few good answers above for distributed hashmap.
For actually copying the file if at all possible I would prefer to not copy anything and just have some shared storage solution. If you must use separate disks for each computer, then something simple such as setting up an FTP server on each computer should work. This doesn't have to be Java based, but if you want Java only solution something like Apache MINA could work.


text:
Q: How to add the OrderNbr hyperlink in SOLine I have a grid which displays only SOLine and SOOrder data.  In my case, SOLine is the main DAC, because the purpose of the grid is to perform mass updates of the transactions.  I wish to add the OrderNbr in the grid, so the user can select and open the sales order popup.  I notice the order number field does not appear as a hyperlink, if use SOOrder table in my grid.  Next I try SOLine.orderNbr.  However the field type is only TextEdit.  Here is a workaround
I created the SOLine cache extended and defined a non-bound field.  Something simple like ExtraSOOrder field.  Next I create a PXAction which creates the SOOrderEntry graph and performs the redirect, and achieves the goal.  I notice something odd in the grid.  OrderNbr is displayed twice.  Although the field is only added once in the grid, the webpage adds the field a second time.  In fact, the user is unable to remove the duplicate order number field, in the column selector.  The duplicate field has a yellow icon which I have not seen before.
What is the best way to add the redirect, to the sales order entry page?  The behavior works perfectly for the Inventory item field in this grid.  OrderNbr is more challenging.

A: All that was required was to add the SOOrder.orderNbr to the grid columns collection.  Then assign the action to the Linkedcommand property, to that field.  No need to create a cache extension for all of this.


text:
Q: how to remove last part of string in c# I was trying to remove last part of a string but failed.Here string named D:\software\VS2012\newtext.txt and i want to trim last section of string so here newtext.txt . I should get D:\software\VS2012 but how to do it in c#.When i tried it is removing all the string that has '\'. Here is  what i did in c#
string str = @"D:\softwares\VS2012\newtext.txt";
           str= str.Remove(str.IndexOf('\\'));
            Console.WriteLine(str);

A: Try using System.IO.Path.GetDirectoryName(string):
string dirname= System.IO.Path.GetDirectoryName(@"D:\softwares\VS2012\newtext.txt");

A: There is a premade function for this in the framework
string str = @"D:\softwares\VS2012\newtext.txt";
string path = System.IO.Path.GetDirectoryName(str);

(Reference)
Note that your original code does not work because you are removing from the first backslash, not the last.  Substitute this line to make your code work
str = str.Remove(str.LastIndexOf('\\'));

A: For removing a known portion of a string you can simply use the Replace.
In your case:
str = str.Replace("\\newtext.txt", ""); //this will give you the same result of the System.IO.Path.GetDirectoryName already suggested by gmiley, but it's more in a string context as per your question

Though if you want to remove the last part of a string by the last encounterd known character then the suggested "LastIndexOff('\')" method already suggested along with the Remove.
If you want to use a delimiter method, so depending on the delimiter character but not on the string format (in your case path format) the LastIndexOff(char) is the best option.
Although you could also split the string into an array and then rejoin the array after removing the last element:
var delmimter = '\\';
var strAy = str.Split(char);
str = String.Join('\\', strAy.SkipLast(1).ToArray());

With this method you don't need to rely on the existence of the delimiter char in the string and the result is always without the delimiter char at the end.
Besides, you can easily create an extension with the delimiter as a parameter.

A: We should check the existance of the char also
string str = @"D:\softwares\VS2012\newtext.txt";

int rstr = str.LastIndexOf('\\');

if (rstr>0) str= str.Remove(rstr);

Console.WriteLine(str);


text:
Q: Creating a custom security encoding/decoding transform I'd like to create a Base16 encoder and decoder for Lion's new Security.framework to complement kSecBase32Encoding and kSecBase64Encoding.  Apple's documentation shows how to write a custom transform (Caesar cipher) using SecTransformRegister.  As far as I can tell, custom transforms registered this way have to operate symmetrically on the data and can't be used to encode and decode data differently.  Does anyone know if writing a custom encoder/decoder is possible, and if so, how?

A: I don't see a way to tie custom encoders into SecEncodeTransformCreate(), which is what kSecBase32Encoding and the others are based on. But it's easy to create a transform that accepts a "encoding" bool and makes use of that to decide whether to encode or decode. In the CaesarTransform example, they attach an attribute called key with SecTransformSetAttribute(). You'd do the same thing, but with a bool encode.
And of course you could just create an encoding transform and a decoding transform.


text:
Q: Does null current means null tension? I know from V=IR that zero current means zero voltage drop, but what if we don't have a resistance?
let's consider the following example (Logical and made with diodes) :

I know that if Va=0 or Vb=0 all the current will flow to the load, and there will be no current that passes to the right (where Vs is) but why will Vs be zero? What is Vs? (Vs is output voltage, doesn't mean a lot to me), can any one help me please?
Thank you

A: The thing to remember with voltage is that it's not an absolute value. It's the difference between potentials at two different points in the circuit - that is why it is also sometimes called potential difference.
Your \$V_S\$ is the the potential difference between that point and ground. Sometimes that will be small, such as the voltage drop across a diode (when an input is LOW). Other times it will be large, governed by the current flow through the load and the pullup resistor.
\$V_S\$ can never be 0V in your example circuit simply because the lowest it can be is the voltage drop across a diode. For a normal silicon diode that is around 0.7V. The only way you could get \$V_S\$ to be 0V would be to connect it directly to ground bypassing the diode. It is then 0V WRT ground because it is itself ground.


text:
Q: Console returns value but Google Tag Manager variable does not When I put dataLayer[1].ecommerce.checkout.products[0].metric2 in the console, it return the correct value.
However, when I try to extract the value from a Custom JavaScript variable ('Test') in Google Tag Manager, it returns undefined when Google Tag Manager is in preview mode.
The JavaScript code:
function(){
var basketSize = dataLayer[1].ecommerce.checkout.products[0].metric2;
return basketSize;
}

A: In case your questions hasn't been answered yet: The thing is you yon't want to reference the dataLayer array inside a dataLayer variable in GTM. This does not make sense, because you already are in the dataLayer "namespace". If you reference the field by simply writing ecommerce./*...*/.metric2 and leaving out the dataLayer[1] part, it will work.


text:
Q: Cant Update and Delete Data from Database I'm trying to update or delete data from database but it's not working. I dont know I did something yesterday night while sleepy trying to fix another problem. And now this is not working. Here's the code for both of them. Where's my problem about that. When I use delete command, it's updating but trying to update table,it's not updating table. Where is my problem , How can I fix this?
 private void cmd_deleteActionPerformed(java.awt.event.ActionEvent evt) {

        String sql="delete  from maintable where İsim =?   ";

        try{

        pst=conn.prepareStatement(sql);

        pst.setString(1, jTextField1.getText());

        pst.execute();

        JOptionPane.showMessageDialog(null, "Silindi");

        }catch(Exception e){

        JOptionPane.showMessageDialog(null, e);

        }

        Update_table();

    }

This is for update:
 private void cmd_updateActionPerformed(java.awt.event.ActionEvent evt) {

try{

String value1=jTextField1.getText();
String value2=jTextField2.getText();
String value3=jTextField3.getText();
String value4=jTextField4.getText();
String value5=jTextField5.getText();

String sql="update maintable set İsim='"+value1+"' ,Yaş ='"+value2+"',Konum ='"+value3+"',EPosta='"+value4+"',KatılımTarihi='"+value5+"' where İsim='"+value1+"' ";
              pst=conn.prepareStatement(sql);
              pst.execute();
              JOptionPane.showMessageDialog(null, "Güncellendi");

}catch(Exception e){;

        JOptionPane.showMessageDialog(null, e);

}
  Update_table();

    }

EDIT: "pst=conn.prepareStatement(sql);" it's giving me red underline errors, which is for sql word in brackets and says "cannot find symbol"
pst=conn.prepareStatement("update maintable set İsim=?,Yaş=?,Konum=?,EPosta=?,KatılımTarihi=?"); pst.setString(1,value1);
pst.setString(2,value2);
pst.setString(3,value3);
pst.setString(4,value4);
pst.setString(5,value5);

pst=conn.prepareStatement(sql);

A: private void cmd_deleteActionPerformed(java.awt.event.ActionEvent evt) {

    String sql="delete  from maintable where İsim =?   ";

    try{

    pst=conn.prepareStatement(sql);

    pst.setString(1, jTextField1.getText());

    pst.executeUpdate();// **error was here**

    JOptionPane.showMessageDialog(null, "Silindi");

    }catch(Exception e){

    JOptionPane.showMessageDialog(null, e);

    }

    Update_table();

}

this is for update
private void cmd_updateActionPerformed(java.awt.event.ActionEvent evt) {

try{

String value1=jTextField1.getText();
String value2=jTextField2.getText();
String value3=jTextField3.getText();
String value4=jTextField4.getText();
String value5=jTextField5.getText();

String sql="update maintable set İsim='"+value1+"' ,Yaş ='"+value2+"',Konum ='"+value3+"',EPosta='"+value4+"',KatılımTarihi='"+value5+"' where İsim='"+value1+"' ";
              pst=conn.prepareStatement(sql);
              pst.executeUpdate();
              JOptionPane.showMessageDialog(null, "Güncellendi");

}catch(Exception e){;

        JOptionPane.showMessageDialog(null, e);

}
  Update_table();

    }

For inserting,updating deleting you should call executeUpdate() not execute()
Note   This is not the proper way of using preparedStatement
 String sql="update maintable set İsim='"+value1+"' ,Yaş ='"+value2+"',Konum ='"+value3+"',EPosta='"+value4+"',KatılımTarihi='"+value5+"' where İsim='"+value1+"' ";
                  pst=conn.prepareStatement(sql);

Use this way
 pst=conn.prepareStatement("update maintable set İsim=?,Yaş=?,Konum=?,EPosta=?,KatılımTarihi=?"); pst.setString(1,value1);
pst.setString(2,value2);
pst.setString(3,value3);
pst.setString(4,value4);
pst.setString(5,value5);

pst.executeUpdate();

A: Instead of pst.execute() use pst.executeUpdate() then it will work fine.
For transactions(INSERT, DELETE, UPDATE) use the method executeUpdate().
For selecting(SELECT) data use executeQuery().


text:
Q: How to make output generated from shortest path in QGIS more reasonable My goal is to generate bus route stop by stop given the bus route and stops with sequence number of single direction.
I tried to achieve this by using shortest path in QGIS stop by stop.

However, the raw bus route is for both direction, and the some of the stops are located at the opposite side by mistakes:

As a result, the shape from shortest path would go all the way back to nearest point where both direction routes meet and then to the destination stop:

Since there are around a thousand routes need to be processed, it is impossible to correct them manually.
Is there a way to tell the algorithm to take real shortest path?
You can find the example files here


text:
Q: Proof that $(a+b, a)$ belongs to $\mathbb{R}^2$ I am aware that the vector $(a+b, a)$ such that $a$, $b$ are real numbers belongs to $\mathbb{R}^2$, which is defined by any vectors $(x_1, x_2)$ such that $x_1, x_2$ are real numbers.
Is there a way to prove that $(a+b, b)$ indeed does equal $(x_1, x_2)$? The reason I am having trouble doing so it because the terms $a+b$ and $b$ have common variables (and hence are related), while $x_1$ and $x_2$ do not.
Any guidance would be appreciated. Thank you.

A: If $a,b \in \mathbb{R}$ then $a+b\in \mathbb{R} $ by closure of real numbers under addition. So, $(a+b, a)\in \mathbb{R}^2$.

A: $\Bbb{R}^2 = \Bbb{R} \times \Bbb{R} = \{(x,y):x,y \in \Bbb{R} \}$ The real numbers are closed under addition, so the addition of any two real numbers is itself a real number. Hence, for any $a,b \in \Bbb{R}$ we know $a+b \in \Bbb{R}$. By definition of $\Bbb{R}^2$ (ALL ordered pairs of real numbers) we know that $(a+b,b) \in \Bbb{R}^2$ because $(a+b,b)$ is an ordered pair of real numbers. If you simply want to pattern match $(a+b,b)$ to some vector $(x_{1},x_{2})$ then let $b = x_{2}$ and $a+b=x_{1}$


text:
Q: Youtube API detect if autoplay is disabled I have used Youtube API to play automatically a video but i have found out that it only works fine on PCs but NOT mobile devices. I did a bit of google-ing and discovered that autoplay feature is disabled on mobile devices.
No the questions is, can i detect if autoplay is disabled ??. Or at least force the video to show youtoube play button if vidio is on state -1.
i.e.
if(event.data == -1) {
    // show play button
}

A: It appears that there is no way of getting this information without testing with you video and checking whether the video's current time has advanced after it has loaded.
It was asked for as a feature in modernizr but as you can see from this comment from Paul Irish, you have to have a video to check.  It looks like they are trying to add this into v3 of modernizr.
So essentially it is doable and his pseudocode should get you started.  Basically the first four points are done already.  You would just need to implement the last two.
create a video element
set video element src to something
add autoplay attribute to it
add element to the dom
bind to that event (something metadata soemthing) that fires when its buffered some
setTimeout after it fires and see if currentTime is > 0

A: A sample to autoplay without using arg autoplay. I only test this solution on PCs not mobile but you can try this code :
LIVE EXAMPLE
HTML

JS
var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    var tag = document.createElement('script');

    tag.src = "https://www.youtube.com/iframe_api";
          var firstScriptTag = document.getElementsByTagName('script')[0];
          firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    var player;
          function onYouTubeIframeAPIReady() {
            player = new YT.Player('player', {
              height: '390',
              width: '640',
              videoId: 'M7lc1UVf-VE',
              events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
              }
            });
          }

          function onPlayerReady(event) {
            event.target.playVideo();
          }

          function onPlayerStateChange(event) {
            if (event.data == YT.PlayerState.PLAYING) {

            } else {

            }
          }
    function stopVideo() {
            player.stopVideo();
          }


text:
Q: eslint-plugin-react requires a peer of eslint? I am trying to set up eslint for ReactJS on Atom Editor, so I am following the answer provided here:
However, when I am tyring to install eslint-plugin-react I am getting the warning:
eslint-plugin-react@7.7.0 requires a peer of eslint@^3.0.0 || ^4.0.0 but none is installed. You must install peer dependencies yourself.
Currently it's installed the eslint version v4.19.1, I don't know if I need to downgrade my eslint since I am still getting an error for the JSX code
..
return (
      <div className="App">

...
Error:
Parsing error: Unexpected token < (Fatal)

A: I had also problems in the past. Here is the way I setup eslint for react & atom. May work for you as well (I know that you may not need some of the packages - leaving this to you):
npm install -g create-react-app

create-react-app my-app
cd my-app

npm install --save-dev eslint babel-eslint eslint-plugin-react eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-flowtype  eslint-plugin-html eslint-config-jquery eslint-plugin-jquery prop-types

npm install --save react

eslint packages installed in Atom:
linter-csslint
linter-eslint
linter-stylelint

And this is my .eslintrc:
{
    "plugins": [
      "html",
      "jquery",
      "react"
   ],

    "extends": [
      "eslint:recommended",
      //"google",
      "jquery"
    ],

    "env": {
      "browser": true,
      "node": true,
      "es6": true
    },

//new3
//"parser": "babel-eslint",

// new2
  "parserOptions": {
      "ecmaVersion": 7,
      "sourceType": "module",
      "ecmaFeatures": {
          "jsx": true,
          experimentalObjectRestSpread: true
      }
  },

//new
//    "parserOptions": {
//      "ecmaVersion": 6,
//      "sourceType": "module"
//    },

    "globals": {
      $: false
    },

    "rules": {
      "react/jsx-uses-react": 2,
      "react/jsx-uses-vars": 2,
      "no-caller": 1,
      "linebreak-style": 0,
      'prefer-arrow-callback': 0,
      'no-var': 0,
      'eslint no-mixed-spaces-and-tabs': 0,
      "spaced-comment": 0,
      "no-mixed-spaces-and-tabs": 0,
      "one-var": 0,
      "space-in-parens": 0,
      "curly": 0,
      "jquery/no-ajax": 2,
      "no-alert": 0,
      "computed-property-spacing": 0,
      "array-bracket-spacing": 0,
      "no-console": 1,
      "jquery/no-animate": 2,
      "jquery/no-attr": 0,
      "jquery/no-bind": 2,
      "jquery/no-class": 2,
      "jquery/no-clone": 2,
      "jquery/no-closest": 2,
      "jquery/no-css": 2,
      "jquery/no-data": 2,
      "jquery/no-deferred": 2,
      "jquery/no-delegate": 2,
      "jquery/no-each": 2,
      "jquery/no-fade": 2,
      "jquery/no-filter": 2,
      "jquery/no-find": 2,
      "jquery/no-global-eval": 2,
      "jquery/no-has": 2,
      "jquery/no-hide": 2,
      "jquery/no-html": 0,
      "jquery/no-in-array": 2,
      "jquery/no-is": 2,
      "jquery/no-load": 2,
      "jquery/no-map": 2,
      "jquery/no-merge": 2,
      "jquery/no-param": 2,
      "jquery/no-parent": 2,
      "jquery/no-parents": 2,
      "jquery/no-parse-html": 2,
      "jquery/no-prop": 2,
      "jquery/no-proxy": 2,
      "jquery/no-ready": 1,
      "jquery/no-serialize": 2,
      "jquery/no-show": 2,
      "jquery/no-size": 2,
      "jquery/no-sizzle": 2,
      "jquery/no-slide": 2,
      "jquery/no-submit": 2,
      "jquery/no-text": 0,
      "jquery/no-toggle": 2,
      "jquery/no-trigger": 2,
      "jquery/no-trim": 2,
      "jquery/no-val": 0,
      "jquery/no-when": 2,
      "jquery/no-wrap": 2,
      "quotes": 0,
      "lines-around-comment": 1,
      "no-unreachable": 1
    }
}


text:
Q: Java DOM - Inserting an element, after another Given the following XML file:
<?xml version="1.0" encoding="UTF-8"?>
<process
    name="TestSVG2"
    xmlns="http://www.example.org"
    targetNamespace="http://www.example.org"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <sequence>
      <receive name="Receive1" createInstance="yes"/>
      <assign name="Assign1"/>
      <invoke name="Invoke1"/>
      <assign name="Assign2"/>
      <reply name="Reply1"/>
   </sequence>
</process>

I want to add a new element inside the <sequence></sequence> after a certain pre-existing element. For example if I want to add the node after "Assign1", the new XML should like this:
   <sequence>
      <receive name="Receive1" createInstance="yes"/>
      <assign name="Assign1"/>
      <newtype name="NewNode"/>
      <invoke name="Invoke1"/>
      <assign name="Assign2"/>
      <reply name="Reply1"/>
   </sequence>

I have to do this by using Java DOM, in a function. The function signature should like this:
 public void addActionDom(String name, String stepType, String stepName)

Where:

*

*name is the pre-existing element, after which the insertion will be made;

*stepType is the inserted element type;

*stepName is the name attribute of the newly inserted element.

Currently I am lacking experience with JDOM, or any other Java XML library. Can you please give a sample code, or point me to a tutorial where an insertion after a certain element is made.
This is the code I have until now:
    public void addActionDom(String name, String stepType, String stepName) {
        File xmlFile = new File(path + "/resources/" + BPELFilename);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db;
        try {
            /* Load XML */
            db = dbf.newDocumentBuilder();
            Document doc = db.parse(xmlFile);
            doc.getDocumentElement().normalize();

            /* Iterate throughout the type tags and delete */
            for (String cTag : typeTags) {
                NodeList cnl = doc.getElementsByTagName(cTag);
                for (int i = 0; i < cnl.getLength(); ++i) {
                    Node cnode = cnl.item(i);
                    if (cnode.getNodeType() == Node.ELEMENT_NODE) {
                        Element elem = (Element)cnode; // 'elem' Element after which the insertion should be made
                        if (elem.getAttribute("name").equals(name)) {
                            Element newElement = doc.createElement(stepType); // Element to be inserted
                            newElement.setAttribute("name", stepName);
                            // CODE HERE
                        }
                    }
                }
            }

            /* Save the editing */
            Transformer transformer =
                TransformerFactory.newInstance().newTransformer();
            StreamResult result =
                new StreamResult(new FileOutputStream(path + "/resources/" +
                                                      BPELFilename));
            DOMSource source = new DOMSource(doc);
            transformer.transform(source, result);
        } catch (Exception e) {
            /* ParserConfigurationException */
            /* SAXException */
            /* IOException */
            /* TransformerConfigurationException */
            /* TransformerException */
            /* Exception */
            e.printStackTrace();
        }
    }
}

A: It's simple but the org.w3c.dom API is a bit ... odd for this:
Node next = cnl.item(i + 1);
Node newChild = createChild();
next.getParent().insertBefore(newChild, next);

With JDom, it's more simple:
Node newChild = createChild();
cnl.getParent().addContent(i, newChild);

A: Ok, Aaron Digulla beat me regarding speed. Had to figure it out myself as well.
I didnt use cnl.item(i+1) but nextSibling():
Element newElement = doc.createElement(stepType); // Element to be inserted
newElement.setAttribute("name", stepName);
elem.getParentNode().insertBefore(newElement, elem.getNextSibling());

You cannot insert Nodes at a specified index. The only node-inserting methods are
appendChild(Node node) //appends the given child to the end of the list of children

and
insertBefore(Node new, Node child) //inserts "new" into the list, before the 'child' node.

If there was a insertAfter(Node new, Node child) method, this would be very easy for you. But there isn't, unfortunately.

A: This is not tested but you should be able to do:
elem.getParentNode().insertBefore(newElement, elem.getNextSibling());

A: As others have pointed out, the DOM API is quite verbose for such simple operations. If you use something like jOOX to wrap the DOM API, you could write any of the following:
// Find the element using XPath, and insert XML text after it
$(document).xpath("//sequence/assign[@name='Assign1']")
           .after("<newtype name=\"NewNode\"/>");

// Find the element using jOOX API, and insert an object after it
$(document).find("sequence")
           .find("assign")
           .filter(attr("name", "Assign1"))
           .after($("newtype").attr("name", "NewNode"));

Note how the API resembles that of jQuery.


text:
Q: What's a good way to return an element's path? say I have a button, but I don't know where it is on run-time. Is it possible to return the location of the button?
edit: The "button" looks like this, and there's more unordered lists that are identical to this

Add

One

Two

Three</span

Add

One

Two

Three</span

Add

One

Two

Three</span

A: Passing 'this' to the handler should give you the element that was clicked. Is this what you want?

Add

One

Two

Three</span


text:
Q: Data from MySQL to JSON to AJAX within PHP website, how? I've got really ambitious problem today as I want to achieve something ridiculously stupid but satisfying.
Basically, I do have a database with data for gym exercises
CREATE TABLE IF NOT EXISTS `gp_progs` (
  `prog_id` int(3) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  `exer` varchar(250) NOT NULL,
  `pic` varchar(15) NOT NULL,
  PRIMARY KEY (`prog_id`),
  UNIQUE KEY `prog_id` (`prog_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;

--
-- Dumping data for table `gp_progs`
--

INSERT INTO `gp_progs` (`prog_id`, `name`, `exer`, `pic`) VALUES
(1, 'ABS', 'TO DO ABS YOU NEED TO DO THIS AND THAT', 'abs.jpg'),
(3, 'Arms2', 'this is what we want', 'abs.jpg'),
(7, 'Biceps', 'curls', 'abs.jpg');

I have treated it after digging the code for many hours with this code in PHP
$jsondb = "data/prog.json";
$q = "SELECT * FROM gp_progs";
$r = @mysqli_query ($dbc, $q);
/*$json = array();
while ($row = mysqli_fetch_assoc($r)){
    $json[] = $row;
    }

$jsondata =  json_encode($json, JSON_PRETTY_PRINT);
if(file_put_contents($jsondb, $jsondata)) {
            echo 'Data successfully saved';
        }

It gave me a json file from which I realy want to build AJAX functional app like this one.
JS:
$(function() {                                    // When the DOM is ready

  var times;                                      // Declare global variable
  $.ajax({
    beforeSend: function(xhr) {                   // Before requesting data
      if (xhr.overrideMimeType) {                 // If supported
        xhr.overrideMimeType("application/json"); // set MIME to prevent errors
      }
    }
  });

  // FUNCTION THAT COLLECTS DATA FROM THE JSON FILE
  function loadTimetable() {                    // Declare function
    $.getJSON('data/events.json')              // Try to collect JSON data
    .done( function(data){                      // If successful
      times = data;                             // Store it in a variable
    }).fail( function() {                       // If a problem: show message
      $('#event').html('Sorry! We could not load the timetable at the moment');
    });
  }

  loadTimetable();                              // Call the function

  // CLICK ON THE EVENT TO LOAD A TIMETABLE
  $('#content').on('click', '#event a', function(e) {  // User clicks on event

    e.preventDefault();                                // Prevent loading page
    var loc = this.id.toUpperCase();                   // Get value of id attr

    var newContent = '';                               // Build up timetable by
    for (var i = 0; i < times[loc].length; i++) {      // looping through events
      newContent += '
' + times[loc][i].time + '';
      newContent += '';
      newContent += times[loc][i].title + '
';
    }

    $('#sessions').html('
' + newContent + '
'); // Display times on page

    $('#event a.current').removeClass('current');       // Update selected item
    $(this).addClass('current');

    $('#details').text('');                             // Clear third column
  });

  // CLICK ON A SESSION TO LOAD THE DESCRIPTION
  $('#content').on('click', '#sessions li a', function(e) { // Click on session
    e.preventDefault();                                     // Prevent loading
    var fragment = this.href;                               // Title is in href

    fragment = fragment.replace('#', ' #');                 // Add space after#
    $('#details').load(fragment);                           // To load info

    $('#sessions a.current').removeClass('current');        // Update selected
    $(this).addClass('current');
  });

  // CLICK ON PRIMARY NAVIGATION
  $('nav a').on('click', function(e) {                       // Click on nav
    e.preventDefault();                                      // Prevent loading
    var url = this.href;                                     // Get URL to load

    $('nav a.current').removeClass('current');               // Update nav
    $(this).addClass('current');

    $('#container').remove();                                // Remove old part
    $('#content').load(url + ' #container').hide().fadeIn('slow'); // Add new
  });

});

HTML:

Upcoming Events in Yorkshire

            Sheffield
            Hull
            Leeds
            York

Select an event from the left

So the result I want to see is to click on the group of exercises e.g. Arms, which will open next exercises e.g. Biceps and then onclick I want to see programme with pictures. But I cannot find out how to change JS so it will give me what I want. Spent on it already 13 hrs and still cannot find anything online.
If something is not clear please let me know as I am still learning how to use overflow.
Thanks in advance!
This is for PHP website with an use of JS, MySQL, Google API and HTML of course.
Edit:
If it was not too clear, I want to get MySQL data to JSON (which I have done already)
[
{
"prog_id": "1",
"catg": "chest",
"name": "Chest",
"exer": "Three exercises per muscle group. Chest: Bench Press (3 sets of 10), Chest cable fly(3 sets of 10) and dumbbell fly (3 sets of 10)",
"pic": "abs.jpg"
}
]

And now I want to use it in AJAX in way of: on page I want to see Groups - 'catg' which on click will open list next to group on the same page with Muscle to train 'name' which afterwards open last list next to previous also on the same page showing Descirption 'exer' and Picture/s 'pic'. Just like in the picture below:

A: I think your problem is that you don't know how to get data from MySQL to JSON in PHP, then get that JSON into Javascript in a form that lets you manipulate it easily.
Here's how I do it. The key here is the use of str_replace.
PHP, using my own SQL() function to retrieve the result set via fetch_all(MYSQLI_ASSOC):
$subcategorydata =
  SQL("select * from subcategoryoptions order by category, subcategoryoption");
$subcategories =
  str_replace('\\"','\\\\"',
  str_replace("'","\'",
  json_encode($subcategorydata)));

Javascript (direct rather than via ajax in my case):
var subcategories = '<?php echo $subcategories; ?>';
var jsonSubcategories = JSON.parse(subcategories);
for (var row in jsonSubcategories) { ....

EDIT: Additional code to load 2 layers, toggling the display of the lower level on/off according to user clicks. This version assumes you've pulled all the data out of MySQL in one go (I've just hard-coded it) - you would probably want to use ajax to load stuff dynamically in practice - and my code is definitely not optimal, but it should do the job.
Main div into which the data is loaded is followed by the javascript to load it. Note the hide(), show(), toggle() and set() functions and the onclick.

A: you have the name of the image already in the records and you should also know, were on the server the images can be found.
You can combine this knowledge and forge a URI from path and filename


text:
Q: Counting the number of ways N people with a score tuple can be ranked Let's say I have $N$ people each with a score tuple $(x_i, y_i)$. The total score each person $i$ receives is $Xx_i + Yy_i$ where $X$ and $Y$ are both positive integers (without any upper bound). The $X$ and $Y$ values are the same for every person. In other words, they act as weights for the score tuple of every person.
Now the question is, assuming we are free to choose any value for $X$ and $Y$, in how many ways can we rank each person? (i.e. in how many ways can we sort them by total score)
Assume that when the scores are equal, we can break ties arbitrarily, meaning that if for example we have two persons $A$ and $B$ and both have equal score tuple, we can rank them in two ways total.
I have made very little progress with this. Some observations I've made are:

*

*If all score tuples are in order, such that $x_i < x_{i+1}$ and $y_i < y_{i+1}$, then it's only possible to rank them in one way. For example $(1, 1)$, $(2, 3)$, $(6, 8)$ has only one possible order, no matter how we choose $X$ and $Y$.

*If we have N people and all the tuples are equal, then the answer should be $N!$.

*If we have two people with $(6, 10)$ and $(10, 6)$, then there are two ways of ranking them.

Also in the case of $(1, 1)$, $(2, 2)$, $(6, 10)$, $(10, 6)$, $(20, 20)$, we can tell that some tuples are in order (following observation 1), and the ones in the middle are the same as observation 3, so the total ways of ranking them is also 2. The two possible ways are:
$(1, 1)$, $(2, 2)$, $(6, 10)$, $(10, 6)$, $(20, 20)$
$(1, 1)$, $(2, 2)$, $(10, 6)$, $(6, 10)$, $(20, 20)$
I kind of think one way would be to discard all tuples that don't generate any "conflict" (in the sense of observation 1) and keep only the ones that could be ranked in many ways, and then do some kind of formula, but I'm not capable of finding it as of yet.
Note: I'm not 100% sure if my observations are correct.

A: Imagine the points $(x_i,y_i)$ in the plane, and consider the family of lines orthogonal to the normal vector $(X,Y)$. These are the lines with slope $-\frac XY$, so you can choose any negative rational slope $m$ and the points get ranked according to which of the family of lines with slope $m$ they're on.
Now let $n_m$ be the number of lines with (negative rational) slope $m$ containing more than one point, and let $n_{mk}$ with $1\le k\le n_m$ be the number of points on the $k$-th line with slope $m$. Points that lie on the same line have the same score, so if you choose one of the "ambiguous" values for $m$ such that $n_{mk}$ points lie on a line, there are $n_{mk}!$ different choices for ordering those points, and if $n_m$ lines have more than one point, an order can be freely chosen on each line independently, so there are $\prod_{k=1}^{n_m}n_{mk}!$ different orders for this value of $m$. One of these orders is the same as the one corresponding to slope $m+\epsilon$, and one is the same as the one corresponding to slope $m-\epsilon$, so if we add all these contributions, we're double-counting all the unambiguous orders between the ambiguous slopes, so we have to subtract $1$ for each ambiguous slope and then add $1$, so the number of different orders is
$$
1+\sum_m\left(\prod_{k=1}^{n_m}n_{mk}!-1\right)\;.
$$


text:
Q: Cypress good practices with cy.wait I have the following test, written in Cypress. I use VueJS with SSR support for my frontend.
My app it's an SPA and I am testing the user click on a menu.
before(() => {
   // mock data etc.
});

it('should check if component render properly without ssr', () => {
    cy.visit('url');
    cy.wait(1000);
    cy.get('.menuElement').click();
    cy.get('.something').should($something => {
        expect($something).to.have.length(10);
    });
});

According to Cypress' best practices, I shouldn't use cy.wait in this form.
But the problem is; without the wait, the test will fail. I tried using:

*

*{ timeout: 10000 } as param in cy.get and cy.visit

*aded something like .should('be.visible'); (for waiting when will be visible)

*added route with cy.wait("@abc")
But none of the above works for me.
Please suggest a solution. What should I do that everything works correctly in my case?

A: A year later, but maybe this will be useful for somebody with a similar issue.
According to this very helpful article - https://www.cypress.io/blog/2020/07/22/do-not-get-too-detached, to implement the desired wait, you should allow application to finish action that came first, before proceeding.
My guess is that in your case, .menuElement is still not mounted in the DOM. And instead of using wait(), you could do something like this:
cy.get('.menuElement').should('not.exist');
cy.get('.menuElement').click();

A: Apart from showing the code with cy.wait(), you didn't show the code that is not working. What is the defaultTimeout you have configured in cypress.json file. And how long is your page taking to load...
Cypress by default takes 4 secs for any cypress command and it gets timeout if element doesn't exist on DOM or page is not loaded. So you can increase pageLoadTimeout so that cypress will wait for page to fully load till 10 secs, if page is loaded within 2 secs, then immediately  it will execute cy.get() command
{
  "defalutTimeout": 5000,
  "pageLoadTimeout": 10000
}

Note: I used to use lot of cy.wait() and after I started using the timeouts effectively, there was no issue for me. Please read cypress configuration documentation


text:
Q: How do I encode video for Philips DCP851 with ffmpeg? An older Philips player i have would play "xvid" files, such as those commonly created by Handbrake & similar tools.  This one won't play all those files i had lying around, nor using the standard recipes I'd previously used with ffmpeg.

A: According to Philips DCP851 manual your device can play DIVX hence the following should apply
Taken out of ffmpeg examples
Convert to DivX
This creates a DivX file, 4:3 aspect ratio, 320x240 resolution, bit rate of 690k for video, 128k for audio. The right sort of size for my Archos AV420 player.

ffmpeg -i inputfile.mpg   -vtag DIVX -f avi -vcodec mpeg4
       -aspect 4:3 -s 320x240  -b 690000 -acodec mp3
       -ab 128000 -ar 48000 -ac 2  outputfile.avi

and the same thing for 16:9 ratio.

ffmpeg -i inputfile.mpg   -vtag DIVX -f avi -vcodec mpeg4
       -aspect 16:9 -s 320x192 -b 690000 -acodec mp3
       -ab 128000 -ar 48000 -ac 2  outputfile.avi

A: These ffmpeg options worked for me.  Took a while to figure out.  This unit is less compatible than an older philips unit I have.
ffmpeg -i input.foo -acodec libmp3lame -ab ABITRATE -ac 2 -s WIDTHxHEIGHT -vcodec libxvid -b VBITRATE -vtag DIVX output.avi

DIVX is just the word DIVX and is required.  I believe that this in particular is the magic parameter to make the DCP851 work.  [EDIT] - MP4S also works.  MP4S works with another hardware player I have that won't work with DIVX (Sony DVP-FX980).   Perhaps it is more broadly compatible?
ABITRATE is audio bit rate - 64k is what i use
VBITRATE is video bit rate - 640k is what i use, but it's crappy; a higher number would give better video quality.
WIDTH and HEIGHT are the pixel size of the output video
The screen is 480x234 so i use that for WIDTHxHEIGHT with 16:9 material.  If you had 4:3 material a good choice would be 304x234 or 320x234.
The video tags (vtag) that are being used for AVIs are called fourcc's.  www.fourcc.org has a pretty large list of these codes.


text:
Q: How to get Object ID after update the document using Node.js and MongoDB I am updating my document using Node.js and I need to get that document id after updated. My code is below:
 var udata={
            name:name,
            company:company,
            position:position,
            mobile:mobile,
            email: email,
            landline: landline,
            url:url,
            postcode:postcode,
            address:address,
            profiletext:profiletext,
            biography:biography,
            updated_date:updateDate,
            file:file
        }
    db.f_card_details.update({userid:userid},{$set:udata},function(error,docum){
        if (!error) {
            if (docum) {
                console.log('document',docum);
                var edata=[{"id": docum._id}];
                var data={"statusCode": 200,"data":edata ,"message": "Your card details has been updated successfully"};
                res.send(data);
        }
}else{
            var data={"statusCode": 404,"error": "Not Found","message": "Your card details could not updated"};
            res.send(data);
}
                        })

Here I am not getting that document object id after update.

A: From mongodb.com this link -
"The update() method returns a WriteResult object that contains the status of the operation. Upon success, the WriteResult object contains the number of documents that matched the query condition, the number of documents inserted by the update, and the number of documents modified:
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
"

A: Try using findOneAndUpdate
It will return old document, but you can set the returnNewDocument : true flag to make it return the new one.
So your code would be something like:
db.f_card_details.findOneAndUpdate({userid:userid},{$set:udata},function(error,docum){

    console.log(docum._id);
})


text:
Q: Add item to "New" context menu in Windows 8 for only one user without admin rights I am trying to edit the registry on my windows 8 computer so that I can create a batch(.bat) file from the "new" menu. The only problem is I don't have admin rights. So I was doing some research and found that you can edit some parts of the registry. Is there some way that I can edit the menu for just my user so I don't need admin rights? maybe would it be in "HKEY_CURRENT_USER". Also I currently have this which needs admin rights:
Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\.bat]
@="batch"

[HKEY_CLASSES_ROOT\.bat\ShellNew]
"NullFile"=""

[HKEY_CLASSES_ROOT\batch]
@="Blank Batch file"

A: Not tried, but:
HKEY_CLASSES_ROOT is a combined view of two registry branches:
HKEY_LOCAL_MACHINE\Software\Classes
HKEY_CURRENT_USER\Software\Classes

The combined view shows the data in the local machine brach by default when there is no data (same key/value) in the current user branch, but the current user branch has precedence. So, in theory, the equivalent to your posted code should be
Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Classes\.bat]
@="batch"

[HKEY_CURRENT_USER\Software\Classes\.bat\ShellNew]
"NullFile"=""

[HKEY_CURRENT_USER\Software\Classes\batch]
@="Blank Batch file"

As it is writting under the current user branch, there is no need for admin rights.


text:
Q: How to change the size of circles/rectangles in progress bar css? I need to increase size to display more data and I have tried changing height & width but there is no change in UI.

 <apex:page >

    <meta charset="UTF-8"/>
    <title>Responsive Checkout Progress Bar</title>

        <link rel="stylesheet" href="css/style.css"/>

    <link href='http://fonts.googleapis.com/css?family=PT+Sans+Caption:400,700' rel='stylesheet' type='text/css'/>

Responsive Checkout Progress Bar

Possible candidate

Forwarded to manager

Phone screen

Interview

Complete

Cancelled

</apex:page>

A: This rule reset the properties. Modifying here worked for me.
@media all and (min-width: 800px) {
...
ul.checkout-bar li:before {
    height: 45px;
    left: 40%;
    line-height: 45px;
    position: absolute;
    top: -65px;
    width: 45px;
    z-index: 99;
}


text:
Q: multiple Thrift services on one transport Just seeking confirmation here : apache Thrift protocol does not seem to support running multiple services on one transport endpoint ? ( a socket, file, whatever )
I cant seem to figure out how to do something like this in Thrift:
service otherService {
    void dosomething()
}

service rootService {
    otherService getOtherService()
}

There does not seem to be any concept of passing in and out service handles, ultimately limited by the protocol. Looks like you can not run two services on one transport pipe. Correct ?

A: Correct. As I understand it, only the second service would be generated by thrift, and this is what would be bound when starting the server you create in your preferred language (java, python, etc).

A: Multiplexed Services (in essence that's what you want to do here) are being integrated right now. There are already patches for a number of languages available, either already accepted or in the process of being reviewed.
https://issues.apache.org/jira/browse/THRIFT-563 is a good place to start.
PS: Reviewers and contributions are welcome ;-)


text:
Q: Embedded Crosswalk increase allocated memory on Android I have a several web application that I want to be able to run through a webview in a native android application. I am currently embedding a crosswalk browser and loading the applications in that. It works great for some of the web applications but as the size of the web application increases I get errors that crash my android application.
Things I have tried:

*

*android:largeHeap="true" - helped I was able to run larger web applications.

*android:hardwareAccelerated="true" - helped I got better performance.

*xwalk-command-line='--ignore-gpu-blacklist' in assets/xwalk-commandline - also helps

There are still some web applications (created through unity) that required me to allocate about 1Gb when I was creating them for desktop testing. I am will be using this android app on the newest phones and would be ok with such a high memory usage.
It works if I try to open this application on a desktop browser so that is what leads me to believe that it is a memory allocation issue. I am using crosswalk 17 which has webGL enabled and the smaller applications run webgl just fine.
I have a few questions:

*

*Is there a way to force the crosswalk embedded browser to allocate 1GB of memory for itself. (I know this is going to crush my device and is probably not great but please indulge me)

*Can I expand my application's memory usage beyond largeHeap. If so how? And do I need to do so to enable such large web applications?

*Are there any issues that I am missing that are possibly masking the real issues here.

*I know this type of application would only ever run on the newest kinds of phones. what are the repercussions for an application that has such a high memory usage?

*Are there any other avenues I should explore to enable me to run large web applications within an android app?

Here are the answers to the FAQs of stack overflow users :)
Xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.mycompany.myproject.webapplicationActivity">

    <org.xwalk.core.XWalkView
        android:id="@+id/xwalkWebView"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="#000000"
        />
</RelativeLayout>

Activity onCreate:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.webapplicationActivity);

    xWalkWebView=(XWalkView)findViewById(R.id.xwalkWebView);

    // turn on debugging
    XWalkPreferences.setValue(XWalkPreferences.REMOTE_DEBUGGING, true);
    xWalkWebView.setKeepScreenOn(true);
    xWalkWebView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
    String urlToBeLoaded = "http://www.google.com";

    Bundle bundle = getIntent().getExtras();
    if (savedInstanceState == null) {
        Bundle extras = getIntent().getExtras();
        if(extras == null) {
            Log.i(TAG,"error in reading extras");
        } else {
            urlToBeLoaded = extras.getString("url");
        }
    }
    xWalkWebView.load(urlToBeLoaded, null);

Permissions
*Crosswalk requires a lot of these and I am using the remainder. But maybe there is a conflict there.
 <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

ADB logcat
GL  : validate_display:255 error 3008 (EGL_BAD_DISPLAY)
02-17 18:11:55.862 23023 23023 W art     : Attempt to remove non-JNI local reference, dumping thread
02-17 18:11:55.903  4335  4448 I ActivityManager: Displayed com.mycompany.myProject/.GamePlayActivity: +464ms
02-17 18:11:55.904 23023 23023 W cr.BindingManager: Cannot call determinedVisibility() - never saw a connection for the pid: 23023
02-17 18:11:55.904 22463 22463 I Keyboard.Facilitator: onFinishInput()
02-17 18:11:55.931 23023 23023 E chromium: [ERROR:layer_tree_host_impl.cc(2121)] Forcing zero-copy tile initialization as worker context is missing
02-17 18:11:55.980  4335  4448 I WindowManager: Screen frozen for +541ms due to Window{f87dd7b u0 com.mycompany.myProject/com.mycompany.myProject.GamePlayActivity}
02-17 18:11:57.987  4335  4448 I art     : Starting a blocking GC Explicit
02-17 18:11:58.205  4335  4448 I art     : Explicit concurrent mark sweep GC freed 12393(780KB) AllocSpace objects, 5(100KB) LOS objects, 23% free, 52MB/68MB, paused 1.298ms total 216.765ms
02-17 18:11:58.206  4335 15896 W InputMethodManagerService: Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@3b6394f attribute=null, token = android.os.BinderProxy@d44f10a
02-17 18:11:58.726 23023 23023 I chromium: [INFO:CONSOLE(1)] "Decompressed Release/StuntRunner_WebGL.memgz in 254ms. You can remove this delay if you configure your web server to host files using gzip compression.", source: https://<source>/Release/UnityLoader.js (1)
02-17 18:11:59.103 22037 22037 I ServiceManager: Waiting for service AtCmdFwd...
02-17 18:11:59.663 23023 23023 I chromium: [INFO:CONSOLE(1)] "Decompressed Release/StuntRunner_WebGL.jsgz in 853ms. You can remove this delay if you configure your web server to host files using gzip compression.", source: https://<source>/Release/UnityLoader.js (1)
02-17 18:11:59.985 23023 23023 I chromium: [INFO:CONSOLE(1)] "optimizing out Math.fround calls", source: https://<source>/Release/UnityLoader.js (1)
02-17 18:12:00.103 22037 22037 I ServiceManager: Waiting for service AtCmdFwd...
02-17 18:12:01.104 22037 22037 I ServiceManager: Waiting for service AtCmdFwd...
02-17 18:12:02.105 22037 22037 I ServiceManager: Waiting for service AtCmdFwd...
02-17 18:12:03.105 22037 22037 I ServiceManager: Waiting for service AtCmdFwd...
02-17 18:12:03.174  4335 22386 D NetlinkSocketObserver: NeighborEvent{elapsedMs=775340136, 192.168.1.1, [100D7F6DFA6E], RTM_NEWNEIGH, NUD_REACHABLE}
02-17 18:12:04.106 22037 22037 W Atfwd_Sendcmd: AtCmdFwd service not published, waiting... retryCnt : 5
02-17 18:12:10.387  4335  6452 D ConnectivityService: ConnectivityService NetworkRequestInfo binderDied(NetworkRequest [ id=842, legacyType=-1, [ Capabilities: INTERNET&NOT_RESTRICTED&TRUSTED&NOT_VPN] ], android.os.BinderProxy@82c1e86)
02-17 18:12:10.392  4335  6549 I ActivityManager: Process com.instagram.android (pid 14465) has died
02-17 18:12:10.409  4335  5621 D ConnectivityService: releasing NetworkRequest NetworkRequest [ id=842, legacyType=-1, [ Capabilities: INTERNET&NOT_RESTRICTED&TRUSTED&NOT_VPN] ]
02-17 18:12:10.504  4335  5621 E ConnectivityService: RemoteException caught trying to send a callback msg for NetworkRequest [ id=842, legacyType=-1, [ Capabilities: INTERNET&NOT_RESTRICTED&TRUSTED&NOT_VPN] ]
02-17 18:12:10.781 23023 23263 F libc    : Fatal signal 4 (SIGILL), code 1, fault addr 0xd3781358 in tid 23263 (Chrome_InProcRe)
02-17 18:12:10.886  3293  3293 F DEBUG   : *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
02-17 18:12:10.887  3293  3293 F DEBUG   : Build fingerprint: 'google/angler/angler:6.0.1/MMB29P/2473553:user/release-keys'
02-17 18:12:10.887  3293  3293 F DEBUG   : Revision: '0'
02-17 18:12:10.887  3293  3293 F DEBUG   : ABI: 'arm'
02-17 18:12:10.887  3293  3293 F DEBUG   : pid: 23023, tid: 23263, name: Chrome_InProcRe  >>> com.mycompany.myProject <<<
02-17 18:12:10.887  3293  3293 F DEBUG   : signal 4 (SIGILL), code 1 (ILL_ILLOPC), fault addr 0xd3781358
02-17 18:12:10.933  3293  3293 F DEBUG   :     r0 d5366044  r1 40005000  r2 0855d000  r3 02182000
02-17 18:12:10.933  3293  3293 F DEBUG   :     r4 d5366044  r5 40000000  r6 00000000  r7 00000000
02-17 18:12:10.933  3293  3293 F DEBUG   :     r8 40005000  r9 d66d4050  sl 40000000  fp d66bee10
02-17 18:12:10.934  3293  3293 F DEBUG   :     ip f70ff624  sp d66bed40  lr d3dfa5e1  pc d3781358  cpsr 80030030
02-17 18:12:10.938  3293  3293 F DEBUG   :
02-17 18:12:10.938  3293  3293 F DEBUG   : backtrace:
02-17 18:12:10.926  3293  3293 W debuggerd: type=1400 audit(0.0:9681): avc: denied { read } for name="kgsl-3d0" dev="tmpfs" ino=1150 scontext=u:r:debuggerd:s0 tcontext=u:object_r:gpu_device:s0 tclass=chr_file permissive=0
02-17 18:12:10.938  3293  3293 F DEBUG   :     #00 pc 001e3358  /data/app/com.mycompany.myProject-1/lib/arm/libxwalkcore.so
02-17 18:12:10.938  3293  3293 F DEBUG   :     #01 pc 0085c5dd  /data/app/com.mycompany.myProject-1/lib/arm/libxwalkcore.so
02-17 18:12:11.276  3293  3293 W debuggerd: type=1400 audit(0.0:9682): avc: denied { read } for name="kgsl-3d0" dev="tmpfs" ino=1150 scontext=u:r:debuggerd:s0 tcontext=u:object_r:gpu_device:s0 tclass=chr_file permissive=0
02-17 18:12:11.817  4335 23497 W ActivityManager:   Force finishing activity com.mycompany.myProject/.GamePlayActivity
02-17 18:12:11.818  3293  3293 F DEBUG   :
02-17 18:12:11.818  3293  3293 F DEBUG   : Tombstone written to: /data/tombstones/tombstone_05
02-17 18:12:11.818  3293  3293 E DEBUG   : AM write failed: Broken pipe
02-17 18:12:11.890  4335 22149 I OpenGLRenderer: Initialized EGL, version 1.4
02-17 18:12:11.987  4335  5717 D GraphicsStats: Buffer count: 4
02-17 18:12:11.989  4335  5980 I WindowState: WIN DEATH: Window{def3a97 u0 com.mycompany.myProject/com.mycompany.myProject.LibraryActivity}
02-17 18:12:11.994  4335  5709 I WindowState: WIN DEATH: Window{9ffe3af u0 com.mycompany.myProject/com.mycompany.myProject.LoginActivity}
02-17 18:12:11.996  4335  4351 I WindowState: WIN DEATH: Window{ee84425 u0 com.mycompany.myProject/com.mycompany.myProject.GameDescriptionActivity}
02-17 18:12:11.999  4335  7252 I WindowState: WIN DEATH: Window{a09b55b u0 SurfaceView}
02-17 18:12:12.001  4335  5717 I WindowState: WIN DEATH: Window{f87dd7b u0 com.mycompany.myProject/com.mycompany.myProject.GamePlayActivity}
02-17 18:12:12.022  3309  3309 I Zygote  : Process 23023 exited due to signal (4)
02-17 18:12:12.024  4335 28075 I ActivityManager: Process com.mycompany.myProject (pid 23023) has died
02-17 18:12:12.073  4335 28075 I ActivityManager: Start proc 23507:com.mycompany.myProject/u0a179 for activity com.mycompany.myProject/.GameDescriptionActivity
02-17 18:12:12.076 23507 23507 I art     : Late-enabling -Xcheck:jni

Thank you in advance!

A: I had a problem like that. I thought this problem came with ads like adsense or some went wrong with JavaScript
Try
 xwalk Release 'org.xwalk:xwalk_core_library:21.51.546.7'

I hope that helps you


text:
Q: Execute multiple lines with python in one line for loop I have a loop that appends to new list named list1 and it is working, but how can I add something more like print(x) or anything useful to list1.append(...)?
word="abcdefg"
list1=[]
[list1.append(word[i]) for i in range(len(word))]
print(list1)

I've tried using list1.append(word[i]);print("working") and with ,

A: As I stated in comment, List Comprehensions are not just for executing for loop in single line. They are very powerful but you need to read about it. You may take a look at: Python List Comprehensions: Explained Visually.
However in your this particular case, all your code is doing is to convert the string to list, and printing it. You may do it in one line as:
>>> print(list("abcdefg"))
['a', 'b', 'c', 'd', 'e', 'f', 'g']

A: define a function that does "more lines of code" and use it in the comprehension
word="abcdefg"
list1=[]
def add_and_print(character, container):
    container.append(character)
    print("adding", character)
[add_and_print(character, list1) for character in word]

comprehensions should be short and easy to read in the first place, avoid having a complex one, one condition one call and one for statement should be the maximum - if you need a complex looping etc, create a generator
[call(something) for something in some_container if something == foo]

A: You could simply do -
list1 = [word[i] for i in range(len(word))]

or
list1 = [w for w in word]


text:
Q: java bufferedreader, declaration readline I am implementing a Socket, which it will accept data from a server. The server will send data record, which will be separated by the stx,data,etx. My question is, if I use the following code:
client = new Socket("XXX.XXX.XXX.XXX", 50000);
BufferedReader d = new BufferedReader(new InputStreamReader(client.getInputStream()));

 String line;
 while ((line = d.readLine()) != null) {
     // do something
 }

It will automatically do the seperation of each data record? Or I have to do it by myself? Thanks
STX = Start Of Text (ASCII character)
ETX = End Of Text (ASCII character)

A: If you read the Javadoc for BufferedReader.readLine()

Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

So you can see it doesn't do anything like what you want.

Or I have to do it by myself?

I suggest you either use Scanner with a custom delimiter or you parse the BufferedReader one character at a time.


text:
Q: Unicorn Meta Zoo #1: Why another podcast? Welcome to the Unicorn Meta Zoo, a brand new podcast by members of the Stack Exchange community team. If you want to avoid spoilers, jump straight to the audio. Listener grooveplex has started a wiki transcript of the episode. Please add to it if you are interested in helping out.
Participants

We're talking about why we're doing a podcast. (I believe this is the traditional podcast pilot topic.) It's not intended to replace Stack Overflow podcast, which is on hiatus. For one thing, our audience is much smaller. If you are reading this post, you are one of the super-engaged users we want to talk with. For another, I pitched this as a quick-to-produce podcast. It takes less than an hour to record and edit.
Links

*

*I mentioned the Meta Stack Overflow announcement, which includes a link to my UserVoice request (archived in the WayBack Machine).

*Abby's go-to site is Worldbuilding.

*Jon has a soft spot for Biblical Hermeneutics.

*Juan is a fan of Stack Overflow en español.

*This episode was sponsored by the Ask Question Wizard.

Meta
For recording we use Zencastr which has a free plan that allows up to three participants. Each participant channel is exported to an MP3 file when the recording session ends. In order to merge the three channels into one channel and add the intro/outro, I wrote
a script, edit_podcast.rb, to create FFmpeg commands. Juan M wrote and performed our music. Cover art was generated by balpha's excellent Unicornify script. For the moment, we're serving the files from a GitHub repository and you can grab an RSS feed there. It's not terribly useful just yet, but when we have more episodes, they'll be delivered automatically to your podcatcher of choice.
We mentioned that we might invite Jaydles to be a guest. We'd recorded the episode well before Jay left the company. I'd still be interested in having him on the show to find out what he's up to and get his thoughts after being away from the company for a while.
What do you think?
Take a listen and respond in the answers below.

A: feature-request status-completed
We've started a Transcription Club for people who want to help transcribe episodes.

Not listened to it yet, so burn me if that was mentioned during it (and/or I missed something), but are you planning on releasing a transcript as well?
I can see it being useful for a couple situations:

*

*deaf/hard-of-hearing people who can't listen to it, obviously;

*non-native speakers who might want to check whether they heard right, or feed the text to an online translator or something;

*people who might not have the time to listen or prefer reading (as mentioned in comments);

*searching for a quote, something that was mentioned, with more ease than randomly skipping through 20+ minutes of sound (also mentioned in comments)

I'm not familiar with podcasts and I get they're mostly audio, but basically I think it would improve accessibility.

A: Since a bunch of people have indicated their desire for a transcript, I'm going to assume many readers are not interested in listening to the audio-only podcast. That's probably a good instinct. As I said in a comment:

It's a traditional first episode. So you can safely ignore it until we get to episode 7 and you find the show interesting.

Assuming volunteers continue filling in the wiki transcript (which was a pleasant surprise!) folks who don't want to listen can eventually get the answer to the question in the title. (Well, to the extent we answered it in the conversation.) But thinking about it, I probably should write up an answer that reflects my considered thinking.
Community Managers, you see, spend significant time in text. We write meta posts, type stuff in chat, edit documents to communicate with other teams in the company and so on and so forth. But we also have meetings via Google Hangouts grumble, grumple Meet. Some of our meetings are irrelevant to the community (HR policies and that sort of thing), but we spend a lot of time talking about the communities we are tasked with managing. While most of those conversations still aren't interesting outside of our team, I sometimes wish we could record our conversation so that we could share our thoughts with you, the engaged users of our sites.
I also admire the early Stack Overflow podcasts for being just the raw conversation between Jeff and Joel as they worked out what the site would become.
I love writing.  Stack Exchange is a network built almost entirely on the written word, which is what attracts me to be a part of it. Writing is thought crystalized or, perhaps, fossilized ideas. But it's not a perfect tool. As Socrates said:

I cannot help feeling, Phaedrus, that writing is unfortunately like painting; for the creations of the painter have the attitude of life, and yet if you ask them a question they preserve a solemn silence. And the same may be said of speeches. You would imagine that they had intelligence, but if you want to know anything and put a question to one of them, the speaker always gives one unvarying answer. And when they have been once written down they are tumbled about anywhere among those who may or may not understand them, and know not to whom they should reply, to whom not: and, if they are maltreated or abused, they have no parent to protect them; and they cannot protect or defend themselves.

There's a deep irony that we only know what he said because Plato wrote it down.
At any rate, I spend a lot of time thinking about how my writings will be understood by various readers. It's an invaluable practice that makes my writing more clear and more accessible. While users can (and do!) ask me about my writing, I know that my words get quoted out of context or are misinterpreted in ways I can't correct. In short, I understand Socrates' protective attitude toward words.
I can't have a conversation with each individual user of the sites, even if y'all wanted that. Publishing a dialog between me and my colleagues gets me a good way there. (In the future, if this goes well, I want to interview users, which would be even closer.) Instead of worrying about exact wording, I can let my tone of voice and the flow of conversation help communicate more effectively and efficiently. The spoken word carries a different load than the written word.
If that sounds good, I encourage you to listen to the episodes as they come out. (We've been on a every-third-week recording schedule, so that's probably the rate I'll put them out.) If you can't or don't want to listen, I don't think you'll be missing anything really important. For the foreseeable future any news we discuss will be weeks or months old anyway. Also we focus on big-picture philosophy-of-community topics that'll be just as useful in the future as they are now. (Which means they might continue to be pointless, of course. ;-)
The recordings are raw and edited only by my script. We spend a couple of minutes deciding who will host the episode and thinking of broad questions to keep the conversation going. Then we record for 25 minutes or so and that's it. The goal is to keep the podcast project fun and not-time-consuming. But that doesn't mean we haven't prepared. In many ways, the podcast distills untold hours of conversation that we've had amongst ourselves into a format we are pleased to share with you, our communities.


text:
Q: May someone let me know what kind of license I need? I was wondering if someone may help me in terms of Salesforce license, I am really puzzle due to there are lot of docs about that even I've talked to sales departament and I think it was worst.
Thing is I just need a license to develop a canvas and have a connected app in my salesforce account in order to connect my website with salesforce. Nowdays we just need to use Oauth and Canvas in Salesforce so I have been reasearching about those topics and I think I have to purchase a light force.com account which is 10$/month pricing-platform . That's actually good nevertheless I am afraid that we need to buy an administrator license to manage to use that connected app, is that true? I mean may someone let me know if we need to buy 2 kind of licenses, adminsitrator license and light force.com account.
Thank you so much

A: In reading between the lines, it appears you have a Salesforce production instance with some existing users, correct? You don't need a separate user account to show them a canvas app through a publisher action, visualforce page, etc.
To create a canvas app, you need to spin up a free Developer Edition org at http://developer.force.com/ and package your app there. The development and management of your app takes place in this free DE org.
http://www.salesforce.com/us/developer/docs/platform_connect/canvas_framework.pdf


text:
Q: Installed xubuntu-desktop on Lubuntu - cannot login to xubuntu/xfce session So, I installed the xubuntu-desktop package on my Lubuntu netbook, but when I went to login to a xubuntu session nothing happened. The screen simply went momentarily blank and then came up with the original login screen again.
I tried with xfce session and got the same result. I was logging in with my ordinary Lubuntu details.
I did find one thing to try, which I did, which was to reset Xauthority... Not sure what that is but it didn't help anyway.
I haven't really found anything else similar to this problem, so I thought I'd ask here if anyone else had seen or experienced a similar issue.

A: This seems to work for me..
sudo chown username:username .Xauthority
sudo chmod a+wt /tmp

A: Make sure you have enough free disk space.
After making sure permissions are correct on ~/.Xauthority and tmp as Scott Goodgame's answer explains, the next step is to make sure you have enough free disk space on the partition that contains /home (as Scott Goodgame also suggested in a comment).
You're able to log in to a Lubuntu Desktop session, so do so, then open an LXTerminal (Ctrl+Alt+T) and run:
df -h

That will show you each mounted partition and statistics about how much space is on it and how full it is. For example, when I run that on my machine, I get:
Filesystem          Size  Used Avail Use% Mounted on
/dev/sda8            15G  7.9G  6.2G  57% /
udev                997M   12K  997M   1% /dev
tmpfs               403M  900K  402M   1% /run
none                5.0M     0  5.0M   0% /run/lock
none               1007M  2.6M 1004M   1% /run/shm
none                100M   48K  100M   1% /run/user
/dev/sda6           240M   91M  138M  40% /boot
/dev/sda9            31G   29G  112M 100% /home

(I've left out some entries representing external hard drives and network drives, which would primarily serve to confuse matters.)
If you have a separate /home partition listed in the Mounted on column, check if it has enough free space to spontaneously create files. Usually this doesn't have to be very much--20M is usually quite sufficient, but I recommend shooting for at least 50M. (And of course, you'd normally want much more free than that so you can download and create big files in your home directory--but as you can see, I only have a little over 100M, and I haven't experienced any problems.)
If you don't have a separate /home partition, then look at the free space on /.
Whether or not you have a separate /home partition, you can make it so your home directory (/home/username) has more free space by deleting files there. Make sure not to delete anything important though! Your Downloads folder is often a good place to check for files you don't need.
If you don't have a separate /home partition, then you can free space in your home directory by deleting files anywhere in / (so long as the location where you remove them is not inside a mount point for something else--for example, if a separate /boot partition listed, then you cannot free space in / by deleting files inside /boot even though /boot is a child directory if /).
Generally, it is best not to manually delete files in / (unless they're in your home directory and you do not need them). Instead, you can free space in / by uninstalling software. However, much software in Ubuntu depends on other software, so don't press y or click OK until you've read through the list of packages that would be removed alongside whatever you've specified for removal. You can remove packages in the Software Center, the Synaptic Package Manager, or on the command-line with apt-get.
If you do not have a separate /boot partition (I do, as you can see above, but these days most installations do not), then since everything in /boot would then be in /, you can free space in / by deleting files from /boot. Again, don't do this manually. Instead, uninstall old kernels:

*

*How do I remove old kernel versions to clean up the boot menu?
You need to uninstall them if you want to free space, not just hide them in the GRUB menu. (Answers there explain both.) Make sure you do not remove all your kernels, because then Ubuntu will not be able to boot, and the fix for that is not very much fun.

*

*It's a good idea to keep at least the kernel you are currently running (as told to you by uname -r).

*It's also advisable to keep one other kernel, both because the one you're currently using could have problems (which you could work around by falling back to another) and because then if you remove one more kernel than you intended, you still have one.

*If you do accidentally remove all kernels but have not rebooted, you can just install a kernel back with sudo apt-get install linux-image or sudo apt-get install linux-image-generic.

Once df -h shows that at least 50M of space is free on / and, if it is listed, on /home, try logging in to an Xubuntu session again.
Try a different display manager.
A display manager provides the graphical login screen. A problem logging in like the one you describe could be related to a problem with the display manager you are currently using. Unless you're using a very old version of Lubuntu, you're almost certainly using LightDM as your display manager. (You can check the picture in that Wikipedia article to see if it looks like your login screen.)
Since you have Lubuntu installed, LXDE's very own display manager is probably installed. This display manager is called LXDM (though the picture there will not necessarily look just like LXDM on your machine).
To make your system use LXDM instead of LightDM, run:
sudo dpkg-reconfigure lxdm

You should see:

When you see that, press Enter. (That clicks the OK "button.")
Then you'll be asked to choose between the display managers that are installed on your system. Most likely there will be two choices: lightdm and lxdm. Use the arrow keys to select lxdm and press Enter:

Then either reboot (properly from the power icon on the upper-right corner of the screen, or with sudo reboot) to apply the change. Or, if you prefer, apply the change in a virtual console (Ctrl+Alt+F1) by logging in and running:
sudo stop lightdm
sudo start lxdm

When you run that first command, all your graphical programs will be quit immediately, even if they have unsaved work. Any unsaved work will be lost. I recommend simply logging out before switching to the virtual console (though it's the running of the commands, and not switching to a virtual console, that will terminate your graphical applications).
On a virtual console, you can switch back to the GUI manually by pressing Alt+F7. But when you run the above commands, you should be placed back on the (new) graphical login screen automatically.
If you were unable to do any of this because dpkg-reconfigure failed and said lxdm was not installed, then just install the lxdm  package. To install it from the command line, run:
sudo apt-get update && sudo apt-get install lxdm

If you install it in the command-line, it should run dpkg-reconfigure automatically. If it does not, you can still run it manually.
Hopefully, if making sure you have enough free space doesn't help, then switching to a different display manager as explained here will help. If it does not, please comment here and add as detailed information as possible to your question about what you did and what happened.

A: Make sure that all files in your home directory, especially files that start with a "." like .Xauthority, but also .bashrc, .profile, .bash_logout etc. are owned by your user.
cd
ls -la

Should tell you all the files with their owners.
You can safely use a
sudo chown $USER:$USER ~/.* -R

to set all files' owner/group to you.
Then the login via lightdm/sddm/gdm etc should work again.


text:
Q: Elasticsearch aggregate function error on laravel Elasticsearch gives error when integrating with laravel using aggregations. This is my code:
        $laws_y = Law::searchByQuery([
            'multi_match' => [
                'query' => $years,
                'fields' => ["law_year"]
            ],
            "aggs" => [
                "group_by_law_year" => ["terms" => ['field' => ["law_year"]]]
            ]
        ]);

I get following error:

BadRequest400Exception in GuzzleConnection.php line 277:
  {"error":{"root_cause":[{"type":"parse_exception","reason":"failed to
  parse search source. expected field name but got
  [START_OBJECT]"}],"type":"search_phase_execution_exception","reason":"all
  shards
  failed","phase":"query","grouped":true,"failed_shards":[{"shard":0,"index":"default","node":"BcRQOVhkS1SwTlvYPCEfHg","reason":{"type":"parse_exception","reason":"failed
  to parse search source. expected field name but got
  [START_OBJECT]"}}]},"status":400}

Does anyone know the solution?

A: From the Elasticquent documentation, the searchByQuery function takes the following parameters (see source here):

*

*query - Your ElasticSearch Query

*aggregations - The Aggregations you wish to return.

*sourceFields - Limits returned set to the selected fields only

*limit - Number of records to return

*offset - Sets the record offset (use for paging results)

*sort - Your sort query

In your call, you need to separate the query (first parameter) from the aggregations (second parameter). Do it like this instead:
     $laws_y = Law::searchByQuery([
        'multi_match' => [
            'query' => $years,
            'fields' => ["law_year"]
        ]
     ],
     [
        "group_by_law_year" => ["terms" => ['field' => "law_year"]]
     ]);


text:
Q: Как добавить произвольное поле к записи, чтобы оно отображалось на сайте и в админке? Как добавить произвольное поле к записи, чтобы оно отображалось на сайте и в админке?

A: Решил проблему плагином Advanced Custom Fields
Вывожу значение полей на страницах Wordpress с помощью shortcode:
add_shortcode('answer', 'answer');
function answer(){
    global $post;
    if(get_post_meta($post->ID, 'answer')){
        $answer = get_post_meta($post->ID, 'answer');
        var_dump($answer);
        $output = '
';
        foreach ($answer as $key => $value) {
            $output .= "
$key

";
            for ($i=0; $i < count($value); $i++) {
                $output .= "
$value[$i]
";
            }
        }
        $output .= '

';
        return $output;
        unset($output);
        unset($answer);
    }
}