title
stringlengths 15
150
| body
stringlengths 38
32.9k
| label
int64 0
3
|
---|---|---|
No enclosing instance of type MainRender is accessible
|
<p>I have a problem with this code </p>
<pre><code>public static void main(String[] args) {
final GLProfile profile = GLProfile.get(GLProfile.GL2);
GLCapabilities capabilities = new GLCapabilities(profile);
final GLCanvas glcanvas = new GLCanvas(capabilities);
MainRender r = new MainRender();
glcanvas.addGLEventListener(r);
glcanvas.setSize(700, 400);
final FPSAnimator animator = new FPSAnimator(glcanvas, 300, true);
final JFrame frame = new JFrame("Render");
frame.getContentPane().add(glcanvas);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
if (animator.isStarted())
animator.stop();
System.exit(0);
}
});
frame.setSize(frame.getContentPane().getPreferredSize());
frame.setLocationRelativeTo(null);
frame.setVisible(true);
JPanel p = new JPanel();
p.setPreferredSize(new Dimension(0, 0));
frame.add(p, BorderLayout.SOUTH);
keyBindings(p, frame, r);
animator.start();
Handler h = new Handler();
p.addMouseListener(new Handler());
p.addMouseMotionListener(new Handler());
}
</code></pre>
<p>At the Handler h = new Handler(); Eclipse shows this message</p>
<p>No enclosing instance of type MainRender is accessible. Must qualify the allocation with an enclosing instance of type MainRender (e.g. x.new A() where x is an instance of MainRender).</p>
<p>Any solutions?</p>
| 2 |
Button enable disble on select dropdown Value
|
<p>I have two Buttons:</p>
<ol>
<li><p>For bulk order</p></li>
<li><p>For sample Order</p></li>
</ol>
<p>By default both buttons are disabled when I click on the dropdown. Value "1" then "Sample order Btn" should be enabled and when I click on the dropdown value more then 1 "Buk Order" Btn should be enabled.</p>
<p>On select again both buttons should be disabled.
Here is my code on select element, it doesn't work and I don't know why.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$("select").on('change',function(){
if ($(this).find('option:selected').text()=="1"){
alert('1');
$("#product-addtocart-button").attr('disabled',true);
$("#product-addtocart-button1").attr('disabled',false);
}
if ($(this).find('option:selected').text()!="1" && $(this).find('option:selected').text()!="0"){
alert('25');
$("#product-addtocart-button1").attr('disabled',true);
$("#product-addtocart-button").attr('disabled',false);
}
if ($(this).find('option:selected').text()=="0"){
alert('sele');
$("#product-addtocart-button").attr('disabled',true);
$("#product-addtocart-button1").attr('disabled',true);
}
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="productextra">
<option selected value="0">select</option>
<option value="1">1</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="75">75</option>
<option value="100">100</option>
<option value="150">150</option>
<option value="200">200</option>
<option value="250">250</option>
<option value="300">300</option>
<option value="400">400</option>
<option value="500">500</option>
<option value="750">750</option>
<option value="1000">1000</option>
</select>
<button type="button" id="product-addtocart-button" class="button btn-cart" disabled="disabled">
<span>
<span>Bulk Order</span>
</span>
</button>
<button type="button" id="product-addtocart-button1" class="button btn-cart select-change" disabled="disabled">
<span>
<span>Sample Order</span>
</span>
</button></code></pre>
</div>
</div>
</p>
| 2 |
HIVE QL: How do I extract info from "show partitions table' and use it in a query?
|
<p>When I want to select the last month from a big table I can do this:</p>
<pre><code>select *
from table
where yyyymm=(select max(yyyymm) from table)
</code></pre>
<p>It takes forever. But</p>
<pre><code>hive> show partitions table
</code></pre>
<p>only takes a second.</p>
<p>Would it be possible to manipulate <code>show partitions table</code> into a text_string and do something like: </p>
<pre><code>select *
from table
where yyyymm=(manipulated 'partition_txt')
</code></pre>
| 2 |
INSERT BASE64 FILE INTO ORACLE BLOB USING PHP
|
<p>I’m trying to save images as BLOB on my ORACLE 11g R2 database through the base64 of files uploaded, but when i retrieve this file from DB, it dont show the a image with base64_encode function. And when i dowload this file from SQL Developer, the file doesn’t the image as well, only a message saying that the image is invalid or is corrupted. Details of my problem below:
I have this form in my web page:
<a href="http://i.stack.imgur.com/6JBoD.png" rel="nofollow">Upload Page 1</a></p>
<p>The “+” button is a file input that when clicked, the user can choose one or more files to upload and these files are showed on a preview, as you can see below:
<a href="http://i.stack.imgur.com/j8Vte.png" rel="nofollow">Upload Page 2</a></p>
<p>The user can open file input, selecet how many images he wants, close file input and re-open it to add more files how many times he wants. For each file added, a javascript create the preview and set the base64 in href of “a” element, as below:</p>
<pre><code> //create preview
$("#exams-fileinput").on('change',function(e){
var input = $(this);
var files = input.prop('files');
var countFiles = files.length;//alert(files.length);
if (window.File && window.FileReader){
var allow = /png|jpg|jpeg|tiff|pdf$/i;
// com suporte a FileReader()
for(i= 0;i <countFiles; i++){
file = files[i];
if(!allow.test(file.name)){continue;}
imageType = /image.*/;
reader = new FileReader();
reader.onload = function(e){
filePreview = e.target;
var fileName = file.name;
var fileResult = filePreview.result;
var fileThumb = file.type.match(imageType) ? fileResult : 'assets/img/file-document.png'; // https://cdn4.iconfinder.com/data/icons/office-20/128/OFFice-51-256.png assets/img/file-document.png
var classIframe = file.type.match(imageType) ? '' : 'fancybox.iframe';
var imgPrevContent =
'<div name="file-added" class="col-xs-6 col-sm-4 col-md-3 ms-file-thumbnail-preview-item" >'+ '<a href="'+fileResult+'" class="ms-filedata fancybox '+classIframe+'" rel="exam" data-type="img" data-file-name="'+fileName+'">'+ //<= aqui vai entrar o "fancybox.iframe", se necessário <= Vamos obter daqui o código do arquivo para subir ".ms-filedata"
'<figure class="img-responsive img-thumbnail" style="background-image:url('+fileThumb+');">'+
'<figcaption>'+
'<p><i class="fa fa-eye fa-3x"></i><p>'+
'<p class="ms-ellipsis">'+fileName+'</p>'+
'</figcaption>'+
'</figure>'+
'</a>'+
'<input type="file" value="'+fileResult+'" id="" style="display: none;">'+
'</div>';
console.log('Nome do arquivo: '+fileName+' - Tamanho: '+ file.size+' - HTML: '+imgPrevContent.length);
fileName='';
$("#exam-view-files").append(imgPrevContent);
};
reader.readAsDataURL(file);
}
}else{
// browser doesn't supor file reader
}
});
</code></pre>
<p>When users click on save button “Salvar”, i take all bases64 of files added and sent by ajax to save in a BLOB field in my ORACLE 11g R2 database as below:</p>
<pre><code>//save function
$("#btn-save-files").click(function(e){
var filesToAdd = [];
$("div[name=file-added]").each(function(e){
filesToAdd.push({
content: $(this).children("a").attr("href"),
name: $(this).children("a").data("file-name")
});
});
$.ajax({
type: 'POST',
url: 'controller/ctrl-person-profile-action.php',
data: { action: "insertfiles",
files: filesToAdd
},
datatype: "json",
async: true,
success: function(response){
response = JSON.parse(response);
switch(response["status"].toLowerCase()){
case "success": swal("Pronto", "Adicionado com sucesso", "success");
break;
case "fail": swal("Atenção", response["message"], "warning");
break;
default: swal("Ops..", "Ocorreu um erro inesperado ao inserir o medicamento", "error");
break;
}
}
});
}
</code></pre>
<p>And a take these files and save by PHP, as below:</p>
<pre><code> //Ajax calls this function
function InsertFiles(){
$files = isset($_REQUEST['files']) ? $_REQUEST['files'] : null;
foreach ($files as $file) {
$fileBase64 = explode(",", explode(";", $file["content"])[1])[1];
$fileType = explode(":",(explode(";", $file["content"])[0]))[1];
$fileInsert = new MyFileClass();
$fileInsert->setFile($fileBase64);
$fileInsert->setType($fileType);
$fileInsert->Insert();
}
//Class MyFile method insert:
public function Insert(){
$sql = "INSERT FILES (ID,
MIME_TYPE,
FILE)
VALUES(SEQ_FILES.NEXTVAL,
'$this->type,
EMPTY_BLOB()
) RETURNING FILE INTO :file";
$conn = GetDBConnection();
$statment = oci_parse($conn, $sql)
// Creates an "empty" OCI-Lob object to bind to the locator
$fileBlob = oci_new_descriptor($conn, OCI_DTYPE_LOB);
// Bind the returned Oracle LOB locator to the PHP LOB object
oci_bind_by_name($statment, ":file", $fileBlob, -1, OCI_B_BLOB);
// Execute the statement using , OCI_DEFAULT - as a transaction
oci_execute($statment, OCI_DEFAULT)
or die ("Erro execute SQL command");
// Now save a value to the LOB
if (!$fileBlob->save('INSERT: '.base64_decode($this->file))) {
// On error, rollback the transaction
oci_rollback($conn);
die("Erro execute SQL command");
} else {
// On success, commit the transaction
oci_commit($conn);
}
// Free resources
oci_free_statement($statment);
$fileBlob->free();
//feca conexão
oci_close($conn);
}
</code></pre>
<p>Can anyone give me some help to save this base64 file into a BLOB field on ORACLE and retrieve a valid file from my BLOB?</p>
<p>Thx a lot!</p>
| 2 |
project Can not execute Findbugs: java.lang.ArrayIndexOutOfBoundsException
|
<p>I am using sonarQube4.5.7 version with JDK 1.8 version. currently getting this error on running </p>
<pre><code>mvn sonar:sonar
</code></pre>
<p>command. can anyone suggest me how to resolve this error.</p>
<p>Logs are:</p>
<pre><code>Unable to get XClass for java/lang/StringBuilder
java.lang.ArrayIndexOutOfBoundsException: 26721
At org.objectweb.asm.ClassReader.readClass(Unknown Source)
At org.objectweb.asm.ClassReader.accept(Unknown Source)
At edu.umd.cs.findbugs.asm.FBClassReader.accept(FBClassReader.java:44)
At org.objectweb.asm.ClassReader.accept(Unknown Source)
At edu.umd.cs.findbugs.classfile.engine.ClassParserUsingASM.parse(ClassParserUsingASM.java:110)
At edu.umd.cs.findbugs.classfile.engine.ClassParserUsingASM.parse(ClassParserUsingASM.java:587)
At edu.umd.cs.findbugs.classfile.engine.ClassInfoAnalysisEngine.analyze(ClassInfoAnalysisEngine.java:76)
At edu.umd.cs.findbugs.classfile.engine.ClassInfoAnalysisEngine.analyze(ClassInfoAnalysisEngine.java:38)
At edu.umd.cs.findbugs.classfile.impl.AnalysisCache.getClassAnalysis(AnalysisCache.java:268)
At edu.umd.cs.findbugs.ba.XFactory.getXClass(XFactory.java:652)
At edu.umd.cs.findbugs.ba.ch.Subtypes2.addInheritanceEdge(Subtypes2.java:1260)
At edu.umd.cs.findbugs.ba.ch.Subtypes2.addSupertypeEdges(Subtypes2.java:1233)
At edu.umd.cs.findbugs.ba.ch.Subtypes2.addClassAndGetClassVertex(Subtypes2.java:275)
At edu.umd.cs.findbugs.ba.ch.Subtypes2.addClass(Subtypes2.java:244)
At edu.umd.cs.findbugs.ba.AnalysisContext.setAppClassList(AnalysisContext.java:941)
At edu.umd.cs.findbugs.FindBugs2.setAppClassList(FindBugs2.java:997)
At edu.umd.cs.findbugs.FindBugs2.execute(FindBugs2.java:225)
At org.sonar.plugins.findbugs.FindbugsExecutor$FindbugsTask.call(FindbugsExecutor.java:207)
At java.util.concurrent.FutureTask.run(FutureTask.java:266)
At java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
At java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
At java.lang.Thread.run(Thread.java:745)
</code></pre>
| 2 |
Difference between using UINavigationController and UINavigationBar
|
<p>I started learning ios development recently. I made a project using <code>UINavigationController</code> by embedding it because I need a title bar. But I can achieve the same thing by using <code>UINavigationBar</code> from the object library. </p>
<p>The only difference I saw is when I use <code>UINavigationController</code> I get a back button when I use segue. Are there any more differences between them? Which one is used in which situations?</p>
<p>By the way, why another <code>NavigationController</code> is added to my storyboard? What is the significance of it?(No one explained about it in any video I have seen)</p>
<p>Thank you.</p>
| 2 |
Deploy postgres via jenkins - continuous integration/deployment
|
<p>I got my database dump (tables, functions, triggers etc) in *.sql files.
At this moment I am deploying them via jenkins, by passing execute shell command:</p>
<pre><code>sudo -u postgres psql -d my_db < /[path_to_my_file].sql
</code></pre>
<p>The problem is, that if something is wrong in my sql file, build finishes as SUCCESS. I would like to got information immediately if something fails, without looking into log and checking if every command executed succesfully.</p>
<p>Is it possible (and how if the answer is 'yes') to deploy postgres database via jenkins other way?</p>
| 2 |
How to generate thumb pdf file only first page in node js
|
<p>I have issue When I upload pdf file in multiple page then generate thumb multiple time.</p>
<p>my code is below</p>
<pre><code>var image = random() + '.png';
imagename = 'uploads/document_thumb/' + image;
var pathToFile = path.join(__dirname, req.files[i].path)
, pathToSnapshot = path.join(__dirname, '/uploads/document_thumb/' + image);
im.resize({
srcPath: pathToFile
, dstPath: pathToSnapshot
, width: 150
, height: 150
, quality: 0
, gravity: "North"
},
function (err, stdout, stderr) {
if (err) {
console.log(err);
}
console.log('resized image', pathToSnapshot);
});
</code></pre>
<p>How to set generate only one page thumb generate.</p>
| 2 |
Does C# 6.0 support .NET Core, or does .NET Core respond to higher version of C#?
|
<p>I've just installed .NET Core 1.0 and run the sample hello world.</p>
<ol>
<li>Is there any relationship with .NET Core 1.0 and its default C# version?</li>
<li>How can I know the C# version of this .NET Core installation via a command line utility?</li>
</ol>
| 2 |
Java 9 javax.money.MonetaryAmount (JSR 354): Unable to convert Pojo to XML and vice versa
|
<p>I'm using Rest Api call to convert Pojo to XML.</p>
<p>Below is my code snippet:</p>
<p><strong>TestAccount.java</strong></p>
<pre><code> import javax.money.MonetaryAmount;
public class TestAccount {
private MonetaryAmount paymentAmount;
private String accountNumber;
public String getAccountNumber() {
return this.accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public MonetaryAmount getPaymentAmount() {
return this.paymentAmount;
}
public void setPaymentAmount(MonetaryAmount paymentAmount) {
this.paymentAmount = paymentAmount;
}
}
</code></pre>
<p><strong>Controller.java</strong></p>
<pre><code>public class Controller extends BaseController {
@RequestMapping(value = "/javaTest", method = RequestMethod.GET, produces = { "application/xml" })
public TestAccount testMoneyPackage() {
TestAccount obj = new TestAccount();
obj.setAccountNumber("101423");
obj.setPaymentAmount(MoneyUtilityCls.of(10.898));
return obj;
}
}
</code></pre>
<p>when running the url on browser </p>
<p><strong><a href="http://localhost:8080/api/javaTest" rel="nofollow">http://localhost:8080/api/javaTest</a></strong></p>
<p><strong>output:</strong></p>
<pre><code><OverdueAccount>
<accountNumber>101423</accountNumber>
<paymentAmount>
<currency>
<context>
<providerName>java.util.Currency</providerName>
<empty>false</empty>
</context>
<defaultFractionDigits>2</defaultFractionDigits>
<currencyCode>USD</currencyCode>
<numericCode>840</numericCode>
</currency>
<number>10.9</number>*****loss of precision*******
<negative>false</negative>
<zero>false</zero>
<precision>3</precision>
<scale>1</scale>
<positiveOrZero>true</positiveOrZero>
<positive>true</positive>
<negativeOrZero>false</negativeOrZero>
<factory>
<defaultMonetaryContext>
<precision>0</precision>
<amountType>org.javamoney.moneta.RoundedMoney</amountType>
<fixedScale>false</fixedScale>
<maxScale>-1</maxScale>
<providerName/>
<empty>false</empty>
</defaultMonetaryContext>
<amountType>org.javamoney.moneta.RoundedMoney</amountType>
<maxNumber/>
<minNumber/>
<maximalMonetaryContext>
<precision>0</precision>
<amountType>org.javamoney.moneta.RoundedMoney</amountType>
<fixedScale>false</fixedScale>
<maxScale>-1</maxScale>
<providerName/>
<empty>false</empty>
</maximalMonetaryContext>
</factory>
<context>
<precision>0</precision>
<amountType>org.javamoney.moneta.RoundedMoney</amountType>
<fixedScale>false</fixedScale>
<maxScale>-1</maxScale>
<providerName/>
<empty>false</empty>
</context>
</paymentAmount>
</OverdueAccount>
</code></pre>
<p>As you can see When setting </p>
<blockquote>
<p>od.setPaymentAmount(MoneyUtil.of(10.898)); </p>
</blockquote>
<p>I'm getting loss of precision in XML as</p>
<p><code><number>10.9</number></code></p>
<p>Also what are those extra XML tags?</p>
<p>This problem occurs only with MonetaryAmount field otherwise code is running properly.
So, What is the Correct way to convert MonetaryAmount field to Pojo to XML and vice versa without losing precision.</p>
| 2 |
Android printing arabic using zebra printer imz320 shows as reversed character
|
<p>here is the zpl code from android </p>
<pre><code> String zplcode="^XA^LRN^CI0^XZ\n" +
"\n" +
"^XA^CWZ,E:TT0003M_.FNT^FS^XZ\n" +
"^XA\n" +
"\n" +
"^FO10,50^CI28^AZN,50,50^F16^FDZebra Technologies^FS\n" +
"^FO10,150^CI28^AZN,50,100^F16^FDUNICODE^FS\n" +
"^FO020,260^CI28^AZN,50,40^F16^FDSwiss 721 Arabic: زيبرة تكنوليجيز اوربا المحدودة^FS\n" +
"^PQ1\n" +
"^XZ";
mmOutputStream.write(message.getBytes());
</code></pre>
<p>the result is reversed arabic characters
any suggestion ?
thanks in advance
<a href="https://i.stack.imgur.com/lnOqt.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/lnOqt.jpg" alt="enter image description here"></a></p>
| 2 |
Weak references and anonymous classes
|
<p>I'm in a situation where I have a static list caching some references. As this is a static list, I want to use WeakReference so I don't keep my objects in memory uselessly.</p>
<p>The issue - I think - I have is that one of the references is an anonymous class. My fear is that if I store the anonymous class as a WeakReference, it might be collected really quickly, and if I store the anonymous class as a strong reference, it will hold a reference to the class that constructed the anonymous class.</p>
<p>I don't know if my explanation is clear, so here is a piece of code:</p>
<pre><code>public interface Callback {
void call();
}
public class A {
public void doIt() {
B.register(this, new Callback() {
public void call() {
// do something
}
});
}
}
public class B {
private static final List<Item> ITEMS = new LinkedList<>();
public static void register(Object key, Callback callback) {
Item item = new Item();
item.key = new WeakReference<>(key);
// ??
item.callback = new WeakReference<>(callback);
ITEMS.add(item);
}
private static class Item {
private WeakReference<Object> key;
private WeakReference<Callback> callback;
}
}
</code></pre>
<p>Basically, if in Item 'callback' is a weak reference, it might be garbage collected before I even get the chance to use it.
And if in Item 'callback' is a standard reference, the instances of 'A' will never be garbage collected.</p>
<p>So my first question: is my understanding right?
Second question: is there a way to make it work or do I have to change the design?</p>
<p>Thanks.</p>
| 2 |
ANDROID start service at specific time every day
|
<p>After the boot is completed, I want to start a service at a specific time (for example at 3 am) every day, but without repeating, for example, every thirty seconds or minutes, or hour but the alarm must repeat every day at 3 am.</p>
<p>Finally, why the alarm start at 3 am after boot complete and if I restart the device at 3.05 am the alarm wakes up anyway?</p>
<p>Sorry for my English</p>
| 2 |
Automapper 5.0.0 missing SourceValue (Custom Converters)
|
<p>After updating automapper version from 4.2.1 to 5.0.0 I got compilateion error that SourceValue is missing.
Here is my example </p>
<pre><code> public class DraftLayoutCellPropertiesConverter : ITypeConverter<DraftLayoutCell, DraftGamePeriodDraftLayoutViewModel>
{
public DraftGamePeriodDraftLayoutViewModel Convert(ResolutionContext context)
{
var input = context.SourceValue as DraftLayoutCell;
var result = new DraftGamePeriodDraftLayoutViewModel();
if (input != null)
{
</code></pre>
<p>What should be the replacement of that property? Is that the best way to do custom converters? I was expecting the update will not break existing code as there are many people using the app.</p>
| 2 |
ryu (SDN) traffic controller from (example) Host 1
|
<p>I created a simple network in the <code>mininet</code> environment with the following command:</p>
<pre><code>$ sudo mn --topo single,3 --mac --controller remote --switch ovsk
</code></pre>
<p>I want use <code>RYU CONTROLLER</code> to calculate bandwidth traffic on special port of switch. I'm thinking of using an <code>OFPEVENTPacketIn</code> event for the incoming packet, but I do not any idea for out coming packet form port.</p>
<p>My code:</p>
<pre><code>from operator import attrgetter
from ryu.app import simple_switch_13
from ryu.controller import ofp_event
from ryu.controller.handler import MAIN_DISPATCHER, DEAD_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.lib import hub
class SimpleMonitor(simple_switch_13.SimpleSwitch13):
def __init__(self, *args, **kwargs):
super(SimpleMonitor, self).__init__(*args, **kwargs)
self.datapaths = {}
self.monitor_thread = hub.spawn(self._monitor)
@set_ev_cls(ofp_event.EventOFPStateChange,
[MAIN_DISPATCHER, DEAD_DISPATCHER])
def _state_change_handler1(self, ev):
datapath = ev.datapath
if ev.state == MAIN_DISPATCHER:
if not datapath.id in self.datapaths:
self.logger.debug('register datapath: %016x', datapath.id)
self.datapaths[datapath.id] = datapath
elif ev.state == DEAD_DISPATCHER:
if datapath.id in self.datapaths:
self.logger.debug('unregister datapath: %016x', datapath.id)
del self.datapaths[datapath.id]
def _monitor(self):
while True:
for dp in self.datapaths.values():
self._request_stats(dp)
hub.sleep(10)
def _request_stats(self, datapath):
self.logger.debug('send stats request: %016x', datapath.id)
ofproto = datapath.ofproto
parser = datapath.ofproto_parser
req = parser.OFPFlowStatsRequest(datapath)
datapath.send_msg(req)
req = parser.OFPPortStatsRequest(datapath, 0, ofproto.OFPP_ANY)
datapath.send_msg(req)
@set_ev_cls(ofp_event.EventOFPFlowStatsReply, MAIN_DISPATCHER)
def _flow_stats_reply_handler(self, ev):
body = ev.msg.body
self.logger.info('datapath '
'in-port eth-dst '
'out-port packets bytes')
self.logger.info('---------------- '
'-------- ----------------- '
'-------- -------- --------')
for stat in sorted([flow for flow in body if flow.priority == 1],
key=lambda flow: (flow.match['in_port'],
flow.match['eth_dst'])):
# self.logger.info('%016x %8x %17s %8x %8d %8d',
if stat.match['in_port']==1:
self.logger.info('%x %x %s %x %d %d',
ev.msg.datapath.id,
stat.match['in_port'], stat.match['eth_dst'],
stat.instructions[0].actions[0].port,
stat.packet_count, stat.byte_count)
#for stat in [1234]#sorted([flow for flow in body if flow.priority == 1],
# key=lambda flow: (flow.match['in_port'],
# flow.match['eth_dst'])):
# self.logger.info('%016x %8x %17s %8x %8d %8d',
# if stat.match['in_port']==1:
# self.logger.info('%x %x %s %x %d %d',
# ev.msg.datapath.id,
# stat.match['in_port'], stat.match['eth_dst'],
# stat.instructions[0].actions[0].port,
# stat.packet_count, stat.byte_count)
@set_ev_cls(ofp_event.EventOFPPortStatsReply, MAIN_DISPATCHER)
def _port_stats_reply_handler(self, ev):
body = ev.msg.body
self.logger.info('datapath port '
'rx-pkts rx-bytes rx-error '
'tx-pkts tx-bytes tx-error')
self.logger.info('---------------- -------- '
'-------- -------- -------- '
'-------- -------- --------')
for stat in sorted(body, key=attrgetter('port_no')):
if stat.port_no==1:
self.logger.info('%016x %8x %8d %8d %8d %8d %8d %8d',
ev.msg.datapath.id, stat.port_no,
stat.rx_packets, stat.rx_bytes, stat.rx_errors,
stat.tx_packets, stat.tx_bytes, stat.tx_errors)
</code></pre>
<p>Please help me edit this code to answer my question. Thanks.</p>
| 2 |
cocos2dx build fail due to undefined symbol
|
<p>I am new in Cocos2d and Xcode(as well as game development and mac, I was window and eclipse user). I am working on <a href="https://github.com/chukong/programmers-guide-samples" rel="nofollow">programmer guide</a> from coco2dx homepage. I have clone the git and try to run the code, but I am facing compilation error with libcocos2d iOS.a. I have set up library path (to libcocos2d) and header file that caused "cocos2d.h not found" error. But now I have a problem with linker errors. I have googled to figure out build architecture errors but no goods. My current build setting for build architecture is that yes to debug, no to release, architecture is set to standard 64bit x86_64, and valid architectures are -armv7, armv7s, i386, x86_64, and arm64- Can some help me with this? </p>
<pre><code>Undefined symbols for architecture x86_64:
"_OBJC_CLASS_$_CMMotionManager", referenced from:
objc-class-ref in libcocos2d iOS.a(CCDevice-ios.o)
"_OBJC_CLASS_$_EAGLContext", referenced from:
objc-class-ref in libcocos2d iOS.a(CCDirectorCaller-ios.o)
"_OBJC_CLASS_$_UIApplication", referenced from:
objc-class-ref in libcocos2d iOS.a(CCApplication-ios.o)
objc-class-ref in libcocos2d iOS.a(CCDirectorCaller-ios.o)
objc-class-ref in libcocos2d iOS.a(CCDevice-ios.o)
"_OBJC_CLASS_$_UIColor", referenced from:
objc-class-ref in libcocos2d iOS.a(CCDevice-ios.o)
"_OBJC_CLASS_$_UIDevice", referenced from:
objc-class-ref in libcocos2d iOS.a(CCApplication-ios.o)
objc-class-ref in libcocos2d iOS.a(CCDevice-ios.o)
"_OBJC_CLASS_$_UIFont", referenced from:
objc-class-ref in libcocos2d iOS.a(CCDevice-ios.o)
"_OBJC_CLASS_$_UIImage", referenced from:
objc-class-ref in libcocos2d iOS.a(CCImage-ios.o)
"_OBJC_CLASS_$_UIScreen", referenced from:
objc-class-ref in libcocos2d iOS.a(CCDevice-ios.o)
"_UIApplicationDidBecomeActiveNotification", referenced from:
-[CCDirectorCaller init] in libcocos2d iOS.a(CCDirectorCaller-ios.o)
"_UIApplicationWillResignActiveNotification", referenced from:
-[CCDirectorCaller init] in libcocos2d iOS.a(CCDirectorCaller-ios.o)
"_UIGraphicsPopContext", referenced from:
cocos2d::Device::getTextureDataForText(char const*, cocos2d::FontDefinition const&, cocos2d::Device::TextAlign, int&, int&, bool&) in libcocos2d iOS.a(CCDevice-ios.o)
"_UIGraphicsPushContext", referenced from:
cocos2d::Device::getTextureDataForText(char const*, cocos2d::FontDefinition const&, cocos2d::Device::TextAlign, int&, int&, bool&) in libcocos2d iOS.a(CCDevice-ios.o)
"_UIImageJPEGRepresentation", referenced from:
cocos2d::Image::saveToFile(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, bool) in libcocos2d iOS.a(CCImage-ios.o)
"_UIImagePNGRepresentation", referenced from:
cocos2d::Image::saveToFile(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, bool) in libcocos2d iOS.a(CCImage-ios.o)
"AppDelegate::AppDelegate()", referenced from:
_main in main.o
"AppDelegate::~AppDelegate()", referenced from:
_main in main.o
"_glBindVertexArrayOES", referenced from:
cocos2d::GL::bindVAO(unsigned int) in libcocos2d iOS.a(ccGLStateCache.o)
"_glDeleteVertexArraysOES", referenced from:
cocos2d::Renderer::~Renderer() in libcocos2d iOS.a(CCRenderer.o)
cocos2d::MeshCommand::releaseVAO() in libcocos2d iOS.a(CCMeshCommand.o)
cocos2d::TextureAtlas::~TextureAtlas() in libcocos2d iOS.a(CCTextureAtlas.o)
cocos2d::CameraBackgroundSkyBoxBrush::~CameraBackgroundSkyBoxBrush() in libcocos2d iOS.a(CCCameraBackgroundBrush.o)
cocos2d::CameraBackgroundSkyBoxBrush::initBuffer() in libcocos2d iOS.a(CCCameraBackgroundBrush.o)
cocos2d::Physics3DDebugDrawer::~Physics3DDebugDrawer() in libcocos2d iOS.a(CCPhysics3DDebugDrawer.o)
cocos2d::DrawNode::~DrawNode() in libcocos2d iOS.a(CCDrawNode.o)
...
"_glGenVertexArraysOES", referenced from:
cocos2d::Renderer::setupVBOAndVAO() in libcocos2d iOS.a(CCRenderer.o)
cocos2d::MeshCommand::buildVAO() in libcocos2d iOS.a(CCMeshCommand.o)
cocos2d::TextureAtlas::setupVBOandVAO() in libcocos2d iOS.a(CCTextureAtlas.o)
cocos2d::CameraBackgroundSkyBoxBrush::initBuffer() in libcocos2d iOS.a(CCCameraBackgroundBrush.o)
cocos2d::Physics3DDebugDrawer::init() in libcocos2d iOS.a(CCPhysics3DDebugDrawer.o)
cocos2d::DrawNode::init() in libcocos2d iOS.a(CCDrawNode.o)
cocos2d::VertexAttribBinding::init(cocos2d::MeshIndexData*, cocos2d::GLProgramState*) in libcocos2d iOS.a(CCVertexAttribBinding.o)
...
"_glMapBufferOES", referenced from:
cocos2d::Renderer::drawBatchedTriangles() in libcocos2d iOS.a(CCRenderer.o)
cocos2d::TextureAtlas::drawNumberOfQuads(long, long) in libcocos2d iOS.a(CCTextureAtlas.o)
"_glUnmapBufferOES", referenced from:
cocos2d::Renderer::drawBatchedTriangles() in libcocos2d iOS.a(CCRenderer.o)
cocos2d::TextureAtlas::drawNumberOfQuads(long, long) in libcocos2d iOS.a(CCTextureAtlas.o)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code></pre>
| 2 |
How to get permissions by name for each role a liferay user has
|
<p>I've been working on access control.So,In our liferay portlets,how can I get all permissions of a user,I've achieved getting roles of a user by </p>
<pre><code>FacesContext facesContext = FacesContext.getCurrentInstance();
PortletRequest request = (PortletRequest) facesContext
.getExternalContext().getRequest();
User user = (User) request.getAttribute(WebKeys.USER);
List<Role> roles = new ArrayList<Role>();
roles.addAll(RoleLocalServiceUtil.getUserRoles(user.getUserId()));
roles.addAll(RoleLocalServiceUtil.getUserRelatedRoles(user.getUserId(), user.getGroupIds()));
</code></pre>
<p>But I cant find any thing by which I can find if the given user has view/configuration/etc permissions with respect to the portlets.<code>getResourceResourcePermissions</code> gives me the permission but by ids,How can I find permissions with permission name i.e view/config/update</p>
<p><code>liferay 6.2</code></p>
| 2 |
C# universal app: automatically scroll to bottom of textbox after setting new text programmatically
|
<pre><code>{
var stringBuilder = new StringBuilder(OutputTextBox.Text);
stringBuilder.Append("sample text\n");
OutputTextBox.Text = stringBuilder.ToString();
}
</code></pre>
<p>How to automatically scroll to the bottom of the textbox after inserting a new text? I have read that it had worked with the .append method. Unfortunately this method does not exist within universal apps. The textbox is read-only.</p>
<p>The .xaml looks like this:</p>
<pre><code><ScrollViewer Name="ScrollViewer" HorizontalAlignment="Left" Height="175" VerticalAlignment="Top" Width="337" RenderTransformOrigin="1.774,9.9" Margin="95,95,-370,-223">
<TextBox x:Name="OutputTextBox" HorizontalAlignment="Left" Height="175" VerticalAlignment="Top" Width="337" RenderTransformOrigin="1.774,9.9" TextWrapping="Wrap" AcceptsReturn="True" IsReadOnly="True"/>
</ScrollViewer>
</code></pre>
<p>What I have tried to do is:</p>
<pre><code> await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
var stringBuilder = new StringBuilder(OutputTextBox.Text);
stringBuilder.Append("sample text\n");
OutputTextBox.Text = stringBuilder.ToString();
ScrollViewer.ChangeView(0.0f, double.MaxValue, 1.0f);
});
</code></pre>
| 2 |
How to handle indents of very long fo:list-item-labels?
|
<p>I have the following <code>fo</code> markup:</p>
<pre><code><fo:list-block>
<fo:list-item>
<fo:list-item-label end-indent="label-end()">
<fo:block>[KEY]</fo:block>
</fo:list-item-label>
<fo:list-item-body start-indent="body-start()">
<fo:block>Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah
Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah </fo:block>
</fo:list-item-body>
</fo:list-item>
</fo:list-block>
</code></pre>
<p>While this looks fine in print but if I change it to:</p>
<pre><code><fo:list-block>
<fo:list-item>
<fo:list-item-label end-indent="label-end()">
<fo:block>[VERYLONGKEY]</fo:block>
</fo:list-item-label>
<fo:list-item-body start-indent="body-start()">
<fo:block>Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah
Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah </fo:block>
</fo:list-item-body>
</fo:list-item>
</fo:list-block>
</code></pre>
<p>the <code>fo:list-item-label</code> and the following <code>fo:list-item-body</code> overlap. How can I set the <code>start-indent</code> and <code>end-indent</code> to use the actual width of my labels? Currently it seems that <code>label-end()</code> and <code>body-start()</code> is a constant but I would like to have a dynamic label width. Is this possible in xsl-fo?</p>
| 2 |
different behavior when linking with static library vs using object files in C++
|
<p>I'm working with some legacy C++ code that is behaving in a way I don't understand. I'm using the Microsoft compiler but I've tried it with g++ (on Linux) as well—same behavior.</p>
<p>I have 4 files listed below. In essence, it's a registry that's keeping track of a list of members. If I compile all files and link the object files into one program, it shows the correct behavior: <code>registry.memberRegistered</code> is true:</p>
<pre><code>>cl shell.cpp registry.cpp member.cpp
>shell.exe
1
</code></pre>
<p>So somehow the code in member.cpp gets executed (which I don't really understand, but OK).</p>
<p>However, what I want is to build a static library from registry.cpp and member.cpp, and link that against the executable built from shell.cpp. But when I do this, the code in member.cpp does <em>not</em> get executed and <code>registry.memberRegistered</code> is false:</p>
<pre><code>>cl registry.cpp member.cpp /c
>lib registry.obj member.obj -OUT:registry.lib
>cl shell.cpp registry.lib
>shell.exe
0
</code></pre>
<p>My questions: how come it works the first way and not the second and is there a way (e.g. compiler/linker options) to make it work with the second way?</p>
<hr />
<h3>registry.h:</h3>
<pre><code>class Registry {
public:
static Registry& get_registry();
bool memberRegistered;
private:
Registry() {
memberRegistered = false;
}
};
</code></pre>
<hr />
<h3>registry.cpp:</h3>
<pre><code>#include "registry.h"
Registry& Registry::get_registry() {
static Registry registry;
return registry;
}
</code></pre>
<hr />
<h3>member.cpp:</h3>
<pre><code>#include "registry.h"
int dummy() {
Registry::get_registry().memberRegistered = true;
return 0;
}
int x = dummy();
</code></pre>
<hr />
<h3>shell.cpp:</h3>
<pre><code>#include <iostream>
#include "registry.h"
class shell {
public:
shell() {};
void init() {
std::cout << Registry::get_registry().memberRegistered;
};
};
void main() {
shell *cf = new shell;
cf->init();
}
</code></pre>
| 2 |
ffprobe output frame with read_intervals no match given time range
|
<p>I have read ffprobe document at <a href="https://www.ffmpeg.org/ffprobe-all.html#mpeg4_005funpack_005fbframes" rel="nofollow">here</a>.</p>
<p>I don't know why my first time of the frame is 11.745 seconds, even given "-read_intervals 12%13". (12sec ~ 13sec )</p>
<p><code>$ ffprobe -i chrome.webm -show_frames -select_streams v:0 -read_intervals 12%13 -hide_banner -loglevel panic</code></p>
<pre><code>[FRAME]
media_type=video
stream_index=0
key_frame=1
pkt_pts=11745
pkt_pts_time=11.745000
pkt_dts=11745
pkt_dts_time=11.745000
best_effort_timestamp=11745
best_effort_timestamp_time=11.745000
pkt_duration=33
pkt_duration_time=0.033000
pkt_pos=717643
pkt_size=5864
width=480
height=270
pix_fmt=yuv420p
sample_aspect_ratio=1:1
pict_type=I
coded_picture_number=0
display_picture_number=0
interlaced_frame=0
top_field_first=0
repeat_pict=0
[/FRAME]
...
</code></pre>
| 2 |
Schedule Local Notifications at Specific times in the day
|
<p>I want to setup a daily notification system for my app. It should notify the user twice a day, once at 8:00 AM (Hey there, your set of morning doses is ready. Wanna check it out?) and once at 7:00 PM (Ssup! Your evening Dose is waiting inside). I know that by doing this i'll run out of notifications in a month since there's a 64 notifications cap (for local notifications) but by then, the app will be live and i'll be done setting up remote notifications update. </p>
<p>I've looked at this question: <a href="https://stackoverflow.com/questions/26214768/how-to-schedule-a-same-local-notification-in-swift">How to schedule a same local notification in swift</a> and the .Day is all good. I just need to know how to do it twice a day at those specified times;. Thanks in advance!</p>
<p><strong>EDIT:</strong> how to set the specific time on the notification is part of the problem. The NSDate API is giving me funny time intervals (sinceNow/Since1973). I just want to set it to fire at 7 PM. :-/ Can't quite seem to do it with these NSDate apis unless I'm missing something.</p>
| 2 |
Laravel findorfail() redirect
|
<p>I have the following code :</p>
<pre><code>public function showTestProfile($id){
$auth = Auth::user();
$tests = App\Test::findorfail($id);
return view('profile',compact('auth','tests','members'));
}
</code></pre>
<p>if we have an <code>id</code> in the DB table then that will come up with <code>findorfail()</code>,</p>
<p>but if we add not existing <code>id</code> to the url like this :</p>
<p><code>http://NewPro.dev/user-profile/24645645456</code></p>
<p>Then no query can be found and laravel page comes up.</p>
<p>How can I redirect to some route if we have no <code>id</code>?</p>
| 2 |
Scheduled tasks limitations (or how tasks persistence is implemented)?
|
<p>I've started to read Hangfire documentation, and found nothing about task limitations. </p>
<p>As declared, tasks (or jobs) are stored somewhere. </p>
<p>Since they are just delegates, the only thing could be stored, as far as I understand, is a delegate "body" (IL?). But there could be closures, that provides some context for the task, e.g., some external services, that can require to load extra assemblies to run their code, etc.</p>
<p>How Hangfire deals with this?<br>
Can task contain any instructions in its body, or there are any limitations? </p>
| 2 |
Git: Abort all Operations to get a Clean Working Directory
|
<p>I would like to write a script that needs a clean working directory. I want to make sure that any rebases, merges, or anything else that might not have ended properly is completely gone from my working directory.</p>
<p><code>git reset --hard</code> should work for merges, and <code>git rebase --abort</code> will work for rebases, but there are other states like reverting or cherry-picking as well. Is there any sure way to clear all such events in order to get my working directory into a clean state?</p>
<p><strong>EDIT:</strong></p>
<p>For example:</p>
<pre><code>((5d8999f...))
$ git rebase develop
(detached HEAD|REBASE 1/3)
$ git reset --hard
(detached HEAD|REBASE 1/3)
$ git checkout HEAD -- .
(detached HEAD|REBASE 1/3)
$ git status
rebase in progress; onto 41e6808
You are currently rebasing.
(all conflicts fixed: run "git rebase --continue")
</code></pre>
<p>I know that I can do <code>git rebase --abort</code>, but if there is no rebase going on that will cause an error, which I am not in the mood of dealing with. Also, since this will be an automatic script I do not want to find out that there may be other states that I may not have accounted for.</p>
<p>I need one foolproof way to revert my working directory to a pristine state so that I can do any command I want without failure.</p>
| 2 |
jcifs.smb.SmbAuthException though user name and password are correct on Ubuntu
|
<p>We are working on spring boot application. In our application we have to share folder from remote machine from any OS. We are sharing folders to get the list of objects exist in shared folder. We are using SMB and NTLMAuthentication for it.</p>
<p><strong>For authentication :</strong></p>
<pre><code> NtlmPasswordAuthentication credential = new NtlmPasswordAuthentication(
informationStoreDefinition.getProperties().get(DOMAIN),
informationStoreDefinition.getProperties().get(USER),
informationStoreDefinition.getProperties().get(PASSWORD)
);
</code></pre>
<p>Later we are trying to get list of shared folder using the code : </p>
<pre><code> SmbFile file = ((CifsContainerObject) simpleObject).smbFile;
SmbFile[] list = file.listFiles();
</code></pre>
<p>We have tried these combinations to access/share the folder :</p>
<ul>
<li>Windows OS to Ubuntu - WORKING!!</li>
<li>Windows OS to Windows OS - WORKING!!</li>
<li><strong>Ubuntu to Windows - FAILED</strong></li>
<li><strong>Ubuntu to Ubuntu - FAILED</strong></li>
</ul>
<p>We are getting this error for above two case : <strong>jcifs.smb.SmbAuthException: Logon failure: unknown user name or bad password.</strong> </p>
<p>Code throw error at line : <code>SmbFile[] list = file.listFiles();</code>. Our user name, password and domain all are correct. We have accessed folder of Linux on Windows our network, we are successfully able to access the share folder as well as we are getting response on our Windows machine for Linux shared folder. Then why this error thrown?</p>
| 2 |
Summing Groups of Columns within a Pandas Dataframe
|
<p>I have a pandas dataframe with 600 columns (df1), and I want to sum the values of each column in groups of 6. In other words, I want to create a new dataframe (df2) that has 100 columns, each column being the sum of 6 columns from the input dataframe. For example, Each row the first column in df2 will be the sum of the first six columns in df1 (keeping the rows separate). The dataframe I am using also has string values for each column name (here just represented with single letters)</p>
<p>For df1:</p>
<pre><code> A B C D E F G H I J ...
0 9 6 3 4 7 7 6 0 5 2 ...
1 8 0 6 6 0 5 6 5 8 7 ...
2 9 0 7 2 9 5 3 2 1 7 ...
3 5 2 9 6 7 0 3 8 5 0 ...
4 7 1 0 7 4 0 2 0 5 8 ...
5 0 9 2 0 4 9 5 7 6 2 ...
</code></pre>
<p>I would want the first column of df2 to be:</p>
<pre><code> A G ...
0 36
1 25
2 32
3 29
4 19
5 24
</code></pre>
<p>Where each row is the sum of the first six columns of that row. The next column would then be the sum of the next six columns and so on, with the column name being the name of the first column in each set of 6. (First column name is the first column's, the second column name is the seventh column's, etc.)</p>
<p>I've tried using the column indices to sum the correct columns, but I am having issues finding a way to store the sums in new columns with relevant names.</p>
<p>Is there a pythonic way to create these columns, and pull column names from df into df2? </p>
| 2 |
PDFPTable over multiple pages with repeating header
|
<p>I have a PDFPTable that may span over multiple pages. The table should have the same first/header row on every page. </p>
<p>How can I do so?</p>
<p>It seems that since I can't give rows explicitly (which PDFPCells form a row is decided by how many cells have been added before), I have to manually calculate which row would be the first to be displayed on the next page. Is this correct?</p>
<p>How can I calculate that?</p>
| 2 |
Eclipse Team Synchronizing View: How to remove unversioned items in outgoing changes?
|
<p>While viewing the outgoing changes in Eclipse Team Synchronization(Subclipse), I am able to see the unversioned files also, like the generated class files, build folders, etc, which I do not want to see in this view. I dont want to add it to svn:ignore, since I have to do it manually for all the additional folders generated.</p>
<p>Is there any setting to change this to show only versioned files in this mode always?
Tortoise SVN client shows this option while committing, to show only versioned files. I am looking for such an option in Subclipse Team Synchronization view. Thanks in advance.</p>
<p><a href="http://i.stack.imgur.com/25Jov.png" rel="nofollow">eclipse_outgoing_view</a></p>
| 2 |
How to pass an array type in plsql package specification?
|
<p>I am new to plsql. I am trying to put two scripts under the same package. These scripts deal with arrays. How do I pass an array into the procedure? If I am to declare the array, do I do it in the specification or the body? I am trying this right now but it doesn't work.</p>
<pre><code>CREATE PACKAGE cop_cow_script AS
PROCEDURE COP_COW_DATALOAD_V2(arr_claims VARRAY(15000) OF VARCHAR2(10), arr_sql VARRAY(500) OF VARCHAR2(1000));
END cop_cow_script;
</code></pre>
<p>As you see I want to pass in those two arrays. </p>
| 2 |
Options beginAtZero doesn't work in angular-chart.js
|
<p>I use angular-chart.js and chart.js 2.0.2 - I have bar char. It is my code for chart in index.slim</p>
<pre><code>canvas#bar.chart.chart-bar chart-data="data" chart-labels="labels" chart-options="options"
</code></pre>
<p>How Can I set beginAtZero options (other options works (f.e display: true )) in my controller I tried:</p>
<pre><code>$scope.options = {
scale: {
ticks: {
beginAtZero: true
}
}
};
</code></pre>
<p>What I did wrong?</p>
| 2 |
Unicorn, can't restart: "rack and Rack::Builder must be available for processing config.ru"
|
<p>I have an Ubuntu 14.04 server with nginx and unicorn. I have deployed a Rails application with capistrano to <code>/home/rails/myapp</code>.</p>
<p>When trying to restart unicorn with <code>sudo service unicorn restart</code> I get the following:</p>
<pre><code>* Restarting Unicorn web server unicorn
rack not available, functionality reduced
rack and Rack::Builder must be available for processing config.ru
</code></pre>
<p>I'm getting a 502 from nginx when trying to access the site in my browser.</p>
<p>Here's my /etc/default/unicorn file:</p>
<pre><code># Change paramentres below to appropriate values and set CONFIGURED to yes.
CONFIGURED=yes
# Default timeout until child process is killed during server upgrade,
# it has *no* relation to option "timeout" in server's config.rb.
TIMEOUT=60
# Path to your web application, sh'ld be also set in server's config.rb,
# option "working_directory". Rack's config.ru is located here.
APP_ROOT=/home/rails/myapp/current
# Server's config.rb, it's not a rack's config.ru
CONFIG_RB=/etc/unicorn.conf
# Where to store PID, sh'ld be also set in server's config.rb, option "pid".
PID=/home/rails/myapp/current/pids/unicorn.pid
RAILS_ENV="production"
UNICORN_OPTS="-D -c $CONFIG_RB -E $RAILS_ENV"
PATH=/usr/local/rvm/rubies/ruby-2.3.0/bin:/usr/local/sbin:/usr/bin:/bin:/sbin:/usr/local/rvm/bin:/usr/local/rvm/gems/ruby-2.3.0@global/bin:/usr/local/rvm/gems/ruby-2.3.0/bin/
export GEM_HOME=/usr/local/rvm/gems/ruby-2.3.0
export GEM_PATH=/usr/local/rvm/gems/ruby-2.3.0:/usr/local/rvm/gems/ruby-2.3.0@global
DAEMON=/usr/local/rvm/gems/ruby-2.3.0/wrappers/unicorn
</code></pre>
<p>Here's my /etc/unicorn.conf file:</p>
<pre><code>listen "unix:/var/run/unicorn.sock"
worker_processes 4
user "rails"
working_directory "/home/rails/myapp/current"
pid "/var/run/unicorn.pid"
stderr_path "/var/log/unicorn/unicorn.log"
stdout_path "/var/log/unicorn/unicorn.log"
</code></pre>
<p>Any Ideas? I feel like I have tried everything.</p>
| 2 |
How to include Hawaii and Alaska in spatial overlay in R
|
<p>I'm having some troubling getting demographic data points to overlay on a US counties map. I'm able to map just fine, but no data shows up for Hawaii and Alaska. I've identified the origin of the problem -its after my <code>over</code> command. My workflow uses a csv file that can be found here (<a href="https://www.dropbox.com/s/0arazi2n0adivzc/data.dem2.csv?dl=0" rel="nofollow noreferrer">https://www.dropbox.com/s/0arazi2n0adivzc/data.dem2.csv?dl=0</a>). Here's my workflow:</p>
<pre><code>#Load dependencies
devtools::install_github("hrbrmstr/albersusa")
library(albersusa)
library(dplyr)
library(rgeos)
library(maptools)
library(ggplot2)
library(ggalt)
library(ggthemes)
library(viridis)
#Read Data
df<-read.csv("data.dem.csv")
#Retreive polygon shapefile
counties_composite() %>%
subset(df$state %in% unique(df$state)) -> usa #Note I've checked here and Alaska is present, see below
</code></pre>
<p><a href="https://i.stack.imgur.com/5aLPs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5aLPs.png" alt="enter image description here"></a></p>
<pre><code>#Subset just points and create spatial points object
pts <- df[,4:1]
pts<-as.data.frame(pts)
coordinates(pts) <- ~long+lat
proj4string(pts) <- CRS(proj4string(usa)) #Note I've checked here as welland Alaska is present still, see here
</code></pre>
<p><a href="https://i.stack.imgur.com/3jTUL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3jTUL.png" alt="enter image description here"></a></p>
<pre><code>#Spatial overlay
b<-over(pts, usa) #This is where the problem arises: see here
</code></pre>
<p><a href="https://i.stack.imgur.com/hjzR0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hjzR0.png" alt="enter image description here"></a></p>
<pre><code>b<-select(b, -state)
b<-bind_cols(df, b)
bind_cols(df, select(over(pts, usa), -state)) %>%
count(fips, wt=count) -> df
usa_map <- fortify(usa, region="tips")
ggplot()+
geom_map(data=usa_map, map=usa_map,
aes(long, lat, map_id=id),
color="#b2b2b2", size=0.05, fill="grey") +
geom_map(data=df, map=usa_map,
aes(fill=n, map_id=fips),
color="#b2b2b2", size=0.05) +
scale_fill_viridis(name="Count", trans="log10") +
gg + coord_map() +
theme_map() +
theme(legend.position=c(0.85, 0.2))
</code></pre>
<p>The final output, as you might be able to suspect, displays no data for Alaska or Hawaii. I'm not sure what's going on but it seems the <code>over</code> command from the sp package is the source of the problem. Any suggestions are much appreciated.</p>
<p><a href="https://i.stack.imgur.com/fQCQb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fQCQb.png" alt="enter image description here"></a></p>
<p>As a note, this is a different question than the one's found <a href="https://stackoverflow.com/questions/13757771/relocating-alaska-and-hawaii-on-thematic-map-of-the-usa-with-ggplot2">Relocating Alaska and Hawaii on thematic map of the USA with ggplot2</a> and <a href="https://stackoverflow.com/questions/25530358/how-do-you-create-a-50-state-map-instead-of-just-lower-48">How do you create a 50 state map (instead of just lower-48)</a></p>
<p>The questions have nothing to do with one another. This is NOT a duplicate. The first question is in regards to the position of the actual polygons of Hawaii and Alaska, as you can see from my map, I don't have that issue. The second link is in regards to obtaining a map that includes Hawaii and Alaska. Again, my map INCLUDES both those, but somewhere in my data processing workflow the data for those two gets removed (specifically, the overlay function). Please do not mark as duplicate.</p>
| 2 |
Pass Data to a Component in React Native?
|
<p>I'm having trouble with the syntax on props when passing a data structure to a component in React Native. If anyone could help me see how I can reuse the component 'DisplayPerson' below by passing it 'FemaleInfo' and then again 'MaleInfo' would greatly appreciate it.</p>
<pre><code>var FemaleInfo = [
{name: 'Jane Doe', age: 23, occupation: 'Carpenter'},
{name: 'Kate Ryan', age: 31, occupation: 'Lawyer'},
{name: 'Ellen Anderson', age: 42, occupation: 'Doctor'}
];
var MaleInfo = [
{name: 'John Doe', age: 23, occupation: 'Carpenter'},
{name: 'Jack Douglas', age: 31, occupation: 'Lawyer'},
{name: 'Rick Smith', age: 42, occupation: 'Doctor'}
];
var DisplayPerson = React.createClass({
getInitialState: function() {
return {
name: FemaleInfo[0].name,
age: FemaleInfo[0].age,
occupation: FemaleInfo[0].occupation
};
},
render() {
return (
<Text style={styles.data}>
{this.state.name}
</Text>
<Text style={styles.data}>
{this.state.age}
</Text>
<Text style={styles.data}>
{this.state.occupation}
</Text>
})
</code></pre>
| 2 |
How to sort a collection(like top 20) by count of related collection filtered by related colection's attribute?
|
<p>I have the following schemas:</p>
<pre><code>var postSchema = new Schema({
autor: {type: Schema.Types.ObjectId, ref: 'user', required: true},
texto: {type: String},
likes: [{type: Schema.Types.ObjectId, ref: 'like'}],
});
var likeSchema = new Schema({
user: {type: Schema.Types.ObjectId, ref: 'user', required: true},
post: {type: Schema.Types.ObjectId, ref: 'post', required: true},
_created_at:{type: Date},
});
</code></pre>
<p>I want all documents from collection 'post' sorted by the count of relationship 'likes' that were created in the last 24 hours(could be other periods) using the attr '_created_at'. </p>
<p>F.I. "Posts that received the most likes in the past 24 hours"</p>
<p>I heard that using aggregate was a good idea but I lack of experience with it and don't exacly know what pipeline should I go for. </p>
| 2 |
Proguard - Error: A JNI error has occured
|
<p>I've been trying to use ProGuard to obfuscate an application of mine. I have disabled every option exception for obfuscate. Loader is my main class.</p>
<p>The screenshot below is the result when I try to run my obfuscated jar.
No errors were given while obfuscating either.</p>
<p><a href="https://i.stack.imgur.com/o6CxS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/o6CxS.png" alt="enter image description here"></a></p>
<p>My config</p>
<pre><code>-injars 'C:\Users\Corsair\Desktop\obfuscate\Example.jar'
-outjars 'C:\Users\Corsair\Desktop\obfuscate\ExampleOut.jar'
-libraryjars 'C:\Program Files\Java\jre1.8.0_91\lib\rt.jar'
-dontskipnonpubliclibraryclassmembers
-dontshrink
-dontoptimize
-dontusemixedcaseclassnames
-dontpreverify
-dontnote
-dontwarn
-verbose
-keep class Loader
</code></pre>
| 2 |
STUN and TURN clarification
|
<p>I need to establish a connection between a server and clients which can both be behind any type of NAT. For this purpose I have a dedicated host on the internet with clean IP for hosting STUN/TURN server. I'm not going to use WebRTC, I just want to use STUN/TURN server for messaging between clients and a server. After reading RFC's, SO, etc I have some questions left unclear:</p>
<ol>
<li>In which case STUN is used? In my understanding STUN is used only for Full-cone NAT. In all other cases TURN server must be used, because of host and/or port restriction. Is that correct?</li>
<li>It seems I need a signalling server to notify clients about server address and vice versa. But as soon as client/server sends a message to the signalling server, I know their outer host:port, so I let each side know other's side host:port, each side can send messages to this signalling server containing peer's host:port data, which the signalling server can use to detect which peer this message is for and forward it to corresponding peer. At first sight this logic seems to me pretty straight-forward and my signalling server becomes a TURN server - is that how TURN server is implemented? But if so, I don't understand, why would I need a TURN server like "coturn", "reTurn", etc? I know they implement ICE, but how this ICE will work, if my signalling server received message from concrete host:port of a peer, so that is the only candidate that can be used for connection with the peer?</li>
<li>In case of restricted NAT (port, address or symmetric), how long a client outer (public) port is open on router for receiving UDP datagrams? I read that TURN client sends refresh messages to server to keep channel open, is this how client also prevents ports from closing?</li>
</ol>
| 2 |
No suitable driver found (jdbc:pgsql)
|
<p>(using com.impossibl.postgres.api.jdbc)</p>
<p>I'm having issues establishing a connection to a database when I reference something from the hosts file.</p>
<p>It DOES seem to work with 'localhost' though.</p>
<pre><code>Class.forName("com.impossibl.postgres.jdbc.PGDriver");
String url = "jdbc:pgsql://localhost:5432/db";
Connection conn = DriverManager.getConnection(url, "name", "pass");
</code></pre>
<p>I have this running inside of a docker container (on the same host machine as a postgres container). When I use the hosts IP address or the ip of the postgres container it works fine, but whenever I try to use the container name it gives me </p>
<pre><code>java.sql.SQLException: No suitable driver found for jdbc:pgsql://postgres_container:5432/db
</code></pre>
<p>The container was linked to the postgres container when it was run, and the record is in the container's hosts file just as it should be.</p>
<p>Is this driver unable to reference the hosts file? If so, why does it work with localhost?</p>
| 2 |
How to manually create an Instagram token with the public_content scope
|
<p>How to manually generate an Instagram API auth token that has additional scopes, besides just <code>basic</code>?</p>
| 2 |
Java Try-Catch Exception Handling
|
<blockquote>
<h3>The Rectangle class</h3>
<p>Design a class named Rectangle to represent a rectangle. The class contains:</p>
<ul>
<li>Two double data fields named width and height that specify the width and
height of the rectangle. The default values are 1 for both width and height.</li>
<li>A no-arg constructor that creates a default rectangle.</li>
<li>A constructor that creates a rectangle with the specified width and height.</li>
<li>A method named getArea() that returns the area of this rectangle.</li>
<li>A method named getPerimeter() that returns the perimeter.</li>
</ul>
<p>Write a test program that allows the user to enter the data for the rectangles width and height. The program should include try-catch blocks and exception handling. Write the program so that after the user enters the input it is validated in the Class and if valid the appropriate results are shown. If not valid, the Class should throw an exception to the catch block in the Test class which notifies the user with a message about the error and then program should return to the input portions. </p>
</blockquote>
<p>The Rectangle class I have created is below:</p>
<pre><code>public class Rectangle {
//two double data fields width and height, default values are 1 for both.
private double width = 1;
private double height = 1;
private String errorMessage = "";
//no-arg constructor creates default rectangle
public Rectangle() {
}
//fpzc, called by another program with a statement like Rectangle rec = new Rectangle(#, #);
public Rectangle (double _width, double _height) throws Exception {
setWidth(_width);
setHeight(_height);
}
//get functions
public double getArea(){
return (width * height);
}
public double getPerimeter() {
return (2*(width + height));
}
public String getErrorMessage() {
return errorMessage;
}
//set functions
public void setWidth(double _width) throws Exception {
if( !isValidWidth(_width)){
Exception e = new Exception(errorMessage);
throw e;
//System.out.println(errorMessage);
//return false;
}
width = _width;
}
public void setHeight(double _height) throws Exception {
if ( !isValidHeight(_height)){
Exception e = new Exception(errorMessage);
throw e;
//System.out.println(errorMessage);
//return false;
}
height = _height;
}
//isValid methods
public boolean isValidWidth(double _width) {
//default check
//if(_width == 1) {
// return true;
//}
if(_width > 0){
return true;
}
else {
errorMessage = "Invalid value for width, must be greater than zero";
return false;
}
}
public boolean isValidHeight(double _height) {
//default check
//if(_height == 1){
// return true;
//}
if(_height > 0){
return true;
}
else {
errorMessage = "Invalid value for height, must be greater than zero";
return false;
}
}
}
</code></pre>
<p>And the test program i have so far below:</p>
<pre><code>import java.util.Scanner;
import java.util.InputMismatchException;
public class TestRectangle {
//default constructor
public TestRectangle() {
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Rectangle rec = new Rectangle();
boolean Continue = true;
double _width = 1;
double _height = 1;
do {
try {
System.out.println("Please enter a numerical value for the rectangle's width:");
_width = input.nextDouble();
rec.setWidth(_width);
Continue = false;
}
catch (Exception e){
rec.getErrorMessage();
Continue = true;
}
} while (Continue);
do{
try {
System.out.println("Please enter a numerical value for the rectangle's height:");
_height = input.nextDouble();
rec.setHeight(_height);
Continue = false;
}
catch (Exception e){
rec.getErrorMessage();
Continue = true;
}
} while (Continue);
System.out.println("The rectangle has a width of " + _width + " and a height of " + _height);
System.out.println("the area is " + rec.getArea());
System.out.println("The perimeter is " + rec.getPerimeter());
}
}
</code></pre>
<p>Te main issue I am having is that when the exception is caught it does not print out the respective errorMessage. Not sure what I am doing wrong on that one. I cannot just add a print statement into the catch method because the professor wants the error message to be sent from the isValid method in the rectangle class.</p>
<p>The second small issue I am having is how to add another step into the isValid method for both the width and height that makes sure the input from the user is not a letter or other character. And in turn how to add that additional exception as another catch in my try-catch block. </p>
<p>Any help would be much appreciated! </p>
| 2 |
Laravel 5.2 Sessions not persisting
|
<p>I've searched a lot before posting and every 'solution' that I've found did not work.</p>
<p>I can't get a session value from a different route than the current one.</p>
<p>Routes.php</p>
<pre><code>Route::group(['middleware' => 'web', 'prefix' => 'blog', 'namespace' => 'Modules\Blog\Http\Controllers'], function()
{
Route::get('/','PostController@index');
Route::get('/home',['as' => 'home', 'uses' => 'PostController@index']);
Route::get('auth/login', 'Auth\AuthController@showLoginForm');
Route::post('auth/login', 'Auth\AuthController@login');
Route::group(['middleware' => 'blog.auth'], function(){
Route::get('/admin',['as'=>'dashboard','uses'=>'AdminController@index']);
});
});
</code></pre>
<p>Kernel.php</p>
<pre><code>protected $middlewareGroups = [
'web' => [
\ommitedbutcorrect\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class
],
'admin' => [
\Modules\Admin\Http\Middleware\ControllerResolver::class,
],
'admin.auth' => [
\Modules\Admin\Http\Middleware\AdminAuthenticate::class,
],
'blog.auth' => [
\Modules\Blog\Http\Middleware\BlogAuthenticate::class,
],
'api' => [
'throttle:60,1',
],
];
</code></pre>
<p>AuthController.php</p>
<pre><code>class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = '/blog/admin/';
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
public function login()
{
dd(\Session::get('foo'));
$userdata = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
if (\Auth::attempt($userdata)) {
\Session::save();
return redirect($this->redirectTo);
}
else{
return 'f*ck';
}
}
public function showLoginForm()
{
\Session::put('foo', 'bar');
return view('blog::Admin.login');
}
</code></pre>
<p>Chmod 777 on Storage and Bootstrap folders, session driver database.</p>
<p>It seems that the session is creating itself every time with the request that would explain why I can't get the the value with Session:get('foo') which now returns null.</p>
<p>I wasted 3 days on this already :/.</p>
<p>Would appreciate the help, if you guys need more details / code just say the word.</p>
| 2 |
Remove default search path when linking new dylib.
|
<p>I'm trying to link new dylib to my executable, but it link it with absolute path (<code>/usr/local/lib/</code>) how can I remove this default path from the used shared libraries ? </p>
<pre><code>otool -L ../Build/Products/Debug/myexec
../Build/Products/Debug/myexec:
/usr/local/lib/libmylib.dylib (compatibility version 1.0.0, current version 1.0.0)
</code></pre>
| 2 |
Apache Camel - How to set global component options
|
<p>I'm using Camel with Spring Boot. I want to set "connectionTimeToLive" option for http component at global scope so that every use of the component will have the option. How can I do that?</p>
| 2 |
unionAll resulting in StackOverflow
|
<p>I've made some progress with my own question (<a href="https://stackoverflow.com/questions/38185627/how-to-load-a-dataframe-from-a-python-requests-stream-that-is-downloading-a-csv">how to load a dataframe from a python requests stream that is downloading a csv file?</a>) on StackOverflow, but I'm receiving a StackOverflow error:</p>
<pre><code>import requests
import numpy as np
import pandas as pd
import sys
if sys.version_info[0] < 3:
from StringIO import StringIO
else:
from io import StringIO
from pyspark.sql import SQLContext
sqlContext = SQLContext(sc)
chunk_size = 1024
url = "https://{0}:8443/gateway/default/webhdfs/v1/{1}?op=OPEN".format(host, filepath)
r = requests.get(url, auth=(username, password),
verify=False, allow_redirects=True,
stream=True)
df = None
curr_line = 1
remainder = ''
for chunk in r.iter_content(chunk_size):
txt = remainder + chunk
[lines, remainder] = txt.rsplit('\n', 1)
pdf = pd.read_csv(StringIO(lines), sep='|', header=None)
if df == None:
df = sqlContext.createDataFrame(pdf)
else:
df = df.unionAll(sqlContext.createDataFrame(pdf))
print df.count()
</code></pre>
<p>The stacktrace is here:</p>
<pre><code>---------------------------------------------------------------------------
Py4JJavaError Traceback (most recent call last)
<ipython-input-4-b3a89df3c7d8> in <module>()
36 df = sqlContext.createDataFrame(pdf)
37 else:
---> 38 df = df.unionAll(sqlContext.createDataFrame(pdf))
39
40 #curr_line = curr_line + 1
/usr/local/src/spark160master/spark/python/pyspark/sql/dataframe.py in unionAll(self, other)
993 This is equivalent to `UNION ALL` in SQL.
994 """
--> 995 return DataFrame(self._jdf.unionAll(other._jdf), self.sql_ctx)
996
997 @since(1.3)
/usr/local/src/spark160master/spark/python/lib/py4j-0.9-src.zip/py4j/java_gateway.py in __call__(self, *args)
811 answer = self.gateway_client.send_command(command)
812 return_value = get_return_value(
--> 813 answer, self.gateway_client, self.target_id, self.name)
814
815 for temp_arg in temp_args:
/usr/local/src/spark160master/spark/python/pyspark/sql/utils.py in deco(*a, **kw)
43 def deco(*a, **kw):
44 try:
---> 45 return f(*a, **kw)
46 except py4j.protocol.Py4JJavaError as e:
47 s = e.java_exception.toString()
/usr/local/src/spark160master/spark/python/lib/py4j-0.9-src.zip/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)
306 raise Py4JJavaError(
307 "An error occurred while calling {0}{1}{2}.\n".
--> 308 format(target_id, ".", name), value)
309 else:
310 raise Py4JError(
Py4JJavaError: An error occurred while calling o19563.unionAll.
: java.lang.StackOverflowError
</code></pre>
<p>I'm not sure how to fix this. Any tips appreciated.</p>
| 2 |
Display result of js calculation in span
|
<p>I'm trying to calculate something in javascript and then display the result in a <code><span></span></code>.
This is the code that I've got at the moment:</p>
<pre><code><script type="text/javascript">
window.onload = function() {
function minus_number() {
var first_number = '50';
var second_number = '30';
var result = parseInt(first_number) - parseInt(second_number);
document.getElementById('spend').value = result;
}
}
</code></pre>
<p></p>
<p>And the html</p>
<pre><code><p><i class="fa fa-truck"></i>Want free delivery? Spend an extra <span id="spend"></span> for free standard delivery</p>
</code></pre>
<p>It doesn't actually display the result in the span though, can anybody tell me what I'm doing wrong?</p>
| 2 |
WPF DatagridComboBoxColumn displaymemberpath description attribute
|
<p>DataGrid has AutoGeneratedColumns = true.
Some of the properties are enum so the corresponding columns are DatagridComboBoxColumn.
Enum definitions have a Description Attribute as follows:</p>
<pre><code>public enum MyEnum
{
[Description("first")]
FirstEnum,
[Description("second")]
SecondEnum
}
</code></pre>
<p>I already have a utility method to display Description attributes in a ComboBox :</p>
<pre><code>public class EnumToItemsSource : MarkupExtension
{
private readonly Type _type;
public EnumToItemsSource(Type type)
{
_type = type;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return Enum.GetValues(_type).Cast<object>().Select(e => new { Value = e,
Description = GetEnumDescription((Enum)e) });
}
public static string GetEnumDescription(Enum enumObj)
{
FieldInfo fieldInfo = enumObj.GetType().GetField(enumObj.ToString());
object[] attributes = fieldInfo.GetCustomAttributes(false);
if (attributes.Length == 0)
return enumObj.ToString();
else
{
DescriptionAttribute attrib = attributes.OfType<DescriptionAttribute>().FirstOrDefault();
if (attrib != null)
return attrib.Description;
else
return "No description";
}
}
}
</code></pre>
<p>And I use it in xaml as follows :</p>
<pre><code><ComboBox ItemsSource="{utils:EnumToItemsSource {x:Type myenums:MyEnum}}"
DisplayMemberPath="Description"
SelectedValuePath="Value"
SelectedValue="{Binding SomeProperty}"/>
</code></pre>
<p>Now my question is, how can I apply this to an auto generated column?</p>
<p><strong>EDIT First try</strong></p>
<p>I've try a first solution by doing it in the AutoGeneratingColumn event handler :</p>
<pre><code>private void OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
DataGridComboBoxColumn col = e.Column as DataGridComboBoxColumn;
if (col != null)
{
col.ItemsSource = EnumToIEnumerable.GetIEnumerable(e.PropertyType);
col.DisplayMemberPath = "Value";
col.SelectedValuePath = "Key";
col.SelectedValueBinding = new Binding(e.PropertyName);
}
}
</code></pre>
<p>For that, I had to write a new helper static method to provide the list for the combobox items source :</p>
<pre><code>public static class EnumToIEnumerable
{
public static IEnumerable<KeyValuePair<Enum, string>> GetIEnumrable(Type type)
{
return Enum.GetValues(type).Cast<Enum>().Select((e) => new KeyValuePair<Enum, string>(e,
EnumDescriptionConverter.GetEnumDescription((Enum)e)));
}
}
</code></pre>
<p>It's working for displaying the description. But the programm cannot convert SelectedValue to the bound property. It throws silent exceptions and the combobox is red lined.</p>
<p>I try to translate the error message in english :</p>
<pre><code>Conversion of EnumConverter is not possible from System.Collections.Generic.KeyValuePair
System.Windows.Data Error: 7 : ConvertBack cannot convert value '[Surface, m²]' (type 'KeyValuePair`2'). BindingExpression:Path=TypeQuantite; DataItem='MscaGridLineViewModel' (HashCode=39414053); target element is 'TextBlockComboBox' (Name=''); target property is 'SelectedItem' (type 'Object') NotSupportedException:'System.NotSupportedException: Conversion de EnumConverter impossible à partir de System.Collections.Generic.KeyValuePair`2[[System.Enum, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].
</code></pre>
<p>I don't understand why it's written <strong>target property is 'SelectedItem'</strong> because the SelectedValuePath contains an Enum object and the SelectedValueBinding binds it to a Property of Type "MyEnum" which is an enum.</p>
| 2 |
Error converting GUI to standalone executable using Py2exe
|
<p>I am using <code>py2exe</code> to convert my program with multiple GUIs to a standalone executable. I used PyQt to create the GUIs. The main script I run instantiates the main UI, which contains buttons, tabs, etc. that can open sub-UIs. The main script is <code>main_ui.py</code>. </p>
<p>I followed the tutorial on how to use <code>py2exe</code>, so I have the following <code>setup.py</code>:</p>
<pre><code>from distutils.core import setup
import py2exe
setup(windows=['main_ui.py'])
</code></pre>
<p>Then, in the CMD: <code>> python setup.py py2exe</code>. </p>
<p>I tried creating a practice exe with a simple script and everything worked. However, I got an error when I tried creating the exe from <code>main_ui.py</code>. </p>
<p>Here is the output:</p>
<pre><code>L:\internal\(path)>python setup.py py2exe
running py2exe
creating L:\internal\(path)\build
creating L:\internal\(path)\build\bdist.win32
creating L:\internal\(path)\build\bdist.win32\winexe
creating L:\internal\(path)\build\bdist.win32\winexe\collect-2.7
creating L:\internal\(path)\build\bdist.win32\winexe\bundle-2.7
creating L:\internal\(path)\build\bdist.win32\winexe\temp
creating L:\internal\(path)\dist
*** searching for required modules ***
error: compiling 'C:\Python27\lib\site-packages\PyQt4\uic\port_v3\proxy_base.py' failed
SyntaxError: invalid syntax <proxy_base.py, line 26>
</code></pre>
<p>Here's <code>proxy_base.py</code>: </p>
<pre><code>from PyQt4.uic.Compiler.proxy_metaclass import ProxyMetaclass
class ProxyBase(metaclass=ProxyMetaclass):
""" A base class for proxies using Python v3 syntax for setting the
meta-class.
"""
</code></pre>
<p>This came with PyQt4; does anyone know what's going on? Is this the right way to make my program into an executable?</p>
| 2 |
Oracle: Left join very big table and limit the joined rows to one with the largest field value
|
<p>I have two tables. The second one references to the first one by m_id.</p>
<p><strong>Main table</strong></p>
<pre><code>M_ID | M_FIELD
1 | 'main1'
2 | 'main2'
3 | 'main3'
</code></pre>
<p><strong>Sub-table</strong></p>
<pre><code>S_ID | S_FIELD | S_ORDER | M_ID
1 | 'sub1-1' | 1 | 1
2 | 'sub1-2' | 2 | 1
3 | 'sub1-3' | 3 | 1
4 | 'sub2-1' | 1 | 2
5 | 'sub2-2' | 2 | 2
6 | 'sub2-3' | 3 | 2
7 | 'sub3-1' | 1 | 3
8 | 'sub3-2' | 2 | 3
9 | 'sub3-3' | 3 | 3
</code></pre>
<p>I need to join these two tables (by <code>M_ID</code>) but from the <code>Sub-table</code> I need only the row with the largest value of <code>S_ORDER</code>.</p>
<p>So the expected result of the query is:</p>
<pre><code>M_ID | M_FIELD | S_FIELD
1 | 'main1' | 'sub1-3'
2 | 'main2' | 'sub2-3'
3 | 'main3' | 'sub3-3'
</code></pre>
<p>There is working solution with analytical function in the answer of this question: <a href="https://stackoverflow.com/questions/10236229/how-do-i-limit-the-number-of-rows-returned-by-this-left-join-to-one" title="How do I limit the number of rows returned by this LEFT JOIN to one?">How do I limit the number of rows returned by this LEFT JOIN to one?</a>
(I will post it at the bottom)
But the problem is that <code>Sub-Table</code> is very big (and is actually a view with some inner calculations) and this kind of subquery works way too long. So I suppose I need to filter out the table by m_id <em>first</em> and only after that find the field with the largest <code>S_ORDER</code></p>
<p>I need something simple like this (which fails because the second level subquery doesn't see the <code>M.M_ID</code> field outside):</p>
<pre><code>SELECT m.*,
(SELECT s_field
FROM (SELECT s_field
FROM t_sub s
WHERE s.m_id = m.m_id
ORDER BY s_order DESC)
WHERE ROWNUM = 1) s_field
FROM t_main m;
</code></pre>
<p>The code to create and populate the test schema:</p>
<pre><code>CREATE TABLE t_main (m_id NUMBER PRIMARY KEY,
m_field VARCHAR2(10));
CREATE TABLE t_sub (s_id NUMBER PRIMARY KEY,
s_field VARCHAR2(10),
s_order NUMBER,
m_id NUMBER );
INSERT INTO t_main VALUES (1,'main1');
INSERT INTO t_main VALUES (2,'main2');
INSERT INTO t_main VALUES (3,'main3');
INSERT INTO t_sub VALUES (1,'sub1-1', 1, 1);
INSERT INTO t_sub VALUES (2,'sub1-2', 2, 1);
INSERT INTO t_sub VALUES (3,'sub1-3', 3, 1);
INSERT INTO t_sub VALUES (4,'sub2-1', 1, 2);
INSERT INTO t_sub VALUES (5,'sub2-2', 2, 2);
INSERT INTO t_sub VALUES (6,'sub2-3', 3, 2);
INSERT INTO t_sub VALUES (7,'sub3-1', 1, 3);
INSERT INTO t_sub VALUES (8,'sub3-2', 2, 3);
INSERT INTO t_sub VALUES (9,'sub3-3', 3, 3);
COMMIT;
</code></pre>
<p>Working solution mentioned above (working too slow with large <code>T_SUB</code> table):</p>
<pre><code>SELECT m.*,
s.s_field
FROM t_main m
LEFT JOIN
(SELECT *
FROM
(SELECT ts.*,
ROW_NUMBER() OVER (PARTITION BY m_id
ORDER BY s_order DESC) AS seq
FROM t_sub ts)
WHERE seq = 1) s ON s.m_id = m.m_id;
</code></pre>
<p>The DB we use is Oracle 10g</p>
<p>Thank you very much for your help</p>
| 2 |
AngularJs AJAX POST to PHP
|
<p>It's my first time using POST from AngularJs to PHP.</p>
<p>But, Google is my friend - or so I thought.</p>
<p>According to several Google finds, this could should work fine:</p>
<p>AngularJs: </p>
<pre><code> var data = $.param({
json: JSON.stringify({
userName: $scope.registrationData.userName,
email: $scope.registrationData.email,
password : forge_sha256($scope.registrationData.password)
})
});
var url = HOST + 'api/register.php?debug';
console.log('Register at ' + url);
$http.post(url, data)
</code></pre>
<p>PHP </p>
<pre><code> $postdata = file_get_contents("php://input");
$request = json_decode($postdata);
ChromePhp::log('API: JOSON data = ' . $postdata);
ChromePhp::log('API: decoded data = ' . $request);
</code></pre>
<p>But, those two <code>ChromePhp::log</code> showed this in the browser console: </p>
<pre><code>%cF:\DropBox\programs\Xampp\htdocs\api\register.php : 17
log.js:137 API: JOSON data = json=%7B%22userName%22%3A%22n%22%2C%22email%22%3A%22e%22%2C%22password%22%3A%22148de9c5a7a44d19e56cd9ae1a554bf67847afb0c58f6e12fa29ac7ddfca9940%22%7D
log.js:81 %cF:\DropBox\programs\Xampp\htdocs\api\register.php : 18
log.js:137 API: decoded data =
</code></pre>
<p>The decoded JSON is empty :-( So, something is going wrong either with my encoding or my decoding.</p>
<p>I am too close to it to see it - who can spot my d'oh ?</p>
| 2 |
Files not uploading to remote server with Net_SFTP
|
<p>I have the following class for uploading files in a directory, however, the first directory that should be created is getting set up as 'File' rather then a 'File Folder'. Because of that, the items that should be uploaded are not uploading properly. I'm not sure if I am missing a step or not or if I set this up incorrectly.</p>
<p>
<pre><code>include 'Net/SFTP.php';
class SFTPConnection
{
private $sftp;
public function __construct($host, $username, $password)
{
$this->sftp = new Net_SFTP($host);
if (!$this->sftp)
error_log("Could not connect to $host.");
if (!$this->sftp->login($username, $password))
error_log("Could not authenticate with username $username " .
"and password $password.");
}
public function uploadFiles($dir, $to, $from) {
$result = array();
$toDir = str_replace($from, $to, $dir);
$cdir = scandir($dir);
foreach ($cdir as $key => $value) {
if (!in_array($value, array(".", ".."))) {
if (is_dir($dir . DIRECTORY_SEPARATOR . $value)) {
if(!$this->sftp->mkdir($toDir . DIRECTORY_SEPARATOR .$value)) {
echo "Could not create directory <br>'";
exit();
}
$result[$value] = $this->uploadFiles($dir . DIRECTORY_SEPARATOR . $value, $to, $from);
} else {
$result[] = $value;
echo "Uploading $dir/$value <br>";
if(!$this->sftp->put($toDir . DIRECTORY_SEPARATOR . $value, $dir . DIRECTORY_SEPARATOR . $value, NET_SFTP_LOCAL_FILE)) {
echo "Could not upload file <br>";
exit();
}
}
}
}
return $result;
}
}
</code></pre>
| 2 |
How to connect two Raspberry Pi with OPC UA?
|
<p>I have two Raspberry Pi and i want to connect these two via OPC UA making one of them as Server and other as Client. Do you have any Idea or clues or you knows any Websites which helps me to understand the basic ?
Or simply how can i connect Raspberry Pi with PLC machine ?
any small idea can be helpful.
Thanks in Advance !</p>
| 2 |
How to print array with jekyll and liquid
|
<p>I have a json document with some data</p>
<pre><code>{"teams":[{"team":"Team A","evolution":[1,2]},{"team":"Team B","evolution":[3,4]}]}
</code></pre>
<p>I try to print it to my view with liquid</p>
<pre><code>{% for team in teams %}
<tr>
<td><a href="#">{{team.team}}</a></td>
<td>{{team.evolution}}</td>
</tr>
{% endfor%}
</code></pre>
<p>The html result is </p>
<pre><code><tr>
<td><a href="#">Team A</a></td>
<td>12</td>
</tr>
<tr>
<td><a href="#">Team B</a></td>
<td>34</td>
</tr>
</code></pre>
<p>But what I would like to print is the raw array for the second <code><td></code></p>
<pre><code><tr>
<td><a href="#">Team A</a></td>
<td>[1,2]</td>
</tr>
<tr>
<td><a href="#">Team B</a></td>
<td>[3,4]</td>
</tr>
</code></pre>
| 2 |
Django Admin: Overriding Initial Value for Inlines
|
<p>One of my models has a field with a default value that I'm happy with, but I want that default value to be different within the admin. Here's my attempt at achieving this:</p>
<h1>models.py</h1>
<pre><code>from django.db import models
class Parent(models.Model):
parent_field_1 = models.CharField(max_length=255)
parent_field_2 = models.CharField(max_length=255, blank=True)
class Meta:
ordering = ('pk',)
def __unicode__(self):
return self.parent_field_1
class Child(models.Model):
parent = models.ForeignKey(Parent)
child_field_1 = models.CharField(max_length=255)
child_field_2 = models.CharField(max_length=255, blank=True)
child_field_3 = models.IntegerField(default=0)
class Meta:
ordering = ('pk',)
verbose_name_plural = 'children'
def __unicode__(self):
return self.child_field_1
</code></pre>
<h1>forms.py</h1>
<pre><code>from django import forms
from .models import Child
class ChildForm(forms.ModelForm):
class Meta:
model = Child
fields = [
'parent',
'child_field_1',
'child_field_2',
'child_field_3',
]
def __init__(self, *args, **kwargs):
if 'instance' not in kwargs:
initial = kwargs.get('initial', {})
initial['child_field_3'] = '1'
kwargs['initial'] = initial
super(ChildForm, self).__init__(*args, **kwargs)
</code></pre>
<h1>admin.py</h1>
<pre><code>from django.contrib import admin
from .forms import ChildForm
from .models import Parent, Child
class ChildInline(admin.StackedInline):
model = Child
form = ChildForm
class ParentAdmin(admin.ModelAdmin):
inlines = [ChildInline]
class ChildAdmin(admin.ModelAdmin):
form = ChildForm
admin.site.register(Parent, ParentAdmin)
admin.site.register(Child, ChildAdmin)
</code></pre>
<p>When I go to add a child, the "Child field 3" field is populated with "1" (instead of the model's default of "0"), which is what I want. When I go to edit a child, the "Child field 3" field is populated with whatever value is in the database, which is also what I want.</p>
<p>The problem I'm running into comes in when I go to add or edit a parent. If I try to add a parent, I am required to also fill out all of the child inline forms. Likewise, if I try to edit a parent, I am required to fill out all of the extra child inline forms. If I comment out the <code>ChildInline</code> class' <code>form = ChildForm</code> line, I get the correct <em>behavior</em>, but, of course, the incorrect default value ("0" instead of "1"). How can I get the correct behavior and the correct default value?</p>
| 2 |
Pass AttributeSet as parameter in custom view constructor in AppWidget for android
|
<p>I need to pass AttributeSet as a parameter in custom View constructor. Here is the attribute that I need to pass:</p>
<blockquote>
<p><code><?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="DonutChart">
<attr name="radiusDonut" format="dimension"/>
<attr name="donutTextSize" format="dimension"/>
</declare-styleable>
</resources></code></p>
</blockquote>
<p>I need to do this with code, in order that I will add my custom view to RemoteView in my AppWidget. Does anyone has any idea how can I achive this?</p>
| 2 |
Spark, Kryo Serialization Issue with ProtoBuf field
|
<p>I am seeing an error when running my spark job relating to Serialization of a protobuf field when transforming an RDD.</p>
<p>com.esotericsoftware.kryo.KryoException: java.lang.UnsupportedOperationException
Serialization trace:
otherAuthors_ (com.thomsonreuters.kraken.medusa.dbor.proto.Book$DBBooks)</p>
<p>The error seems to be created at this point:</p>
<pre><code>val booksPerTier: Iterable[(TimeTier, RDD[DBBooks])] = allTiers.map {
tier => (tier, books.filter(b => isInTier(endOfInterval, tier, b) && !isBookPublished(o)).mapPartitions( it =>
it.map{ord =>
(ord.getAuthor, ord.getPublisherName, getGenre(ord.getSourceCountry))}))
}
val averagesPerAuthor = booksPerTier.flatMap { case (tier, opt) =>
opt.map(o => (tier, o._1, PublisherCompanyComparison, o._3)).countByValue()
}
val averagesPerPublisher = booksPerTier.flatMap { case (tier, opt) =>
opt.map(o => (tier, o._1, PublisherComparison(o._2), o._3)).countByValue()
}
</code></pre>
<p>The field is a list specified in the protobuf as the below:</p>
<pre><code>otherAuthors_ = java.util.Collections.emptyList()
</code></pre>
<p>As you can see the code is not actually utilising that field from the Book Protobuf, although it still is being transmitted over the network.</p>
<p>Has anyone got any advice on this?</p>
| 2 |
ValueError: Invalid argument 'metric' passed to K.function even with newest Keras/Theano
|
<p>When I run the following very simple neural network in Anaconda / Python2.7 / Keras / Theano:</p>
<pre><code>import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Activation
# import csv
csv = 'https://raw.githubusercontent.com/uiuc-cse/data-fa14/gh-pages/data/iris.csv'
iris = np.genfromtxt(csv, delimiter = ',', dtype = None)
# Munge data
iris = np.delete(iris, 0, 0) # delete header row
iris[iris[:,4] == 'setosa', 4] = 1
iris[(iris[:,4] == 'versicolor') | (iris[:,4] == 'virginica'), 4] = 0
iris = iris.astype(float)
# split into data and label classes
data = iris[:,0:4]
labels = iris[:,4]
labels = np.array([labels])
labels = labels.T
labels = labels.astype(int)
# develop NN
model = Sequential()
model.add(Dense(1, input_dim = 4))
model.add(Activation('softmax'))
model.compile(optimizer = 'rmsprop', loss = 'binary_crossentropy', metric = ['accuracy'])
# fit NN
model.fit(data, labels, nb_epoch = 5, batch_size = 50)
</code></pre>
<p>I receive the following error:</p>
<pre><code> File "C:\Users\bAXTER\Anaconda\lib\site-packages\keras\backend\theano_backend.py", line 539, in function
raise ValueError(msg)
ValueError: Invalid argument 'metric' passed to K.function
</code></pre>
<p>I looked at this <a href="https://stackoverflow.com/questions/36812548/error-in-keras-invalid-argument-metrics-passed-to-k-function">post</a>, but I am already using Keras 1.0.5 and Theano 0.9.0 on Anaconda (Python 2.7) with all relevant packages installed. In addition, the post mentions that I can "remove <code>metrics=['accuracy']</code> from the function call to <code>model.compile()</code>". but I cannot find either of those terms in 'theano_backend.py'. I was not able to comment on that user's answer because I do not have enough reputation.</p>
<p>Any ideas on why keras is causing this error? I know this is a less explored area of python so any help would be appreciated.</p>
| 2 |
UIPageViewController indicators don't change color
|
<p>I've read many other threads here about this problem, it appears that the best solution now is to set it as follows:</p>
<pre><code> let pageControl = UIPageControl.init(frame: CGRectMake(0, UIScreen.mainScreen().bounds.size.height*14/15, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height))
pageControl.backgroundColor = UIColor(red: 0, green: 147/255, blue: 229/255, alpha: 1)
pageControl.pageIndicatorTintColor = UIColor.lightGrayColor()
pageControl.currentPageIndicatorTintColor = UIColor.blackColor()
view.addSubview(pageControl)
</code></pre>
<p>But for some reason, this does not work for me. Page control background changes its color, but the indicators remain white.</p>
<p>My entire viewDidLoad() method</p>
<pre><code>override func viewDidLoad() {
super.viewDidLoad()
self.pageViewController = self.storyboard!.instantiateViewControllerWithIdentifier("OnboardingPageViewController") as! UIPageViewController
self.pageViewController.dataSource = self
let startingViewController:OnboardingPageContentViewController = self.viewControllerAtIndex(0)!
let viewControllers:Array<OnboardingPageContentViewController> = [startingViewController]
self.pageViewController.setViewControllers(viewControllers, direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil)
let pageControl = UIPageControl.init(frame: CGRectMake(0, UIScreen.mainScreen().bounds.size.height*14/15, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height))
pageControl.backgroundColor = UIColor(red: 0, green: 147/255, blue: 229/255, alpha: 1)
pageControl.pageIndicatorTintColor = UIColor.lightGrayColor()
pageControl.currentPageIndicatorTintColor = UIColor.blackColor()
view.addSubview(pageControl)
self.pageViewController.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)
self.addChildViewController(pageViewController)
self.view.addSubview(pageViewController.view)
self.pageViewController.didMoveToParentViewController(self)
}
</code></pre>
<p>Thanks in advance</p>
| 2 |
How can I mock a function/property of a node module exported as a function using sinon?
|
<p>I have a service module that is exported as a function. I need to pass a couple of things into it, like a configuration object so it does need to retain this structure. I am trying to stub out a function from the service but can't figure it out. In my app, I have a function that makes an API call that is problematic during testing so I'd like to stub it. (I understand I'd have to write my test differently to handle the async issue)</p>
<pre><code>// myService.js
module.exports = function(config) {
function foo() {
returns 'bar';
}
return {
foo: foo
};
};
// test.js
var config = require('../../config');
var request = require('supertest');
var chai = require('chai');
var expect = chai.expect;
var sinon = require('sinon');
var myService = require('./myService.js')(config);
describe('Simple test', function(done) {
it('should expect "something else", function(done) {
var stub = sinon.stub(myService, 'foo').returns('something else');
request(server) // this object is passed into my test. I'm using Express
.get('/testRoute')
.expect(200)
.expect(function(res) {
expect(res.body).to.equal('something else');
stub.restore();
})
.end(done);
});
});
* /testRoute I set up as a simple GET route that simply returns the value from myService.foo()
</code></pre>
<p>The above is not working, and I believe it has to do with the way my service is exporting. If I write the service as below, the stub works fine.</p>
<pre><code>module.exports = {
test: function() {
return 'something';
}
};
</code></pre>
<p>But again, I need to be able to pass in information to the module so I would like to keep my modules in the original structure above. Is there a way to stub a function from a module that exports in that manner? I was also looking into proxyquire but not sure if that is the answer.</p>
| 2 |
ionic, php server, mysql database, and rest api
|
<p>i'm new to ionic and restful api, and i have to make a mobile app that uses these technologies and a server that uses php. Does anyone have any idea about how the rest api should look like and the server too or any example that can help... thank you!</p>
| 2 |
Node.js es6 module export async variable
|
<p>I've implemented tests with <code>supertest</code> that are run after the user logs in:</p>
<pre><code>// ../prepare.login
"use strict";
import {default as request} from "supertest";
import {default as app} from "../../server.js";
const postUrl = "/api/v1/login";
const postData = {
"username": "user",
"password": "pass"
};
module.exports = {
prepare: function(done) {
request(app.listen())
.post(postUrl)
.send(postData)
.end((err, res) => {
if (err) {
throw err;
}
module.exports.token = res.body.token;
done();
});
}
}
</code></pre>
<p>Until now I was using es5 and used that <code>module.exports.token</code> as sort of ugly hack to send the token to the actual test:</p>
<pre><code>// users.js
...
var login = require("../prepare.login");
describe("authenticated /api/v1/users", function() {
beforeEach(function(done) {
login.prepare(done);
});
});
...
it("On GET /api/v1/users I want to get all the users in an array", function(done) {
request(app.listen())
.get("/api/v1/users")
.set("X-Access-Token", login.token)
.expect(200)
...
</code></pre>
<p>I switched to es6 that doesn't allow <code>import</code> and <code>export</code> statements anywhere else than the top level of the module. Thus, I'm not really sure how this should be implemented. Should I wait asynchronously for the result? Is it even possible? Is there any other way?</p>
| 2 |
ag-grid setRowData does not load any data
|
<p>No data gets loaded in the grid. I am not where it is going wrong.
html:</p>
<pre><code> <div ng-controller="ScoreController">
<div ag-grid="scoreCntl.gridOptions" class="ag-blue"
style="height: 65%">
</div>
</div>
</code></pre>
<p>Controller:<code>$scope.gridOptions = {
columnDefs : columnDefs<br>
};
$http.get('url').success(function(data) {
sampleData = data;<br>
$scope.gridOptions.onRegisterApi = function(gridApi) {
$scope.gridOptions.api = gridApi;<br>
$scope.gridOptions.api.setRowData(scoreData);<br>
};<br>
});</code></p>
| 2 |
Android cropped image quality issue
|
<p>I am trying to save an image as cropped from android and then show it in my app. I am using the code below, but when I try to view the image in my app the image quality is not good as in the attached image. Am doing anything wrong? Any help would be great.</p>
<p><a href="https://i.stack.imgur.com/zHrxx.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zHrxx.jpg" alt="printscreeiphone6"></a></p>
<p>My code is:</p>
<pre><code>dipToPixel = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, getResources().getDisplayMetrics());
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == getActivity().RESULT_OK && data != null) {
picUri = data.getData();
performCrop();
}
if (requestCode == 111 && resultCode == getActivity().RESULT_OK && data != null) {
Bundle extras = data.getExtras();
Bitmap bitmapImage = extras.getParcelable("data");
tweetImage.setImageBitmap(bitmapImage);
tweetImage.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
tweetImage.getViewTreeObserver().removeOnPreDrawListener(this);
widthPixel = tweetImage.getMeasuredWidth();
heightPixel = tweetImage.getMeasuredHeight();
return true;
}
});
System.out.println("photo added");
addPhotoVar = 1;
addPhotoBtn.setText("remove");
}
callbackManager.onActivityResult(requestCode, resultCode, data);
}
private void performCrop() {
try {
//call the standard crop action intent (the user device may not support it)
Intent cropIntent = new Intent("com.android.camera.action.CROP");
//indicate image type and Uri
cropIntent.setDataAndType(picUri, "image/*");
//set crop properties
cropIntent.putExtra("crop", "true");
//indicate aspect of desired crop
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
//indicate output X and Y
cropIntent.putExtra("outputX", Math.round(screenWidth / dipToPixel)-10);
cropIntent.putExtra("outputY", Math.round(screenWidth / dipToPixel)-10);
//retrieve data on return
cropIntent.putExtra("return-data", true);
//start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, 111);
}
// respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe) {
// display an error message
String errorMessage = "your device doesn't support the crop action!";
Toast toast = Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
</code></pre>
<p>Below is the code that I use the image and save to database:</p>
<pre><code> tweetImage.buildDrawingCache();
bm = tweetImage.getDrawingCache();
if (widthPixel < heightPixel) {
basePixel = widthPixel;
}
else {
basePixel = heightPixel;
}
if (basePixel > 768) {
widthRatio = (float) 768/basePixel;
heightRatio = (float) 768/basePixel;
}
else {
widthRatio = 1;
heightRatio = 1;
}
Bitmap bmResized = Bitmap.createScaledBitmap(bm,(int)(widthPixel*widthRatio), (int)(heightPixel*heightRatio), true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmResized.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byteArray1 = stream.toByteArray();
image1 = new ParseFile("profilePhoto.jpg", byteArray1, "image/jpg");
</code></pre>
| 2 |
Stacking images with CSS Flexbox
|
<p>I am learning to use <code>CSS</code> flexbox and I would like to render a big image on the left and two small images stacked on top of each other. How can I do this using <code>CSS</code> flexbox? </p>
<p><a href="https://i.stack.imgur.com/a97H6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/a97H6.png" alt="enter image description here"></a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<img class="image1" src="#" alt="null">
<img class="image1" src="#" alt="null">
<img class="image3" src="#" alt="null">
</div></code></pre>
</div>
</div>
</p>
| 2 |
Dynamic segments other than id in Ember.js
|
<p>I'm trying to wrap my head around dynamic segments and I want to be able to use a slug or other property instead of the id. When I can get things working it feels like a fluke. (I'm using ember 2.7+)</p>
<p>I've been looking at the following sources/threads for ideas:
<a href="https://guides.emberjs.com/v1.10.0/cookbook/ember_data/linking_to_slugs" rel="nofollow">https://guides.emberjs.com/v1.10.0/cookbook/ember_data/linking_to_slugs</a> (1.10)
<a href="http://discuss.emberjs.com/t/slugs-for-replacing-id-path-for-dynamic-segments" rel="nofollow">http://discuss.emberjs.com/t/slugs-for-replacing-id-path-for-dynamic-segments</a></p>
<p>I plan on using ember-data, but I want to ensure I'm in control - and so I don't want to use the :post_slug / underscore style that has some built in magic that I want to avoid.</p>
<p>Here is an <a href="https://ember-twiddle.com/41ecbfd2d82a1541965b00b2c8065e24?openFiles=templates.cats.index.hbs%2C&route=%2Fcats" rel="nofollow">ember-twiddle</a>
Here are <a href="https://github.com/sheriffderek/dynamic-segments-tests/commits/queryRecord" rel="nofollow">step-by-step commits in a github repo</a></p>
<p><br><br></p>
<h2>My thought process</h2>
<p><br>
1. Conceptually, lets say I need a list of cats - so I need to describe the model for what a 'cat' is.</p>
<p><em>models/cat.js</em></p>
<pre><code>import Model from "ember-data/model";
import attr from "ember-data/attr";
export default Model.extend({
name: attr('string'),
slug: attr('string')
});
</code></pre>
<p><br>
2. define where the dynamic segment will be in the url. I'm going to use catId to prove a point instead of cat_id or :id like most of the tutorials I've seen. For this example, I'm also writing an actual app structure instead of the smallest router possible - to test the edges of this. + what if I needed something like this later: animals.com/cats/:catId/best-friend/:dogId</p>
<p><em>router.js</em></p>
<pre><code>Router.map(function() {
this.route('index', { path: '/' });
this.route('cats', { path: '/cats' }, function() {
this.route('index', { path: '/' }); // list of cats
this.route('cat', { path: '/:catId' }); // cat spotlight
});
});
</code></pre>
<p><br>
3. pull in the catData into the store ~ in the /cats route</p>
<p><em>routes/cats.js</em></p>
<pre><code>import Ember from 'ember';
const catData = [
{
id: 1,
name: 'Dolly',
slug: 'dolly'
},
{
id: 2,
name: 'kitty cat',
slug: 'kitty-cat'
},
{
id: 3,
name: 'Cleopatra',
slug: 'cleo'
}
];
export default Ember.Route.extend({
model() {
return catData;
// return this.get('store').findAll('cat'); // with mirage or live api
}
});
</code></pre>
<p><br>
Update from comments: </p>
<blockquote>
<p>I do not believe that you can use queryRecord with your test data.
Ember data plays dumb with query and queryRecord; it doesn't assume
anything about your data and just passes the call on to your server.</p>
</blockquote>
<p>~ @xcskier56</p>
<p>So this kinda blows my twiddle as is. The git repo example is Mirage.</p>
<p><br>
4. create the templates... + set up the 'cat' route. The records are in the <em>store</em>... right? so I should be able to 'peek' at them based on id. The docs use <code>params</code> - but - </p>
<blockquote>
<p>Ember will extract the value of the dynamic segment from the URL for
you - and pass them <em>as a hash</em> to the model hook as the first argument</p>
</blockquote>
<p>: ~ and so the params object name isn't special and could really be anything you wanted... and is just replaced with a hash - so to that point / I'm using 'passedInThing' just to assert control over the confusing conventions (many tutorials use <em>param</em> instead of <em>params</em>)</p>
<p><em>routes/cats/cat.js</em></p>
<pre><code>model( passedInThing ) {
return this.store.peekRecord('cat', passedInThing.catId );
} // not going to happen - but in theory...
model( passedInThing ) {
return this.store.queryRecord('cat', { slug: passedInThing.catId } );
}
</code></pre>
<p><br>
5. At this point, I should be able to navigate to the url /cats/2 - and the <code>2</code> should get passed through the model hook - to the query. "Go get a 'cat' with an id of 2" --- right??? ((the twiddle example uses a hard-coded set of catData - but in my other attempts I'm using mirage with a combination of fixtures and dynamic slugs: <a href="https://github.com/sheriffderek/dynamic-segments-tests/commits/queryRecord" rel="nofollow">https://github.com/sheriffderek/dynamic-segments-tests/commits/queryRecord</a></p>
<p><br>
6. Typing in the segment works - but for <code>link-to</code> helpers I need to pass in the explicit <code>cat.id</code></p>
<pre><code>{{#link-to 'cats.cat' cat.id}}
<span>{{cat.name}}</span>
{{/link-to}}
</code></pre>
<p><br>
<strong>7.</strong> I can get all that working - but I don't want an ID in the URL. I want <code>cats/cleo</code> with the 'slug' ~ in theory I can just switch <code>catId</code> for <code>catSlug</code> and <code>cat.id</code> to <code>cat.slug</code> etc - but that is not the case. I've seen many tutorials outlining this but they are outdated. I've tried passing in <code>{ slug: params.slug }</code> and every combo of find query and peek etc. Sometimes the url will work but the model wont render - or the opposite.</p>
<p><br>
<strong>8.</strong> This seems like 101 stuff. Can anyone explain this to me? Oh wise emberinos - come to my aid!</p>
<p><br></p>
<h2>UPDATES</h2>
<ul>
<li><a href="https://embermap.com/video/friendly-urls-with-slugs" rel="nofollow">A nice video showing how to use <code>serialize()</code> in this case</a></li>
<li>There is supposedly an example coming to the Ember tutorial, but I haven't seen it land yet.</li>
</ul>
| 2 |
Freeswitch originate
|
<p>I'm using Freeswitch 1.6 ESL and when I place a call using API and remote IP Address I get: </p>
<p><strong>NO_ROUTE_DESTINATION</strong></p>
<pre><code>2016-07-08 06:24:13.381491 [DEBUG] switch_core_state_machine.c:296 No Dialplan on answered channel, changing state to HANGUP
</code></pre>
<p>It works fine If Im using a Phone registered to Freeswitch or instead of an IP I use a FQDN using SRV 5060 from my Service Provider.</p>
<pre><code>2016-07-08 06:23:17.401446 [DEBUG] switch_core_state_machine.c:300 No Dialplan, changing state to CONSUME_MEDIA
</code></pre>
<p>This is the command I'm using:</p>
<pre><code>originate {origination_uuid=89f6f5d9-ab9f-4c12-80dd-46854ad8f80b,originate_timeout=18,origination_caller_id_number=+14082223333}sofia/external/[email protected] & park()
</code></pre>
<p><strong>New channel</strong></p>
<pre><code>2016-07-08 05:58:32.061466 [NOTICE] switch_channel.c:1104 New Channel sofia/external/[email protected] [5a31b17e-2284-449e-bca0-d54f6bb5c35e]
</code></pre>
<p><strong>sofia global siptrace on</strong></p>
<pre><code>2016-07-08 05:58:32.081459 [NOTICE] sofia.c:7968 Channel [sofia/external/[email protected]] has been answered
2016-07-08 05:58:32.081459 [DEBUG] switch_channel.c:3770 (sofia/external/[email protected]) Callstate Change DOWN -> ACTIVE
2016-07-08 05:58:32.081459 [DEBUG] switch_ivr_originate.c:3607 Originate Resulted in Success: [sofia/external/[email protected]]
2016-07-08 05:58:32.081459 [DEBUG] switch_ivr.c:2160 (sofia/external/[email protected]) State Change CS_CONSUME_MEDIA -> CS_ROUTING
2016-07-08 05:58:32.081459 [NOTICE] switch_ivr.c:2167 Transfer sofia/external/[email protected] to park()[&@default]
2016-07-08 05:58:32.081459 [DEBUG] switch_core_state_machine.c:543 (sofia/external/[email protected]) Running State Change CS_ROUTING
2016-07-08 05:58:32.081459 [DEBUG] switch_core_state_machine.c:602 (sofia/external/[email protected]) State ROUTING
2016-07-08 05:58:32.081459 [DEBUG] mod_sofia.c:143 sofia/external/[email protected] SOFIA ROUTING
2016-07-08 05:58:32.081459 [DEBUG] switch_core_state_machine.c:236 sofia/external/[email protected] Standard ROUTING
2016-07-08 05:58:32.081459 [DEBUG] switch_core_state_machine.c:296 No Dialplan on answered channel, changing state to HANGUP
2016-07-08 05:58:32.081459 [NOTICE] switch_core_state_machine.c:298 Hangup sofia/external/[email protected] [CS_ROUTING] [NO_ROUTE_DESTINATION]
</code></pre>
<p><strong>asterisk.xml</strong></p>
<pre><code><include>
<gateway name="asterisk">
<param name="proxy" value="1.1.1.1"/>
<param name="register" value="false"/>
<param name="outbound_caller_id_number" value="+14082223333"/>
<param name="caller-id-in-from" value="true"/>
</gateway>
</include>
</code></pre>
<p><strong>outboundcalls.xml</strong></p>
<pre><code><include>
<extension name="test">
<condition field="destination_number" expression="^(999\d{11})$">
<action application="set" data="effective_caller_id_number=1408222333"/>
<action application="set" data="effective_caller_id_name=${outbound_caller_id_name}"/>
<action application="bridge" data="sofia/gateway/asterisk/$1"/>
</condition>
</extension>
<extension name="domestic">
<condition field="destination_number" expression="^(\d{11})$">
<action application="set" data="effective_caller_id_number=1408222333"/>
<action application="set" data="effective_caller_id_name=${outbound_caller_id_name}"/>
<action application="bridge" data="sofia/gateway/twilio/+$1"/>
</condition>
</extension>
</include>
</code></pre>
| 2 |
Grading using weighted averages in php
|
<p>How could I grade this test with php? I need a percentage score...</p>
<p>I have an array of questions containing the correct / incorrect bool and the corresponding weight.</p>
<p>Do I need to find the average of correct answers first?</p>
<p>What would the equation be?</p>
<pre><code>$questions = array(
0=>array(
'Question'=>"Some Question",
'Correct'=>true,
'Weight'=>5,
),
1=>array(
'Question'=>"Some Question",
'Correct'=>false,
'Weight'=>5,
),
2=>array(
'Question'=>"Some Question",
'Correct'=>true,
'Weight'=>4,
),
3=>array(
'Question'=>"Some Question",
'Correct'=>true,
'Weight'=>0,
),
4=>array(
'Question'=>"Some Question",
'Correct'=>false,
'Weight'=>5,
),
5=>array(
'Question'=>"Some Question",
'Correct'=>true,
'Weight'=>4,
),
);
$weights = array(
0=>0
1=>0
2=>.05
3=>.20
4=>.25
5=>.50
);
$totalQuestions=0;
$correctAnswers=0;
$points=0;
foreach($questions as $question){
$totalQuestions++;
if($question['Correct']){
$correctAnswers++;
$points = $points = $weights[$question['Weight'];
}
}
</code></pre>
| 2 |
SQL Server query to select all columns of a certain type and also show its max values
|
<p>I am using SQL Server 2012.</p>
<p>The first part of my query is already answered in this <a href="https://stackoverflow.com/questions/9678260/find-all-columns-of-a-certain-type-in-all-tables-in-a-sql-server-database">thread</a>. But I also want a second column that will show the corresponding maximum value of that column in its corresponding table. </p>
<p>I have tried this approach: use a function that takes in table name and column name as parameter and return the max value. But it is illegal to use dynamic SQL from a function. Moreover, i cannot seem to call a function from within a SELECT query. </p>
<p>I have also tried using stored procedure, but i cannot figure out how to call it and use it. Please suggest alternative ways to achieve this.</p>
<p>I am new to SQL Server.</p>
<p>Thanks</p>
| 2 |
Store Hibernate query results into Hashmap
|
<p>i want to store name and id of HQL query result into a Hashmap . here is my code. is there any better way to do it?</p>
<pre><code> String hql = "FROM Student";
Session session = HibernateUtil.getSessionFactory().openSession();
Query query = session.createQuery(hql);
List queryResults = query.list();
List<Student> result = new ArrayList<Student>();
Iterator it = queryResults.iterator();
while (it.hasNext()) {
Student student = (Student) it.next();
result.add(student);
}
Map mapresult = new LinkedHashMap<Integer,String>();
for (Student Maprslt : result)
mapresult.put(Maprslt.getId(), Maprslt.getName());
</code></pre>
| 2 |
Firebase: Listen for changes on child nodes after retrieving them all using .once()?
|
<p>In reference to the answer given at <a href="https://stackoverflow.com/questions/34355819/is-it-possible-to-avoid-oom-when-loading-a-large-data-set-using-cordova">Is it possible to avoid OOM when loading a large data set using Cordova?</a> and <a href="https://stackoverflow.com/a/28589093/3005222">https://stackoverflow.com/a/28589093/3005222</a>, I adapted the JSFiddle <a href="http://jsfiddle.net/firebase/AgBN7/" rel="nofollow noreferrer">http://jsfiddle.net/firebase/AgBN7/</a> provided by Kato to recursively page through a large Firebase data set (instead of relying on a user clicking the next page button). </p>
<p>It goes through a page of 100 nodes, using <code>ref.startAt(pri, lastKey).limitToFirst(100).once("value", ...)</code> and saves the data to a local variable. Then goes on to the next page and so on. At the end, I have a big local copy of the data that I use in my application. That's great but I'd now like to listen for changes and I have two options: </p>
<p><strong>Option 1:</strong>
Change the paging code to use <code>.on()</code> instead of <code>.once()</code></p>
<p><strong>Option 2:</strong>
After getting all the data, have a <code>ref.on("value", ...)</code> </p>
<p>My question is, which option is better from a performance perspective? I did this whole paging thing because my Cordova app was crashing when retrieving all the data in one go with <code>ref.on("value",...)</code> and changing it to the paged method has fixed that. Now I wonder if I go with option 1, will it create lots of active listeners? If I go with option 2, will it make the paging redundant, i.e. what does adding a <code>.on()</code> listener do if I've already gone through all the data using <code>.once()</code>?</p>
| 2 |
Proper way to bundle and consume webpack-built typescript library?
|
<p>I'm started using typescript recently and cannot understand how to build a typescript library which would be used in another typescript module using webpack.</p>
<p>Also this library and is intended to run in browser.</p>
<p>Currently I have ended up with following structure and build output:</p>
<pre><code>lib
├── build
│ ├── typings // tsc output with declaration:true
│ │ ├── Bar.d.ts
│ │ └── Foo.d.ts
│ └── lib.bundle.js //webpack bundle file
├── src
│ ├── Bar.ts
│ └── Foo.ts
├── bower.json
├── package.json
└── tconfig.json
</code></pre>
<p><strong>webpack configuration</strong>:</p>
<pre class="lang-js prettyprint-override"><code>webpackOptions = {
resolve: { extensions: ['', '.ts'] },
module: {
loaders: [{ test: /\.ts$/, exclude: [/node_modules/,/out/,/.*\.d\.ts/],include:[/\.ts$/], loaders: ['ts-loader']}]
},
ts:{
compilerOptions:compilerOptions
},
output: {
library:"mylib",
libraryTarget:'commonjs',
filename: 'mylib.bundle.js'
}
}
</code></pre>
<p><strong>tsconfig.json</strong>:</p>
<pre class="lang-json prettyprint-override"><code>{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"sourceMap": true,
"outDir":"out",
"declaration": true
},
"exclude": [
"node_modules",
"bower_components",
"typings/global",
"build"
]
}
</code></pre>
<p>And <strong>Foo.ts</strong> for example:</p>
<pre class="lang-ts prettyprint-override"><code>export class Foo{
foo(){}
}
</code></pre>
<p><strong>Bar.ts</strong>:</p>
<pre class="lang-ts prettyprint-override"><code>import {Foo} from './Foo'
export class Bar{
public foo:Foo = new Foo();
}
</code></pre>
<p>So I have following build output:</p>
<ul>
<li>webpack bundle</li>
<li>typescript declaration for each file</li>
</ul>
<p>And the questions are:</p>
<ul>
<li>How can I import/consume this library via bower in another browser application(which will use typescript with webpack too)?</li>
<li>Which import syntax would be used in application consuming this library(e.g. <code>import .. from</code> or <code>require</code> )?</li>
<li>Maybe I shouldn't use webpack for bundling library at all?</li>
</ul>
<p><strong>UPDATE:</strong> Used NPM to manage local dependencies between typescript modules without bower as suggested by @basarat and everything worked fine</p>
| 2 |
Laravel 5.2 Create query using url get parameters to select fields, match string and sort
|
<p>I have seen some API have simple query that can be constructed in url. For example, I have products table with Product model. </p>
<p>products table properties:</p>
<ul>
<li>id</li>
<li>product_name</li>
<li>barcode</li>
<li>category_id</li>
<li>description</li>
<li>price</li>
</ul>
<p>How can I do query in url as below (fields parameter means to select those specified fields):</p>
<p><code>http://example.com/product?fields=id,product_name,price,barcode&sortby=price</code></p>
<p>or maybe like this to get price equalto 10.00:</p>
<p><code>http://example.com/product?fields=id,product_name,price,barcode&price=10.00</code></p>
<p>I know in laravel we can check the get parameters using <code>$request->has()</code> and get the value using <code>$request->input('fieldname)</code> to check and retrieve the value one by one</p>
<p>But I think there should be a better way to do that or maybe there is a wrapper function that can be used for all controllers to read the query from url get parameters.</p>
<p>Thanks</p>
| 2 |
Two level grouped plots
|
<p>Is there any way to create a two level grouped bar chart (i.e. groups on the x-axis) using Python matplotlib and / or pandas.</p>
<p>An example of what I mean is shown <a href="https://i.stack.imgur.com/Sn9iF.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Sn9iF.jpg" alt="here"></a></p>
| 2 |
Elastic Search Invalid Pattern Given
|
<p>I have this code below:</p>
<pre><code>def main(args: Array[String]) {
val sparkConf = new SparkConf().setAppName("Spark-Hbase").setMaster("local[2]")
.set("es.index.auto.create", "true")
.set("es.resource", "test")
.set("es.nodes", "127.0.0.1")
.set("es.output.json", "true")
/* More code */
DStream.map {
_._2
}.foreachRDD { (rdd: RDD[String]) =>
EsSpark.saveJsonToEs(rdd, "127.0.0.1")
}
</code></pre>
<p>I keep getting an error for the <code>elastic search</code> es.nodes property saying:</p>
<pre><code>Caused by: org.elasticsearch.hadoop.EsHadoopIllegalArgumentException: invalid pattern given 127.0.0.1/
at org.elasticsearch.hadoop.util.Assert.isTrue(Assert.java:50)
at org.elasticsearch.hadoop.serialization.field.AbstractIndexExtractor.compile(AbstractIndexExtractor.java:51)
at org.elasticsearch.hadoop.rest.RestService.createWriter(RestService.java:398)
at org.elasticsearch.spark.rdd.EsRDDWriter.write(EsRDDWriter.scala:40)
at org.elasticsearch.spark.rdd.EsSpark$$anonfun$saveToEs$1.apply(EsSpark.scala:67)
at org.elasticsearch.spark.rdd.EsSpark$$anonfun$saveToEs$1.apply(EsSpark.scala:67)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:66)
at org.apache.spark.scheduler.Task.run(Task.scala:89)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:214)
... 3 more
</code></pre>
<p>Am I doing something wrong by putting <code>127.0.0.1</code>? I tried putting the port as by doing <code>127.0.0.1:9200</code> but it still didn't work. Does anyone have any pointers? Thanks.</p>
| 2 |
javascript function to select option and submit a django form
|
<p>I'm building an app in django and I've got a filter form that is a dropdown and you can switch between "new" and "popular" (aka filter by date or number of votes). I decided that I want this to be formatted as buttons (kind of like how it is on yik yak) where it is easier to toggle between the two.</p>
<p>I am using django widget tweaks to display my forms so my generated HTML looks like:</p>
<pre><code><form action="/board/Intuna/" method="post" class="ng-pristine ng-valid">
<input type="hidden" name="csrfmiddlewaretoken" value="io55AwNMPKNzAkv69qWkcRzqNV7mwo1w">
<div class="form-group">
<label class="col-sm-1 control-label" for="id_filterType">Filter By</label>
<div class="col-sm-11">
<select class="form-control" id="id_filterType" name="filterType" onchange="this.form.submit();">
<option value="0" selected="selected">Most Recent</option>
<option value="1">Popularity</option>
</select>
</div>
</div>
</form>
</code></pre>
<p>UPDATE: I tried writing this javascript function to select the choice in my form</p>
<pre><code>function filter(valueToSelect) {
var item = document.getElementById('id_filterType');
console.log(item);
if (item) {
item.value = valueToSelect;
}
}
</code></pre>
<p>And lastly in my HTML template I have two buttons</p>
<pre><code><button class="btn btn-primary" onclick="filter('0');">New</button>
<button class="btn btn-primary" onclick="filter('1');">Hot</button>
</code></pre>
<p>When I click the buttons, the selected option in my form changes but it doesn't submit, which does not make sense to me since it is supposed to automatically submit when the option is changed. Any ideas?</p>
| 2 |
Python: Compute all possible pairwise distances of a list (DTW)
|
<p>I have a list of items like so: <code>T=[T_0, T_1, ..., T_N]</code> where each of <code>T_i</code> is itself a time series. I want to find the pairwise distances (via DTW) for all potential pairs. </p>
<p>E.g. If <code>T=[T_0, T_1, T_2]</code> and I had a DTW function <code>f</code>, I want to find <code>f(T_0, T_1), f(T_0, T_2), f(T_1, T_2)</code>.</p>
<p>Note <code>T_i</code> actually looks like <code>( id of i, [ time series values ] )</code>.</p>
<p>My code snippet looks like this:</p>
<pre><code>cluster = defaultdict( list )
donotcluster = defaultdict( list )
for i, lst1 in tqdm(enumerate(T)):
for lst2 in tqdm(T):
if lst2 in cluster[lst1[0]] or lst2 in donotcluster[lst1[0]]:
pass
else:
distance, path = fastdtw(lst1[1], lst2[1], dist=euclidean)
if distance <= distance_threshold:
cluster[lst1[0]] += [ lst2 ]
cluster[lst2[0]] += [ lst1 ]
else:
donotcluster[lst1[0]] += [ lst2 ]
donotcluster[lst2[0]] += [ lst1 ]
</code></pre>
<p>Right now I have around 20,000 time series and this take way too long (it will run in about 5 days). I am using the python library <code>fastdtw</code>. Is there a more optimised library? Or just a better/faster way of computing all possible distances? Since distances are symmetric I don't have to calculate for example <code>f(T_41,T_33)</code> if I have already calculated <code>f(T_33, T_41)</code></p>
| 2 |
Variable Range as Input
|
<p>I am a new user of VBA for Excel (2013), and I've been struggling with a problem for quite a while.</p>
<p>I want to create a function that, among the other input variables that the user has to provide, has several ranges of cells, that should be variable and "easily selectable" by the user themselves.
It should be something like (for example) the Excel "SUM" formula, where you can input several ranges such as "A1:C1,F1:H1,...", selecting them with your mouse.</p>
<p>Moreover, I have to transfer the values selected by the user in a 2D array. Every range selected by the user has to become a row of my 2D array.</p>
<p>Further to what I've said so far, the number of ranges that the user inputs should be anyone, and only the first one should be mandatory.</p>
<p>Given the "structure" of my spreadsheet, all the data that the user has to select are arranged in rows. (Does it make any difference if they are arranged in rows or in columns?)</p>
<p>Please note that I shouldn't use the "Input Box", because it slows down a lot the procedure when I "drag down" a row to apply the formula to many rows below the active one.</p>
<p>Below, I report the only parts of the code that I was able to write (not very much...)</p>
<pre><code>Function Trial_Version(MyRange1 As Range, MyRange2 As Range, MyRange3 As Range) As Double
''' The number of ranges that the user is be able to input
'''should be anyone. Only the first Range should be mandatory
Dim TotalArray()() As Double
'''The user should be able to input as many "sub-arrays" as they want,
'''so I do not know how many parentheses to write
TotalArray = (MyRange1)(MyRange2)
'''here, the same problem as the previous line
RANGE_TO_ARRAY = TotalArray
'''This is the output of my function
End Function
</code></pre>
<p>Thank you very much in advance,
Orlando</p>
| 2 |
Gspread - Change Listener?
|
<p>I currently run a daemon thread that grabs all cell values, calculates if there's a change, and then writes out dependent cells in a loop, ie:</p>
<pre><code>def f():
while not event.is_set():
update()
event.wait(15)
Thread(target=f).start()
</code></pre>
<p>This works, but the looped get-all calls are significant I/O.</p>
<p>Rather than doing this, it would be much cleaner if the thread was notified of changes by Google Sheets. Is there a way to do this?</p>
| 2 |
Using assert_select to find a select box value?
|
<p>I'm struggling to test whether my select box has a value of 6.</p>
<pre><code><form class="edit_line_item" id="edit_line_item_7" action="/line_items/7" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓"><input type="hidden" name="_method" value="patch">
<select name="line_item[quantity]" id="line_item_quantity"><option selected="selected" value="1">1</option>
</select>
</form>
</code></pre>
<p>My rspec code</p>
<pre><code>assert_select "select#line_item_quantity", value: 6
</code></pre>
<p>Whatever I change the value to my test still passes so I am wrong somewhere.</p>
| 2 |
can i use i18n key name with spaces and some special characters?
|
<p>I want to use the JSTL tags with i18n.</p>
<p>In creation of the i18n key value pair, <strong>can i use i18n key name with spaces and some special characters?</strong></p>
| 2 |
Onvif RTSP over HTTP
|
<p>I`m trying to make an IP Camera to work with the onvif specification. (I try to develop the services on the camera, the server)</p>
<p>The Camera does only support rtsp over http and I have no idea how to get this working with e.g. the Onvif test tool.</p>
<p>I have the rtsp stream uri but when I send it to the client it gives me a describe error. what do I have to send to the Client so it knows that it is rtsp over http?</p>
| 2 |
PHP Fatal error: Uncaught Error: Cannot access property started with '\\0'
|
<p>So I'm using Timber v0.22.5. I have it currently running on my local and a dev environment right now. Everything is running great no issues. Both environments are running PHP 5.5.9.</p>
<p>I just migrated it to my production server which is running PHP 7.0. I am now getting the following error from Timber.</p>
<blockquote>
<p>Fatal error: Uncaught Error: Cannot access property started with '\0'
in
/var/www/html/wp-content/plugins/timber-library/lib/timber-core.php:67</p>
</blockquote>
<p>I'm not sure what exactly else is different between the environments other than different versions of PHP. I cannot update to Timber v1 because well the guide seems to suggest not doing that because of some backwards compatibility issues.</p>
<p>I'm going to try installing PHP 5.5.9 and see if that does the trick but was wondering if anyone else was having this issue.</p>
<p>Thanks!</p>
| 2 |
bootstrap 4 with card-columns, can't get media-query to work
|
<p>I have a simple bootstrap card example here that used 14 cards <a href="http://www.bootply.com/1ERCHtYa8k" rel="nofollow">http://www.bootply.com/1ERCHtYa8k</a>. I used a media query to adjust the column count from the usual fixed count of 3 to more or less columns based on screen size. </p>
<p>For some reason at the large break point where I've specified 6 columns, it always shows 5. The other breakpoints work OK and i'm not sure why it's doing this or how to fix. </p>
<p>I've noticed as well that as i vary the card count, at large the number of columns changes in weird ways. For example the same example but with only 7 cards <a href="http://www.bootply.com/7yubrPSKgQ#" rel="nofollow">http://www.bootply.com/7yubrPSKgQ#</a> when sized to large will only show 4 columns. Don't understand why. </p>
<p>I'm using latest Chrome on Windows 10 machine. </p>
<p>Any info/help appreciated. Thanks.</p>
| 2 |
switched from rbenv from rvm and now not able to rails s. can't activate bundler-1.12.5, already activated bundler-1.13.0.rc.1 (Gem::LoadError)
|
<p>FIRST ERROR:</p>
<pre><code>`check_version_conflict': can't activate bundler-1.12.5, already activated bundler-1.13.0.rc.1 (Gem::LoadError)
</code></pre>
<p>TURNED INTO THIS ERROR:</p>
<pre><code>/Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/sqlite3-1.3.11/lib/sqlite3.rb:6:in `require': dlopen(/Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/sqlite3-1.3.11/lib/sqlite3/sqlite3_native.bundle, 9): Library not loaded: /Users/phillipjones/.rvm/rubies/ruby-2.3.1/lib/libruby.2.3.0.dylib (LoadError)
Referenced from: /Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/sqlite3-1.3.11/lib/sqlite3/sqlite3_native.bundle
Reason: image not found - /Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/sqlite3-1.3.11/lib/sqlite3/sqlite3_native.bundle
</code></pre>
<p>These are the the circumstances leading up to this issue and my steps to try and resolve:</p>
<p>After switching to rbenv from rvm I am having trouble with apps that I created using rvm. I cannot run rails s. </p>
<p>First I got this error: </p>
<pre><code>Phillip-Joness-MacBook:messengerApp phillipjones$ rails s
/Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/specification.rb:2274:in `check_version_conflict': can't activate bundler-1.12.5, already activated bundler-1.13.0.rc.1 (Gem::LoadError)
from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/specification.rb:1403:in `activate'
from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_gem.rb:68:in `block in gem'
from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_gem.rb:67:in `synchronize'
from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_gem.rb:67:in `gem'
from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/bundler-1.13.0.rc.1/lib/bundler/postit_trampoline.rb:32:in `<top (required)>'
from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/bundler-1.13.0.rc.1/lib/bundler/setup.rb:2:in `<top (required)>'
from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /Users/phillipjones/workspace/messengerApp/config/boot.rb:3:in `<top (required)>'
from /Users/phillipjones/workspace/messengerApp/bin/rails:8:in `require_relative'
from /Users/phillipjones/workspace/messengerApp/bin/rails:8:in `<top (required)>'
from /Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/spring-1.7.1/lib/spring/client/rails.rb:28:in `load'
from /Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/spring-1.7.1/lib/spring/client/rails.rb:28:in `call'
from /Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/spring-1.7.1/lib/spring/client/command.rb:7:in `call'
from /Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/spring-1.7.1/lib/spring/client.rb:30:in `run'
from /Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/spring-1.7.1/bin/spring:49:in `<top (required)>'
from /Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/spring-1.7.1/lib/spring/binstub.rb:11:in `load'
from /Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/spring-1.7.1/lib/spring/binstub.rb:11:in `<top (required)>'
from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /Users/phillipjones/workspace/messengerApp/bin/spring:13:in `<top (required)>'
from bin/rails:3:in `load'
from bin/rails:3:in `<main>'
</code></pre>
<p>Then I tried bundle update. no change
so I tried to install the bundler gem: </p>
<pre><code>Phillip-Joness-MacBook:messengerApp phillipjones$ gem install bundler
Successfully installed bundler-1.12.5
Parsing documentation for bundler-1.12.5
Done installing documentation for bundler after 5 seconds
1 gem installed
</code></pre>
<p>no change.</p>
<p>I tried to install the exact bundler version</p>
<pre><code>Phillip-Joness-MacBook:messengerApp phillipjones$ gem install bundler-1.12.5
ERROR: Could not find a valid gem 'bundler-1.12.5' (>= 0) in any repository
</code></pre>
<p>no change.</p>
<p>I homebrew installed rbenv-bundler</p>
<pre><code>hillip-Joness-MacBook:rubygems phillipjones$ brew install rbenv-bundler
==> Downloading https://github.com/carsomyr/rbenv-bundler/archive/0.99.tar.gz
==> Downloading from https://codeload.github.com/carsomyr/rbenv-bundler/tar.gz/0.99
######################################################################## 100.0%
/usr/local/Cellar/rbenv-bundler/0.99: 13 files, 46.6K, built in 10 seconds
</code></pre>
<p>installed the bundler again, deleted the gemlock.file and ran a bundle install</p>
<pre><code>Phillip-Joness-MacBook:rubygems phillipjones$ gem install bundler
Successfully installed bundler-1.12.5
Parsing documentation for bundler-1.12.5
Done installing documentation for bundler after 5 seconds
1 gem installed
Phillip-Joness-MacBook:rubygems phillipjones$ bundle install
Could not locate Gemfile
Phillip-Joness-MacBook:rubygems phillipjones$ cd ~/workspace/messengerApp/
Phillip-Joness-MacBook:messengerApp phillipjones$ bundle install
Using rake 11.2.2
Using i18n 0.7.0
Using json 1.8.3
Using minitest 5.9.0
Using thread_safe 0.3.5
Using builder 3.2.2
Using erubis 2.7.0
Using mini_portile2 2.1.0
Using pkg-config 1.1.7
Using rack 1.6.4
Using mime-types-data 3.2016.0521
Using arel 6.0.3
Using ansi 1.5.0
Using execjs 2.7.0
Using debug_inspector 0.0.2
Using thor 0.19.1
Using sass 3.4.22
Using byebug 9.0.5
Using coderay 1.1.1
Using coffee-script-source 1.10.0
Using concurrent-ruby 1.0.2
Using ffi 1.9.13
Using bundler 1.12.5
Using formatador 0.2.5
Using rb-fsevent 0.9.7
Using ruby_dep 1.3.1
Using lumberjack 1.0.10
Using nenv 0.3.0
Using shellany 0.0.1
Using method_source 0.8.2
Using slop 3.6.0
Using guard-compat 1.2.1
Using multi_json 1.12.1
Using turbolinks-source 5.0.0
Using ruby-progressbar 1.8.1
Using tilt 2.0.5
Using spring 1.7.2
Using sqlite3 1.3.11
Using rdoc 4.2.2
Using tzinfo 1.2.2
Using nokogiri 1.6.8
Using rack-test 0.6.3
Using mime-types 3.1
Using autoprefixer-rails 6.3.7
Using uglifier 3.0.0
Using binding_of_caller 0.7.2
Using bootstrap-sass 3.2.0.2
Using coffee-script 2.4.1
Using sprockets 3.6.3
Using rb-inotify 0.9.7
Using notiffany 0.1.0
Using pry 0.10.3
Using guard-minitest 2.4.4
Using turbolinks 5.0.0
Using minitest-reporters 1.1.9
Using sdoc 0.4.1
Using activesupport 4.2.6
Using loofah 2.0.3
Using mail 2.6.4
Using listen 3.1.5
Using rails-deprecated_sanitizer 1.0.3
Using globalid 0.3.6
Using activemodel 4.2.6
Using jbuilder 2.5.0
Using rails-html-sanitizer 1.0.3
Using guard 2.13.0
Using rails-dom-testing 1.0.7
Using activejob 4.2.6
Using activerecord 4.2.6
Using actionview 4.2.6
Using actionpack 4.2.6
Using actionmailer 4.2.6
Using railties 4.2.6
Using sprockets-rails 3.1.1
Using simple_form 3.2.1
Using bootstrap-datepicker-rails 1.6.1.1
Using bootstrap-modal-rails 2.2.5
Using coffee-rails 4.1.1
Using font-awesome-rails 4.6.3.1
Using jquery-rails 4.1.1
Using jquery-turbolinks 2.1.0
Using responders 2.2.0
Using rails 4.2.6
Using sass-rails 5.0.5
Using web-console 2.3.0
Using figaro 0.7.0
Using rails-controller-testing 0.0.3
Bundle complete! 28 Gemfile dependencies, 87 gems now installed.
Gems in the group production were not installed.
Bundled gems are installed into ./vendor/bundle.
</code></pre>
<p>then I checked the rbenv local. did a rbenv rehash. checked the rake. and tried rails s again. this time I got a new error:</p>
<pre><code>Phillip-Joness-MacBook:messengerApp phillipjones$ rbenv local
ruby-2.3.1
Phillip-Joness-MacBook:messengerApp phillipjones$ rbenv rehash
Phillip-Joness-MacBook:messengerApp phillipjones$ rbenv which rake
/Users/phillipjones/.rbenv/versions/2.3.1/bin/rake
Phillip-Joness-MacBook:messengerApp phillipjones$ rails ss
/Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/specification.rb:2274:in `check_version_conflict': can't activate bundler-1.12.5, already activated bundler-1.13.0.rc.1 (Gem::LoadError)
from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/specification.rb:1403:in `activate'
from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_gem.rb:68:in `block in gem'
from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_gem.rb:67:in `synchronize'
from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_gem.rb:67:in `gem'
from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/bundler-1.13.0.rc.1/lib/bundler/postit_trampoline.rb:32:in `<top (required)>'
from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/bundler-1.13.0.rc.1/lib/bundler/setup.rb:2:in `<top (required)>'
from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /Users/phillipjones/workspace/messengerApp/config/boot.rb:3:in `<top (required)>'
from /Users/phillipjones/workspace/messengerApp/bin/rails:8:in `require_relative'
from /Users/phillipjones/workspace/messengerApp/bin/rails:8:in `<top (required)>'
from /Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/spring-1.7.2/lib/spring/client/rails.rb:28:in `load'
from /Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/spring-1.7.2/lib/spring/client/rails.rb:28:in `call'
from /Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/spring-1.7.2/lib/spring/client/command.rb:7:in `call'
from /Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/spring-1.7.2/lib/spring/client.rb:30:in `run'
from /Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/spring-1.7.2/bin/spring:49:in `<top (required)>'
from /Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/spring-1.7.2/lib/spring/binstub.rb:11:in `load'
from /Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/spring-1.7.2/lib/spring/binstub.rb:11:in `<top (required)>'
from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
from /Users/phillipjones/workspace/messengerApp/bin/spring:13:in `<top (required)>'
from bin/rails:3:in `load'
from bin/rails:3:in `<main>'
</code></pre>
| 2 |
Add enctype in jquery form
|
<pre><code>var form = $('<form/>', {
action: 'SupportRequest',
method: 'POST',
name: 'myForm',
id: 'myForm'
}).appendTo('body');
</code></pre>
<p>I have to add <code>enctype="multipart/form-data"</code> manually during form creation, how do i do this so that the above code looks like </p>
<pre><code><form class="hidden" id="myForm" mrthod="post" enctype = "multipart/form-data" action="myservlet">
</code></pre>
<p>and also please tell me how to make it of class='hidden' manually</p>
| 2 |
Returning XDocument from Controller (dotnet coreclr)
|
<p>I have a XDocument inside a controller that I want to server as xml and json (depending on the Accept header of the request).</p>
<p>I am using dotnet core:</p>
<p>In my startup.cs/ConfigureServices I have this:</p>
<pre><code>services.AddMvc().AddXmlDataContractSerializerFormatters();
</code></pre>
<p>My controller essentially is this:</p>
<pre><code>public async Task<IActionResult> getData(int id)
{
XDocument xmlDoc = db.getData(id);
return Ok(xmlDoc);
}
</code></pre>
<p>When making a request with <code>Accept: application/json</code>, I get my data properly formatted as JSON. When making a request with <code>Accept: application/xml</code>, I still get a JSON response (same as with <code>application/json</code>).</p>
<p>I have also tried with:</p>
<pre><code>services.AddMvc().AddXmlSerializerFormatters();
</code></pre>
<p>but that was even worse as even normal objects were served as JSON (XmlDataContractSerializer could handle normal objects, but not XDocument).</p>
<p>When I add <code>[Produces("application/xml")]</code>to the controller (using <code>AddXmlSerializerFormatters</code>), I get a Http 406 error when serving XDocument, but I do get a XML output when returning normal objects.</p>
<p>Do I have to convert the XDocument to objects to output XML from a controller? Is there an easy way to convert XDocuments to objects?</p>
| 2 |
python vim tmux linux - copy multiple lines from vim to ipython
|
<p>I am trying to copy a block of text (im in linux debian) from vim to ipython
I select the block of text "yank", exit vim with ctrl-Z, enter ipython and shift-insert.</p>
<p>However it always only paste the first line of my originaly copied block of text..</p>
<p>Any idea how to paste multi lines?</p>
<p>(Edit by @maxymoo to add a MCVE)</p>
<pre><code>docker run -t -i ubuntu /bin/bash
apt-get update && apt-get -y upgrade
apt-get install python-pip tmux vim
pip install --upgrade pip
pip install ipython
</code></pre>
<p>Now start up a tmux session, <code>C-b %</code> to split pane, start <code>vim</code> and enter the following lines:</p>
<pre><code>print("first line")
print("second line")
</code></pre>
<p>Copy it to tmux clipboard with <code>C-b [ C-space <arrow keys to select all> M-w</code></p>
<p>Switch to the other pane with <code>C-b o</code> and start an <code>ipython</code> session.
Paste the text with <code>C-b ]</code></p>
<p>Output:</p>
<pre><code>In [1]: print("first line")
first line
In [2]:
</code></pre>
<p>The paste works properly if I force line-continuation mode by using <code>%%time</code> cell magic:</p>
<pre><code>In [3]: %%time
...: print("first line")
...: print("second line")
...:
first line
second line
CPU times: user 0 ns, sys: 0 ns, total: 0 ns
Wall time: 42.2 us
</code></pre>
| 2 |
Auto-convert snake case to camel case in Grails REST API?
|
<p>In a Grails REST API project, by default Grails reads properties and renders properties assuming camel case (<a href="https://en.wikipedia.org/wiki/CamelCase" rel="nofollow">camelCase</a>). However, in many prevalent REST APIs the name of parameters are standardized on snake case (<a href="https://en.wikipedia.org/wiki/Snake_case" rel="nofollow">snake_case</a>). How can I most effectively enable this automatic conversion in Grails?</p>
<p>For example, in a request body I'd like to accept snake case input.</p>
<pre><code>{
"first_name": "John"
}
</code></pre>
<p>And in the response body I'd like to send snake case output.</p>
<pre><code>{
"last_name": "Doe"
}
</code></pre>
<p>But I want to keep my domain class streamlined following Groovy conventions in Grails, using camel case and Groovy's auto-generated getters and setters.</p>
<pre><code>class User {
String firstName
String lastName
}
</code></pre>
<p>And I'd like to avoid changing my MongoDB schema, where 99% of fields are named with camelCase. However I do see that at least <a href="https://docs.mongodb.com/manual/core/data-model-design/" rel="nofollow">in the MongoDB docs</a>, the preference is to name MongoDB fields with snake_case.</p>
| 2 |
how to fire a button action method in didselectrowatindexpath in iOS, objective c
|
<p>I have a tableview with custom tableview cell. in the tableview cell there are two labels and one button.what I want it to fire the button action for user selected row to hide a label in the same row.</p>
<p>this is my controller for table view</p>
<p><strong>ViweController.h</strong></p>
<pre><code> #import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tablev;
@end
</code></pre>
<p><strong>ViewController.m</strong></p>
<pre><code>#import "ViewController.h"
#import "TestTableViewCell.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
TestTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"mycell"];
cell.selectionStyle = UITableViewCellFocusStyleCustom;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger sec = indexPath.section;
NSInteger rw = indexPath.row;
TestTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"mycell"];
cell.numberlabel.hidden = YES;
NSLog(@"selected section :%li ---> selected row :%li",(long)sec, (long)rw);
//in here I want fire the button acction in the cell for each row when cell tap.(not when the button click in the cell).
}
</code></pre>
<p><strong>TestTableViewCell.h</strong></p>
<pre><code>#import <UIKit/UIKit.h>
@interface TestTableViewCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *staticlabel;
@property (weak, nonatomic) IBOutlet UILabel *numberlabel;
@property (weak, nonatomic) IBOutlet UIButton *hidebutton;
@end
</code></pre>
<p><strong>TestTableViewCell.m</strong>
//I have tried to implement button click method here.It worked.but at that point it didn't recognised which cell is taped. </p>
<p>**NOTE : I have tried to implement button click method here.I worked.but at that point it didn't recognised which cell is taped. **</p>
| 2 |
.hbs files strips javascript
|
<p>I am including a script in .hbs file, but every time I assemble grunt assemble this .hbs file, the hbs template inside the script is ignored in the HTML output.
This is my .hbs file</p>
<pre><code><script id="myTemplate1" type="text/x-handlebars-template">
{{#each}}
<div class="sample">
....
</div>
{{/each}}
</script>
</code></pre>
<p>I assembling the above .hbs file using grunt assemble and it just ignores all the content inside the script tag and I could see only the following in the HTML output</p>
<pre><code><script id="myTemplate1" type="text/x-handlebars-template">
</script>
</code></pre>
<p>What's wrong here? I tried to have the script as a separate JS file but didn't work? I also tried to include the script in the HTML output but every time I assemble, it overwrites and I get only the empty tags.</p>
| 2 |
Specify the git branch code to be deployed in Elastic Beanstalk environment
|
<p>Is there any way to specify which git branch code to be deployed to an Elastic Beanstalk environment?</p>
<p>Assume, I have two git branches named <strong>test</strong> and <strong>stage</strong> and I have an Elastic Beanstalk environment named <strong>test-env</strong>.</p>
<p>Now, I set the branch defaults in <code>config.yml</code> as below:</p>
<pre><code>branch-defaults:
test:
environment: test-env
group_suffix: null
global:
application_name: test
default_ec2_keyname: abcde
default_platform: Ruby 2.2 (Puma)
default_region: us-west-2
profile: eb-cli
sc: git
</code></pre>
<p>Now, what I need is if I deploy from <strong>stage</strong> branch with <code>eb deploy test-env</code> it should automatically deploy the code from <strong>test</strong> branch or it should throw an error..</p>
<p>Is there any way to do it. If no please suggest me some other way to do it..</p>
<p>Thanks..</p>
| 2 |
How to Style Specific Element On Hover With CSS?
|
<p>This question is for <a href="http://chameleonwebsolutions.com" rel="nofollow noreferrer">http://chameleonwebsolutions.com</a>. I need it so that when you hover over the social media links, their color changes to a darker green (#72984a). I tried:</p>
<pre><code>.site-header .fa a:hover {
color: #72984a !important;
}
.fa .fa-facebook-square a:hover {
color:#72984a !important;
}
.social-icons a:hover {
color:#72984a !important;
}
.logo .mobile-social-icons .hidden-tablet a:hover {
color:#72984a !important;
}
.social-icons .hidden-mobile .responsive-header-gutter a:hover {
color: #72984a !important;
}
</code></pre>
<p>In the stylesheet but none of them are showing up in the inspector. I would try just a:hover in the stylesheet (no class before it) but then of course that would apply to all of the hyperlinks. How can I style only the social media links when you hover over them? Thanks!</p>
<p><a href="https://i.imgur.com/xajGHxH.jpg" rel="nofollow noreferrer" title="Screenshot"><img src="https://i.imgur.com/xajGHxH.jpg" alt="Screenshot" title="Screenshot"></a></p>
| 2 |
Variable transitions in React using ReactCSSTransitionGroup
|
<p><a href="https://facebook.github.io/react/docs/animation.html" rel="nofollow"><code>ReactCSSTransitionGroup</code></a> uses a CSS file to define and store transitions. That is nice and works well. But what if a component needs a variable transition configuration e.g a variable <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/transition-duration" rel="nofollow"><code>transition-duration</code></a> that takes any value from 0ms to 10000ms? How would I change the value of <code>transition-duration</code> from within the component's Javascript class, when it is stored in a CSS file?</p>
<p><strong>Example:</strong></p>
<p>Let's say you want to make a slideshow component and you want to implement an option to change the <em>fading-duration</em> (the time the animation takes to fade from one slide to another). You call the component like this:</p>
<pre><code><Slideshow fadeDuration={1000}>
</code></pre>
<p>This is how the component adds the transitions to the slide element that is going to be rendered:</p>
<pre><code>render: function() {
return (
<div>
<ReactCSSTransitionGroup
transitionName="example"
transitionEnterTimeout={500}
transitionLeaveTimeout={300}>
{this.slide}
</ReactCSSTransitionGroup>
</div>
);
}
</code></pre>
<p>This is the css file needed by <code>ReactCSSTransitionGroup</code> to define the transitions:</p>
<pre><code>.example-enter {
opacity: 0.01;
}
.example-enter.example-enter-active {
opacity: 1;
transition: opacity 500ms ease-in;
}
.example-leave {
opacity: 1;
}
.example-leave.example-leave-active {
opacity: 0.01;
transition: opacity 300ms ease-in;
}
</code></pre>
<p>Now how do I use <code>props.fadeDuration</code> inside the component to change the value of <code>transition-duration</code> which lays inside the css file?</p>
<p>So far the only thing that came to my mind was, that I have to remove the <code>ReactCSSTransitionGroup</code> and create the transitions manually using <a href="https://facebook.github.io/react/docs/more-about-refs.html#the-ref-callback-attribute" rel="nofollow">refs</a> and the <a href="http://www.w3schools.com/jsref/prop_style_transition.asp" rel="nofollow">'Style Object' 'transition' property</a>. Is this the way to go? Or how would I do it?</p>
| 2 |
How to create breakpad symbols?
|
<p>I run a <a href="https://github.com/electron/mini-breakpad-server" rel="nofollow noreferrer">mini-breakpad-server</a> on my server and it's collecting the reports correctly from my <code>Electron</code> app, however I don't know how to create breakpad symbols (for windows, OSX, Linux) to work with my Electron app, could you give me a hint please?</p>
| 2 |
GMSMapView tracking mode heading
|
<p>In my app, I am using <code>GMSMapView</code>, and I would like to change tracking mode. In iOS MapKit, I can change the tracking mode to <code>MKUserTrackingModeFollowWithHeading</code>, but don't know how to change it in <code>GMSMapView</code>.</p>
<p>In the app <code>Google Maps</code>, it is working after second touch on <code>myLocationButton</code>. Is it possible?</p>
| 2 |
Mockito mock a context.getApplicationInfo in Android Unit Testing
|
<p>First time writing unit tests ever, so I read the Android developer guide on mockito. I am trying to achieve something similar when they mock the context, however, I am getting a NullPointerException on my test because I'm not correctly substituting <code>mMockContext.getApplicationInfo()</code></p>
<p>Test looks like this:</p>
<pre><code>package com.cinnamint.cotidiano;
import android.app.Application;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class MainUnitTest {
@Mock
Context mMockContext;
@Mock
ApplicationInfo mApplicationInfo;
@Test
public void dateValidator_CorrectNumberOfWordsGrab_ReturnWords() throws Exception {
when(mMockContext.getApplicationInfo()).thenReturn(mApplicationInfo);
WordDatabase testWordDatabase = new WordDatabase(mMockContext);
testWordDatabase.open();
List<Words> results = testWordDatabase.getEveryWordByDate(4);
testWordDatabase.close();
assertThat(results.size(), is(4));
}
}
</code></pre>
<p>I should note that the database is using SQLiteAssetHelper, and NOT accessing an external database through online protocol or anything like that. The database is stored as an asset to the APK and is only loaded once.</p>
<p>LogCat:</p>
<pre><code>java.lang.NullPointerException
at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.<init>(SQLiteAssetHelper.java:109)
at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.<init>(SQLiteAssetHelper.java:129)
at com.cinnamint.cotidiano.WordDatabase.<init>(WordDatabase.java:20)
at com.cinnamint.cotidiano.MainUnitTest.dateValidator_CorrectNumberOfWordsGrab_ReturnWords(MainUnitTest.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
</code></pre>
<p>Edit: New version of test</p>
<pre><code>@Test
public void dateValidator_CorrectNumberOfWordsGrab_ReturnWords() throws Exception {
when(mMockContext.getApplicationInfo()).thenReturn(mApplicationInfo);
when(mMockContext.getAssets()).thenReturn(mAssetManager);
when(mAssetManager.open("null/databases/word.db")).thenReturn(mInputStream);
WordDatabase testWordDatabase = new WordDatabase(mMockContext);
when(testWordDatabase.getWritableDatabase()).thenReturn(mSQLiteDatabase);
testWordDatabase.open();
List<Words> results = testWordDatabase.getEveryWordByDate(4);
testWordDatabase.close();
assertThat(results.size(), is(4));
}
</code></pre>
<p>New stacktrace:</p>
<pre><code>com.readystatesoftware.sqliteasset.SQLiteAssetHelper$SQLiteAssetException
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(FileOutputStream.java:270)
at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
at java.io.FileOutputStream.<init>(FileOutputStream.java:101)
at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.copyDatabaseFromAssets(SQLiteAssetHelper.java:455)
at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.createOrOpenDatabase(SQLiteAssetHelper.java:400)
at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.getWritableDatabase(SQLiteAssetHelper.java:176)
at com.cinnamint.cotidiano.MainUnitTest.dateValidator_CorrectNumberOfWordsGrab_ReturnWords(MainUnitTest.java:88)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
</code></pre>
| 2 |
How to find element with specific class attributes in selenium (python)?
|
<p>On Windows Server 2012 I am using selenium 2.53.6, and I want to check if the <code>class</code> contains the element <code>lock-icon</code> for the following html element:</p>
<pre><code><a href="http://my.page/link/somewhere" class="more-link lock-icon" target="_blank">
Selenium Projekt dianep geheim
</a>
</code></pre>
<p>I tried the following expression with the python API:</p>
<pre><code>find_element(by=By.CSS_SELECTOR, value="more-link.lock-icon")
</code></pre>
<p>but it returns a <code>None</code> although the element (shown above) is visible on the website. </p>
<p>How to do it correctly?</p>
| 2 |
Sublime Text Editor: Boxes Appear instead of Spaces
|
<p><a href="https://i.stack.imgur.com/Zb69F.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Zb69F.png" alt="enter image description here"></a></p>
<p>I might have pressed something on my keyboard by accident. The spaces on my code turned into boxes and it's annoying. How do I remove it?</p>
| 2 |
Android NDK Linker wrong path
|
<p>I'm currently working with a NDK Project that uses shared libraries. And I have two shared libraries to integrate: libsatprotocol.so and libsat-tanca.so.</p>
<p>So I added to my Android.mk these libraries so I could make a wrapper. For libsatprotocol everything is working fine. But for libsat-tanca, I get a crash on android:</p>
<pre><code> java.lang.UnsatisfiedLinkError: dlopen failed: could not load library "/home/lucas/Rockspoon/satlib/Android/app/src/main/obj/local/armeabi/libsat-tanca.so" needed by "libsat-jni.so"; caused by library "/home/lucas/Rockspoon/satlib/Android/app/src/main/obj/local/armeabi/libsat-tanca.so" not found
at java.lang.Runtime.loadLibrary(Runtime.java:371)
at java.lang.System.loadLibrary(System.java:989)
</code></pre>
<p>So the weird thing is that this path in my computer path for the library, and I have no clue from where it is getting it. If I remove the libsat-tanca of the dependencies, it works fine (in libsatprotocol).</p>
<p>Here are my Android.mk:</p>
<pre><code>LOCAL_PATH := $(call my-dir)
#LOCAL_ALLOW_UNDEFINED_SYMBOLS=true
include $(CLEAR_VARS)
LOCAL_MODULE := sat-tanca
LOCAL_SRC_FILES := tanca/$(TARGET_ARCH_ABI)/libsat-tanca.so
include $(PREBUILT_SHARED_LIBRARY)
include $(CLEAR_VARS)
LOCAL_MODULE := sat-dimep
LOCAL_SRC_FILES := dimep/$(TARGET_ARCH_ABI)/libsatprotocol.so
include $(PREBUILT_SHARED_LIBRARY)
include $(CLEAR_VARS)
LOCAL_MODULE := sat-jni
LOCAL_SRC_FILES := satlib.c
LOCAL_LDLIBS += -L$(SYSROOT)/usr/lib -lz -llog
LOCAL_SHARED_LIBRARIES := sat-tanca sat-dimep
include $(BUILD_SHARED_LIBRARY)
</code></pre>
<p>Application.mk</p>
<pre><code>APP_ABI := armeabi #armeabi-v7a mips x86 x86_64
LOCAL_SRC_FILES := $(TARGET_ARCH_ABI)/libsatprotocol.so $(TARGET_ARCH_ABI)/libsat-tanca.so
</code></pre>
<p>SATControl.java</p>
<pre><code>static {
System.loadLibrary("sat-jni");
}
</code></pre>
<p>build.gradle (app)</p>
<p>apply plugin: 'com.android.application'</p>
<pre><code>android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
applicationId "com.rockspoon.libraries.satlib"
minSdkVersion 19
targetSdkVersion 23
versionCode 1
versionName "1.0"
ndk {
moduleName "sat-jni"
}
}
sourceSets.main {
jni.srcDirs = [] // This prevents the auto generation of Android.mk
jniLibs.srcDir 'src/main/libs' // This is not necessary unless you have precompiled libraries in your project.
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
task buildNative(type: Exec, description: 'Compile JNI source via NDK') {
def ndkDir = android.ndkDirectory
commandLine "$ndkDir/ndk-build",
'-C', file('src/main/jni').absolutePath, // Change src/main/jni the relative path to your jni source
'-j', Runtime.runtime.availableProcessors(),
'all',
'NDK_DEBUG=1'
}
task cleanNative(type: Exec, description: 'Clean JNI object files') {
def ndkDir = android.ndkDirectory
commandLine "$ndkDir/ndk-build",
'-C', file('src/main/jni').absolutePath, // Change src/main/jni the relative path to your jni source
'clean'
}
clean.dependsOn 'cleanNative'
tasks.withType(JavaCompile) {
compileTask -> compileTask.dependsOn buildNative
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.4.0'
}
</code></pre>
<p>Any idea why it is linking just the libsat-tanca.so with my PC path?</p>
| 2 |
Python2.7: How to create bar graph using index and column information?
|
<p>I have just started learning Python 2.7 for data science and encounter a difficulty which I could not solve after googling... I would appreciate if you could help me how to create a bar graph.</p>
<p>So I have a data frame like this.
<a href="https://i.stack.imgur.com/aHKvR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aHKvR.png" alt="dataframe I have"></a>
I created this data frame from original data using the pivot table, allocating popular activities as an index and countries in column. The data inside is a total # of votes for popular activity in each country.
From this I would like to make bar graphs based on each country. It could look like something like this.
<a href="https://i.stack.imgur.com/5VbEG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5VbEG.png" alt="this is a graph I want"></a></p>
<p>I would appreciate if anyone could give me some tips to make this kind of graph? I could not figure out how I allocate index on y axis and frequency in x axis.</p>
<p>Thank you!</p>
| 2 |
Insert 2 values from two different tables into one table
|
<p>I have a problem with insert 2 values from 2 different tables during inserting to third table.</p>
<p>First table is:</p>
<ul>
<li>author_id (PK)</li>
<li>author_name</li>
<li>author_email</li>
</ul>
<p>Second table is:</p>
<ul>
<li>category_id (PK)</li>
<li>category_name</li>
</ul>
<p>Third table is:</p>
<ul>
<li>post_id</li>
<li>post_category</li>
<li>post_author</li>
<li>post_title</li>
<li>post_content</li>
<li>post_date</li>
</ul>
<p>and I want get <code>author_name</code> from the first table and <code>category_name</code> from the second table during inserting data into third table. </p>
<p>I got something like this but it's not working.</p>
<pre><code>INSERT INTO posts (post_category, post_author, post_title, post_content)
SELECT
category_name
FROM
categories
WHERE
category_name='python',
SELECT
author_name
FROM
authors
WHERE
author_name = 'm0jito',
'Lorem Ipsum',
'Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum ')
</code></pre>
<p>Looking forward for your help. </p>
| 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.