input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
How to iterate through a property in object within an array in Angular? <p>In AngularJs, I'm using ng-repeat option to display <code>questionText</code> property inside each object in an array.</p>
<pre><code>[{
"_id": "57fa2df95010362edb8ce504",
"__v": 0,
"answers": [],
"options": [],
"questionText": "what is your name?,What is your qualification?,Which city do you reside in?",
"questionId": "H1Mb0jPA",
"surveyId": "ryVj6Pf0"
}, {
"_id": "57fa441e5010362edb8ce507",
"__v": 4,
"answers": [],
"options": ["BE", "MBA", "MS", "MTech"],
"questionText": "What is your degree name?",
"questionId": "BJPQ46vC",
"surveyId": "ryVj6Pf0"
}, {
"_id": "57fa6fb65010362edb8ce509",
"__v": 0,
"answers": [],
"options": [],
"questionText": "Which city do you live in?",
"questionId": "ryA2Jgd0",
"surveyId": "ryVj6Pf0"
}, {
"_id": "57fa70125010362edb8ce50a",
"__v": 0,
"answers": [],
"options": [],
"questionText": "Have you tried this product?",
"questionId": "BJqGlxOR",
"surveyId": "ryVj6Pf0"
}, {
"_id": "57fa71085010362edb8ce50b",
"__v": 0,
"answers": [],
"options": [],
"questionText": "wassup?",
"questionId": "H1WMbluC",
"surveyId": "ryVj6Pf0"
}]
</code></pre>
<p>The above is the array that I'm trying to go through.</p>
<p>This is my HTML code for the <code>ng-repeat</code>.</p>
<pre><code><div ng-controller="viewQuestionController as viewQuestions">
<div ng-repeat="questionText in viewQuestions.questions">
<h2>{{viewQuestions.questions[0].questionText}}</h2>
</div>
</div>
</code></pre>
<p>It just iterates through the object in the first index 5 times. How do I make it iterate through each object?
I tried <code>viewQuestions.questions.questionText</code> and <code>viewQuestions.questions[].questionText</code>
Neither of it is working.</p>
| <p>questionText property value would be displayed like the below in ng-repeat ,where questionText in ng-repeat will represent object in questions list</p>
<pre><code><div ng-controller="viewQuestionController as viewQuestions">
<div ng-repeat="questionText in viewQuestions.questions">
<h2>{{questionText.questionText}}</h2>
</div>
</code></pre>
<p></p>
<p>You should rename the questionText in ng-repeat to like question so each repeated div will represent a question in questions list/array.</p>
<pre><code><div ng-controller="viewQuestionController as viewQuestions">
<div ng-repeat="question in viewQuestions.questions">
<h2>{{question.questionText}}</h2>
</div>
</code></pre>
<p></p>
<p>ng-repeat expression -</p>
<pre><code>ng-repeat="variable in expression"
</code></pre>
<p>where variable is the user defined loop variable and expression is a scope expression giving the collection to enumerate.
Read more here - <a href="https://docs.angularjs.org/api/ng/directive/ngRepeat" rel="nofollow">https://docs.angularjs.org/api/ng/directive/ngRepeat</a> </p>
|
How to send a single message to multi connections using UE? <p>I have tried to send messages to various connections via unification engine and it works fine. It's mentioned here (<a href="https://developer.unificationengine.com/" rel="nofollow">https://developer.unificationengine.com/</a>) that its possible to send only one message to unification engine mentioning various connections and it sends it to respective social media apps. However, I am not able to find a way to get it to work. Please advise if anyone has tried.</p>
<p>Appreciate your help!</p>
<p>Thanks & Best Regards,
Anand Patil</p>
| <p>It is possible to send same message to multiple connections via unification engine.
The following command will send the same messsage to two facebook connections and a twitter connection</p>
<p>curl -XPOST <a href="https://apiv2.unificationengine.com/v2/message/send" rel="nofollow">https://apiv2.unificationengine.com/v2/message/send</a> --data "{ \"message\": {
\"receivers\": [</p>
<p>{\"name\": \"Me\", \"address\": \"\" , \"Connector\": \"UNIQUE_CONNECTION_IDENTIFIER_FACEBOOK_1\"},</p>
<p>{\"name\": \"Me\", \"address\": \"\" , \"Connector\": \"UNIQUE_CONNECTION_IDENTIFIER_FACEBOOK_2\"},</p>
<p>{\"name\": \"name\", \"address\": \"TWITTER_HANDLE\" , \"Connector\": \"UNIQUE_CONNECTION_IDENTIFIER_TWITTER_1\"}</p>
<p>],</p>
<p>\"parts\": </p>
<p>[{\"id\": \"1\",\"contentType\": \"text/plain\", \"data\":\"MESSAGE_BODY\" ,\"size\": MESSAGE_BODY_SIZE,\"type\": \"body\",\"sort\":0}]</p>
<p>}}" -u USER_ACCESSKEY:USER_ACCESSSECRET -k</p>
|
How to dynamically load email configuration file as per database in rails <p>We write all email configuration information in development.rb file.Is it possible to save all this information in database and if we change our database then email will be gone as per our database and All the records must be fetched from the database and the email must be sent as per that.</p>
| <p>You can save the settings in a separate table in the DB, and load it from the DB dynamically in your settings file or when even needed.</p>
<p>A major downside for that would be performances - you will take a big hit for accessing DB to fetch these settings. possible solution here would be using caching. </p>
|
NSURL with JSON returns null <p>I'm keep getting a <code>(null)</code> error when I try to build my NSURL to open another app.</p>
<p>The URL should be </p>
<p><code>ms-test-app://eventSourceId=evtSrcId&eventID=13675016&eventType=0&json={"meterresults":[{"clean":"2","raw":"2","status":"0"}]}</code></p>
<p>but when I try to build my URL it's always null.</p>
<p>At first I thought it has something to do with the URL itself, but it's the same as I got it from the example <a href="https://github.com/Movilizer/movilizer-external-events-ios" rel="nofollow">here</a>.</p>
<p>Another thought was that IOS got some problems with the double quotes in the JSON, but I replaced them with <code>%22</code>, but this doesn't work either.</p>
<p>Here is the code, where I build the URL:</p>
<pre><code>NSString *jsonString = [NSString stringWithFormat:@"{%22meterresults%22:[{%22clean%22:%22%@%22,%22raw%22:%22%@%22,%22status%22:%22%@%22}]}", cleanReadingString, rawReadingString, status];
NSLog(@"JSON= %@",jsonString);
//Send the result JSON back to the movilizer app
NSString *eventSourceId = @"evtSrcId";
NSString *encodedQueryString = [NSString stringWithFormat:@"?eventSourceId=%@&eventID=%d&eventType=0&json=%@",
eventSourceId, _eventId, jsonString];[NSCharacterSet URLQueryAllowedCharacterSet]]
NSString *urlStr = [NSString stringWithFormat:@"%@%@",
[_endpointUrls objectForKey:[NSNumber numberWithInt:(int)_selectedEndpoint]],
encodedQueryString];
NSURL *url = [NSURL URLWithString:urlStr];
</code></pre>
<p>I don't know where I'm wrong and I would be glad if someone got any idea.</p>
<p>Thanks in advance.</p>
| <p>You should really be using <code>NSURLComponents</code> to create URLs rather than trying to format them into a string. </p>
<pre><code> NSDictionary* jsonDict = @{@"clean": @"2", @"raw": @"2", @"status": @"0"};
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:0 error:NULL];
NSString* jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSURLComponents* components = [[NSURLComponents alloc] init];
components.scheme = @"ms-test-app";
components.queryItems = @[
[[NSURLQueryItem alloc] initWithName:@"eventSourceId" value:eventSourceId],
[[NSURLQueryItem alloc] initWithName:@"eventID" value:@(_eventId).stringValue],
[[NSURLQueryItem alloc] initWithName:@"json" value:jsonString]
];
NSURL* url = components.URL;
</code></pre>
<p>Once you build the URL that way, it becomes apparent that your string doesn't have a host portion (or more accurately, one of your parameters is being used as the host portion).</p>
<p>The other comments about not being able to send JSON as an URL parameter are incorrect. As long as the system on the other side that is parsing the query string can handle it, you can send anything you want as an URL parameter.</p>
|
Run a Process silently in background without any window <p>I want to run NETSH command silently (with no window).
I wrote this code but it does not work.</p>
<pre><code>public static bool ExecuteApplication(string Address, string workingDir, string arguments, bool showWindow)
{
Process proc = new Process();
proc.StartInfo.FileName = Address;
proc.StartInfo.WorkingDirectory = workingDir;
proc.StartInfo.Arguments = arguments;
proc.StartInfo.CreateNoWindow = showWindow;
return proc.Start();
}
string cmd= "interface set interface name=\"" + InterfaceName+"\" admin=enable";
ExecuteApplication("netsh.exe","",cmd, false);
</code></pre>
| <p>This is how I do it in a project of mine:</p>
<pre><code>ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "netsh";
psi.UseShellExecute = false;
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
psi.Arguments = "SOME_ARGUMENTS";
Process proc = Process.Start(psi);
proc.WaitForExit();
string errorOutput = proc.StandardError.ReadToEnd();
string standardOutput = proc.StandardOutput.ReadToEnd();
if (proc.ExitCode != 0)
throw new Exception("netsh exit code: " + proc.ExitCode.ToString() + " " + (!string.IsNullOrEmpty(errorOutput) ? " " + errorOutput : "") + " " + (!string.IsNullOrEmpty(standardOutput) ? " " + standardOutput : ""));
</code></pre>
<p>It also accounts for the outputs of the command.</p>
|
Ruby sub not applying in the output file using IO.write <p>I have an issue about getting the same result in the output txt file that I get applying the sub method in a string. So the thing is when I apply the following code in a single string I get the \n before the capital letter in the middle of the string:</p>
<pre><code>line3= "We were winning The Home Secretary played a
important role."
line3.sub(/(?<!^) *+(?=[A-Z])/, "\n")
=> "We were winning\nThe Home Secretary played a\n important role."
</code></pre>
<p>But if I apply the following code the txt file that I get doesn't have any \n before the capital letter.</p>
<pre><code>old= File.readlines("Modificado word.txt")
second= old.join
third= second.sub(/(?<!^) *+(?=[A-Z])/, "\n")
new= IO.write("new.txt", third)
</code></pre>
<p>I've tried multiple ways of encoding(surely in the wrong way) because I thought the the issue might be there but any of them worked. Even the gsub, but didn't work either.</p>
| <p>Ok, I've got the solution, I don't know why but the type of encode of the txt file is in a format that the readlines command is not even able to read, so I copied all the content in another txt file which should be created from scratch and it worked :)</p>
|
How to use ManagedExecutorService with @Asynchronous method? <p>I have a Java EE app that's deployed on WildFly AS.
I have a method annotated with <code>@Asynchronous</code> and I need to set the max number of threads for this method.
I configured a new <code><managed-executor-service></code> in server config, but I don't know how to bind it to an async method.</p>
| <p>This link: <a href="https://developer.jboss.org/message/851027#851027" rel="nofollow">https://developer.jboss.org/message/851027#851027</a></p>
<p>provides a good answer to how (or when) to use @Asynchronous and when to use JSR-236 ExecutorService and concurrency utilities:</p>
<blockquote>
<p>In short, @Asynchronous is a annotation (EE6) to mark an EJB method as async.
You can invoke the method and keep the future object to check whether the method is finished and get the result. The EJB Concurrency Utilities are provided to have a safe way in EE7 to delegate work to a parallel thread. Threads started by this ConcurrentUtilities are managed by the container.
In difference to a direct start of a Thread (which is not allowed for an EE application). There is less overhead than using @Async and you have a bit more control.</p>
</blockquote>
<p>See also this link about how to inject a MES: </p>
<ul>
<li><a href="http://www.adam-bien.com/roller/abien/entry/injecting_an_executorservice_with_java" rel="nofollow">http://www.adam-bien.com/roller/abien/entry/injecting_an_executorservice_with_java</a></li>
</ul>
|
Facebook App review for B2B web based solutions <p>I have a ticketing solution that is configured to one FB page, from that FB page my application can read the post and comments ad create them as tickets. In a ticket I can post a comment back to the FB page. </p>
<p>My issue is this is not an app also users of the ticketing solution which are agents they dont login through FB, app has its own login module. </p>
<p>So how can I get my web based application reviewed when I cant create any Test Users as no can login with a FB account into the app.</p>
| <p>I totally agree with @Gary</p>
<p>According to the documentation of the <a href="https://developers.facebook.com/docs/apps/test-users/" rel="nofollow">test-users</a> in the facebook developer there are some important things to note while creating the test users</p>
<ul>
<li>They are invisible to the real accounts.</li>
<li>Test users are exempt from spam or fake detection systems so you can test the app without getting disabled</li>
</ul>
<p>Once you add a new test user you will be prompted with some of the options</p>
<p><strong>Number to Create</strong> determines how many individual test user accounts are created. If you want to create more in bulk, you should use the Graph API instead.</p>
<p><strong>Authorize Test Users</strong> for This App determines whether each newly created test account will already have logged into the app (using Facebook Login), without having to accept the Login Dialog, etc.</p>
<p><strong>Enable Ticker</strong> allows anyone logged into each of these test accounts to view the ticker for that user.</p>
<p><strong>Under 18</strong> determines whether the accounts will have an age under 18 years old, which is useful for testing demographic restrictions. You can still change this age later manually by logging into the test account.</p>
<p>Language chooses the locale that the test accounts will use to view Facebook.</p>
<p>This answers your question</p>
<p>//Full attribution goes to the <a href="https://developers.facebook.com/docs/apps/test-users/" rel="nofollow">documentation</a></p>
|
How to display image from current working directory in Python <p>I would like to display an image using multiple label in a GUI(Qt Designer). The image file should be grab from current working directory and display on it own label upon user press Push Button.</p>
<p>Image can be displayed in label_2 when i hardcoded the image directory path but not for label_1. </p>
<pre><code> def capture_image(self):
cam = cv2.VideoCapture(0)
print('Execute_captureImage')
i = 1
while i <= int(self.qty_selected):
# while i < 2:
ret, frame = cam.read()
cv2.imshow('Please review image before capture', frame)
if not ret:
break
k = cv2.waitKey(1)
if k % 256 == 27:
# ESC pressed
print("Escape hit, closing...")
break
if k % 256 == 32:
# SPACE pressed
self.img_name = self.lotId + '_{}.jpeg'.format(i)
path = 'c:\\Users\\Desktop\\Python\\Testing' + '\\' + self.lotId + '\\' + self.img_name
print('CurrentImage = ' + path)
if not os.path.exists(path):
print('Not yet exist')
cv2.imwrite(
os.path.join('c:\\Users\\Desktop\\Python\\Testing' + '\\' + self.lotId,
self.img_name),
frame)
print("{}".format(self.img_name))
# i += 1
break
else:
print('Image already exist')
i += 1
cam.release()
cv2.destroyAllWindows()
def display_image(self):
label_vid01 = 'c:\\Users\\Desktop\\Python\\Testing' + '\\' + self.lotId + '\\' + self.img_name
label_vid02 = 'c:\\Users\\Desktop\\Python\\Testing' + '\\' + self.lotId + '\\' + self.img_name
# label_vid03 = 'c:/Users/Desktop/Python/Image/image3.jpg'
self.label_vid01.setScaledContents(True)
self.label_vid02.setScaledContents(True)
self.label_vid03.setScaledContents(True)
self.label_vid01.setPixmap(QtGui.QPixmap(label_vid01))
self.label_vid02.setPixmap(QtGui.QPixmap(label_vid02))
print(repr(label_vid01))
print(os.path.exists(label_vid01))
</code></pre>
<p>May i know where is the mistake?</p>
<p>'self.lotId' is input text based on user input.</p>
<p><a href="http://i.stack.imgur.com/qXEtw.jpg" rel="nofollow">label snapshot</a></p>
| <p>The demo script below works for me on Windows XP. If this also works for you, the problem must be in the <code>capture_image</code> function in your example (which I cannot test at the moment).</p>
<pre><code>import sys, os
from PyQt4 import QtCore, QtGui
class Window(QtGui.QWidget):
def __init__(self):
super(Window, self).__init__()
layout = QtGui.QVBoxLayout(self)
self.viewer = QtGui.QListWidget(self)
self.viewer.setViewMode(QtGui.QListView.IconMode)
self.viewer.setIconSize(QtCore.QSize(256, 256))
self.viewer.setResizeMode(QtGui.QListView.Adjust)
self.viewer.setSpacing(10)
self.button = QtGui.QPushButton('Test', self)
self.button.clicked.connect(self.handleButton)
self.edit = QtGui.QLineEdit(self)
layout.addWidget(self.viewer)
layout.addWidget(self.edit)
layout.addWidget(self.button)
def handleButton(self):
self.viewer.clear()
name = self.edit.text()
for index in range(3):
pixmap = QtGui.QPixmap()
path = r'E:\Python\Testing\%s\%s_%d.jpg' % (name, name, index + 1)
print('load (%s) %r' % (pixmap.load(path), path))
item = QtGui.QListWidgetItem(os.path.basename(path))
item.setIcon(QtGui.QIcon(path))
self.viewer.addItem(item)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = Window()
window.setGeometry(800, 150, 650, 500)
window.show()
sys.exit(app.exec_())
</code></pre>
|
Nlog log file is not created <p>I am trying to log exceptions in console application. I have done everything as always (and then it worked for me...):</p>
<p>NLog.config:</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="false"
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
<targets>
<target name="LogFile" xsi:type="File"
fileName="${basedir}/Log/${date:format=yyyyMMdd} myLog.txt"
layout="${longdate}|${level:uppercase=true}|${message}|${exception}" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="LogFile" />
</rules>
</nlog>
</code></pre>
<pre><code>class Program
{
private static Logger _log = LogManager.GetCurrentClassLogger();
static void Main(string[] args)
{
_log.Error("test");
}
}
</code></pre>
<p>For some mysterious reason file is never created nowhere on my computer. Any ideas why</p>
| <p>Your config looks valid, so that shouldn't be the issue.</p>
<p>Some things to check:</p>
<ol>
<li><p>Is you nlog.config in the correct directory? The best way to test is to copy the nlog.config to the directory with your .dll or .exe.</p></li>
<li><p>Enable exceptions to be sure that errors are not captured by Nlog: <code>throwExceptions="true"</code></p></li>
<li><p>Check the internal log by setting <code>internalLogLevel="Info"</code> and check "c:\temp\nlog-internal.log"</p></li>
</ol>
<p>A full tutorial to troubleshoot could be found on the <a href="https://github.com/NLog/NLog/wiki/Logging-troubleshooting" rel="nofollow">NLog documentation</a>.</p>
|
implement linear probing in c++ for a generic type <p>I wanted to implement linear probing for hashtabe in c++,but the key,value
pair would be of generic type like: <strong>vector< pair< key,value> ></strong>(where key,value is of generic type).</p>
<p>Now,in linear probing if a cell is occupied we traverse the vector until we find an empty cell and then place the new pair in that cell.</p>
<p>The problem is,that in generic type,how would I be able to check if a particular cell is occupied or not?
I cannot use these conditions:</p>
<pre><code>if(key == '\0')//As key is not of type string
</code></pre>
<p><strong>OR</strong></p>
<pre><code>if(key == 0)//As key is not of type int
</code></pre>
<p>So,how will be able to check if a paricular cell in the vector is empty or not?
Please correct me if I misunderstood the concept.</p>
| <p>I think you can just check if the element of the vector has meaningful key and value:</p>
<pre><code>if(vector[i] == std::pair<key, value>())
//empty
</code></pre>
<p>or, if you only care about the keys</p>
<pre><code>if(vector[i].first == key())
//empty
</code></pre>
<p>This approach assumes that the default constructor of <code>key</code> type constructs an object that would be considered an "empty" or "invalid" key.</p>
|
Adding additional information to Simple Jquery FileUpload <p>I'm trying to integrate juqery fileupload with an ajax form submit. The ajax form sends the text and returns the ID of the newly created event, This is necessary to know which event to link with when uploading.
The simple upload demo uses the following code</p>
<p>Here's the ajax that first upload the non-file fields </p>
<pre><code>$.ajax({
type: 'post',
url: '/whats-on/upload-event/',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
traditional: true,
success: function (return_data) {
console.log(return_data)
}
});
</code></pre>
<p>It returns the following json </p>
<pre><code>Object {status: true, id: 17162}
</code></pre>
<p>However the fileupload sends the files without declaring <code>data: data,</code></p>
<pre><code><!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>jQuery File Upload Example</title>
</head>
<body>
<input id="fileupload" type="file" data-url="server/php/">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="js/vendor/jquery.ui.widget.js"></script>
<script src="js/jquery.iframe-transport.js"></script>
<script src="js/jquery.fileupload.js"></script>
<script>
$(function () {
$('#fileupload').fileupload({
dataType: 'json',
done: function (e, data) {
//Returns ID as e['id'] and 200 status also with e['status']
}
});
});
</script>
</body>
</html>
</code></pre>
| <p>You first need to get the event Id with an ajax post:</p>
<pre><code>function uploadClick(){
var eventId = getEvent();
uploadFile(eventId)
}
function getEvent(){
// make an ajax and return your id
}
</code></pre>
<p>One you got it, then create an URL with a query string indicating the eventId. this URL is where you want to post your file:</p>
<pre><code>function uploadFile(eventId){
// attatch the id to the URL with query string
url = url + '&eventId=' + eventId;
// submit here your file
}
</code></pre>
<p>This way you can post in the same ajax call the file itself and the event id. In you server side action you need to get this query string and then pick the posted file.</p>
|
Entity Framework Core Self reference optional property <p>I am using Microsoft.EntityFrameworkCore.Sqlite v1.0.1.
This is my entity:</p>
<pre><code>public class Category
{
public int CategoryId { get;set;}
public Category ParentCategory { get; set; }
public int? ParentCategoryId { get; set; }
public string Name { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateModified { get; set; }
}
</code></pre>
<p>So i need to configure ParentCategory as an optional property. How can i do this in EF core?
This is my fluent mapping until now:</p>
<pre><code>modelBuilder.Entity<Category>(e =>
{
e.HasKey(c => c.CategoryId);
e.Property(c => c.DateCreated).ValueGeneratedOnAdd();
e.Property(c => c.DateModified).ValueGeneratedOnAddOrUpdate();
});
</code></pre>
| <p>Your <code>ParentCategoryId</code> is already optional based on the fact that it is nullable. If it wasn't nullable, it would be required. You don't need to configure it further.</p>
<p>Note, you don't need to configure <code>CategoryId</code> as the Key for <code>Category</code>. It will be configured as the key because it already follows the naming convention for an entity key. </p>
|
Can't synchronize my threads in C <p>I've a problem when I try to sychronize my threads. I have the next code:</p>
<pre><code>static void* CarProcess(void *str);
int main()
{
thread_t *pthreadsArray;
pthreadsArray = (thread_t*)malloc(sizeof(thread_t) * 10);
for (int i = 0; i < 10; i++)
{
int pthread = mythread_create(&pthreadsArray[i], NULL, CarProcess, i);
}
for (int i = 0; i < 10; i++)
{
mythread_join(pthreadsArray[i], NULL);
}
}
static void* CarProcess(void *str)
{
while(1){
printf("Thread ID: %i\n", str);
}
}
</code></pre>
<p>When I execute the program, I have this output:</p>
<pre><code>Thread ID: 0
Thread ID: 0
Thread ID: 0
Thread ID: 0
...
</code></pre>
<p>But never appears "Thread ID: 1", "Thread ID: 2", "Thread ID: 3"....or "Thread ID: 9". I think that it could be solved using Mutex, locking and unloking Mutex.. Does any body have idea how to solve that? Thanks </p>
| <p>One possible source of the problem is that <code>str</code> is not really an <code>int</code> variable. You need to do some casting (both when creating the thread and when getting the argument).</p>
<p>To create a the thread and to properly pass the integer to ity ou first need to cast the value to an <code>intptr_t</code>, which is a <a href="http://en.cppreference.com/w/c/types/integer" rel="nofollow">standard integer type</a> big enough to fit both an integer or a pointer. Then you should cast it to a generic pointer (i.e. <code>void *</code>):</p>
<pre><code>pthread_create(&pthreadsArray[i], NULL, CarProcess, (void *) (intptr_t) i);
</code></pre>
<p>Then to get the integer value inside the thread function you need to do the opposite casting:</p>
<pre><code>static void* CarProcess(void *str)
{
int i = (int) (intptr_t) str;
printf("Thread ID: %i\n", i);
}
</code></pre>
|
What will be the AngularJS equivalent of jQuery's .bind() / .trigger() <p>I have this trigger / bind code:</p>
<p>service:</p>
<pre><code>$('body').trigger('ready');
</code></pre>
<p>directive:</p>
<pre><code> $('body').bind("ready", function(){
alert("Ready was triggered");
});
</code></pre>
<p>Can I do the exact same thing only using angular? If yes, how?</p>
| <p>You need to use events in AngularJS check the below sample example I hope it will be of help to you, please check <a href="https://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/" rel="nofollow">this</a> article for more information on <code>$emit</code>, <code>$on</code> and <code>$broadcast</code> event system in AngularJS</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>angular
.module('demo', [])
.controller('DefaultController', DefaultController)
.factory('helloService', helloService)
.directive('hello', hello);
function DefaultController() {
var vm = this;
}
helloService.$inject = ['$rootScope'];
function helloService($rootScope) {
var service = {
sendHello: sendHello
};
return service;
function sendHello() {
$rootScope.$broadcast('helloEvent', 'Hello, World!');
}
}
hello.$inject = ['$rootScope', 'helloService'];
function hello($rootScope, helloService) {
var directive = {
restrict: 'E',
scope: {
message: '='
},
link: linkFunc
}
return directive;
function linkFunc(scope, element, attrs, ngModelCtrl) {
scope.$on('helloEvent', function (event, data) {
element.text(data);
});
sendHello();
function sendHello() {
helloService.sendHello();
}
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo">
<div ng-controller="DefaultController as ctrl">
<hello></hello>
</div>
</div></code></pre>
</div>
</div>
</p>
|
How to develop NPM module for Ionic <p>I am developing library for Ionic 2, that should be installed via NPM, but i can't do this in classic way. If you want to develop module you can use <em>npm link</em> command to link module to your project where you want test and develop it, but in Ionic it everytime fall on compilation error, when is module linked using <em>npm link</em>.</p>
<p>This is error that i get evertime:</p>
<pre><code>[10:14:15] Error: Could not resolve entry (./.tmp/app/main.dev.js)
at /Users/daniel/ionic/cache-test/node_modules/rollup/dist/rollup.js:8602:28
at process._tickCallback (internal/process/next_tick.js:103:7)
</code></pre>
<p>So, is there any trick how to develop and test NPM module in Ionic 2?</p>
<p>Thanks.</p>
| <p>We did experiment with this, to share ngrx-based core module in between a web Angular2 app and an Ionic2 mobile app:
<a href="https://github.com/benorama/ngrx-demo-apps" rel="nofollow">https://github.com/benorama/ngrx-demo-apps</a></p>
<p>However, we did not manage to make it work through <code>npm link</code>, only with <code>npm pack/install</code>.</p>
<p>The trick is to define your external lib in a custom <code>rollup.config.js</code>. You can find more info here:
<a href="http://ionicframework.com/docs/v2/resources/third-party-libs/" rel="nofollow">http://ionicframework.com/docs/v2/resources/third-party-libs/</a>
<a href="http://ionicframework.com/docs/v2/resources/app-scripts/" rel="nofollow">http://ionicframework.com/docs/v2/resources/app-scripts/</a></p>
|
React Redux with redux-observable use the router to navigate to a different page after async action complete <p>I am using <a href="https://github.com/redux-observable/redux-observable" rel="nofollow">redux-observable</a> and this is my login epic:</p>
<pre><code>const login = ( action$ ) => {
return action$.ofType(SessionActions.LOGIN_USER)
.flatMap(( {payload} ) => {
return sessionService.login(payload)
.do(payload => {
sessionService.setSession(payload));
// Here I want to redirect the user back to his last location
}).map(result => ({
type: SessionActions.LOGIN_SUCCESS,
payload: result
}));
});
}
</code></pre>
<p>But how I am redirecting the user to a different page after the login action success.</p>
<p>What is the redux way to do this?</p>
| <p>I'm totally new to react/redux, but I face the same problem as you, so I create a small APP with a login page.</p>
<pre><code>// On your Login.JS you could implement the component lifecycle
componentWillReceiveProps(nextProps) {
if (nextProps.isAuthenticated){
this.context.router.push({pathname:'/'});
}
}
</code></pre>
<p>So, when your 'action' send to the 'reducer' the type: LOGIN_SUCCESS your going to change the corresponding state and when your component 'receive props' your going to check and redirect. I hope this small example help you.</p>
|
Capturing Ctrl+W on browser <p>First of all, I know there are plenty of questions about this matter already, I've searched for them and most of them are a few years old, that's the main reason I'm asking.</p>
<p>I kinda need to capture Ctrl+W Yes or Yes in all browsers (at least the most common ones, Chrome, Firefox and IE11/Edge, maybe Safari).</p>
<p>I'm running an Operative System virtualization inside a div and I want to block the Ctrl + W, so the browser doesn't close and the user can use this command in its virutalization (and if I can also other commands such as Ctrl + S, etc, but the most important one is the close command).</p>
<p>I've looked for plugins, hacks and vanilla JS code but none works, perhaps Ctrl + W is the most difficult command to capture. Do you guys know if its possible? And if it is, any ideas on how I could manage to do it? </p>
<p>Thanks.</p>
| <p>Just in case someone ends up in here.</p>
<p>As Jaromanda told in the comments section (and many others in other posts) <a href="https://developer.mozilla.org/es/docs/Web/API/WindowEventHandlers/onbeforeunload" rel="nofollow">window.onbeforeunload</a> is our best ally. In this precise case, it doesn't serve me well, as this prompts an alert and I just want to capture it so it doesn't really executes. Haven't found any answer to just capturing Ctrl + W as it's a complex thing to "abort" a close command.</p>
<p>EDIT #1:
It seems the problem is Chrome, you can capture these comands in Firefox (haven't tested them in IE/Edge nor Safari). If by any chance someone knows/comes up with any ideas, they will be gratefully accepted</p>
|
How can I handle camera and gallery output simultaneously, without using 2 times onActivityResult? <p>I have a dialogue, which asks you to choose if to take a picture or to upload one from gallery. The taken/chosen image I set as background on a Button. how can I handle both outputs, as I can't use 2 times onActivityResult?
Here is the method that invokes the camera: </p>
<pre><code>private void invokeCamera() {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
</code></pre>
<p>And the method that lets you choose from a gallery:</p>
<pre><code>private void openGallery() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
</code></pre>
<p>I handle the image received from the camera on the following way:</p>
<pre><code>protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && data != null) {
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = (Bitmap) extras.get("data");
if (photo != null) {
findViewById(), and whose background you want to update
if (Build.VERSION.SDK_INT > 16) {
imageUploader5.setBackground(new BitmapDrawable(getResources(), photo));
}
} else {
imageUploader5.setBackgroundDrawable(new BitmapDrawable(getResources(), photo));
}
}
}
}
}
</code></pre>
| <p>First, make a global variable</p>
<pre><code>private final static int GET_PHOTO_BITMAP = 1234;
</code></pre>
<p>Then do the following</p>
<pre><code>private void invokeCamera() {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, GET_PHOTO_BITMAP);
}
private void openGallery() {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, GET_PHOTO_BITMAP);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == GET_PHOTO_BITMAP && data != null) {
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = (Bitmap) extras.get("data");
if (photo != null) {
findViewById(), and whose background you want to update
if (Build.VERSION.SDK_INT > 16) {
imageUploader5.setBackground(new BitmapDrawable(getResources(), photo));
}
} else {
imageUploader5.setBackgroundDrawable(new BitmapDrawable(getResources(), photo));
}
}
}
}
}
</code></pre>
<p>Here the key part is request code which is the second parameter of the <code>startActivityForResult(Intent intent, int requestCode)</code></p>
<p>you can have different <code>requestCodes</code> for different operations and handle it this way in</p>
<pre><code>protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case code1:
//task1
break;
case code2:
//task2
break;
//and so on
}
}
</code></pre>
<p>but since your case both the callbakcs for <code>startActivityForResult()</code> are supposed to perform the same operation, you can pass same code for both the calls as I have done in the above solution. But make sure that you pass same code when the operations done in the callback are similar.</p>
|
Using external variables in Javascript <p>In my <code>views.py</code> I had things like that:</p>
<pre><code>...
if mymodel.name == 'Myname1':
#do something
elif mymodel.name == 'Myname2':
#do something else
...
</code></pre>
<p>but I didn't like it because if <code>Myname</code> change I should search all my code to correct it, so I create a file where I keep all this words:</p>
<p><code>hardcoded_words.py</code>:</p>
<pre><code>myname1='Myname1'
myname1='Myname2'
myname1='Myname3'
...
</code></pre>
<p>and my <code>views.py</code> become:</p>
<pre><code>from myapp import hardcoded_words
...
if mymodel.name==hardcoded_words.myname1:
#do something
elif mymodel.name==hardcoded_words.myname2:
#do something else
...
</code></pre>
<p>If Myname1 changes I need to correct just one file: </p>
<p><code>hardcoded_words.py</code>:</p>
<pre><code>...
myname1='Myname1_b'
...
</code></pre>
<p>Maybe there's some better way (fell free to tell) but the problem is with Javascript. There's a way to do something like that?</p>
<p>My javascript.js:</p>
<pre><code>function myfunction1(myvariable1, myvariable2) {
switch (myvariable1) {
case 'Myname1':
//do something
break;
case 'Myname2':
//do something else
break;
...
</code></pre>
<p>Thank you for your help</p>
| <p>If you really need to have the same list in javascript then I'd recommend creating a view you can call from an AJAX request that will just return the python dictionary that stores all of these values. This way there isn't any duplication and places where you'd need to update the same thing twice (DRY).</p>
<p>Then simply, in the areas where your logic will need to use this, make sure that this view is called before you ever use the values.</p>
<p>Ideally though, you may want to look into the logic involved here and see if there really is a requirement for "magic" strings.</p>
|
Chrome -- Access-Control-Allow-Origin <p><strong>chrome -- XMLHttpRequest cannot load <a href="http://127.0.0.1:3000/" rel="nofollow">http://127.0.0.1:3000/</a>. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.</strong></p>
<p>My web service is running in tomcat and it is returning the JSON response, I am trying to use D3.js tree to populate a tree with the JSON data. </p>
<p>When I inspect the elements in chrome I get the above error , I have tried to run lighttpd and did the configuration it looks like </p>
<pre><code>server.document-root = "http://127.0.0.1:8080/helloworld/rest/"
server.port = 3000
mimetype.assign = (
".html" => "text/html",
".txt" => "text/plain",
".jpg" => "image/jpeg",
".png" => "image/png"
)
</code></pre>
<p>and the url in postman works fine for lighttpd which the returns the exact JSON.</p>
<p>Please help me to get out of this situation.</p>
| <p>By requesting <code>http://127.0.0.1:3000/</code> from <code>http://127.0.0.1:8080</code> (and vice versa) you violate the <a href="https://www.w3.org/Security/wiki/Same_Origin_Policy" rel="nofollow">same origin policy</a>, because</p>
<blockquote>
<p>An origin is defined by the scheme, host, and port of a URL. </p>
</blockquote>
<p>Obviously, you haven't configured <a href="https://www.w3.org/TR/cors/" rel="nofollow">cross-origin resource sharing</a> on your server.</p>
<p>So you should configure the server to return the <a href="https://www.w3.org/TR/cors/#access-control-allow-origin-response-header" rel="nofollow"><code>Access-Control-Allow-Origin</code></a> HTTP response header. For instance,</p>
<pre><code>Access-Control-Allow-Origin: http://127.0.0.1:8080
</code></pre>
<p>or even (all origins)</p>
<pre><code>Access-Control-Allow-Origin: *
</code></pre>
|
Apple TV force focus another view <p>I'm working on Apple TV project. The project contains tab bar view controller, normally the tab bar will be appeared when swiping up on remote and hidden when swiping down. But now I reverse that behavior and I want to force focus another view when swiping up(normally focus on tab bar). Any way to do that? Thank you. </p>
| <p>I got the same issue with focus of UITabbarController before and I found the solution in Apple Support</p>
<blockquote>
<p>Because UIViewController conforms to UIFocusEnvironment, custom view
controllers in your app can override UIFocusEnvironment delegate
methods to achieve custom focus behaviors. Custom view controllers
can:</p>
<p>Override the preferredFocusedView to specify where focus should start
by default. Override shouldUpdateFocusInContext: to define where focus
is allowed to move. Override
didUpdateFocusInContext:withAnimationCoordinator: to respond to focus
updates when they occur and update your appâs internal state. Your
view controllers can also request that the focus engine reset focus to
the current preferredFocusedView by callingsetNeedsFocusUpdate. Note
that calling setNeedsFocusUpdate only has an effect if the view
controller contains the currently focused view.</p>
</blockquote>
<p>For more detail, please check this link
<a href="https://developer.apple.com/library/content/documentation/General/Conceptual/AppleTV_PG/WorkingwiththeAppleTVRemote.html#//apple_ref/doc/uid/TP40015241-CH5-SW14" rel="nofollow">https://developer.apple.com/library/content/documentation/General/Conceptual/AppleTV_PG/WorkingwiththeAppleTVRemote.html#//apple_ref/doc/uid/TP40015241-CH5-SW14</a></p>
|
Generate Signed APK: Project Name <p>While trying to publish my first Android App to Google play I was about to generate the signed APK when I noticed the module name is "app".</p>
<p>From the instructions I followed, I've understood this should be the actual name of my app? (my app's name is not "app", the package name does mention my app name.) </p>
<p>From the androidManifest.xml I have made the label name "blank", I removed my app name from there because I don't want the app name to appear in the action bar/tool bar. I've used my own special font for that.</p>
<p>Question 1:I am wondering what would happen if I just continue with "app" in module name, will my app be published with the name "app"? Do I have to change it to reflect my app's actual name? If yes then see question #2 below.</p>
<p>Question 2. If required to change then how I can change that folder name from "app" to my actual app name? Assuming changing this will then reflect the correct name in the module while generating the signed APK? The first folder in the top left corner under project is called "app"??</p>
| <p>Module name does not influence a name that your app is published with. See <a href="http://stackoverflow.com/questions/5443304/how-to-change-an-android-apps-name">here</a> how to do so (you need to change <code>label</code> in your manifest). By default, module name influences such internal things as a folder name or an APK file name generated by Android Studio. </p>
<p>Although you don't need to change <code>app</code> to match your application name in any way, you may want to give your project's modules some logical names that just make sense. To do so, use Refactor -> Rename feature of Android Studio (available on right click on module name). See <a href="http://stackoverflow.com/questions/26936812/renaming-modules-in-android-studio">here</a> for more information. </p>
|
Message: Call to undefined function redirect() <p>I am having a serious problem in using <code>redirect()</code> method. </p>
<p>This is my code;</p>
<pre><code>class ictcon extends CI_controller{
function __construct(){
parent::__construct();
if(!$this->session->userdata("in")) redirect("wew");
}
....
</code></pre>
<p>the other controller</p>
<pre><code><?php
class wew extends CI_controller{
function __construct(){
parent::__construct();
}
function index(){
$this->load->view("login");
}
}
</code></pre>
<p>It returns </p>
<blockquote>
<p>Call to undefined function redirect()</p>
</blockquote>
<p>Why would that be?</p>
| <p>This function belongs to the url helper. Try loading this helper in autoload file or run this before calling <code>redirect()</code>:</p>
<pre><code>$this->load->helper('url');
</code></pre>
|
When to use $ vs #? <p>I am confused about using <code>$ vs #</code>. I didn't found any guides for this. I used them as<br>
<code>name = #{name}</code>, <code>name like '%${word}%'</code>, <code>order by name ${orderAs}</code>,<code>where name = #{word}</code><br>
Sometimes , these are work fine but at the sometimes , parameters aren't included or gave me error like </p>
<blockquote>
<p>org.apache.ibatis.reflection.ReflectionException: There is no getter
for property named 'name'.......</p>
</blockquote>
<p>So, I'd like to know when to use <code>$</code> or <code>#</code> ? Can someone guide me please ?</p>
| <p>Following the <code>myBatis</code> guidelines <code>#{}</code> is used in your sql statements. </p>
<p>If you take a look any of MyBatis Reference in the Section <a href="http://www.mybatis.org/mybatis-3/sqlmap-xml.html#select" rel="nofollow">Mapper XML Files</a> it says explicity:</p>
<blockquote>
<p>Notice the parameter notation:</p>
<p><code>#{id}</code></p>
</blockquote>
<p>Otherwise <code>${}</code> is for </p>
<p>1- Configuration <a href="http://www.mybatis.org/mybatis-3/configuration.html#properties" rel="nofollow">properties</a>. </p>
<p>For example:</p>
<pre><code><properties resource="org/mybatis/example/config.properties">
<property name="username" value="dev_user"/>
<property name="password" value="F2Fa3!33TYyg"/>
</properties>
</code></pre>
<p>Then the properties can be used like next:</p>
<pre><code><dataSource type="POOLED">
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</code></pre>
<p>2- String Substitution <code>${}</code> (<a href="http://www.mybatis.org/mybatis-3/sqlmap-xml.html#Parameters" rel="nofollow">Parameters section</a>):</p>
<blockquote>
<p>By default, using the #{} syntax will cause MyBatis to generate
PreparedStatement properties and set the values safely against the
PreparedStatement parameters (e.g. ?). While this is safer, faster and
almost always preferred, sometimes you just want to directly inject a
string unmodified into the SQL Statement. For example, for ORDER BY,
you might use something like this:</p>
<p>ORDER BY ${columnName} </p>
<p>Here MyBatis won't modify or escape the string.</p>
<p>NOTE It's not safe to accept input from a user and supply it to a
statement unmodified in this way. This leads to potential SQL
Injection attacks and therefore you should either disallow user input
in these fields, or always perform your own escapes and checks.</p>
</blockquote>
<p>So definitively in <code>name like '%${word}%' or</code>order by name ${orderAs}` you need to use String substitution not a prepared statement.</p>
|
Insertion in sorted doubly linked list <p>I am given the pointer to the head node of a sorted doubly linked list and an integer to insert into the list.I am told to create a node and insert it into the appropriate position in the list such that its sorted order is maintained. The head node might be NULL.</p>
<p>Sample Input</p>
<p>NULL , data = 2 </p>
<p>NULL <-- 2 <--> 4 <--> 6 --> NULL , data = 5</p>
<p>Sample Output</p>
<p>NULL <-- 2 --> NULL</p>
<p>NULL <-- 2 <--> 4 <--> 5 <--> 6 --> NULL</p>
<p>I tried the above problem.But My program is terminating due to timeout.What am I doing wrong in the below code. Assume Node class and main function is already there. Many Thanks in advance!!</p>
<pre><code>Node SortedInsert(Node head,int data) {
Node newn = new Node();
newn.data = data;
newn.prev=null;
newn.next = null;
Node ptr = head;
Node nex=head.next;
while(ptr!=null && nex!=null) {
if(ptr.data<=newn.data && nex.data>=newn.data) {
newn.next = nex;
newn.prev = ptr;
nex.prev = newn;
ptr.next = newn;
}
else {
nex=nex.next;
ptr=ptr.next;
}
}
if(ptr!=null && nex==null) {
if(ptr.data>=newn.data) {
newn.next=ptr;
ptr.prev=newn;
newn.prev=null;
head=newn;
}
else {
ptr.next=newn;
newn.prev = head;
}
}
if(head==null) {
head = newn;
}
return head;
}
</code></pre>
| <p>Fairly simple:
You are not breaking out of the loop after succesfully inserting. Therefore it keeps looping over the position it inserts the node in. Make a tiny change:</p>
<pre><code>if(ptr.data>=newn.data)
{
newn.next=ptr;
ptr.prev=newn;
newn.prev=null;
head=newn;
break;
}
</code></pre>
<p>However, you have some redundant code written. This is shorter and doesn't contain redundant code:</p>
<pre><code>Node SortedInsert(Node head,int data) {
Node newn = new Node();
newn.data = data;
Node ptr = head;
if (ptr == null) {
head = newn;
} else if ( ptr.data > newn.data ) {
newn.next = ptr;
ptr.prev = newn;
head = newn;
} else {
Node nex = head.next;
while (nex != null && nex.data <= newn.data) {
ptr = nex;
nex = nex.next;
}
ptr.next = newn;
newn.prev = ptr;
if (nex != null) {
nex.prev = newn;
newn.next = nex;
}
}
return head;
}
</code></pre>
|
Call Skype ID from Twilio? <p>Is that possible to call a Skype ID (not a Skype number) using Twilio client application? If possible then how to accomplish this? Please help me if anyone have any idea.</p>
| <p>Twilio developer evangelist here.</p>
<p>I'm afraid that Twilio Client can only call phone numbers or other Twilio Client IDs and not a Skype ID.</p>
|
How can I reuse the same controller class using different constructor arguments <p>I have a controller that accepts some dependency as a constructor argument:</p>
<pre><code>public class AccountsController : ApiController
{
public AccountsController(IAccountsService accountService)
{
this.accountService = accountService;
}
// actions
}
public interface IAccountsService
{
IEnumerable<AccountDto> GetAccounts(string userName);
}
</code></pre>
<p>To resolve this dependency I use <a href="https://www.nuget.org/packages/Unity.WebAPI/" rel="nofollow">Unity.WebApi</a> package:</p>
<pre><code>public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// other configuration
config.DependencyResolver = new UnityDependencyResolver(myContainer);
}
}
</code></pre>
<p>I have two different implementations of <code>IAccountsService</code> and I'd like to expose both of them using the same controller class. From the routing perspective, I'd like to use different controller-level paths and the same underlying path structure for actions and parameters.</p>
<p>My way is to inherit two controllers from <code>AccountsController</code> and register them in <code>UnityContainer</code> to use different <code>IAccountsService</code> implementations.</p>
<pre><code>public class Accounts1Controller : AccountsController
{
public Accounts1Controller([Dependency("Service1")]IAccountsService accountService) :
base(accountService) { }
}
public class Accounts2Controller : AccountsController
{
public Accounts2Controller([Dependency("Service2")]IAccountsService accountService) :
base(accountService) { }
}
</code></pre>
<p>Is there a more straightforward way to do this?</p>
<p>I'd prefer to make the controller(s) container-unaware and to avoid the redundant inheritance (regardless to DI framework - Unity is not a single option).</p>
| <p>Here is one way to do it:</p>
<p>Let's say that the two routes are as follows:</p>
<pre><code>config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi2",
routeTemplate: "api2/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
</code></pre>
<p>You can make Unity resolve the correct service based on the Url of the request like this:</p>
<pre><code>//Map IAccountsService to AccountsService1 with name Service1
container.RegisterType<IAccountsService, AccountsService1>("Service1");
//Map IAccountsService to AccountsService2 with name Service2
container.RegisterType<IAccountsService, AccountsService2>("Service2");
//At composition time, map IAccountsService to appropriate
//service based on Url
container.RegisterType<IAccountsService>(new InjectionFactory(c =>
{
var pathAndQuery = HttpContext.Current.Request.Url.PathAndQuery;
if(pathAndQuery.StartsWith("/api2"))
return c.Resolve<IAccountsService>("Service2");
else if(pathAndQuery.StartsWith("/api"))
return c.Resolve<IAccountsService>("Service1");
throw new Exception("Unexpected Url");
}));
</code></pre>
<p><strong>UPDATE:</strong></p>
<p>In the case where Self-Hosting is used, <code>HttpContext.Current</code> would be null.</p>
<p>What you can do is create a custom <code>IHttpControllerActivator</code>. This will allow you customize the way controllers are created in a context where the current <code>HttpRequestMessage</code> is available.</p>
<p>Here is an example of such custom <code>IHttpControllerActivator</code>:</p>
<pre><code>public class MyControllerActivator : IHttpControllerActivator
{
public IHttpController Create(
HttpRequestMessage request,
HttpControllerDescriptor controllerDescriptor,
Type controllerType)
{
if (controllerType == typeof (ValuesController))
{
var pathAndQuery = request.RequestUri.PathAndQuery;
IAccountsService svc;
if (pathAndQuery.StartsWith("/api2"))
svc = new Service2();
else if (pathAndQuery.StartsWith("/api"))
svc = new Service1();
else
throw new Exception("Unexpected Url");
return new ValuesController(svc);
}
throw new Exception("Unexpected Controller Type");
}
}
</code></pre>
<p>You can get more details about this approach <a href="http://blog.ploeh.dk/2012/09/28/DependencyInjectionandLifetimeManagementwithASP.NETWebAPI/" rel="nofollow">here</a>.</p>
<p>Note that although the example I provided does not use a DI container (and thus uses <a href="http://blog.ploeh.dk/2014/06/10/pure-di/" rel="nofollow">Pure DI</a>), you should be able to make it work with a container.</p>
<p>Don't forget to remove the code that sets the <code>DependencyResolver</code> since we are using a different seam to extend the framework.</p>
|
Looping each row in file1.txt over all rows of file2.txt for comparing <p>I have two text files, say file1.txt contains something like</p>
<p>100.145 10.0728</p>
<p>100.298 10.04</p>
<p>and file2.txt contains something like</p>
<p>100.223 8.92739</p>
<p>100.209 9.04269</p>
<p>100.084 9.08411</p>
<p>100.023 9.01252</p>
<p>I want to compare column 1 and column 2 of both files and print match if the difference of both columns in file1.txt and in file2.txt is less or equal to 0.001.</p>
<p>since both files don't have equal no. or rows, i want row1 of file1.txt to be compared with all the rows of file2.txt, then it will now pick row2 of file1.txt and do same until all rows of file1.txt are exhausted. Difference should like this ($1 file1.txt - $1 file2.txt) and ($2 file1.txt - $2 file2.txt) if difference of both is less or equal 0.001, it should print the rows in both file that match</p>
| <p>you can try this;</p>
<pre><code>#!/bin/bash
while read line; do
while read line2; do
Col1F1=$(echo $line | awk '{print $1}')
Col1F2=$(echo $line2 | awk '{print $1}')
Col2F1=$(echo $line | awk '{print $2}')
Col2F2=$(echo $line2 | awk '{print $2}')
if [ ! -z "${Col1F1}" ] && [ ! -z "${Col1F2}" ]; then
diffCol1=$(awk '{print $1-$2}' <<< "$Col1F1 $Col1F2")
diffCol2=$(awk '{print $1-$2}' <<< "$Col2F1 $Col2F2")
if (( $(echo "$diffCol1 < 0.001" |bc -l) && $(echo "$diffCol2 < 0.001" |bc -l))); then
echo -e ${Col1F1} "\t" ${Col2F1} "\t" ${Col1F2} "\t" ${Col2F2} "\n"
fi
fi
done < file2.txt
done < file1.txt
</code></pre>
|
I've got a form filter but I also need to sort (MS Access VBA) <p>I've got an on_load sub to set the filter of a subform which liiks like this:</p>
<pre><code>Me.TabMonths.Pages("pge" & i).Controls("frmTileSchedule" & i).Form.Filter = "[MonthNo] = " & i & " and [YearNo] = " & intYear & ""
Me.TabMonths.Pages("pge" & i).Controls("frmTileSchedule" & i).Form.FilterOn = True
</code></pre>
<p>I now also need to sort it alphabetically on a field called 'Tile', and have tried </p>
<pre><code>DoCmd.SetOrderBy "Tile ASC"
</code></pre>
<p>As well as</p>
<pre><code>Me.TabMonths.Pages("pge" & i).Controls("frmTileSchedule" & i).Form.OrderBy = "Tile ASC"
</code></pre>
<p>But no luck with these. Can anyone help?</p>
| <p>It's similar to filtering:</p>
<pre><code>Me.TabMonths.Pages("pge" & i).Controls("frmTileSchedule" & i).Form.OrderBy = "Tile ASC"
Me.TabMonths.Pages("pge" & i).Controls("frmTileSchedule" & i).Form.OrderByOn= True
</code></pre>
|
making an arrow with before + after <p>Good day
I have a a link which must have text + arrow looking like this:</p>
<p><a href="http://i.stack.imgur.com/uNvQo.png" rel="nofollow"><img src="http://i.stack.imgur.com/uNvQo.png" alt="enter image description here"></a></p>
<p>I have done arrow,but dont know how to make that white background
the thing is i have to use pseudoelements</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-css lang-css prettyprint-override"><code>.hiretext{
margin-top:185px;
padding:5px 2px 5px 5px;
position:absolute;
background-color: #1a1e27;
color:white;
font-family:FrutigerCELight,Arial,Helvetica,sans-serif;
font-size:20px;
text-transform: uppercase;
font-weight: 900;
}
.hirelink{
display:inline-block;
width: 0;
height: 0;
border-top: solid transparent;
border-bottom: solid transparent;
border-left: solid black;
border-width:7px;
content:' ';
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="hiretext">
<a href="#" class="hirelink">
hire us
</a>
</div> </code></pre>
</div>
</div>
</p>
| <p>Here's how you create from pseudo element. Just change the color.</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-css lang-css prettyprint-override"><code>.hiretext {
margin-top:105px;
padding:5px 2px 5px 5px;
position:absolute;
color:white;
font-family:FrutigerCELight,Arial,Helvetica,sans-serif;
font-size:20px;
text-transform: uppercase;
font-weight: 900;
}
.hirelink {
position: relative;
}
.hirelink:after {
content: '';
border-left: 10px solid black;
border-top: 6px solid transparent;
border-bottom: 6px solid transparent;
width: 0;
height: 0;
position: absolute;
top: 10px;
right: -42px;
}
.hirelink:before {
content: '';
height: 30px;
width: 30px;
background: red;
border-radius: 50%;
position: absolute;
top: 0;
right: -50px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="hiretext">
<a href="#" class="hirelink"> hire us</a>
</div> </code></pre>
</div>
</div>
</p>
<p>Hope it helps. Cheers!</p>
|
How to auto open react DatePicker <p>I have the following code</p>
<pre><code> case 'date':
if (Modernizr.touchevents && Modernizr.inputtypes && Modernizr.inputtypes.date) {
element = (
<input
type='date'
id={this.props.id}
name={this.props.name}
onChange={arg => this.changeValue(moment(arg && arg.currentTarget ? arg.currentTarget.value : arg))}
onBlur={arg => this.blurValue(moment(arg && arg.currentTarget ? arg.currentTarget.value : arg))}
value={this.getValue() ? moment(this.getValue()).format('YYYY-MM-DD') : moment(this.props.minDate).format('YYYY-MM-DD')}
tabIndex={this.props.tabIndex}
min={this.props.minDate || null}
max={this.props.maxDate || null}
/>
);
} else {
element = (
<DatePicker
{...this.props}
name={this.props.name}
onChange={this.changeValue}
selected={this.getValue() || this.props.selected}
startDate={this.props.startDate || null}
endDate={this.props.endDate || null}
minDate={this.props.minDate || null}
tabIndex={this.props.tabIndex}
placeholderText={this.props.placeholder}
ref={this.props.elRef}
disabled={this.props.disabled}
showYearDropdown={this.props.showYearDropdown}
locale={this.lang}
/>
);
}
break;
}
</code></pre>
<p>This loads a react date picker on my landing page.</p>
<p>Since it's been used a lot, I'd like to make it more user-friendly by auto opening the datepicker when the page loads.
I've been searching a lot but I have not found an easy, direct approach to this.</p>
<p>I found this topic (<a href="https://github.com/Hacker0x01/react-datepicker/issues/276" rel="nofollow">https://github.com/Hacker0x01/react-datepicker/issues/276</a>) but since I'm a bit new to Javascript and React, I need a bit more explanations on how to implement this code in mine, so it would be awesome if anyone could explain to me where exactly I should put my code to implement this function</p>
<p>Thanks a lot everyone ! </p>
| <p>Have you tried adding the autofocus property, since the DatePicker opens OnFocus</p>
<pre><code><input type="text" name="inputname" autofocus>
</code></pre>
<p>should work :)</p>
<p>for your code:</p>
<pre><code> element = (
<input
type='date'
id={this.props.id}
name={this.props.name}
onChange={arg => this.changeValue(moment(arg && arg.currentTarget ? arg.currentTarget.value : arg))}
onBlur={arg => this.blurValue(moment(arg && arg.currentTarget ? arg.currentTarget.value : arg))}
value={this.getValue() ? moment(this.getValue()).format('YYYY-MM-DD') : moment(this.props.minDate).format('YYYY-MM-DD')}
tabIndex={this.props.tabIndex}
min={this.props.minDate || null}
max={this.props.maxDate || null}
autofocus
/>
);
</code></pre>
|
JavaScript test whether variable is a possible DOM element <p>This question has sort of been asked before, but (a) a long time ago and (b) some of the past answers include jQuery.</p>
<p>For current browsers (including IE >= 8) what is the simplest reliable way to test whether a variable is a DOM element?</p>
<p>I donât care whether the element is currently in the DOM. Iâm more interested in whether the variable contains a valid element object.</p>
<p>I am writing a function which needs to choose between a document element and a string. Here is my take on it:</p>
<pre><code>function doit(element) {
if (element instanceof Element) {
// document element
} else if (typeof element == 'string') {
// string
}
// else out of luck
}
</code></pre>
<p>Here have used <code>instanceof</code> for the Element and <code>typeof</code> for the string, piecing together what I have read elsewhere.</p>
<p>In todayâs browsers (and yesterday's if you include IE), is this the most efficient/correct method?</p>
<p>Thanks</p>
| <p>You could check it the other way around like:</p>
<pre><code>function doit(element) {
if(typeof element === 'string') { // to be save -> always use type check in js (===)
// string
}
else {
// assuming it is a document element
}
}
</code></pre>
<p>If you really want to check it on HTML element, you can also rely on <a href="http://stackoverflow.com/questions/5034067/jquery-test-whether-input-variable-is-dom-element">this post</a>.</p>
<p>Spoiler: <code>... instanceof HTMLElement</code></p>
|
get related data from ms dynamics crm using XRM SDK <p>I'm trying to retrieve data from crm in a .net application, using the SDK.
I've managed to do simple queries to retrieve lists, but I would now like to get the related entities with items, rather than the ids.</p>
<p>I have tried things like</p>
<pre><code>QueryExpression query = new QueryExpression
{
EntityName = "opportunity",
....
LinkEntity linkEntityAccount = new LinkEntity()
{
LinkFromEntityName = "opportunity",
LinkFromAttributeName = "opportunityid",
LinkToEntityName = "serviceappointment",
LinkToAttributeName = "regardingobjectid",
JoinOperator = JoinOperator.Inner,
Columns = new ColumnSet(new string[] { "scheduledstart", "scheduledend" }),
EntityAlias = "service"
};
query.LinkEntities.Add(linkEntityAccount);
</code></pre>
<p>(This will return a collection of entities from the opportunity table)</p>
<p>However the LinkedEntities just put the two columns in the returns entities. </p>
<p>What i would like is (say for this example) is a <code>entity.serviceappointment</code> to be the the entity containing the service appointment entity/data. Instead of in entity there being fields such as <code>service.scheduledstart</code> and <code>service.scheduledend</code></p>
<p>I have looked at the <code>Relationship</code> and <code>RelationshipQueryCollection</code> things in the SDK but i have been unable to setup a query that will do the query, without first getting the <code>opportunity</code> entities. But it looks like that maybe what I need? I'm not sure.</p>
<p>Is this even possible? Or should I just continue to query entities individually?</p>
<p>Thanks</p>
| <p>In the <code>QueryExpression</code> the <code>LinkEntity</code> represents a join. That's why the fields of the joined table are in the <code>Entity</code> row. They can be distinguished from the 'real' entity attributes by the fact that their names are prefixed (including a dot) and their values are wrapped in an <code>AliasedValue</code> object.</p>
<p>It is possible to unwrap them and create strong typed <code>Entity</code> objects, but you will need to write the code yourself.</p>
<p>Alternatively you can consider a few other options:</p>
<ol>
<li>Query for <code>serviceappointment</code> records and join the <code>opportunity</code> records.</li>
<li>Retrieve <code>opportunity</code> records one by one using the <code>RetrieveRequest</code> and include the query for the related service appointments in the request. (See also this discussion on <a href="http://stackoverflow.com/questions/33327565/what-is-the-differences-between-retrieverequest-and-iorganizationservice-retriev">StackOverflow</a>.)</li>
<li>Create an Action returning all data you need in a convenient <code>OrganizationResponse</code>.</li>
</ol>
|
iron-pages: Page Changed Event <p>Is there any event that can be captured by a web component when the page is changed, or even a lifecycle callback?</p>
<p>I tried using the attached callback but it doesn't being fired again..</p>
| <ul>
<li><p>From the parent element of <code><iron-pages></code>, you could <a href="https://www.polymer-project.org/1.0/docs/devguide/observers#change-callbacks" rel="nofollow">observe</a> changes to <a href="https://elements.polymer-project.org/elements/iron-pages#property-selected" rel="nofollow"><code><iron-pages>.selected</code></a> to monitor the page index/name:</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
<base href="https://polygit.org/polymer+1.7.0/components/">
<script src="webcomponentsjs/webcomponents-lite.min.js"></script>
<link rel="import" href="polymer/polymer.html">
<link rel="import" href="paper-button/paper-button.html">
<link rel="import" href="iron-pages/iron-pages.html">
</head>
<body>
<x-foo></x-foo>
<dom-module id="x-foo">
<template>
<iron-pages id="pages" selected="{{selected}}">
<div>One</div>
<div>Two</div>
<div>Three</div>
</iron-pages>
<paper-button on-tap="_prev">Prev</paper-button>
<paper-button on-tap="_next">Next</paper-button>
</template>
<script>
HTMLImports.whenReady(function() {
Polymer({
is: 'x-foo',
properties : {
selected: {
type: Number,
value: 0,
observer: '_selectedChanged'
}
},
_selectedChanged: function(newPage, oldPage) {
console.log('<iron-pages>.selected', 'new', newPage, 'old', oldPage);
},
_prev: function() {
this.$.pages.selectPrevious();
},
_next: function() {
this.$.pages.selectNext();
}
});
});
</script>
</dom-module>
</body></code></pre>
</div>
</div>
</p>
<p><sup><a href="http://codepen.io/tony19/pen/rrvVRB?editors=1011" rel="nofollow">codepen</a></sup></p></li>
<li><p>Or you could setup an <a href="https://www.polymer-project.org/1.0/docs/devguide/events#event-listeners" rel="nofollow">event listener</a> for the <a href="https://elements.polymer-project.org/elements/iron-pages#event-iron-select" rel="nofollow"><code><iron-pages>.iron-select</code></a> and <a href="https://elements.polymer-project.org/elements/iron-pages#event-iron-deselect" rel="nofollow"><code><iron-pages>.iron-deselect</code></a> events in order to watch the selected and deselected elements.</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
<base href="https://polygit.org/polymer+1.7.0/components/">
<script src="webcomponentsjs/webcomponents-lite.min.js"></script>
<link rel="import" href="polymer/polymer.html">
<link rel="import" href="paper-button/paper-button.html">
<link rel="import" href="iron-pages/iron-pages.html">
</head>
<body>
<x-foo></x-foo>
<dom-module id="x-foo">
<template>
<iron-pages id="pages" selected="0"
on-iron-select="_pageSelected"
on-iron-deselect="_pageDeselected">
<div>One</div>
<div>Two</div>
<div>Three</div>
</iron-pages>
<paper-button on-tap="_prev">Prev</paper-button>
<paper-button on-tap="_next">Next</paper-button>
</template>
<script>
HTMLImports.whenReady(function() {
Polymer({
is: 'x-foo',
_pageSelected: function(e) {
var page = e.detail.item;
console.log('page selected', page);
},
_pageDeselected: function(e) {
var page = e.detail.item;
console.log('page deselected', page);
},
_prev: function() {
this.$.pages.selectPrevious();
},
_next: function() {
this.$.pages.selectNext();
}
});
});
</script>
</dom-module>
</body></code></pre>
</div>
</div>
</p>
<p><sup><a href="http://codepen.io/tony19/pen/rrvVRB?editors=1011" rel="nofollow">codepen</a></sup></p></li>
<li><p>Or you could configure <a href="https://elements.polymer-project.org/elements/iron-pages#property-selectedAttribute" rel="nofollow"><code><iron-pages>.selectedAttribute</code></a> so that it sets an attribute on the newly and previously selected pages, which you could observe from within the page itself. When the page selection changes, the previously selected page's attribute is set to <code>false</code>, and the newly selected to <code>true</code>.</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
<base href="https://polygit.org/polymer+1.7.0/components/">
<script src="webcomponentsjs/webcomponents-lite.min.js"></script>
<link rel="import" href="polymer/polymer.html">
<link rel="import" href="paper-button/paper-button.html">
<link rel="import" href="iron-pages/iron-pages.html">
</head>
<body>
<x-foo></x-foo>
<dom-module id="x-foo">
<template>
<iron-pages id="pages" selected="0" selected-attribute="selected">
<x-page data-name="p1">One</x-page>
<x-page data-name="p2">Two</x-page>
<x-page data-name="p3">Three</x-page>
</iron-pages>
<paper-button on-tap="_prev">Prev</paper-button>
<paper-button on-tap="_next">Next</paper-button>
</template>
<script>
HTMLImports.whenReady(function() {
Polymer({
is: 'x-foo',
_prev: function() {
this.$.pages.selectPrevious();
},
_next: function() {
this.$.pages.selectNext();
}
});
});
</script>
</dom-module>
<dom-module id="x-page">
<template>
<content id="content"></content>
</template>
<script>
HTMLImports.whenReady(function() {
Polymer({
is: 'x-page',
properties: {
selected: {
type: Boolean,
value: false,
observer: '_selectedChanged'
}
},
_selectedChanged: function(selected) {
console.log('<x-page>.sel', this.dataset.name, selected);
}
});
});
</script>
</dom-module>
</body></code></pre>
</div>
</div>
</p>
<p><sup><a href="http://codepen.io/tony19/pen/yajNkm?editors=1001" rel="nofollow">codepen</a></sup></p></li>
</ul>
|
Google Dataproc node idle <p>One of my nodes in my Dataproc cluster is always idle when running a spark job. I've tried deleting and recreating the cluster ect. but it always has one idle node.</p>
<p>The reason seems to be indicated by these three lines from the log that come up every few seconds:</p>
<pre><code>Trying to fulfill reservation for application application_1476080745886_0001 on node: cluster-4-w-0.c.xxxx.internal:39080
Reserved container application=application_1476080745886_0001 resource=<memory:4608, vCores:1> queue=default: capacity=1.0, absoluteCapacity=1.0, usedResources=<memory:25600, vCores:6>, usedCapacity=0.90909094, absoluteUsedCapacity=0.90909094, numApps=1, numContainers=6 usedCapacity=0.90909094 absoluteUsedCapacity=0.90909094 used=<memory:25600, vCores:6> cluster=<memory:28160, vCores:40>
Skipping scheduling since node cluster-4-w-0.c.xxxx.internal:39080 is reserved by application appattempt_1476080745886_0001_000001
</code></pre>
<p>Node cluster-4-w-0.c.xxxx.internal is the idle one. Why is a node reserved by appattempt_1476080745886_0001_000001 and unusable as an executor?</p>
| <p>Since the app attempt, matches the Application ID of your Spark Application, I believe the app attempt is Spark's YARN AppMaster. By default, Spark AppMasters have the (somewhat excessive) same footprint as Executors (half a node). So by default half a worker should be consumed.</p>
<p>If you didn't change some memory configuration, I'm not sure why there wouldn't be at least one executor on that node. In any case you can shrink the AppMaster by decreasing <a href="http://spark.apache.org/docs/latest/running-on-yarn.html#spark-properties" rel="nofollow">spark.yarn.am.cores and spark.yarn.am.memory</a>.</p>
<p>You can better debug the container packing by SSHing into the cluster and running <code>yarn application -list</code> or by navigating to the <a href="https://cloud.google.com/dataproc/docs/concepts/cluster-web-interfaces" rel="nofollow">ResourceManager's WebUI</a>.</p>
|
Specific background color for Tk in Python <p>How to set specific color such as #B0BF1A instead of black,white,grey</p>
<pre><code>window.configure(background='white')
browse_label = gui.Label(window, text="Image path :", bg="white").place(x=20, y=20)
</code></pre>
| <p>I'm not sure whether this is compatible in python 2.7, but try this:
<a href="http://stackoverflow.com/questions/11340765/default-window-colour-tkinter-and-hex-colour-codes">Default window colour Tkinter and hex colour codes</a> </p>
<p>The code of the accepted answer is as follows (NOT MINE):</p>
<pre><code>import Tkinter
mycolor = '#%02x%02x%02x' % (64, 204, 208) # set your favourite rgb color
mycolor2 = '#40E0D0' # or use hex if you prefer
root = Tkinter.Tk()
root.configure(bg=mycolor)
Tkinter.Button(root, text="Press me!", bg=mycolor, fg='black',
activebackground='black', activeforeground=mycolor2).pack()
root.mainloop()
</code></pre>
|
How to save fileobject/stream to text file on disk in python? <p>I have a file object which is just a string with a large number of youtube urls taken from a playlist, how would I go about saving it to a .txt file?
Thanks</p>
| <p>Assuming your file object is f:</p>
<pre><code>with open("urls.txt", "w") as urls_file:
urls_file.write(f.read())
</code></pre>
<p>It may need improvement depending on the file size.</p>
|
What WordPress theme is this http://www.geekgiftsunder50.com? <p>Hello WordPress gurus can any one tell what theme is used in this website
<a href="http://www.geekgiftsunder50.com/" rel="nofollow">http://www.geekgiftsunder50.com/</a>
Its an Amazon Affialiate website can you guys suggest any theme close to it if not this</p>
| <p>I think it's this theme. If not, i think it's close.</p>
<p><a href="http://repick.wpsoul.net/" rel="nofollow">http://repick.wpsoul.net/</a></p>
<p>Hope this helps.</p>
|
ES6 + jQuery + Bootstrap - Uncaught ReferenceError: jQuery is not defined? <p>How can I import jQuery as the dependency for bootstrap in ES6?</p>
<p>I tried with:</p>
<pre><code>import {$,jQuery} from 'jquery';
import bootstrap from 'bootstrap';
</code></pre>
<p>But I always get this error:</p>
<blockquote>
<p>transition.js:59 Uncaught ReferenceError: jQuery is not defined</p>
</blockquote>
<p>Which points to this file:</p>
<pre><code>/* ========================================================================
* Bootstrap: transition.js v3.3.7
* http://getbootstrap.com/javascript/#transitions
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
// ============================================================
function transitionEnd() {
var el = document.createElement('bootstrap')
var transEndEventNames = {
WebkitTransition : 'webkitTransitionEnd',
MozTransition : 'transitionend',
OTransition : 'oTransitionEnd otransitionend',
transition : 'transitionend'
}
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return { end: transEndEventNames[name] }
}
}
return false // explicit for ie8 ( ._.)
}
// http://blog.alexmaccaw.com/css-transitions
$.fn.emulateTransitionEnd = function (duration) {
var called = false
var $el = this
$(this).one('bsTransitionEnd', function () { called = true })
var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
setTimeout(callback, duration)
return this
}
$(function () {
$.support.transition = transitionEnd()
if (!$.support.transition) return
$.event.special.bsTransitionEnd = {
bindType: $.support.transition.end,
delegateType: $.support.transition.end,
handle: function (e) {
if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments)
}
}
})
}(jQuery);
</code></pre>
<p>Any ideas?</p>
<p><strong>EDIT:</strong></p>
<p>my gulp file:</p>
<pre><code>var gulp = require('gulp');
var browserify = require('browserify');
var babelify = require('babelify');
var source = require('vinyl-source-stream');
var gutil = require('gulp-util');
gulp.task('es6', function() {
browserify({
entries: 'js/app.js',
debug: true
})
.transform(babelify, { presets: ['es2015'] })
.on('error',gutil.log)
.bundle()
.on('error',gutil.log)
.pipe(source('compile.js'))
.pipe(gulp.dest('js'));
});
gulp.task('default', ['es6']);
</code></pre>
<p><strong>EDIT 2:</strong> </p>
<p>package.json:</p>
<pre><code>{
"name": "es6",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-preset-es2015": "^6.16.0",
"babelify": "^7.3.0",
"browserify": "^13.1.0",
"gulp": "^3.9.1",
"gulp-uglify": "^2.0.0",
"gulp-util": "^3.0.7",
"pump": "^1.0.1",
"vinyl-source-stream": "^1.1.0"
},
"browser": {
"jquery": "./node_modules/jquery/dist/jquery.js",
},
"browserify-shim": {
"jquery": "$", // or change it to jQuery
},
"browserify": {
"transform": [
"browserify-shim"
]
}
}
</code></pre>
<p>error:</p>
<blockquote>
<p>Starting 'build'... events.js:160
throw er; // Unhandled 'error' event
^</p>
<p>Error: SyntaxError: Unexpected token } in JSON at position 526 while
parsing json file</p>
</blockquote>
| <p>In Webpack I usually use (<code>webpack.config.js</code>):</p>
<pre><code>externals: {
jquery: "jQuery"
}
</code></pre>
<p>And then:</p>
<pre><code>import jQuery from 'jQuery';
</code></pre>
<p>You could also try:</p>
<pre><code>import * as jQuery from 'jQuery';
</code></pre>
|
Developing algorithmic thinking <p>I encountered a question where a given array of integers I needed to find the pair which could satisfy the given sum.</p>
<p>The first solution that came to me was to check all possible pairs which was about O(n^2) time, but the interviewer requested me to come up with the improved run time at which I suggested to sort the array and then do binary search but that was also O(nlogn).</p>
<p>Overall I failed to come up with the O(n) solution. Googling that I came to know that it can be achieved via extra memory using set.</p>
<p>I know that there cannot be any fix rules to thinking about algorithms but I am optimistic and think that there must be some heuristic or mental model while thinking algorithms on array. I want to know if there is any generic strategy or array specific thinking which would help me explore more about solution rather than acting dead.</p>
| <p>Generally, think about how to do it naively first. If in an interview, make clear what you are doing, say "well the naive algorithm would be ...".</p>
<p>Then see if you can see any repeated work or redundant steps. Interview questions tend to be a bit unrealistic, mathematical special case type questions. Real problems more often come down to using hash tables or sorted arrays. A sort is N log N, but it make all subsequent searches O log N, so it's usually worth sorting data. If data is dynamic, keep it sorted via a binary search tree (C++ "set"). </p>
<p>Secondly, can you "divide and conquer" or "build up". Is the N = 2 case trivial? In than case, can we divide N = 4 into two N = 2 cases, and another integration step? You might need to divide the input into two groups, low and high, in which case it is "divide and conquer", or you might need to start with random pairs, then merge into fours, eights and so on, in which case it is "build up".</p>
<p>If the problem is geometrical, can you exploit local coherence? If the problem is realistic instead of mathematical, and there typical inputs you can exploit (real travelling salesmen don't travel between cities on a random grid, but over a hub and spoke transport system with fast roads connecting major cities and slow roads then branching out to customer destinations)?</p>
|
Is it possible to make image the primary key in sql? <p>hello guys i'm developing a face recognition program in c# using <code>eigenface algorithm</code>. </p>
<p>My program does save the live image to sql and if i want to retreive the image the program should compare to the sql if image in live capture and in sql database is equal then the image will retreive.</p>
<p><strong>ASK:</strong><br>
is it possible if the image will be the primary key? because im currently using the label that is attach to the face for comparing</p>
| <p>You could make a encoded picture out of it. For example converting it to Base64 <a href="http://stackoverflow.com/questions/17874733/converting-image-to-base64">Converting Image to Base64</a> and then comparing the strings. Or a Hash of the picture. <a href="http://www.vcskicks.com/image-hash.php" rel="nofollow">hash of a picture</a></p>
<p>I don't know what database you are using and if you can use blobs or something like that, but generally I wouldn't really suggest making an image a primary key on the first thought.</p>
|
Employee management database design <p>I am wondering about my database design is a bad design, especially at the jobhistory part. Anyone can advise me? Database is totally new to me and i still in learning process.</p>
<p><a href="http://i.stack.imgur.com/0y1dl.jpg" rel="nofollow">Employee management database ERD</a></p>
| <p>I think, you are keeping 'jobhistory' table for auditing purpose. Use Triggering. When Employee table updated position, then startdate, endDate as today and old position will be inserted in jobhistory table.</p>
<p>You can show Triggering in your ERD.</p>
<p>You can add following field in Employee table,</p>
<ul>
<li>status- currently employed/ absent /Disable</li>
<li>startDate- Start Date.</li>
</ul>
|
Windows: Operation could not be completed (error 0x00000002) while using rundll32 <p>I'm new with programming and came across this issue(I'm using windows 7 64x). I'm running this command <code>RUNDLL32.EXE PRINTUI.DLL,PrintUIEntry /ia /m "Printer" /f "C:\Program Files (x86)\Project\bin\drivers\Print\printer.inf</code> and it gives me error saying <code>Operation could not be completed (error 0x00000002)</code> I've searched around and found few solutions, like restarting <code>Print Spooler</code> and etc. But none of them worked for me, So I've searched and error <code>0x00000002</code> means <code>The system cannot find the file specified.</code> I've opened and inf file which looks like this:<br></p>
<pre><code>[Version]
Signature="$Windows NT$"
Provider="Ukve"
ClassGUID={4D36E979-D525-7CE-BLC1-08002BE10318}
Class=Printer
CatalogFile=printer.cat
DriverVer=03/26/2015,6
DriverPackageDisplayName="Printer Adapter"
[Manufacturer]
"Ukve" = printer, NTamd64
[printer]
"Ukve Printer" = printer.gpd, printer
[printer.NTamd64]
"Printer" = printer.gpd, printer
[printer.gpd]
CopyFiles=@printer.gpd
DataSection=UNIDRV_DATA
Include=NTPRINT.INF
Needs=UNIDRV.OEM,TTFSUB.OEM
[DestinationDirs]
DefaultDestDir=66000
[SourceDisksNames]
1 = "Printer Disk"
[SourceDisksFiles]
printer.gpd = 1
</code></pre>
<p>I can see that <code>printer.gpd</code> file is in same directory with the printer security catalog. My question is depending on this, what files could be missing? Hope you can hep, thanks.</p>
| <p>I think Windows cannot connect to the printer.please refer the below path:
<a href="https://support.microsoft.com/en-in/kb/2793718" rel="nofollow">https://support.microsoft.com/en-in/kb/2793718</a></p>
|
r ggplot error: Aesthetics must be either length 1 or the same as the data (250000): <p>I run sample code to generate a graph to describe Markov Chain Monte Carlo.
<a href="https://github.com/davharris/mcmc-tutorial" rel="nofollow">https://github.com/davharris/mcmc-tutorial</a>
However I encounter the following exception thrown by the last line of code.
"Error: Aesthetics must be either length 1 or the same as the data (250000): x, y"</p>
<p>The code has been listed in the following.</p>
<pre><code>library(MASS)
library(ggplot2)
lik = function(x, y) {
dnorm(x - 3) * dnorm(y - x + 2)
}
grid.values = seq(min.x, max.x, length = 500)
grid = expand.grid(x = grid.values, y = grid.values)
z = lik(grid$x, grid$y)
gaussian.plot = ggplot(data = grid, aes(x = x, y = y)) + geom_raster(aes(fill = z)) + scale_fill_gradient2() + coord_equal()
gaussian.plot
maxit = 50
samples = matrix(NA, nrow = maxit, ncol = 2, dimnames = list(NULL, c("x", "y")))
samples[1, ] = c(0, 0) # start at 0,0
for (i in 2:maxit) {
# propose a new sample point
proposal = samples[i - 1, ] + rnorm(2, mean = 0, sd = 1)
# Compare its likelihood with the current position
old.lik = lik(samples[i - 1, "x"], samples[i - 1, "y"])
new.lik = lik(proposal["x"], proposal["y"])
ratio = new.lik/old.lik
# flip a coin and accept the new proposal with probability min(ratio, 1)
if (rbinom(1, size = 1, prob = min(ratio, 1))) {
samples[i, ] = proposal
} else {
# If you don't accept the proposal, just keep what you had in the last
# time step
samples[i, ] = samples[i - 1, ]
}
}
gaussian.plot + geom_path(mapping = aes(x = samples[, "x"], y = samples[, "y"]),
color = "orange") + geom_point(mapping = aes(x = samples[, "x"], y = samples[,
"y"]))
</code></pre>
| <p><code>samples</code>is a matrix, convert it to a dataframe with <code>as.data.frame()</code> so that <code>ggplot2</code>can work with it.<br>
Since you want to have points that are from a different dataframe than the one used for the top plot which is <code>gaussian.plot</code>, you need to define where the data comes from.
This should work: </p>
<pre><code> gaussian.plot + geom_path(data=samples,aes(x = x, y = y),color = "orange") + geom_point(data=samples,aes(x = x, y = y))
</code></pre>
|
Collapse the result of the cartesian product <p>To calculate cartesian product with python is very simple. Just need to use
<a href="https://docs.python.org/3/library/itertools.html#itertools.product" rel="nofollow">itertools.product</a></p>
<pre><code>>>> source = [['a', 'b', 'c'], [1, 2, 3]]
>>> list(itertools.product(*source))
[('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3), ('c', 1), ('c', 2), ('c', 3)]
</code></pre>
<p>But I can't find the reverse operation. How to find the source <code>[['a', 'b', 'c'], [1, 2, 3]]</code> from the result of a product. Does anyone know the universal solution?</p>
<p>I appreciate any suggestions.</p>
| <p>Its only a partial solution but assuming you <strong>know for certain</strong> that the result is a valid cartesian product generated by <code>itertools.product</code> and it is over lists of <strong>distinct</strong> values</p>
<pre><code>>>> [list(collections.OrderedDict.fromkeys(y)) for y in zip(*cartesian_product)]
[['a', 'b', 'c'], [1, 2, 3]]
</code></pre>
<p>Here we simply use the <code>zip(*...)</code> idiom to unpack the tuples and then use <code>OrderedDict</code> in lieu of an <code>OrderedSet</code> to reduce them to their unique values.</p>
<p>This approach generalises to larger <code>itertools.product</code> of distinct values. For example:</p>
<pre><code>>>> source = [['a', 'b', 'c'], [1, 2, 3], [3, 5, 7]]
>>> cartesian_product = itertools.product(*source)
>>> [list(collections.OrderedDict.fromkeys(y)) for y in zip(*cartesian_product)]
[['a', 'b', 'c'], [1, 2, 3], [3, 5, 7]]
</code></pre>
|
Admob not working with webview <p>My problem is my app don't work anymore. But when I added admob. My webview don't show up anymore. I programmed my app in html and Css. Also now their are not adds showed to.</p>
<p>Main Activity.java</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>package webbased.wingcrony.by.worldconqueror3tipsandtricks;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.WebView;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.ads.AdRequest;
import static webbased.wingcrony.by.worldconqueror3tipsandtricks.R.id.activity_main_webview;
public class MainActivity extends Activity {
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView mWebView = (WebView) findViewById(activity_main_webview);
mWebView.loadUrl("file:///android_asset/www/index.html");
// Force links and redirects to open in the WebView instead of in a browser
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Main Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-HTTP-HOST-HERE]/main"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
@Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
@Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
}</code></pre>
</div>
</div>
</p>
<p>Activity_main.xml </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><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:ads="http://schemas.android.com/apk/res-auto">
<com.google.android.gms.ads.AdView
android:id="@+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
ads:adSize="BANNER"
ads:adUnitId="@string/banner_ad_unit_id"/>
<WebView
android:id="@+id/activity_main_webview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout></code></pre>
</div>
</div>
</p>
<p>build.gradle file</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>apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "24.0.3"
defaultConfig {
applicationId "webbased.wingcrony.by.worldconqueror3tipsandtricks"
minSdkVersion 11
targetSdkVersion 24
versionCode 3
versionName "3.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.google.android.gms:play-services-appindexing:9.6.1'
compile 'com.google.firebase:firebase-ads:9.6.1'
testCompile 'junit:junit:4.12'
return true
}
// `return void` removes the lint error: `Not all execution paths return a value`.
return void
}</code></pre>
</div>
</div>
</p>
<p>AndroidManifest.xml</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><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="webbased.wingcrony.by.worldconqueror3tipsandtricks">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter><!-- ATTENTION: This intent was auto-generated. Follow instructions at
https://g.co/AppIndexing/AndroidStudio to publish your URLs. -->
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<!-- ATTENTION: This data URL was auto-generated. We recommend that you use the HTTP scheme.
TODO: Change the host or pathPrefix as necessary. -->
<data
android:host="[ENTER-YOUR-HTTP-HOST-HERE]"
android:pathPrefix="/main"
android:scheme="http" />
</intent-filter>
</activity><!-- ATTENTION: This was auto-generated to add Google Play services to your project for
App Indexing. See https://g.co/AppIndexing/AndroidStudio for more information. -->
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
</application>
</manifest></code></pre>
</div>
</div>
</p>
<p>Can anyone helpme so my webview app work with admob?
I think I did something wrong. But I don't know what.</p>
| <pre><code> <com.google.android.gms.ads.AdView xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="@+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
ads:adSize="SMART_BANNER"
ads:adUnitId="@string/banner_ad_unit_id1"></com.google.android.gms.ads.AdView>
</code></pre>
<p>Use this code for AdView</p>
|
Select distinct rows order by highest values <p>I have a table like</p>
<hr>
<pre><code>Name | Image | Points | Country
-------------------------------
Bob | a.jpg | 100 | USA
Bob | b.jpg | 56 | USA
Sal | c.jpg | 87 | UK
Jim | d.jpg | 34 | UK
Bet | e.jpg | 23 | USA
Bren | f.jpg | 5 | USA
Bren | g.jpg | 15 | UK
Test | h.jpg | 10 | USA
</code></pre>
<p>I want to get the top 4 highest rows based on the "Points" column where the country is "USA" and removing duplicate "Names", so the desired outcome would be</p>
<hr>
<pre><code>Name | Image | Points | Country
-------------------------------
Bob | a.jpg | 100 | USA
Bet | e.jpg | 23 | USA
Test | h.jpg | 10 | USA
Bren | f.jpg | 5 | USA
</code></pre>
<p>Any help would be appreciated thank you</p>
| <pre><code>DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(image VARCHAR(12) NOT NULL PRIMARY KEY
,name VARCHAR(12) NOT NULL
,points INT NOT NULL
,country VARCHAR(12) NOT NULL
);
INSERT INTO my_table VALUES
('a.jpg','Bob' ,100,'USA'),
('b.jpg','Bob' , 56,'USA'),
('c.jpg','Sal' , 87,'UK'),
('d.jpg','Jim' , 34,'UK'),
('e.jpg','Bet' , 23,'USA'),
('f.jpg','Bren', 5,'USA'),
('g.jpg','Bren', 15,'UK'),
('h.jpg','Test', 10,'USA');
SELECT a.*
FROM my_table a
JOIN
( SELECT name,MAX(points) points FROM my_table WHERE country = 'USA' GROUP BY name ) b
ON b.name = a.name
AND b.points = a.points
ORDER
BY points DESC
LIMIT 4;
+-------+------+--------+---------+
| image | name | points | country |
+-------+------+--------+---------+
| a.jpg | Bob | 100 | USA |
| e.jpg | Bet | 23 | USA |
| h.jpg | Test | 10 | USA |
| f.jpg | Bren | 5 | USA |
+-------+------+--------+---------+
</code></pre>
|
Scala Spark count regex matches in a file <p>I am learning Spark+Scala and I am stuck with this problem. I have one file that contains many sentences, and another file with a large number of regular expressions. Both files have one element per line.</p>
<p>What I want is to count how many times each regex has a match in the whole sentences file. For example if the sentences file (after becoming an array or list) was represented by <code>["hello world and hello life", "hello i m fine", "what is your name"]</code>, and the regex files by <code>["hello \\w+", "what \\w+ your", ...]</code> then I would like the output to be something like: <code>[("hello \\w+", 3),("what \\w+ your",1), ...]</code></p>
<p>My code is like this:</p>
<pre><code>object PatternCount_v2 {
def main(args: Array[String]) {
// The text where we will find the patterns
val inputFile = args(0);
// The list of patterns
val inputPatterns = args(1)
val outputPath = args(2);
val conf = new SparkConf().setAppName("Simple Application")
val sc = new SparkContext(conf)
// Load the text file
val textFile = sc.textFile(inputFile).cache()
// Load the patterns
val patterns = Source.fromFile(inputPatterns).getLines.map(line => line.r).toList
val patternCounts = textFile.flatMap(line => {
println(line)
patterns.foreach(
pattern => {
println(pattern)
(pattern,pattern.findAllIn(line).length )
}
)
}
)
patternCounts.saveAsTextFile(outputPath)
}}
</code></pre>
<p>But the compiler complains:</p>
<p><a href="http://i.stack.imgur.com/q5zOR.png" rel="nofollow"><img src="http://i.stack.imgur.com/q5zOR.png" alt="enter image description here"></a></p>
<p>If I change the flatMap to just map the code runs but returns a bunch of empty tuples () () () ()</p>
<p>Please help! This is driving me crazy.
Thanks,</p>
| <p>As far as I can see, there are two issues here:</p>
<ol>
<li><p>You should use <code>map</code> instead of <code>foreach</code>: <code>foreach</code> returns <code>Unit</code>, it performs an action with a potential <em>side effect</em> on each element of a collection, it doesn't return a new collection. <code>map</code> on the other hand transform a collection into a new one by applying the supplied function to each element</p></li>
<li><p>You're missing the part where you <em>aggregate</em> the results of <code>flatMap</code> to get the actual count per "key" (pattern). This can be done easily with <code>reduceByKey</code></p></li>
</ol>
<p>Altogether - this does what you need:</p>
<pre><code>val patternCounts = textFile
.flatMap(line => patterns.map(pattern => (pattern, pattern.findAllIn(line).length)))
.reduceByKey(_ + _)
</code></pre>
|
pass parameters as per url in routing <p>I want to pass parameters from one action to another action.
my url routing is like below:</p>
<pre><code> routes.MapRoute("SearchDealbyPrice", "Deal/CategoriesID/{CategoriesID}/FromPrice/{FromPrice}/ToPrice/{ToPrice}/Price/{Price}/GreenCars/{GreenCars}/PageName/{PageName}", defaults: new { controller = "Deal", action = "Index" });
</code></pre>
<p>I need to display URL like below:</p>
<pre><code>Deal/CategoriesID/9/FromPrice/100/ToPrice/200/Price/0/GreenCars/0/PageName/Garrage
</code></pre>
<p>How can I achieve this from controller?
from controller I need to pass these parameters and URL should display like above.</p>
<p>Thanks
Lalitha</p>
| <p>Is it what you are looking for ?
I've added your route to RouteConfig and in DealController I've put a RedirectExample method :</p>
<pre><code>public ActionResult RedirectExample() {
return RedirectToRoute("SearchDealbyPrice", new {CategoriesID = 9,FromPrice = 100,ToPrice = 200,Price = 0,GreenCars = 0,PageName= "Garrage"}); }
</code></pre>
<p>It works fine. When I go to <a href="http://localhost:51639/Deal/RedirectExample" rel="nofollow">http://localhost:51639/Deal/RedirectExample</a> then route redirects to the Index method in the Deal controller and the result URL is as follows <a href="http://localhost:51639/Deal/CategoriesID/9/FromPrice/100/ToPrice/200/Price/0/GreenCars/0/PageName/Garrage" rel="nofollow">http://localhost:51639/Deal/CategoriesID/9/FromPrice/100/ToPrice/200/Price/0/GreenCars/0/PageName/Garrage</a></p>
|
Rails paperclip image size depending on device size <p>I'm using paperclip in my rails application for uploading images.
There are options to resize images.</p>
<pre><code>has_attached_file :photo, styles: {large: '1000x1000>', medium: '500x500>'}
</code></pre>
<p>Is it possible to take the large image for large devices like iPad oder Full HD screen, and for mobile devices the medium sized image?</p>
<p>I'm implementing the images like that:</p>
<pre><code><div class="teaser" style="background: url(<%=@object.photo_url %>)"></div>
</code></pre>
| <p>You have two options for this:</p>
<ol>
<li>Create multiple sizes when you save the image and reference them in the HTML</li>
<li>Save it at the largest size and resize it on demand</li>
</ol>
<p>For option 1, you can use the <a href="https://github.com/thoughtbot/paperclip#dynamic-styles" rel="nofollow">dynamic styles option</a> in the paperclip settings. </p>
<p>Having said that, I recommend option 2. We use <a href="https://www.imgix.com/" rel="nofollow">Imgix</a> at my current employer and it's been an amazingly good option for us. You upload the largest image you have to S3 and then control its size using GET parameters e.g. <code>httsp://yours3bucket.imgix.com/yourfolder/yourimage.png?width=205&height=354&hue=158</code> This has the enormous advantage of future-proofing your images as you don't need to regenerate them in different sizes if you change your mind about the resolutions you want - you just change the params in your HTML and Imgix sorts it out. You can also apply a load of dynamic effects like cropping the image, altering the colour balance etc. Only downside is it costs money, but depending on your use case, this could be very cost effective.</p>
<p>Either way, you then need to tell the browser to use the right size image. I'd recommend using <a href="http://caniuse.com/srcset/embed" rel="nofollow">srcset</a> to do this, although IE still doesn't support it. <a href="https://github.com/scottjehl/picturefill" rel="nofollow">This polyfill</a> is a good option in the meantime.</p>
|
Duplicating video Stream Actionscript 3 <p>Good Morning,</p>
<p>i am working on a video class, using a CRTMP Server for streaming. This works fine, but for my solution i need to duplicate the video stream (for some effects).</p>
<p>I googled for duplicate MovieClips and tried to duplicate the video like this.</p>
<pre><code>import flash.display.*;
import flash.events.*;
import flash.net.*;
import flash.media.*;
import flash.system.*;
import flash.utils.ByteArray;
public class Main extends MovieClip
{
public var netStreamObj:NetStream;
public var nc:NetConnection;
public var vid:Video;
public var vid2:Video;
public var streamID:String;
public var videoURL:String;
public var metaListener:Object;
public function Main()
{
init_RTMP();
}
private function init_RTMP():void
{
streamID = "szene3.f4v";
videoURL = "rtmp://213.136.73.230/maya";
vid = new Video(); //typo! was "vid = new video();"
vid2 = new Video();
nc = new NetConnection();
nc.addEventListener(NetStatusEvent.NET_STATUS, onConnectionStatus);
nc.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
nc.client = {onBWDone: function():void
{
}};
nc.connect(videoURL);
}
private function onConnectionStatus(e:NetStatusEvent):void
{
if (e.info.code == "NetConnection.Connect.Success")
{
trace("Creating NetStream");
netStreamObj = new NetStream(nc);
metaListener = new Object();
metaListener.onMetaData = received_Meta;
netStreamObj.client = metaListener;
netStreamObj.play(streamID);
vid.attachNetStream(netStreamObj);
//vid2.attachNetStream(netStreamObj); // wont work
addChild(vid);
// addChild(vid2); // wont work either
//intervalID = setInterval(playback, 1000);
}
}
private function asyncErrorHandler(event:AsyncErrorEvent):void
{
trace("asyncErrorHandler.." + "\r");
}
private function received_Meta(data:Object):void
{
var _stageW:int = stage.stageWidth;
var _stageH:int = stage.stageHeight;
var _videoW:int;
var _videoH:int;
var _aspectH:int;
var Aspect_num:Number; //should be an "int" but that gives blank picture with sound
Aspect_num = data.width / data.height;
//Aspect ratio calculated here..
_videoW = _stageW;
_videoH = _videoW / Aspect_num;
_aspectH = (_stageH - _videoH) / 2;
vid.x = 0;
vid.y = _aspectH;
vid.width = _videoW;
vid.height = _videoH;
vid2.x = 0;
vid2.y = _aspectH ;
}
}
</code></pre>
<p>It should be possible to duplicate the video stream. 2 Instance of the same videoStream. What am i doing wrong ?</p>
<p>Thanks for help.</p>
| <blockquote>
<ul>
<li><em>"This means that i have to double the netstream. This is not what i want."</em></li>
<li><em>"I tried to duplicate the video per <code>Bitmap.clone</code>. But i got an sandbox violation."</em></li>
</ul>
</blockquote>
<p>You can try the workaround suggested here: <a href="http://gamespoweredby.com/blog/2014/11/netstream-playnull-bitmapdata-workaround/" rel="nofollow"><strong><code>Netstream Play(null) Bitmapdata Workaround</code></strong></a></p>
<p>I'll show a quick demo of how it can be applied to your code.
This demo code assumes your canvas is width=550 & height=400. Keep that ratio if scaling up.</p>
<pre><code>package
{
import flash.display.*;
import flash.events.*;
import flash.net.*;
import flash.media.*;
import flash.system.*;
import flash.utils.ByteArray;
import flash.geom.*;
import flash.filters.ColorMatrixFilter;
public class Main extends MovieClip
{
public var netStreamObj:NetStream;
public var nc:NetConnection;
public var vid:Video;
public var streamID:String;
public var videoURL:String;
public var metaListener:Object;
public var vid1_sprite : Sprite = new Sprite();
public var vid2_sprite : Sprite = new Sprite();
public var vid2_BMP : Bitmap;
public var vid2_BMD : BitmapData;
public var colMtx:Array = new Array(); //for ColorMatrix effects
public var CMfilter:ColorMatrixFilter;
public function Main()
{
init_RTMP();
}
private function init_RTMP():void
{
streamID = "szene3.f4v";
videoURL = "rtmp://213.136.73.230/maya";
vid = new Video();
nc = new NetConnection();
nc.addEventListener(NetStatusEvent.NET_STATUS, onConnectionStatus);
nc.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
nc.client = { onBWDone: function():void { } };
//nc.connect(null); //for file playback
nc.connect(videoURL); //for RTMP streams
}
private function onConnectionStatus(e:NetStatusEvent):void
{
if (e.info.code == "NetConnection.Connect.Success")
{
trace("Creating NetStream");
netStreamObj = new NetStream(nc);
metaListener = new Object();
metaListener.onMetaData = received_Meta;
netStreamObj.client = metaListener;
//netStreamObj.play("vid.flv"); //if File
netStreamObj.play(streamID); //if RTMP
vid.attachNetStream(netStreamObj);
}
}
private function asyncErrorHandler(event:AsyncErrorEvent):void
{
trace("asyncErrorHandler.." + "\r");
}
private function received_Meta(data:Object):void
{
trace("Getting metadata");
var _stageW:int = stage.stageWidth;
var _stageH:int = stage.stageHeight;
var _videoW:int = data.width;
var _videoH:int = data.height;
var _aspectH:int = 0;
var Aspect_num:Number;
Aspect_num = data.width / data.height;
//Aspect ratio calculated here..
_videoW = _stageW;
_videoH = _videoW / Aspect_num;
_aspectH = (_stageH - _videoH) / 2;
trace("_videoW : " + _videoW);
trace("_videoW : " + _videoH);
trace("_aspectH : " + _aspectH);
vid.x = 0;
vid.y = 0;
vid.width = _videoW;
vid.height = _videoH;
setup_Copy(); //# Do this after video resize
}
public function setup_Copy () : void
{
vid2_BMD = new BitmapData(vid.width, vid.height, false, 0);
vid2_BMP = new Bitmap( vid2_BMD );
vid1_sprite.addChild(vid);
vid1_sprite.x = 0;
vid1_sprite.y = 0;
addChild( vid1_sprite );
vid2_sprite.addChild( vid2_BMP );
vid2_sprite.x = 0;
vid2_sprite.y = vid.height + 5;
addChild( vid2_sprite );
stage.addEventListener(Event.ENTER_FRAME, draw_Video);
}
public function draw_Video (evt:Event) : void
{
if ( netStreamObj.client.decodedFrames == netStreamObj.decodedFrames ) { return; } // Here we skip multiple readings
//# Get bitmapdata directly from container of video
if ( vid1_sprite.graphics.readGraphicsData().length > 0 )
{
vid2_BMD = GraphicsBitmapFill(vid1_sprite.graphics.readGraphicsData()[0]).bitmapData;
}
effect_BitmapData(); //# Do an effect to bitmapdata
}
public function effect_BitmapData ( ) : void
{
//# Matrix for Black & White effect
colMtx = colMtx.concat([1/3, 1/3, 1/3, 0, 0]); // red
colMtx = colMtx.concat([1/3, 1/3, 1/3, 0, 0]); // green
colMtx = colMtx.concat([1/3, 1/3, 1/3, 0, 0]); // blue
colMtx = colMtx.concat([0, 0, 0, 1, 0]); // alpha
CMfilter = new ColorMatrixFilter(colMtx);
vid2_BMP.bitmapData.applyFilter(vid2_BMD, new Rectangle(0, 0, vid.width, vid.height), new Point(0, 0), CMfilter);
}
}
}
</code></pre>
|
Cannot start container : [8] System error: exec: "up3": executable file not found in $PATH <p>I'm new to Stack Overflow and I checked the similar issue in Stack Overflow but not found what I expected answer. so hopefully my questions aren't too silly.
I cannot start my container after I created it.
I use the command:<strong><code>docker start 6069dba3cb02</code></strong>
and get the below error message:</p>
<pre><code>root@boot2docker:/mnt/sda1/var/lib/docker/containers# docker start 6069dba3cb02
Error response from daemon: Cannot start container 6069dba3cb02: [8] System error: exec: "up3": executable file not found in $PATH
Error: failed to start containers: [6069dba3cb02]
</code></pre>
<p><a href="http://i.stack.imgur.com/zx8DU.png" rel="nofollow">enter image description here</a>
The container info as below:</p>
<p>Even I use the other command: "<code>docker restart 6069dba3cb02</code>" or "<code>docker run ubuntu:14.04 up3</code>", I still get the error</p>
<p>Docker info: Operating System: Boot2Docker 1.8.0 (TCL 6.3);
Install path: <a href="https://github.com/boot2docker/windows-installer/releases" rel="nofollow">https://github.com/boot2docker/windows-installer/releases</a> </p>
| <p>What do you want to achieve with the parameter <code>up3</code>? This command is executed inside of the container you just started. But Ubuntu does not know this command, because it simply does not exist in the plain Ubuntu image (that's what the error message said: <code>executable file not found</code>).</p>
<p>Therefore you have to install your up3 tool before you try to access it. Or you have a misunderstanding about what up3 should do with your container, i don't know.</p>
<p>Try to replace <code>up3</code> with <code>ls /</code> or something like this to understand what the last arguments do when running docker:</p>
<pre><code>docker run --rm ubuntu ls /
</code></pre>
<p><code>--rm</code> removes the container after the command exits.</p>
<p>To give your container the name <code>up3</code>, you have to add this to your command:</p>
<pre><code>docker create --name up3 ubuntu:14.04
</code></pre>
<p>Then you can start your container by name:</p>
<pre><code>docker start up3
</code></pre>
|
django rest framework - Nested serialization not including nested object fields <p>i'm trying to get nested object fields populated, however the only thing being returned is the primary key of each object (output below):</p>
<pre><code>{
"name": "3037",
"description": "this is our first test product",
"components": [
1,
2,
3,
4
]
}
</code></pre>
<p>How do I have the component model's fields populated as well (and not just the PKs)? I would like to have the name and description included.</p>
<p><strong>models.py</strong></p>
<pre><code>class Product(models.Model):
name = models.CharField('Bag name', max_length=64)
description = models.TextField ('Description of bag', max_length=512, blank=True)
urlKey = models.SlugField('URL Key', unique=True, max_length=64)
def __str__(self):
return self.name
class Component(models.Model):
name = models.CharField('Component name', max_length=64)
description = models.TextField('Component of product', max_length=512, blank=True)
fits = models.ForeignKey('Product', related_name='components')
def __str__(self):
return self.fits.name + "-" + self.name
</code></pre>
<p><strong>serializers.py</strong></p>
<pre><code>from rest_framework import serializers
from app.models import Product, Component, Finish, Variant
class componentSerializer(serializers.ModelSerializer):
class Meta:
model = Component
fields = ('name', 'description', 'fits')
class productSerializer(serializers.ModelSerializer):
#components_that_fit = componentSerializer(many=True)
class Meta:
model = Product
fields = ('name', 'description', 'components')
#fields = ('name', 'description', 'components_that_fit' )
</code></pre>
<p>The <a href="http://www.django-rest-framework.org/api-guide/relations/#reverse-relations" rel="nofollow">documented approach</a> doesn't seem to be working for me, and gives me the following error (you can see the lines following the standard approach commented out in the serializers.py entry above:</p>
<p><code>Got AttributeError when attempting to get a value for field 'components_that_fit' on serializer 'productSerializer'.
The serializer field might be named incorrectly and not match any attribute or key on the 'Product' instance.
Original exception text was: 'Product' object has no attribute 'components_that_fit'.</code></p>
<p><strong>Update based on answer</strong></p>
<p>Thanks to @Carlton's answer below, here's what is working for me:
<em>serializers.py</em> was changed and now looks like this:</p>
<pre><code>class productSerializer(serializers.ModelSerializer):
components = componentSerializer(many=True)
class Meta:
model = Product
fields = ('name', 'description', 'components')
</code></pre>
| <p>By calling the field <code>components_that_fit</code>, you're having the serialiser look for an attribute by that name. (There isn't one, hence your error.)</p>
<p>Two ways to fix it:</p>
<ul>
<li>Call the field <code>components</code>, but declare it as <code>components = componentSerializer(many=True)</code> </li>
<li>Set <code>source='components'</code> <a href="http://www.django-rest-framework.org/api-guide/fields/#source" rel="nofollow">field option</a> when declaring the <code>components_that_fit</code> field. </li>
</ul>
<p>The reason you get primary keys is that, unless declared explicitly, <a href="http://www.django-rest-framework.org/api-guide/relations/#primarykeyrelatedfield" rel="nofollow">relations default to <code>PrimaryKeyRelatedField</code></a>.</p>
<p>I hope that helps. </p>
|
Angular2 HTTP POST An error occurred SyntaxError: Unexpected end of JSON input <p>I have error meantime angular2 post rest data to NodeJS backend.</p>
<p>I see POST is done, server is LOG correct data, but error is showing up on browser.</p>
<p>An error occurred:
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data</p>
<p>My NG2 call and service:</p>
<pre><code>onSubmit(form:FormGroup) {
let userform: FormGroup = form.value;
console.log("userform: ", userform);
if (form.valid) {
console.log(form.value);
this.appService.signIn(userform)
.subscribe(form => console.log('subscribe: ', form))
} else {
console.log("Form is not VALID!");
}
}
</code></pre>
<p>SERVICE: </p>
<pre><code>signIn(dataUser: Object): Observable<User> {
dataUser = JSON.stringify(dataUser);
debugger;
let headers = new Headers({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': 'http://127.0.0.1:3005'
});
let options = new RequestOptions({ headers: headers });
console.log("data: ", dataUser, "\nHeaders: ", headers);
return this.http
.post( this.signInUrl, dataUser, options)
.map( (res:Response) => res.json().data || { } as User )
.catch(this.handleError);
}
</code></pre>
<p>and nodeJS:</p>
<pre><code>app.post('/login', function (req, res) {
console.log("Recived login request!");
console.log("Request: ", req.body);
res.header({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE',
'Accept': 'q=0.8;application/json;q=0.9'
})
res.end();
});
</code></pre>
<p>In post we have: "{"username":"username","password":"password"}".</p>
<p>What I'am making wrong? Please for help or solution.</p>
| <p>Awwwww. That was my bad, Take care of your NodeJS Server response. After get POST, should be sended any <code>res.json({status: "OK"})</code> or sommething similar, to get response. This error was not because of Angular2, but because of NodeJS. Browser get empty response from nodeJS, or it was not JSON format.</p>
|
FluentValidation message for nested properties <p>I have a class with complex property:</p>
<pre><code>public class A
{
public B Prop { get; set; }
}
public class B
{
public int Id { get; set; }
}
</code></pre>
<p>I've added a validator:</p>
<pre><code>public class AValidator : AbstractValidator<A>
{
public AValidator()
{
RuleFor(x => x.A.Id).NotEmpty().WithMessage("Please ensure you have selected the A object");
}
}
</code></pre>
<p>But during client-side validation for A.Id I still have a default val-message: "'Id' must not be empty". How can I change it to my string from the validator?</p>
| <p>You can achieve this by using custom validator for nested object:</p>
<pre><code>public class AValidator : AbstractValidator<A>
{
public AValidator()
{
RuleFor(x => x.B).NotNull().SetValidator(new BValidator());
}
class BValidator : AbstractValidator<B>
{
public BValidator()
{
RuleFor(x => x.Id).NotEmpty().WithMessage("Please ensure you have selected the B object");
}
}
}
public class A
{
public B B { get; set; }
}
public class B
{
public int Id { get; set; }
}
</code></pre>
|
How to use a JPanel as JButton? <p>I must use a swing-ui designer tool to create my UI, that only supports graphically editing JPanels. Those panels (they basically contain complex button designs) to work like a JButton. I cannot use anything other than JPanel as base class of these panels (UI editor limitation).</p>
<p>What is the most generic solution to do this? </p>
<ul>
<li>Create a custom button that uses the panel's draw method instead of
it's own? </li>
<li>Create a base-panel class that reimplements the whole
button? </li>
<li>Another more elegant solution?</li>
</ul>
| <p>Here is a quick demo, to show you how you could use borders to simulate a button.</p>
<p>The demo also reacts to mouse and key events :</p>
<pre><code>import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
public class JPanelButton extends JPanel {
Border raisedetched = BorderFactory.createEtchedBorder(EtchedBorder.RAISED);
Border loweredetched = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED);
public static void main(final String[] args) {
JFrame frame = new JFrame();
final JPanelButton panel = new JPanelButton();
panel.raiseBorder();
panel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(final MouseEvent e) {
panel.lowerBorder();
}
@Override
public void mouseReleased(final MouseEvent e) {
panel.raiseBorder();
}
});
panel.setFocusable(true); // you need this or the panel won't get the key events
panel.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(final KeyEvent e) {
panel.lowerBorder();
}
@Override
public void keyReleased(final KeyEvent e) {
panel.raiseBorder();
}
});
frame.setContentPane(panel);
frame.setSize(100, 100);
frame.setVisible(true);
}
public void raiseBorder() {
setBorder(raisedetched);
}
public void lowerBorder() {
setBorder(loweredetched);
}
}
</code></pre>
|
Goto statement with condition in C <p>How to do goto statement with if and else condition
i want from my user to make a decision if he/she wants to startover or not</p>
<pre><code> loop1 :
printf("how many dagre entering ? \n");
scanf("%d", &NumOfGrade);
for ( i = 0 ; i < NumOfGrade ; i ++ ) {
printf("\nenter the grade\n");
scanf("%d", &grade);
totalGrade += grade ;
if ( grade < 12 )
failsCount ++;
}
ave = (float) totalGrade / NumOfGrade ;
printf("the ave of ur grade are : \n");
printf("%.2f\n", ave);
printf("%d subj fails\n", failsCount);
printf("do you want to startover ? (Y or N) \n");
ans = getchar();
if ( ans == 'Y')
goto loop1 ;
</code></pre>
<p>It's not going to loop1, and i cant see why.</p>
| <p>you did't clear input buffer, try this:</p>
<pre><code>loop1 :
printf("how many dagre entering ? \n");
scanf("%d", &NumOfGrade);
for ( i = 0 ; i < NumOfGrade ; i ++ ) {
printf("\nenter the grade\n");
scanf("%d", &grade);
totalGrade += grade ;
if ( grade < 12 )
failsCount ++;
}
ave = (float) totalGrade / NumOfGrade ;
printf("the ave of ur grade are : \n");
printf("%.2f\n", ave);
printf("%d subj fails\n", failsCount);
printf("do you want to startover ? (Y or N) \n");
__fpurge(stdin); // clear your input buffer, on window, try fflush(stdin)
ans = getchar();
if ( ans == 'Y')
goto loop1 ;
</code></pre>
|
Python google query with requests module, get responce in http format <p>I want to execute a google query with requests module in python. Here is my script:</p>
<pre><code>import requests
searchfor = 'test'
payload = {'q': searchfor, 'key': API_KEY, 'cx': SEARCH_ENGINE_ID}
link = 'https://www.googleapis.com/customesearch/v1'
r = requests.get(link, paramas=payload)
print r.content
</code></pre>
<p>and then run the script as: ./googler.py > out</p>
<p>and the out is in json format.</p>
<p>How can I get the responce in http format?</p>
| <p>The google api only supports <a href="https://developers.google.com/custom-search/json-api/v1/overview" rel="nofollow">atom/Json</a>. </p>
<p>So you have to parse the JSON to HTML.
You maybe want to check <a href="https://docs.python.org/2/library/json.html" rel="nofollow">json package</a>.</p>
<p>append something like this to your file:</p>
<pre><code>import json
items = json.loads(r)['items']
print "<html><body>"
for item in items:
print "<a href=" +item['url'] + ">" + item['title'] + "</a>"
print "</body></html>"
</code></pre>
|
Symfony 2.8 redirect to extenalURL with post data <p>How can i redirect a user to my client shop system and send POST login data to our client Shop system.</p>
<p>This is what the form looks like however its not secure as anybody can read the username and password</p>
<pre><code><form action="http://externalUrl/login.php" method="post" name="ExtLogin" target="_blank">
<input name="extlogin" value="1" type="hidden">
<input name="custno" value="11111" type="hidden">
<input name="custappno" value="1" type="hidden">
<input name="pwd" value="111111" type="hidden">
<button type="submit" href="#">Client Shop</button>
</code></pre>
<p>New Code:</p>
<p>shop.html.twig:</p>
<pre><code><a href="{{ path('forward_shop') }}" target="_blank"><input type="Submit" value="Go to shop" /></a>
</code></pre>
<p>ShopController.php</p>
<pre><code>public function ShopAction(){
return $this->redirect('http://externalUrl/login.php');
}
</code></pre>
<p>How do i redirect to the URL along with the post data, if such request cannot be made is there any alternative?</p>
| <p>You could use BuzzBundle (<a href="https://github.com/sensiolabs/SensioBuzzBundle" rel="nofollow">https://github.com/sensiolabs/SensioBuzzBundle</a>), a simple bundle for making http requests.</p>
|
Regarding Maintenance mode in ASP.NET Core <p>I am working on ASP.NET Core web app with MVC6. I want to implement maintenance mode in my web app such that only certain type of users are allowed to login to web app when it is under maintenance mode. For example all user EXCEPT user with role <code>user</code> are allowed to login. To achieve this functionality I tried following code.</p>
<pre><code>//Sign in user with provided username and password
var res = await _signInManager.PasswordSignInAsync(suser.UserName, user.Password, user.Remember, false);
if (res.Succeeded)
{
//check if web app is under maintenance mode and if it is, then check the role of the user
if (_env.IsEnvironment("Maintenance") && await _userManager.IsInRoleAsync(suser, "user"))
return View("Maintenance"); //if user is in 'user' role redirect to maintenance view
else
{
//else redirect to main page
}
}
</code></pre>
<p>The above code is executed when specific user tries to login to web app. The problem with above code is that it won't work when user is already logged in and tries to access the web app. in that case it will be redirected to the main page of web app regardless of maintenance mode. How do Logout already logged in user when they tried to access web app under maintenance mode?</p>
| <p>Create an action filter or a middle ware that executes the same check for every request</p>
<p>To read more about filters, check this link <a href="https://docs.asp.net/en/latest/mvc/controllers/filters.html" rel="nofollow">https://docs.asp.net/en/latest/mvc/controllers/filters.html</a> </p>
|
Errno::EACCES: Permission denied - /Library/Ruby/Gems/2.0.0/extensions/universal-darwin-16/2.0.0/sqlite3-1.3.12/gem_make.out <p>I've been trying to start a new project of mine, but I had some issues using Rails.</p>
<p>I start by saying that I'm using macOS Sierra 10.12 and Xcode version 8.0 (8A218a).</p>
<p>When I write in the designed directory <em>rails new projectname</em> it happens as follows:</p>
<pre><code>rails new hello_app
create
create README.rdoc
create Rakefile
create config.ru
create .gitignore
create Gemfile
create app
create app/assets/javascripts/application.js
create app/assets/stylesheets/application.css
create app/controllers/application_controller.rb
create app/helpers/application_helper.rb
create app/views/layouts/application.html.erb
create app/assets/images/.keep
create app/mailers/.keep
create app/models/.keep
create app/controllers/concerns/.keep
create app/models/concerns/.keep
create bin
create bin/bundle
create bin/rails
create bin/rake
create bin/setup
create config
create config/routes.rb
create config/application.rb
create config/environment.rb
create config/secrets.yml
create config/environments
create config/environments/development.rb
create config/environments/production.rb
create config/environments/test.rb
create config/initializers
create config/initializers/assets.rb
create config/initializers/backtrace_silencers.rb
create config/initializers/cookies_serializer.rb
create config/initializers/filter_parameter_logging.rb
create config/initializers/inflections.rb
create config/initializers/mime_types.rb
create config/initializers/session_store.rb
create config/initializers/wrap_parameters.rb
create config/locales
create config/locales/en.yml
create config/boot.rb
create config/database.yml
create db
create db/seeds.rb
create lib
create lib/tasks
create lib/tasks/.keep
create lib/assets
create lib/assets/.keep
create log
create log/.keep
create public
create public/404.html
create public/422.html
create public/500.html
create public/favicon.ico
create public/robots.txt
create test/fixtures
create test/fixtures/.keep
create test/controllers
create test/controllers/.keep
create test/mailers
create test/mailers/.keep
create test/models
create test/models/.keep
create test/helpers
create test/helpers/.keep
create test/integration
create test/integration/.keep
create test/test_helper.rb
create tmp/cache
create tmp/cache/assets
create vendor/assets/javascripts
create vendor/assets/javascripts/.keep
create vendor/assets/stylesheets
create vendor/assets/stylesheets/.keep
run bundle install
Ignoring ffi-1.9.14 because its extensions are not built. Try: gem pristine ffi --version 1.9.14
Your user account isn't allowed to install to the system Rubygems.
You can cancel this installation and run:
bundle install --path vendor/bundle
to install the gems into ./vendor/bundle/, or you can enter your
password
and install the bundled gems to Rubygems using sudo.
Password:
Fetching gem metadata from ht.tps://rubygems.org/...........
Fetching version metadata from https://rubygems.org/...
Fetching dependency metadata from https://rubygems.org/..
Resolving dependencies.......
Using rake 11.3.0
Using i18n 0.7.0
Using json 1.8.3
Using minitest 5.9.1
Using thread_safe 0.3.5
Using builder 3.2.2
Using erubis 2.7.0
Using mini_portile2 2.1.0
Using rack 1.6.4
Using mime-types-data 3.2016.0521
Using arel 6.0.3
Using debug_inspector 0.0.2
Using bundler 1.11.2
Installing byebug 9.0.6 with native extensions
Errno::EACCES: Permission denied - /Library/Ruby/Gems/2.0.0/extensions/universal-darwin-16/2.0.0/byebug- 9.0.6/gem_make.out
Using coffee-script-source 1.10.0
Using execjs 2.7.0
Using thor 0.19.1
Using concurrent-ruby 1.0.2
Using multi_json 1.12.1
Using sass 3.4.22
Using tilt 2.0.5
Installing sqlite3 1.3.12 with native extensions
Errno::EACCES: Permission denied - /Library/Ruby/Gems/2.0.0/extensions/universal-darwin-16/2.0.0/sqlite3-1.3.12/gem_make.out
Using turbolinks-source 5.0.0
Using rdoc 4.2.2
Using tzinfo 1.2.2
Installing nokogiri 1.6.8.1 with native extensions
Errno::EACCES: Permission denied - /Library/Ruby/Gems/2.0.0/extensions/universal-darwin-16/2.0.0/nokogiri-1.6.8.1/gem_make.out
Using rack-test 0.6.3
Using mime-types 3.1
Using binding_of_caller 0.7.2
An error occurred while installing byebug (9.0.6), and Bundler cannot continue.
Make sure that `gem install byebug -v '9.0.6'` succeeds before bundling.
run bundle exec spring binstub --all
* bin/rake: spring inserted
* bin/rails: spring inserted
</code></pre>
<p>I tried some solutions but they didn't work.
First of all:</p>
<blockquote>
<p>Ignoring ffi-1.9.14 because its extensions are not built. Try: gem pristine ffi --version 1.9.14</p>
</blockquote>
<p>Is it important? How can I work it out?</p>
<p>Then I have all the errors you can see, do you know how I can find a solution?</p>
<p>It's important that these solutions don't create problems in making all the project run on other unixlike machines, because it's a group work.</p>
<p>Thank you a lot in advance. </p>
<p>EDIT:</p>
<p>even using <em>sudo rails new helloapp</em> the problems occurred. Besides I couldn't do anything without root permissions and that was a mess. </p>
<p>I installed manually byebug, nokogiri and ffi through this line:</p>
<blockquote>
<p>sudo gem install -n /usr/local/bin gemname</p>
</blockquote>
<p>This is the result:</p>
<pre><code>rails new toyapp
create
create README.rdoc
create Rakefile
create config.ru
create .gitignore
create Gemfile
create app
create app/assets/javascripts/application.js
create app/assets/stylesheets/application.css
create app/controllers/application_controller.rb
create app/helpers/application_helper.rb
create app/views/layouts/application.html.erb
create app/assets/images/.keep
create app/mailers/.keep
create app/models/.keep
create app/controllers/concerns/.keep
create app/models/concerns/.keep
create bin
create bin/bundle
create bin/rails
create bin/rake
create bin/setup
create config
create config/routes.rb
create config/application.rb
create config/environment.rb
create config/secrets.yml
create config/environments
create config/environments/development.rb
create config/environments/production.rb
create config/environments/test.rb
create config/initializers
create config/initializers/assets.rb
create config/initializers/backtrace_silencers.rb
create config/initializers/cookies_serializer.rb
create config/initializers/filter_parameter_logging.rb
create config/initializers/inflections.rb
create config/initializers/mime_types.rb
create config/initializers/session_store.rb
create config/initializers/wrap_parameters.rb
create config/locales
create config/locales/en.yml
create config/boot.rb
create config/database.yml
create db
create db/seeds.rb
create lib
create lib/tasks
create lib/tasks/.keep
create lib/assets
create lib/assets/.keep
create log
create log/.keep
create public
create public/404.html
create public/422.html
create public/500.html
create public/favicon.ico
create public/robots.txt
create test/fixtures
create test/fixtures/.keep
create test/controllers
create test/controllers/.keep
create test/mailers
create test/mailers/.keep
create test/models
create test/models/.keep
create test/helpers
create test/helpers/.keep
create test/integration
create test/integration/.keep
create test/test_helper.rb
create tmp/cache
create tmp/cache/assets
create vendor/assets/javascripts
create vendor/assets/javascripts/.keep
create vendor/assets/stylesheets
create vendor/assets/stylesheets/.keep
run bundle install
Fetching gem metadata from https://rubygems.org/...........
Fetching version metadata from https://rubygems.org/...
Fetching dependency metadata from https://rubygems.org/..
Resolving dependencies.....
Using rake 11.3.0
Using i18n 0.7.0
Using json 1.8.3
Using minitest 5.9.1
Using thread_safe 0.3.5
Using builder 3.2.2
Using erubis 2.7.0
Using mini_portile2 2.1.0
Using rack 1.6.4
Using mime-types-data 3.2016.0521
Using arel 6.0.3
Using debug_inspector 0.0.2
Using bundler 1.11.2
Using byebug 9.0.6
Using coffee-script-source 1.10.0
Using execjs 2.7.0
Using thor 0.19.1
Using concurrent-ruby 1.0.2
Using multi_json 1.12.1
Using sass 3.4.22
Using tilt 2.0.5
Using sqlite3 1.3.12
Using turbolinks-source 5.0.0
Using rdoc 4.2.2
Using tzinfo 1.2.2
Using nokogiri 1.6.8.1
Using rack-test 0.6.3
Using mime-types 3.1
Using binding_of_caller 0.7.2
Using coffee-script 2.4.1
Using uglifier 3.0.2
Using sprockets 3.7.0
Using turbolinks 5.0.1
Using sdoc 0.4.2
Using activesupport 4.2.6
Using loofah 2.0.3
Using mail 2.6.4
Using rails-deprecated_sanitizer 1.0.3
Using globalid 0.3.7
Using activemodel 4.2.6
Using jbuilder 2.6.0
Using spring 2.0.0
Using rails-html-sanitizer 1.0.3
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.2.0
Using coffee-rails 4.1.1
Using jquery-rails 4.2.1
Using rails 4.2.6
Using sass-rails 5.0.6
Using web-console 2.3.0
Bundle complete! 12 Gemfile dependencies, 56 gems now installed.
Use `bundle show [gemname]` to see where a bundled gem is installed.
run bundle exec spring binstub --all
* bin/rake: spring inserted
* bin/rails: spring inserted
</code></pre>
<p>Now everything should be okay, am I right?</p>
| <p>"Your user account isn't allowed to install to the system Rubygems".
This means that you dont have write permissions to the gems installation dir.
Install the gems (with errors in your log) using <code>sudo gem install <gem_name></code>
or say <code>sudo bundle install</code></p>
|
how to make an event listener execute last in javascript <p>Two or more event listeners are listening to a radio button. </p>
<p>How can i make one of them execute the last? </p>
<pre><code> jQuery(document).on('change', '#payment_id_2', function(){
location.reload();
});
</code></pre>
<p>This the event listener that i want to be executed the last. </p>
<p>I don't know where are the other event listeners to put them first. </p>
| <p>You can set a timeout but i think its a bad practise to let the browser wait like this. Since this is in async though i dont think there is another way of doing it.</p>
|
Multidimentional array php post <p>I created a form to input a schedule to a certain location and the location will have multiple schedule<br>
The form looks like this (I can add more input form as much as I need)</p>
<pre><code><input name="location[]" type="text">
<input name="address[]" type="text">
<input name="day[]" type="text">
<input name="start[]" type="text">
<input name="end[]" type="text">
</code></pre>
<p>And so on. The problem is, I want to insert the <code>location</code> and <code>address</code> to <code>addresses</code> table, and <code>day</code>,<code>start</code>,<code>end</code> to <code>schedules</code> table and make sure that the <code>schedule</code> has the right <code>address_id</code> just like below</p>
<p><code>addresses</code> table </p>
<pre><code>+----+----------+----------+
| id | location | address |
+----+----------+----------+
| 1 | loc 1 | addr 1 |
| 2 | loc 2 | addr 2 |
+----+----------+----------+
</code></pre>
<p><code>schedules</code> table </p>
<pre><code> +----+----------+----------+-------+------------+
| id | day | start | end | address_id |
+----+----------+----------+-------+------------+
| 1 | day a | start a | end a | 1 |
| 2 | day b | start b | end b | 1 |
| 3 | day c | start c | end c | 2 |
| 4 | day d | start d | end d | 2 |
+----+----------+----------+-------+------------+
</code></pre>
<p>I've read that I need to use <code>foreach</code> to do this, but the problem is how to loop the input and make sure that the schedule has the right <code>address_id</code> value? </p>
<p>edit, thanks for the downvote :/<br>
I use laravel:</p>
<pre><code>$address = Input::get('address');
$location = Input::get('location');
$day = Input::get('day');
$start = Input::get('start');
$end = Input::get('end');
foreach($location as $key => $value) {
$addr = new Address;
$addr->location = $location[$key];
$addr->address = $address[$key];
$addr->save();
foreach($day as $key => $value) {
$sched = new Schedule;
$sched->day = $day[$key];
$sched->start = $start[$key];
$sched->end = $end[$key];
$sched->address_id = $addr->id;
$sched->save();
}
}
</code></pre>
| <p>You need to loop by <code>address</code> for example and insert first of all in <code>address</code> table. After that you need to get the id of the inserted row and use it when you insert in <code>schedules</code> table.</p>
<p>As you didn't try any code I just explain here how you should do and if something is not working let me know what have you tried and what error you have.</p>
<pre><code>foreach($_POST['address'] as $key => $value){
//insert to address table: $_POST['location'][$key] and $_POST['address'][$key]
//$last_inserted_id_from_address = Get the latest inserted id from address table.
//insert to schedules tables: $_POST['day'][$key] ,.... and $last_inserted_id_from_address
}
</code></pre>
<hr>
<p><strong>UPDATE</strong></p>
<p>You don't need to loop twice if you want to have match 1 to 1.
Change your loop to this:</p>
<pre><code>foreach($location as $key => $value) {
$addr = new Address;
$addr->location = $location[$key];
$addr->address = $address[$key];
$addr->save();
//Use the same $key when creating Schedule. For each address will create one schedule.
$sched = new Schedule;
$sched->day = $day[$key];
$sched->start = $start[$key];
$sched->end = $end[$key];
$sched->address_id = $addr->id;
$sched->save();
}
</code></pre>
|
Traverse a javascript object recursively and replace a value by key <p>Since JSON can not perfom functions i need to eval a JSON string by a key flag in the JSON object. I want to mutate the JSON data when it's in Object form.</p>
<p>I can't find a function/method online that can give me the full path to key based on a known key pattern.</p>
<p>Given this data:</p>
<pre><code> {
"js:bindto": "#chart-1", // note the key here 'js:'
"point": {
"r": 5
},
"data": {
"x": "x",
"xFormat": "%Y",
"columns": [
...
],
"colors": {
"company": "#ed1b34",
"trendline": "#ffffff"
}
},
"legend": {
"show": false
},
"axis": {
"x": {
"padding": {
"left": 0
},
"type": "timeseries",
"tick": {
"format": "%Y",
"outer": false
}
},
"y": {
"tick": {
"outer": false,
"js:format": "d3.format(\"$\")" // note the key here 'js:'
}
}
},
"grid": {
"lines": {
"front": false
},
"y": {
"lines": [...]
}
}
}
</code></pre>
<p>The flags are keys beginning with <code>js:</code>.</p>
<p>If I look up <code>js:format</code>, I'd expect it's path to be something like: <code>/js:bindto</code> and <code>/axis/y/tick/js:format</code>. Open to suggestions.</p>
<p>In context:</p>
<pre><code>mutateGraphData<T>(data:T):T {
// data here is a parsed JSON string. ( an object as shown above )
let jsonKeys = this.findKeysInJSON(JSON.stringify(data), "js:");
// jsonKeys = ["js:bindto","js:format"]
jsonKeys.map((key:string) => {
// find the key in data, then modify the value. (stuck here)
// i need the full path to the key so i can change the data property that has the key in question
});
});
return data;
}
findKeysInJSON<T>(jsonString:string, key:string):Array<T> {
let keys = [];
if (Boolean(~(jsonString.indexOf(`"${key}`)))) {
let regEx = new RegExp(key + "(\\w|\\-)+", "g");
keys = jsonString.match(regEx);
}
return keys;
}
</code></pre>
<p>I have been around a few npm packages:</p>
<ul>
<li><a href="https://www.npmjs.com/package/object-search" rel="nofollow">object search</a> no wild card lookaround</li>
<li><a href="https://www.npmjs.com/package/dotty" rel="nofollow">dotty</a> looks good, but fails with search: "*.js:format"</li>
<li><a href="https://github.com/capaj/object-resolve-path" rel="nofollow">https://github.com/capaj/object-resolve-path</a> - needs full path to key. I don't know that in advance.</li>
</ul>
<p>I have looked at</p>
<ul>
<li><a href="http://stackoverflow.com/questions/22222599/javascript-recursive-search-in-json-object">JavaScript recursive search in JSON object</a></li>
<li><a href="http://stackoverflow.com/questions/15642494/find-property-by-name-in-a-deep-object">Find property by name in a deep object</a></li>
<li>DefiantJS ( no npm module )</li>
<li><a href="https://gist.github.com/iwek/3924925" rel="nofollow">https://gist.github.com/iwek/3924925</a></li>
</ul>
<p>Nothing have I seen can return the full path to the key in question so I can modify it, nor work directly on the object itself so I can change its properties.</p>
| <p>You could go with <a href="http://ramdajs.com" rel="nofollow">Ramda</a>. It has built in functions that will allow you to map over an object and modify parts of the object in a completely immutable way.</p>
<p>Ramda offers <code>R.lensPath</code> that will allow you to dig into the object, and modify it as needed. It doesn't follow the pattern you want, but we can quickly patch it with the <code>lensify</code> function. </p>
<p>It is using the <code>R.set</code> function to set the node to the passed in value, and creating a pipeline that will run all the operations on the passed in object.</p>
<p>You can do some really cool stuff with ramda and lenses. Checkout evilsoft on livecoding.tv for a really good overview.</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>const obj={"js:bindto":"#chart-1",point:{r:5},data:{x:"x",xFormat:"%Y",columns:[],colors:{company:"#ed1b34",trendline:"#ffffff"}},legend:{show:!1},axis:{x:{padding:{left:0},type:"timeseries",tick:{format:"%Y",outer:!1}},y:{tick:{outer:!1,"js:format":'d3.format("$")'}}},grid:{lines:{front:!1},y:{lines:[]}}}
const lensify = path => R.lensPath(path.split('/'))
// create the property accessors split by /
const bindToLens = lensify('js:bindto')
const formatLens = lensify('axis/y/tick/js:format')
const modifyObj = R.pipe(
R.set(bindToLens, 'dis be bind'),
R.set(formatLens, 'I been here')
)
console.log(modifyObj(obj))</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.22.1/ramda.min.js"></script></code></pre>
</div>
</div>
</p>
|
Angular form submission is not working in ng-repeat loop <p>If i submit a form in ng repeat loop then form value is not passed.</p>
<pre><code><li ng-repeat="com in post.comments">{{ com.body }}
<h4>Reply</h4>
<form ng-submit="addReply()">
<textarea name="rbody" ng-model="rbody"> </textarea>
<button type="submit">Reply</button>
</form>
</li>
</code></pre>
<p>in Controller :</p>
<pre><code>$scope.addReply = function(){
console.log($scope.rbody);
};
</code></pre>
<p>But If i keep the form outside of loop then then I get value in console. What's the problem in my code</p>
| <p>You are using a single istance of your <code>$scope.rbody</code>variable: hence, it's getting replaced on every iteration of ng-repeat.</p>
<p>To fix this issue, simply attach the <code>ng-model</code> of the form to the current ng-repeat iteration, for example:</p>
<pre><code><li ng-repeat="com in post.comments">{{ com.body }}
<h4>Reply</h4>
<form ng-submit="addReply(com)">
<textarea name="rbody" ng-model="com.rbody"></textarea>
<button type="submit">Reply</button>
</form>
</li>
</code></pre>
<p>then in your controller you will be able to get every inserted value of your array:</p>
<pre><code>$scope.addReply = function(comObj){
console.log(comObj.rbody);
};
</code></pre>
|
How to write media queries for 1360*768 Screen? <p>Hi i am working on media queries for my site. I created media queries for 1024*768 screen size it works good. i created 1360*768 screen size also but it's not working. Can anyone suggest how this can be done? Here is what I've got so far:</p>
<pre><code>@media (min-width: 992px) and (max-width: 1199px){ #loginrow{ padding: 135px 0; } }
@media (max-width: 1360px){ #loginrow{ padding: 135px 0; } }
</code></pre>
| <p>Just use min-widths, when you hit the higher resolution your queries will override what came before it.</p>
<pre><code>@media (min-width: 992px) and (max-width: 1199px){ #loginrow{ padding: 135px 0; } }
@media (min-width: 1360px){ #loginrow{ padding: 135px 0; } }
</code></pre>
|
MySQL - How to select 'DISTINCT' overlapping periods (dates or number ranges) <p>Put succinctly, if a query tells me A overlaps B then I don't need it to also tell me that B also overlaps A as they overlap each other. </p>
<p>So I am trying to use a self join in sql to select just 'DISTINCT' overlaps.</p>
<p>To illustrate, here is a simple SQL fiddle that I wrote to show inclusive overlap selection (<a href="http://sqlfiddle.com/#!9/7af84f/1" rel="nofollow">http://sqlfiddle.com/#!9/7af84f/1</a>)</p>
<p>In detail...</p>
<p>Assume I have a table of name (char), d1 (int), d2 (int) , the schema of which is below. Here d1 and d2 represent the start and end of some interval that might overlap with another interval in the same table,.</p>
<pre><code>CREATE TABLE test (
letter char ,
d1 int ,
d2 int
) ;
</code></pre>
<p>Given this table I fill it with some values</p>
<pre><code>INSERT INTO test (letter,d1,d2)
VALUES
('A', 2, 10), -- overlaps C and D
('B', 12, 20), -- overlaps E
('C', 5, 10), -- overlaps A and D
('D', 1, 8), -- overlaps A and C
('E', 13, 15), -- overlaps B
('F', 25, 30); -- doesn't overlap anything
</code></pre>
<p>and run the following query that uses a self join to correctly find the rows where d1 and d2 in one row has an inclusive overlap with d1 and d2 in other rows.</p>
<pre><code>-- selects all records that overlap in the range d1 - d2 inclusive
-- (excluding the implicit overlap between a record and itself)
-- The results are sorted by letter followed by d1
SELECT
basetable.letter as test_letter,
basetable.d1,
basetable.d2,
overlaptable.letter as overlap_letter,
overlaptable.d1 as overlap_d1,
overlaptable.d2 as overlap_d2
FROM
test as basetable,
test as overlaptable
WHERE
-- there is an inclusive overlap
basetable.d1 <= overlaptable.d2 and basetable.d2 >= overlaptable.d1
AND
-- the row being checked is not itsself
basetable.letter <> overlaptable.letter
AND
basetable.d1 <> overlaptable.d1
AND
basetable.d2 <> overlaptable.d2
ORDER BY
basetable.letter,
basetable.d1
</code></pre>
<p>That correctly gives me the following, showing all 6 versions of overlaps eg left hand column indicates that A overlaps C and another row shows that C overlaps A (note the sqlfiddle doesn't seem to understand field aliases so my column headers are different)</p>
<pre><code>test_letter d1 d2 overlap_letter overlap_d1 overlap_d2
A 2 10 D 1 8
B 12 20 E 13 15
C 5 10 D 1 8
D 1 8 A 2 10
D 1 8 C 5 10
E 13 15 B 12 20
</code></pre>
<p>My question is this:</p>
<p><strong>How can I alter the sql to just get four rows of 'DISTINCT' or 'one way' overlaps?</strong> </p>
<p>ie this result...</p>
<pre><code>test_letter d1 d2 overlap_letter overlap_d1 overlap_d2
A 2 10 D 1 8
A 2 10 C 5 10
B 12 20 E 13 15
C 5 10 D 1 8
</code></pre>
<p>eg:<br>
a result that just shows records for A, B and C in the left hand column according to the following reasoning</p>
<ul>
<li>A(2,10) overlaps with D(1,8) and C(5,10) and {SHOW THESE TWO ROWS}</li>
<li>B(12,20) overlaps with E(13,15) {SHOW THIS ROW}</li>
<li>C(5,10) overlaps with D(1,8) {SHOW THIS ROW but don't show the A(1,10) overlap as row 2 already shows that A and C overlap} </li>
<li>D(1,8) {DON'T SHOW anything new as we already know about A(1,10) and C(5,10)} </li>
<li>E(13,15) {DON'T SHOW anything new as we already know about B(12,20) } </li>
<li>F(25,30) {DON'T SHOW anything as there are no overlaps}</li>
</ul>
| <p>You can just change to an inequality. And, you should also use <code>JOIN</code>:</p>
<pre><code>SELECT basetable.letter as test_letter, basetable.d1, basetable.d2,
overlaptable.letter as overlap_letter, overlaptable.d1 as overlap_d1, overlaptable.d2 as overlap_d2
FROM test basetable JOIN
test overlaptable
ON basetable.d1 <= overlaptable.d2 AND
basetable.d2 >= overlaptable.d1
WHERE basetable.letter < overlaptable.letter -- This is the change
ORDER BY basetable.letter, basetable.d1;
</code></pre>
|
Which angular 2 release version is more stable for production? <p>Which release is the most stable to use for angular 2 production app?
For example 2.1.0 is more stable than 2.0.0? Or it's the same? </p>
| <p><strong><code>Angular-2.0.2</code></strong> is stable. So, You can use it.</p>
<p>check here : <a href="https://github.com/angular/angular/blob/master/CHANGELOG.md" rel="nofollow">https://github.com/angular/angular/blob/master/CHANGELOG.md</a></p>
<p>Now, Angular2 is going thorugh - <strong><code>2.1.0- RC</code></strong> phase(s)...</p>
|
How to set long text inside editext in such a way that it must display the end of the text? <p>i m creating a browser for my self.so when i set text of edittext by passing the url of some link it shows only the beginning of the url.Ex- if the url is </p>
<p><a href="http://stackoverflow.com/howtocreateabutton/">http://stackoverflow.com/howtocreateabutton/</a> </p>
<p>but the edittext shows only </p>
<p><a href="http://stackoverflow.com/how">http://stackoverflow.com/how</a> </p>
<p>beacuse of overflow from the screen but i want to display the last of the link like - </p>
<p>com/howtocreateabutton/</p>
<p>Xml Code for Edittext:</p>
<pre><code> <EditText
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight="10"
android:onClick="enterAgain"
android:layout_marginTop="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:inputType="textUri"
android:gravity="center_vertical"
android:hint="Enter URL..."
android:autoText="true"
android:layout_marginRight="10dp"
android:textColorHighlight="#4384d4"
android:textColor="#c1bfbf"
android:maxLines="1"
android:scrollHorizontally="true"
android:foregroundGravity="right"
android:clickable="true"
android:imeOptions="actionGo"
android:id="@+id/edit_url"
android:background="#FFFFFF"/>
</code></pre>
<p>....help me guys...;(</p>
| <p>so damn simple jsut do this after setting the text:</p>
<pre><code>et.setSelection(et.getText().length());
</code></pre>
<p>i tested and it worked for me if anything wrong put a comment on this post ;)</p>
|
How to check if a file is empty avoid reading the whole file in a submit form? <p>I am using django, and in a web submit form, I want to check if a uploading file is empty, but avoid uploading or reading the whole file to get the file size, because it might be huge and take time to calculate.</p>
| <p>You are probably looking for <a href="https://docs.python.org/2/library/os.html#os.stat" rel="nofollow">os.stat</a></p>
<p>os.stat(path)</p>
<blockquote>
<p>Perform the equivalent of a stat() system call on the given path.
(This function follows symlinks; to stat a symlink use lstat().)</p>
<p>The return value is an object whose attributes correspond to the
members of the stat structure, namely:</p>
<p>st_mode - protection bits,<br>
st_ino - inode number,<br>
st_dev - device,<br>
st_nlink - number of hard links,<br>
st_uid - user id of owner,<br>
st_gid -
group id of owner,<br>
<strong>st_size - size of file, in bytes</strong>,</p>
</blockquote>
<p>so you just do</p>
<pre><code>import os
os.stat('/uploaded/file/path')
</code></pre>
|
Gerrit Replication to gitlab failed <p>When I configure the replication from Gerrit to gitlab, the replication_log keep reporting:</p>
<pre><code>[2016-10-10 09:36:07,517] [d0b90d12] Missing repository created; retry replication to git@mo-3394cf6e0.mo.sap.corp:CI_prep_group/sprmvc-ui5.git
[2016-10-10 09:37:07,517] [d0b90d12] Replication to git@mo-3394cf6e0.mo.sap.corp:CI_prep_group/sprmvc-ui5.git started...
[2016-10-10 09:37:07,874] [d0b90d12] Created remote repository: git@mo-3394cf6e0.mo.sap.corp:CI_prep_group/sprmvc-ui5.git
[2016-10-10 09:37:07,874] [d0b90d12] Missing repository created; retry replication to git@mo-3394cf6e0.mo.sap.corp:CI_prep_group/sprmvc-ui5.git
[2016-10-10 09:38:07,875] [d0b90d12] Replication to git@mo-3394cf6e0.mo.sap.corp:CI_prep_group/sprmvc-ui5.git started...
[2016-10-10 09:38:08,259] [d0b90d12] Created remote repository: git@mo-3394cf6e0.mo.sap.corp:CI_prep_group/sprmvc-ui5.git
</code></pre>
<p>My replication.config file:</p>
<pre><code> [remote "sprmvc-ui5"]
projects = sprmvc-ui5
url = git@mo-3394cf6e0.mo.sap.corp:CI_prep_group/sprmvc-ui5.git
push = +refs/heads/*:refs/heads/*
push = +refs/tags/*:refs/tags/*
push = +refs/changes/*:refs/changes/*
threads = 3
</code></pre>
<p>My .ssh/config file:</p>
<pre><code>Host mo-3394cf6e0.mo.sap.corp
HostName mo-3394cf6e0.mo.sap.corp
User git
IdentityFile ~/.ssh/id_rsa
StrictHostKeyChecking no
UserKnownHostsFile /dev/null
</code></pre>
<p>Can anyone give me an advice?</p>
| <p>I solved it by create a new user in gitlab and give it full access to my project, maintain the public key which comes from gerrit server. </p>
|
ETag not received after changing get Request Parameters <p>I am trying to track a unique ID using ETags. </p>
<p>I have a java spring controller deployed - localhost:8080/testTag/hitApi.html</p>
<p>Issue is that i am receiving two different ETags for below two requests. The only difference is in get query parameters - </p>
<blockquote>
<p>get Request 1 - localhost:8080/testTag/hitApi.html?<strong>name=user1</strong>&id=123</p>
<p>get Request 2 -localhost:8080/testTag/hitApi.html?<strong>name=user2</strong>&id=123</p>
</blockquote>
<p>is this the normal behavior in case of ETags?</p>
<p>Can I get same ETag for two requests above?</p>
<p>Thanks and Regards,
Vibhav</p>
| <p>ETag value is based on the content on the response <a href="http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/filter/ShallowEtagHeaderFilter.html" rel="nofollow">http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/filter/ShallowEtagHeaderFilter.html</a></p>
|
Why is my instance variable (@reservation.room) nil? <p>I am currently working on a reservation system in rails 5.0.1. I have a user, room and reservation model:</p>
<p><strong>user.rb</strong></p>
<pre><code>has_many :reservations
</code></pre>
<p><strong>room.rb</strong></p>
<pre><code>has_many :reservations
</code></pre>
<p><strong>reservation.rb</strong></p>
<pre><code>belongs_to :user
belongs_to :room
</code></pre>
<p><strong>reservation_controller.rb</strong></p>
<pre><code>class ReservationsController < ApplicationController
before_action :authenticate_user!
def create
@reservation = current_user.reservations.create(reservation_params)
redirect_to @reservation.room, notice: "Your reservation has been created"
end
private
def reservation_params
params.require(:reservation).permit(:start_date, :end_date, :price, :total, :room_id, :user_id)
end
end
</code></pre>
<p><strong>_form.html.erb (view)</strong></p>
<pre><code><%= form_for([@room, @room.reservations.new]) do |f| %>
<%= f.text_field :start_date %>
<%= f.text_field :end_date %>
<%= f.hidden_field :room_id, value: @room_id %>
<%= f.hidden_field :price, value: @room_price %>
<br>
<%= f.submit "Book Now", class: "btn btn-primary" %>
<% end %>
</code></pre>
<p>I'm getting this error: </p>
<p><a href="http://i.stack.imgur.com/QfZDD.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/QfZDD.jpg" alt="enter image description here"></a></p>
<h2>Question:</h2>
<p><strong>Why is my @reservation.room nil?</strong> </p>
<p>If I type in the rails console: @reserveration = current_user.reservations.create(reservation_params)
Then I am getting:
NameError: undefined local variable or method `current_user' for main:Object</p>
<p>If you need further information just let me know!</p>
| <blockquote>
<p>Why is my instance variable (<code>@reservation</code>) nil?</p>
</blockquote>
<p>It's not. It is <code>@reservation.room</code> that is nil.</p>
<p>Before you ask "why is that then?", inspect your params that you post to the action.</p>
|
Jquery replace html <p>In confluence I need to change text on a page into an image
Inside of a table i have multiple values that need to be replaced by an image.
So i created following Jquery and put it into a usermacro.</p>
<pre><code><script>
AJS.toInit(function() {
AJS.$("body").html($("body").html().replace(/text to be replaced/g,'<img src="image.png">'))
});
</script>
</code></pre>
<p>This works fine to change the text with the image. But it breaks the left menu when put in a macro.
When i run the line
AJS.$("body")...
directly in developer tools in the console from google chrome it does not break the menu.</p>
<p>I can't seem to figure out how to solve this. Anyone have an idea?</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>$(document).ready(function(){
$("#btn2").click(function(){
var a= $("#a").html();
a=a.replace('<i> with Italic</i>','<u> with UnderLine</u>');
alert("HTML: " + $("#a").html());
$("#a").html(a);
alert("HTML: " + a);
});
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script></head>
<body>
<div id ='a'>
This is a div<i> with Italic</i></br>
<b>and bold</b>
</div>
<button id="btn2">Show HTML</button>
</body>
</html></code></pre>
</div>
</div>
</p>
|
How is exponent calculated for subnormals in floating point <p>Suppose I have the floating point bits representation like this:</p>
<pre><code>0 0000000000 00000000000000000000000000000000000000000000000000001
</code></pre>
<p>I know that the floating point numbers with the exponent of all zeros are called subnormals or denormals. And the exponent is calculated differently than for normal floating point numbers where the bias is taken into account. </p>
<p>So how is exponent calcualted for subnormals?</p>
| <p>The exponent isn't calculated differently. The only difference subnormals have is a leading 0 instead of a leading 1 (so your example is equal to <code>0.0000···0001 * 2^-1022</code> instead of <code>1.0000···0001 * 2^-1022</code>.</p>
<p>If you're looking for an equivalent mantissa and exponent such that there <em>is</em> a leading 1, just count the leading zeros in the mantissa and add one, subtract the result from the original exponent, and also shift the mantissa left by the result (so <code>0.000000101 * 2^-50</code> would result in 6+1 and become <code>1.01 * 2^-57</code>).</p>
|
Right Aligning Of ' # ' character in C <p>So I was doing my cs50 problem sets and i got stuck in the right aligning of the characters in my output.</p>
<p>The code for my program ( mario.c) is : </p>
<pre><code>#include<stdio.h>
int main(void)
{
int height=-1;
while(height<0 || height>23)
{
scanf("%d",&height);
printf("height: %d\n",height);
}
for(int i=1; i<=height; ++i)
{
for(int j=1;j<=i+1;++j)
{
printf("#");
}
printf("\n");
}
}
</code></pre>
<p>Here is the output that i want:</p>
<p><a href="http://i.stack.imgur.com/JLBpH.png" rel="nofollow">Output ( that i want )</a></p>
<p>and the output that i am getting :</p>
<p><a href="http://i.stack.imgur.com/6lwpj.png" rel="nofollow">Output ( that i am getting )</a></p>
<p>Please help me out. Thanks in advance.</p>
| <p>printf whitespace first.</p>
<pre><code>for(int i = 1; i <= height; ++i)
{
for (int k = 1; k <= height - i; ++k)
printf(" ");
for(int j = 1; j <= i + 1; ++j)
{
printf("#");
}
printf("\n");
}
</code></pre>
|
Facebook Instant articles' views not counted by Google Analytics <p>I want to share with you the following issue. I have implemented the Facebook Instant articles on my WordPress website via the Instant Articles for WP plugin. The articles show up nicely on Facebook, however, the tracking of an Instant article does not get recorded by Google Analytics. Please help, the code I use in the plugin is as follows (the code is added in the 'embed code' field of the plugin:</p>
<pre><code><script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','__gaTracker');
__gaTracker('create', 'MyGAID', 'auto');
__gaTracker('set', 'forceSSL', false);
__gaTracker('send','pageview', {title: 'POST TITLE'});</script>
</code></pre>
<p>I have researched the issue on the Internet and still did not find the solution, the above code is suggested here:</p>
<p><a href="https://github.com/Automattic/facebook-instant-articles-wp/issues/321" rel="nofollow">https://github.com/Automattic/facebook-instant-articles-wp/issues/321</a></p>
<p>Another highly relevant topic to the issue is this one:
<a href="http://stackoverflow.com/questions/36310439/how-to-track-content-statistics-for-facebook-instant-articles-with-google-analyt/39953511#39953511">How to track content Statistics for Facebook Instant Articles with Google Analytics</a></p>
<p>Do you have any ideas/improvement suggestions how to get the Instant Articles tracking by Google Analytics work? </p>
<p>Appreciate your help!</p>
| <p>My script looks like this: </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><figure class="op-tracker">
<iframe>
<!-- Google Analytics Code -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXXX-XX', 'auto'); // Replace with your Google Analytics Account
ga('set', 'campaignSource', 'Facebook');
ga('set', 'campaignMedium', 'Social Instant Article');
ga('send', 'pageview', {title: 'POST TITLE'}); // Replace POST TITLE with real post title
</script>
<!-- End Google Analytics -->
</iframe>
</figure></code></pre>
</div>
</div>
</p>
<p>Remember you have to put that into body-part of your instant article.</p>
|
Is it possible to install ONLY JBoss AS server tools by URL? <p>Is it possible to have an URL to install only JBoss AS tools server from Jboss Tools pack?</p>
<p>I'm preparing an instruction which I should be simple and avoid error options. I found that instruction "find Jboss tools and select JBOSS AS tools" often ends with full installation, what is not correct for me.</p>
<p>For example I can install separated component by URL <a href="http://download.jboss.org/jbosstools/builds/staging/m2e-apt/all/repo/" rel="nofollow">http://download.jboss.org/jbosstools/builds/staging/m2e-apt/all/repo/</a></p>
<p>I' know that I can install required feature by command line but I prefer install by URL</p>
| <p>@michaldo, unfortunately, no. When you try to install plugin via link, the first thing Eclipse is looking at is <em>p2.index</em> file.
See for more information <a href="https://wiki.eclipse.org/Equinox/p2/p2_index" rel="nofollow">here</a>:</p>
<blockquote>
<p>For example the example p2.index contents below will cause p2 to look for compositeContent.jar, and if not found, then compositeContent.xml and would skip looking for content.jar or content.xml as it normally would look for them first. (And, then, naturally, if it needed artifacts from that site, would look for compositeArtifacts.jar and if not found compositeArtifacts.xml and would skip looking for artifacts.jar and artifacts.xml).</p>
</blockquote>
<p>And features don't have these auxiliary files, that Eclipse p2 can look for and use.
Everything is ok for you with m2e, because it contains only one feature.</p>
|
Using Blade/Mustache templating mixing Laravel and Vue.Js <p>So I'm trying to build an application with both <strong>Laravel</strong> and <strong>VueJs</strong> but I'm stuck at one point.</p>
<p>Is it possible to use VueJs mustache templating (which is <code>{{exemple}}</code> ) without launching a Laravel error since laravel used it too like <code>{{$exemple}}</code>? </p>
| <p>I think you can do what you're after using the <code>@{{ example }}</code> syntax that Blade allows us to use when using a JS framework inside Laravel.</p>
<p>Hope this helps! :)</p>
|
Elasticsearch - Get locale specific date in Groovy script <p>I need to update existing documents of a particular type with a new field. This new field should be set to the local day name of a date given by a datetime field in the document. The date time field is in the format yyyy-MM-dd'T'HH:mm:ss, is in UTC but has no explicit timezone code.</p>
<p>I'd like to do this with Groovy but have no Java experience. I'm guessing I need to:</p>
<p>1) Set the datetime to UTC locale</p>
<p>2) Convert to local locale (set to Europe/London) in this case</p>
<p>3) Get the day name from converted date and set new field (dayname) value with it</p>
<p>If I use the following update_by_query:</p>
<pre><code>POST /myindex/_update_by_query
{
"script": {
"inline": "ctx._source.dayname = Some_function(ctx._source.datetime)"
},
"query": {
"term": {
"_type": "myDocType"
}
}
}
</code></pre>
<p>Is there a simple way to do this with a some Groovy functions (replacing Some_function above).</p>
<p>Any hints would be very much appreciated!</p>
<p>UPDATE - Thanks to tim_yates i have the following Sense console code:</p>
<pre><code>POST /rating/_update_by_query
{
"script": {
"inline": "ctx._source.day = Date.parse(\"yyyy-MM-dd'T'HH:mm:ss\", ctx._source.datetime, java.util.TimeZone.getTimeZone('UTC')).format('EEEE', java.util.TimeZone.getTimeZone('Europe/London'))"
},
"query": {
"term": {
"_type": "transaction"
}
}
}
</code></pre>
<p>Unfortunately this generates the following error message:</p>
<pre><code>{
"error": {
"root_cause": [
{
"type": "script_exception",
"reason": "failed to run inline script [ctx._source.day = Date.parse(\"yyyy-MM-dd'T'HH:mm:ss\", ctx._source.datetime, java.util.TimeZone.getTimeZone('UTC')).format('EEEE', java.util.TimeZone.getTimeZone('Europe/London'))] using lang [groovy]"
}
],
"type": "script_exception",
"reason": "failed to run inline script [ctx._source.day = Date.parse(\"yyyy-MM-dd'T'HH:mm:ss\", ctx._source.datetime, java.util.TimeZone.getTimeZone('UTC')).format('EEEE', java.util.TimeZone.getTimeZone('Europe/London'))] using lang [groovy]",
"caused_by": {
"type": "missing_property_exception",
"reason": "No such property: java for class: 1209ff7fb16beac3a71ff2a276ac2225f7c4505b"
}
},
"status": 500
}
</code></pre>
<p>Though it does work if I remove reference to the getTimeZone - exact Sense console code as follows:</p>
<pre><code>POST /rating/_update_by_query
{
"script": {
"inline": "ctx._source.day = Date.parse(\"yyyy-MM-dd'T'HH:mm:ss\", ctx._source.datetime).format('EEEE')"
},
"query": {
"term": {
"_type": "transaction"
}
}
}
</code></pre>
<p>I'm not sure why the getTimeZone method is failing. I've tried "TimeZone.getTimeZone" instead of "java.util.TimeZone.getTimeZone"</p>
| <p>The Groovy code (for Java 7) you will need is going to be very similar to this:</p>
<pre><code>Date.parse("yyyy-MM-dd'T'HH:mm:ss", ctx._source.datetime, TimeZone.getTimeZone('UTC'))
.format('EEEE', TimeZone.getTimeZone("Europe/London"))
</code></pre>
|
How implement join queries in parse.com javascript? <p>I am new on parse server ( parse.com ). I have two classes "students_records" and "students_fee". I am storing fee records in class "students_fee" with objectId of "students_records" in column "student_id". Now I want to collect records from both classes by one query similar to join query we do in mysql with base on column 'fee_year' in class "students_fee". for example get all students who have 'fee_year'=2016 and 'student_id'=objectId of "students_records", this is link <a href="https://parseplatform.github.io/docs/js/guide/" rel="nofollow">https://parseplatform.github.io/docs/js/guide/</a> of guide I am currently getting help, but i can't find such thing. Can anyone tell me how to do that?</p>
<p>Thanks.</p>
| <p>Since parse use MongoDB (NoSQL) behind the scenes there is no real "join". What you can do is to create a array relationship from students to records and then use <strong>include</strong> in your query in order to include all the <strong>records</strong> under a student. </p>
<p>You can read more about it <a href="http://parseplatform.github.io/docs/js/guide/#relations" rel="nofollow">here</a></p>
<p>I recommend you to use Parse SDK's here in order to keep it simple.
the Parse SDK is available for all the popular programming languages (e.g. iOS, Android, PHP, JavaScript and more)</p>
|
Devise | autogenerated user password does not show up in email sent <p>I am trying to set up an email where a referrer will fill in some information in a form about a referee. The referee will receive an email to subscribe to my services with 2 different messages depending if he is already existing in the database or not (ghost status). But when the email is sent, the password is not automatically generated. Why ?</p>
<p>Email sent: </p>
<pre><code>You have been registered as a teacher on XX.
Please confirm your account
<a href="http://localhost:3000/en/users/confirmation?confirmation_token=6Ac-y5Ymv1GNAkb5whUK">Confirm my account</a>
and connect with these credentials log in:<br />
login: bb@ee.fr<br />
password:
</code></pre>
<p>My controller: </p>
<pre><code>def new_teacher_registered(teacher, user = nil)
@teacher = teacher
@user = user
@password = user.generate_password
mail(from: 'XX', to: teacher.email, bcc: "YY", subject: 'You have been registered on XYZ')
end
</code></pre>
<p>My view: </p>
<pre><code><% if @user.ghost? %>
You have been registered as a teacher on XXX.
Please confirm your account
<%= link_to "Confirm my account",
confirmation_url(@user, I18n.locale, :confirmation_token => @user.confirmation_token) %>
and connect with these credentials log in:<br />
login: <%= @user.email %> <br />
password: <%= @password %>
<%else%>
You have been registered on XX by <%= @teacher.studios.first.user.contact.location.name %>
</code></pre>
<p>And I have the generate_password method in my User controller</p>
<pre><code>class User < ActiveRecord::Base
.....
def generate_password
unless self.encrypted_password
@password = Devise.friendly_token.first(8)
if self.update(password: password, password_confirmation: password)
@password
else
false
end
end
end
......
end
</code></pre>
| <p>Instead of sending them an email with a password (not a best practice), why not send them a link where they can create their own password on your secure site?</p>
<p>The below example will create a reset link for them to click and give them a temporary password so that devise is happy, and then send an email with the link(the raw token).</p>
<pre><code>raw_token, hashed_token = Devise.token_generator.generate(User, :reset_password_token)
self.reset_password_token = hashed_token
self.reset_password_sent_at = Time.now.utc
self.password = Devise.friendly_token.first(8)
self.save
UserMailer.add_to_website(course, self, raw_token).deliver_later
</code></pre>
|
Activity not destroying completely <p>I have an application with the following activities:</p>
<pre><code>A->B->C
</code></pre>
<p>On <code>C</code> I am using the following code to play an mp3 file in loop when my web service returns true (which we check for periodically):</p>
<pre><code>void PlayBeepLoop()
{
try {
if(player.isPlaying())
return;
AssetFileDescriptor descriptor = getAssets().openFd("beep.mp3");
player.reset();
player.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
player.prepare();
player.setVolume(1f, 1f);
player.setLooping(true);
player.start();
} catch (Exception e) {
e.printStackTrace();
}
}
</code></pre>
<p>The problem is that if I go from <code>C->B</code> on pressing back, I believe the loop keeps on running and it beeps when it returns true.</p>
<p>Following code on <code>C</code> also does not work:</p>
<pre><code>public void onBackPressed() {
super.onBackPressed();
finish();
}
</code></pre>
<p>Please help
PS: I need the beep to stop only when the back button is pressed. Pressing home button while app is still showing <code>C</code> should allow the beeps to happen, when the app is in background.</p>
| <p>Remove super.onBackPressed() and add @Override above your onBackPressed() method.</p>
|
JUnit assertThat: check that Object equals String <p>I have <code>Map</code> declared as following:</p>
<pre><code>Map<String, Object> data
</code></pre>
<p>I put a <code>String</code> in it and verify its value like this:</p>
<pre><code>assertEquals("value", data.get("key"));
</code></pre>
<p>Now, I'd like to rewrite the verification to use <code>assertThat</code> instead of <code>assertEquals</code>. I've tried the following:</p>
<pre><code>assertThat(data.get("key"), equalTo("value"));
</code></pre>
<p>And of course it didn't work because of type mismatch:</p>
<blockquote>
<p><code>Wrong 2nd argument type. Found: 'org.hamcrest.Matcher<java.lang.String>', required: 'org.hamcrest.Matcher<? super java.lang.Object>' less...</code></p>
</blockquote>
<p>Explicit type cast of the first argument to <code>String</code> helps, but I'd like to avoid it. For example <code>assertEquals</code> doesn't require type cast.
So, how can I check that the value, which was put into <code>Map</code> object, declared above, is equal to particular <code>String</code>, using the <code>assertThat</code> method?</p>
| <p>The "more assertThat" way of doing things would be:</p>
<pre><code>Map<String, Object> expectedData = Collections.singletonMap("key", "value");
asssertThat(data, is(expectedData));
</code></pre>
<p>Please note:</p>
<ul>
<li>Maybe you need type hints for the call to singletonMap</li>
<li>Besides the <em>is</em> matcher, there are other matchers that would allow you to check that data <em>contains</em> your "expected" map data</li>
</ul>
<p>For your specific problem: that is caused because how generics come into play here; it might be sufficient to use <code>(String) data.get("key")</code> - to tell the compiler that the "actual" argument is of type String.</p>
<p>In the end - I have no idea what your problem is. I wrote down this piece of code:</p>
<pre><code>public void test() {
Map<String, Object> data = new HashMap<>();
data.put("key", "value");
assertThat(data.get("key"), is("value"));
Map<String, Object> expectedData = Collections.singletonMap("key", "value");
assertThat(data, is(expectedData));
}
</code></pre>
<p>It compiles fine, and the unit test runs and passes. In other words: actually I am unable to repro your problem.</p>
|
chef recipe - how to add a timeout to ::File.exists? in ruby_block <p>Consider this code:</p>
<pre><code>ruby_block 'wait for tomcat' do
block do
true until ::File.exists?('/usr/share/tomcat/webapps/system/WEB-INF')
end
end
</code></pre>
<p>How can I add a <code>timeout</code>, so that in the case that the deployment went wrong (and the file will never exist), my recipe can continue (and fail) after (say) 30 seconds?</p>
| <p>Just using ruby (untested, I may have forgot something there):</p>
<pre><code>ruby_block 'wait for tomcat' do
block do
iter=0
until ::File.exists?('/usr/share/tomcat/webapps/system/WEB-INF') || iter > 5 do
sleep 6
iter++
end
raise "Timeout waiting for tomcat startup" unless iter <= 5
end
end
</code></pre>
<p>But this kind of construct usually means you're falling into the converge vs compile problem. and thus you're probably trying to solve an XY problem. As the tomcat may not start before the end of the run anyway.</p>
<p>TL;DR: you're trying to code a state change instead of describing a resulting state, this goes against Configuration Management philosophy.</p>
|
Extract parent from a filepath <p>I would like to decompose a GCS URI of form :</p>
<pre><code>gs://bucket/folder1/folder2/test.csv
</code></pre>
<p>I need these capturing groups : "bucket" and "folder1/folder2/test.csv"</p>
<p>The problem is that I do not know how to exclude / from a group of any character.</p>
<p>The beginning does not work :</p>
<pre><code>^(gs:\/\/){1}(?!\/)
</code></pre>
<p>I also tried </p>
<pre><code>^(gs:\/\/){1}(?!.*\/)
</code></pre>
<p>I do not understand why it does not work because I saw answer elsewhere and it worked. I use java/clojure.</p>
<p>Thanks !</p>
<p><strong>EDIT</strong></p>
<p>My point is to do something like isolating the "bucket" name in my GCS. I tought this would match any string that does not conatin : / :</p>
<pre><code>(?!\/)
</code></pre>
<p>I saw a thread elsewhere but this beginning captured the whole chain after gs:// for me.</p>
| <p>Here is a sample in JS to match your require, another language should the same.</p>
<pre><code>/^gs:\/\/(.+?)\/(.+)$/
</code></pre>
<p>Check result <a href="http://scriptular.com/#%5Egs%3A%5C%2F%5C%2F(.%2B%3F)%5C%2F(.%2B)%24%7C%7C%7C%7C%7C%7C%7C%7C%5B%22gs%3A%2F%2Fbucket%2Ffolder1%2Ffolder2%2Ftest.csv%22%5D" rel="nofollow">here</a> </p>
|
Syntax error near END keyword? <p>I am defining this SQL Server SP, but I am getting the following error message, which is not very detailed:</p>
<p><code>Incorrect syntax near the keyword 'end'. 32 8</code></p>
<p>I am closing all <code>BEGIN</code> with an <code>END</code>, therefore I can't get it why is the engine complaining.</p>
<pre><code>CREATE PROCEDURE dbo.addReading
@deviceId int,
@facilityId int,
@reading real,
@insertionTimestamp datetime2,
@isMeter bit
AS BEGIN
IF (@isMeter = 1)
BEGIN
DECLARE @lastReading real;
DECLARE @newReading real;
-- Get last reading
SELECT @lastReading = lastReading FROM devices
WHERE facilityId = @facilityId AND id = @deviceId;
-- Update lastReading with the new one
UPDATE devices SET lastReading = @reading
WHERE facilityId = @facilityId AND id = @deviceId;
IF (@lastReading IS NOT NULL)
BEGIN
SET @newReading = @reading - @lastReading;
INSERT INTO readings (deviceId, facilityId, reading, insertionTimestamp)
VALUES (@deviceId, @facilityId, @newReading, @insertionTimestamp);
END
ELSE
BEGIN
-- Do nothing
END
END -- ---------------------------------- LINE 32 (ERROR HERE!)
ELSE
BEGIN
INSERT INTO readings (deviceId, facilityId, reading, insertionTimestamp)
VALUES (@deviceId, @facilityId, @reading, @insertionTimestamp);
END
END
GO
</code></pre>
<p>What is wrong with the <code>END</code>?</p>
| <p>From <a href="https://msdn.microsoft.com/en-us/library/ms190487.aspx" rel="nofollow"><strong>MSDN</strong></a></p>
<pre><code>BEGIN
{ sql_statement | statement_block }
END
</code></pre>
<p><em>{ sql_statement | statement_block }</em></p>
<blockquote>
<p>Is any valid Transact-SQL statement or statement grouping as defined
by using a statement block.</p>
</blockquote>
<p>You need to have a valid Transact-SQL statement between <code>Begin</code> and <code>END</code>, so cannot have this </p>
<pre><code> ELSE
BEGIN
-- Do nothing
END
</code></pre>
<p>If your <code>ELSE</code> part is not going to do anything then remove it </p>
<pre><code>IF (@isMeter = 1)
BEGIN
DECLARE @lastReading real;
DECLARE @newReading real;
-- Get last reading
SELECT @lastReading = lastReading FROM devices
WHERE facilityId = @facilityId AND id = @deviceId;
-- Update lastReading with the new one
UPDATE devices SET lastReading = @reading
WHERE facilityId = @facilityId AND id = @deviceId;
IF (@lastReading IS NOT NULL)
BEGIN
SET @newReading = @reading - @lastReading;
INSERT INTO readings (deviceId, facilityId, reading, insertionTimestamp)
VALUES (@deviceId, @facilityId, @newReading, @insertionTimestamp);
END
END
</code></pre>
|
aiohttp how to log access log? <p>I am trying to get a basic logger for aiohttp working, but there are simply no log messages being logged. Note_ logging custom messages works as expected.</p>
<pre><code>async def main_page(request: web.Request):
return "hello world"
def setup_routes(app):
app.router.add_get('/', main_page)
async def init(loop):
# load config from yaml file in current dir
conf = load_config(str(pathlib.Path('.') / 'async_config.yml'))
# setup application and extensions
app = web.Application(loop=loop)
# setup views and routes
setup_routes(app)
host, port = conf['host'], conf['port']
app['gmt_file'] = _get_gmt_file()
return app, host, port
LOG_FORMAT = '%a %l %u %t "%r" %s %b "%{Referrer}i" "%{User-Agent}i"'
log_file = "log.text"
handler = handlers.TimedRotatingFileHandler(log_file, when='midnight',
backupCount=5)
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter(LOG_FORMAT)
handler.setFormatter(formatter)
handler.name = "file_log"
loop = asyncio.get_event_loop()
app, host, port = loop.run_until_complete(init(loop))
logging.getLogger("aiohttp").addHandler(handler)
# todo host ziehen per aiohttp methods, so we are externally visible.
web.run_app(app, host=host, port=port)
</code></pre>
| <p><code>LOG_FORMAT</code> should be "%s" if any.
<code>'%a %l %u %t "%r" %s %b "%{Referrer}i" "%{User-Agent}i"'</code> is a valid parameter for <code>.make_handler(access_log_format=...)</code> call, not <code>logging.Formatter</code>.</p>
<p>As first step I suggest setting up root logger and after that going down to error/access logs.
Perhaps access log worth own private file like <code>access.log</code>. To achieving this you need to setup a handler for <code>aiohttp.access</code> logger, not for top-level <code>aiohttp</code>.</p>
|
Spring MVC 4 controllers not called <p>EDIT: I realized I made a mistake in my <code>ComponentScan</code> as a lot of commenters pointed out, I changed it but it is still not working (still 404). </p>
<p>I have a project and I'm using all annotations-based configuration. Here is the configuration files:</p>
<p><code>WebConfig.java</code></p>
<pre><code>@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "src.controller")
public class WebConfig extends WebMvcConfigurerAdapter{
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/jsp/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
</code></pre>
<p><code>WebInitializer.java</code></p>
<pre><code>public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { WebConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
</code></pre>
<p>I also have a persistence config but I don't think that's relevant to this problem. Anyways, here is my root path controller:</p>
<p><code>AuthorController.java</code>
</p>
<pre><code>@Controller
@RequestMapping({"/authors", "/"})
public class AuthorController {
@Autowired
AuthorService authorservice;
@RequestMapping(method=RequestMethod.GET)
public String getAuthors(ModelMap model){
System.out.println("----------called--------------"); //not printed
List<Author> authors = authorservice.getAllAuthors();
model.addAttribute("authors", authors);
return "authors";
}
}
</code></pre>
<p>The controller never gets called and I end up getting a 404 error. </p>
| <p>Can you tell the name of the package to which 'AuthorController' belongs ? I think issue is with <code>@ComponentScan(basePackages = "src")</code>. Here you should add package name of the controller classes.</p>
<pre><code>@ComponentScan(basePackages = "com.sample.app")
@ComponentScan(basePackages = "com.sample.*")
@ComponentScan(basePackages = "com.*")
</code></pre>
<p>All the above are valid entries for ComponentScan annotation.</p>
|
Plotting decision tree, graphvizm pydotplus <p>I'm following the tutorial for decision tree on <a href="http://scikit-learn.org/stable/modules/tree.html" rel="nofollow">scikit</a> documentation.
I have <code>pydotplus 2.0.2</code> but it is telling me that it does not have <code>write</code> method - error below. I've been struggling for a while with it now, any ideas, please? Many thanks!</p>
<pre><code>from sklearn import tree
from sklearn.datasets import load_iris
iris = load_iris()
clf = tree.DecisionTreeClassifier()
clf = clf.fit(iris.data, iris.target)
from IPython.display import Image
dot_data = tree.export_graphviz(clf, out_file=None)
import pydotplus
graph = pydotplus.graphviz.graph_from_dot_data(dot_data)
Image(graph.create_png())
</code></pre>
<p>and my error is </p>
<pre><code> /Users/air/anaconda/bin/python /Users/air/PycharmProjects/kiwi/hemr.py
Traceback (most recent call last):
File "/Users/air/PycharmProjects/kiwi/hemr.py", line 10, in <module>
dot_data = tree.export_graphviz(clf, out_file=None)
File "/Users/air/anaconda/lib/python2.7/site-packages/sklearn/tree/export.py", line 375, in export_graphviz
out_file.write('digraph Tree {\n')
AttributeError: 'NoneType' object has no attribute 'write'
Process finished with exit code 1
</code></pre>
<p>----- UPDATE -----</p>
<p>Using the fix with <code>out_file</code>, it throws another error:</p>
<pre><code> Traceback (most recent call last):
File "/Users/air/PycharmProjects/kiwi/hemr.py", line 13, in <module>
graph = pydotplus.graphviz.graph_from_dot_data(dot_data)
File "/Users/air/anaconda/lib/python2.7/site-packages/pydotplus/graphviz.py", line 302, in graph_from_dot_data
return parser.parse_dot_data(data)
File "/Users/air/anaconda/lib/python2.7/site-packages/pydotplus/parser.py", line 548, in parse_dot_data
if data.startswith(codecs.BOM_UTF8):
AttributeError: 'NoneType' object has no attribute 'startswith'
</code></pre>
| <p>The problem is that you are setting the parameter <code>out_file' to</code>None<code>.
If you look at the [documentation][1], if you set it at</code>None<code>it returns the</code>string<code>file directly and does not create a file. And of course a</code>string` does not have a 'write' method.</p>
<p>Therefore, do as follows :</p>
<pre><code>dot_data = tree.export_graphviz(clf)
graph = pydotplus.graphviz.graph_from_dot_data(dot_data)
</code></pre>
|
Seaching big files using list in Python - How can improve the speed? <p>I have a folder with 300+ .txt files with total size of 15GB+. These files contain tweets. Each line is a different tweet. I have a list of keywords I'd like to search the tweets for. I have created a script that searches each line of every file for every item on my list. If the tweet contains the keyword, then it writes the line into another file. This is my code: </p>
<pre><code># Search each file for every item in keywords
print("Searching the files of " + filename + " for the appropriate keywords...")
for file in os.listdir(file_path):
f = open(file_path + file, 'r')
for line in f:
for key in keywords:
if re.search(key, line, re.IGNORECASE):
db.write(line)
</code></pre>
<p>This is the format each line has: </p>
<pre><code>{"created_at":"Wed Feb 03 06:53:42 +0000 2016","id":694775753754316801,"id_str":"694775753754316801","text":"me with Dibyabhumi Multiple College students https:\/\/t.co\/MqmDwbCDAF","source":"\u003ca href=\"http:\/\/www.facebook.com\/twitter\" rel=\"nofollow\"\u003eFacebook\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":5981342,"id_str":"5981342","name":"Lava Kafle","screen_name":"lkafle","location":"Kathmandu, Nepal","url":"http:\/\/about.me\/lavakafle","description":"@deerwalkinc 24000+ tweeps bigdata #Team #Genomics http:\/\/deerwalk.com #Genetic #Testing #population #health #management #BigData #Analytics #java #hadoop","protected":false,"verified":false,"followers_count":24742,"friends_count":23169,"listed_count":1481,"favourites_count":147252,"statuses_count":171880,"created_at":"Sat May 12 04:49:14 +0000 2007","utc_offset":20700,"time_zone":"Kathmandu","geo_enabled":true,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"EDECE9","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme3\/bg.gif","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme3\/bg.gif","profile_background_tile":false,"profile_link_color":"088253","profile_sidebar_border_color":"FFFFFF","profile_sidebar_fill_color":"E3E2DE","profile_text_color":"634047","profile_use_background_image":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/677805092859420672\/kzoS-GZ__normal.jpg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/677805092859420672\/kzoS-GZ__normal.jpg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/5981342\/1416802075","default_profile":false,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"is_quote_status":false,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[],"urls":[{"url":"https:\/\/t.co\/MqmDwbCDAF","expanded_url":"http:\/\/fb.me\/Yj1JW9bJ","display_url":"fb.me\/Yj1JW9bJ","indices":[45,68]}],"user_mentions":[],"symbols":[]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"low","lang":"en","timestamp_ms":"1454482422661"}
</code></pre>
<p>The script works but <strong>it takes a lot of time</strong>. For ~40 keywords it needs more than 2 hours. Obviously my code is not optimized. What can I do to improve the speed? </p>
<p>p.s. I have read some relevant questions regarding searching and speed but I suspect that the problem in my script lies in the fact that I'm using a list for the keywords. I've tried some of the suggested solutions but to no avail. </p>
| <h2>1) External library</h2>
<p>If you're willing to lean on external libraries (and time to execute is more important than the one-off time cost to install), you might be able to gain some speed by loading each file into a simple Pandas DataFrame and performing the keyword search as a vector operation. To get the matching tweets, you would do something like:</p>
<pre><code>import pandas as pd
dataframe_from_text = pd.read_csv("/path/to/file.txt")
matched_tweets_index = dataframe_from_text.str.match("keyword_a|keyword_b")
dataframe_from_text[matched_tweets_index] # Uses the boolean search above to filter the full dataframe
# You'd then have a mini dataframe of matching tweets in `dataframe_from_text`.
# You could loop through these to save them out to a file using the `.to_dict(orient="records")` format.
</code></pre>
<p>Dataframe operations within Pandas can be really quick so might be worth investigating.</p>
<h2>2) Group your regex</h2>
<p>Looks like you're not logging which keyword you matched against. If this is true, you could group your keywords into a single regex query like so:</p>
<pre><code>for line in f:
keywords_combined = "|".join(keywords)
if re.search(keywords_combined, line, re.IGNORECASE):
db.write(line)
</code></pre>
<p>I've not tested this but by reducing the number of loops per line, that could trim some time off.</p>
|
Cannot resolve symbol activity_is_not_in_background? <p>activity_is_not_in_background is showing red line in if statement
i just follow this tutorial <a href="http://stackoverflow.com/questions/19145061/how-can-i-create-a-thread-that-running-on-background-on-android">How can i create a Thread that running on background on Android</a></p>
<pre><code>public void run() {
// DO your work here
// get the data
if (activity_is_not_in_background) {
runOnUiThread(new Runnable() {
@Override
public void run() {
//uddate UI
runInBackground();
}
});
} else {
runInBackground();
}
}
</code></pre>
| <p>You need to initiate the variable first
e.g.
boolean activity_is_not_in_background = true;</p>
<p>you will need to make this variable false, when you start another activity. If you still did not get it, u may comment and I will get back to you ASAP.</p>
|
LIRC mode2 waits for continuous user input, in Raspberry pi I am building a universal remote using java. looking for receiving input (RAW). <p>I am looking for a solution in java for recording inputs for LIRC codes of any remote. </p>
<p>i have tried</p>
<pre><code> Process p = Runtime.getRuntime().exec("mode2 [driver_details] -m");
</code></pre>
<p>it executes but hangs the UI and i cant stop it implicitly...</p>
<p>every time i had to stop it forcefully...</p>
<p>please help me i have been looking for the answer for 2 months and i got nothing..</p>
<p>or suggest me some library for java for LIRC..</p>
<p>i have tried <strong>jlirc</strong> but i cant found to record the raw inputs...
similarly i can send the ir signals using same method and didn't faced any problem.</p>
<p>I have even tried <strong>waitfor()</strong> method of <strong>process</strong> but didn't got anything</p>
| <p>First of all there is already at least one Java application which can record LIRC codes for any remote: IrScrutinizer at <a href="http://www.harctoolbox.org/IrScrutinizer.html" rel="nofollow">http://www.harctoolbox.org/IrScrutinizer.html</a></p>
<p>That said, you did not mention the lirc version used. IIRC, older versions including the really old 0.9.0 was not able to redirect the mode2 output. So, if you still want to follow this path, updating lirc to current 0.9.4b is a starter. Depending on your platform this might or might not require you to build it from upstream sources from <a href="https://sourceforge.net/projects/lirc/files/LIRC/0.9.4b/" rel="nofollow">https://sourceforge.net/projects/lirc/files/LIRC/0.9.4b/</a> </p>
<p>Note that the update from 0.9.0 to 0.9.4 is non-trivial, the configuration is very different. </p>
|
Fade out elements then fade in selected <p>I've been trying to write a function that fades out all of my elements and then fades in the selected one only I can't get it working for some reason. </p>
<p>I've used other articles on SO only it hasn't seemed to have helped.</p>
<p>Can anybody point me int he right direction?</p>
<p><a href="https://jsfiddle.net/mL329edr/" rel="nofollow">https://jsfiddle.net/mL329edr/</a></p>
<pre><code>$('.vacancy-title a').on('click', function(e){
e.preventDefault();
var item = $(this).attr('data-dept') + '-verticals';
$.when($('.vertical').fadeOut('slow')).done(function () {
alert(item);
$(item).fadeIn('slow');
});
});
</code></pre>
| <p>The problem is that you're not using the right selector.</p>
<p>This uses the exact same code but fixes your problem which is the missing selector which was the <code>.</code> before the variable <code>item</code></p>
<p>Update <a href="https://jsfiddle.net/mL329edr/2/" rel="nofollow">JSFiddle</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-js lang-js prettyprint-override"><code>$('.vacancy-title a').on('click', function(e) {
e.preventDefault();
var item = $(this).attr('data-dept') + '-verticals';
$.when($('.vertical').fadeOut('slow')).done(function() {
$('.' + item).fadeIn('slow');
});
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.vertical {
display: none;
}
.vertical:first-child {
display: block
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Vacancies -->
<section class="vacancies">
<div class="row">
<div class="inner">
<nav class="vacancy-title">
<ul>
<li><a href="#" data-dept="design">Design</a>
</li>
<li><a href="#" data-dept="seo">SEO</a>
</li>
<li><a href="#" data-dept="development">Development</a>
</li>
</ul>
</nav>
</div>
</div>
<div class="row">
<div class="inner">
<div class="vacancy-verticals">
<!-- Design -->
<div class="design-verticals vertical">dessssign
<div class="columns small-12 large-4">
<article>
<header>
<h3 itemprop="title">Front End Designers</h3>
</header>
</article>
</div>
<div class="columns small-12 large-4">
<article>
<header>
<h3 itemprop="title">Front End Designers</h3>
</header>
</article>
</div>
<div class="columns small-12 large-4">
<article>
<header>
<h3 itemprop="title">Front End Designers</h3>
</header>
</article>
</div>
</div>
<!-- SEO -->
<div class="seo-verticals vertical">
<div class="columns small-12 large-4">
<article>
<header>
<h3 itemprop="title">Front End Designers</h3>
</header>
</article>
</div>
<div class="columns small-12 large-4">
<article>
<header>
<h3 itemprop="title">Front End Designers</h3>
</header>
</article>
</div>
<div class="columns small-12 large-4">
<article>
<header>
<h3 itemprop="title">Front End Designers</h3>
</header>
</article>
</div>
</div>
<!-- DEV -->
<div class="development-verticals vertical">
<div class="columns small-12 large-4">
<article>
<header>
<h3 itemprop="title">Front End Designers</h3>
</header>
</article>
</div>
<div class="columns small-12 large-4">
<article>
<header>
<h3 itemprop="title">Front End Designers</h3>
</header>
</article>
</div>
<div class="columns small-12 large-4">
<article>
<header>
<h3 itemprop="title">Front End Designers</h3>
</header>
</article>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- Vacancies -->
</div></code></pre>
</div>
</div>
</p>
|
Create a custom URL and outputting HTML form data <p>For my first Flask project I wanted to create a basic Flask app using Riot Game's API for League of Legends. I've got all the processing of API working but I'm having trouble going about outputting it.</p>
<p>I take the input from a form on one page.</p>
<pre><code><form class="navbar-form navbar-left" action="{{ url_for('current_game_output') }}" method="POST">
<div class="form-group">
<input type="text" class="form-control" placeholder="Summoner Name" name="summoner_name">
<select class="form-control" name="region">
<option value="oce">Oceanic</option>
<option value="na">North America</option>
<option value="euw">Europe West</option>
</select>
</div>
<button type="submit" class="btn btn-default" value="Send">Submit</button>
</form>
</code></pre>
<p>And I am trying to output the data returned from the API onto the next page.</p>
<pre><code>{% extends "header.html" %}
{% block body %}
<h3> Team 2 </h3>
<table class="table table-bordered" width="50%">
<tr>
<th width="48%">Summoner Name</th>
<th width="48%">Champion</th>
<th width="4%">Pic</th>
</tr>
{% for player in team1 %}
<tr>
<td>{{ player[0] }}</td>
<td>{{ player[1] }}</td>
<td><img width="20px" src="{{ url_for('static', filename='images/championIcons/') }}{{ player[1].replace(" ", "") }}_Square_0.png"></td>
</tr>
{% endfor %}
</table>
<h3> Team 1 </h3>
<table class="table table-bordered" width="50%">
<tr>
<th width="48%">Summoner Name</th>
<th width="48%">Champion</th>
<th width="4%">Pic</th>
</tr>
{% for player in team2 %}
<tr>
<td>{{ player[0] }}</td>
<td>{{ player[1] }}</td>
<td><img width="20px" src="{{ url_for('static', filename='images/championIcons/') }}{{ player[1].replace(" ", "") }}_Square_0.png"></td>
</tr>
{% endfor %}
</table>
{% endblock %}
</code></pre>
<p>I'd like the URL of the output page to be dynamic'/currentgame/region/username' but keep getting errors when trying to do so. </p>
<p>Relevant part of my views.py file (hidden my api key):</p>
<pre><code>@app.route('/header')
def header():
return render_template("header.html")
@app.route('/current')
def current():
return render_template("current.html")
@app.route('/currentgame/<region>/<name>', methods=['POST'])
def current_game_output(region, name):
region = request.form['region']
summoner_name = request.form['summoner_name']
api = RiotAPI('APIKEYGOESHERE', region)
team1, team2 = current_game_data(summoner_name, region, api)
return render_template("output.html",team1=team1,team2=team2)
</code></pre>
<p>Any help/pointers on the best way to output/return the data would be appreciated.
Thanks</p>
| <p>You should post the error as well.</p>
<p>In a quick looks this should be fixed:</p>
<pre><code>@app.route('/currentgame/<string:region>/<string:name>', methods=['POST'])
def current_game_output(region, name):
region = request.form['region']
summoner_name = request.form['summoner_name']
api = RiotAPI('APIKEYGOESHERE', region)
team1, team2 = current_game_data(summoner_name, region, api)
return render_template("output.html",team1=team1,team2=team2)
</code></pre>
<p>Change route to <code>/currentgame/<string:region>/<string:name></code></p>
|
How to create html with link-to property inside custom jquery plugin? <p>I have a custom jquery plugin that use to create drop down html for a search box.
Inside that, html is created as follows.</p>
<pre><code>$.each(stack, function (i, stackItem) {
var url = _getItemURL(stackItem, lang);
if (stackItem.INS !== undefined) {
html += '<li class="row"> <a href="' + url + '">' + stackItem.DS_HIGHLIGHTED + ' - ' + stackItem.E + '<br>' + stackItem.TICKER_DESC + '</a> </li>';
} else {
html += '<li class="row"> <a href="' + url + '">' + stackItem.COMPANY_DESC_HIGHLIGHTED + '<br>' /*+ _getCountry(stackItem.CC, lang)*/ + '</a> </li>';
}
itemCount++;
});
</code></pre>
<p>As you can see href attribute is used to create links in this html. But when user click on those links application reloads the browser page. I want it to correctly map to different route in the application like in hbs files as follows</p>
<pre><code><li> {{#link-to 'stock-overview' 'en' 'tdwl' '1010'}}Stock{{/link-to}} </li>
</code></pre>
<p>How can I generate html like that inside previous java script code. </p>
<p>Appreciate any help?</p>
| <p>First, I would recommend you to think if you really need that jQuery plugin or could go with a plain ember solution. There are some pretty fancy addons like <a href="http://www.ember-power-select.com" rel="nofollow">ember-power-select</a>.</p>
<p>But if you really want to do that you need to understand that a <code>{{#link-to}}</code> does not only generate a <code><a></code> tag but only handles clicks on it and then doing a <code>transitionTo</code>.</p>
<p>So no, its not possible to do this when you simply append the HTML to the DOM. You would have to catch the <code>click</code> events on the <code><a></code> tags manually and then trigger the transition. It depends a bit how you inject the <code>html</code> into the DOM.</p>
<p>One thing you could do is to create a unique <code>id</code> for each <code><a></code> tag and after you inserted the html into the DOM you find the <code><a></code> tags by the <code>id</code> and attach the <code>onclick</code> event.</p>
<p>A better way would be to create DOM instead of HTML, so manually call <code>document.createElement</code> and then attach the <code>click</code> event.</p>
<p>To trigger the transition you can do something like this inside any Object that has the owner injected (like a component):</p>
<pre><code>Ember.getOwner(this).lookup('controller:application').transitionToRoute('stock-overview', 'en', 'tdwl', '1010');
</code></pre>
<p>However cleanly the best solution would be to go for a ember handlebars template and a <code>{{#each}}</code> loop instead of the jQuery solution. To tell you how to do that however we need more information. So best is probably you ask a new question and explain exactly what you want to achieve, and now ask about a problem you have with a probably wrong solution for another problem.</p>
|
Updated Android Studio, receiving DuplicateFileException <p>I just updated Android Studio and I cannot build my app after doing so. I receive an exception looking like this:</p>
<pre><code>Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'.
> com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK META-INF/LICENSE
File1: /Users/andersvincentlund/.gradle/caches/modules-2/files-2.1/com.fasterxml.jackson.core/jackson-core/2.2.2/d20be6a5ddd6f8cfd36ebf6dea329873a1c41f1b/jackson-core-2.2.2.jar
File2: /Users/andersvincentlund/.gradle/caches/modules-2/files-2.1/com.fasterxml.jackson.core/jackson-databind/2.2.2/3c8f6018eaa72d43b261181e801e6f8676c16ef6/jackson-databind-2.2.2.jar
File3: /Users/andersvincentlund/.gradle/caches/modules-2/files-2.1/com.fasterxml.jackson.core/jackson-annotations/2.2.2/285cb9c666f0f0f3dd8a1be04e1f457eb7b15113/jackson-annotations-2.2.2.jar
</code></pre>
<p>I have googled this type of error and have been suggested to add:</p>
<pre><code>packagingOptions {
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
exclude '...'
}
</code></pre>
<p>in the android clause in gradle. This changes nothing(except makes my build potentially illegal since I would be ignoring licensing for OS code?). Does anyone have an idea on how to solve this? I was hoping an update would not break the code.</p>
<p>EDIT:</p>
<p>I got a comment regarding gradle file so I am posting the entire thing below:</p>
<pre><code>apply plugin: 'com.android.application'â¨
apply plugin: 'com.neenbedankt.android-apt'â¨
apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'
android {
packagingOptions {
exclude 'META-INF/NOTICE' // will not include NOTICE file
exclude 'META-INF/LICENSE' // will not include LICENSE file
exclude 'META-INF/notice'
exclude 'META-INF/notice.txt'
exclude 'META-INF/license'
exclude 'META-INF/license.txt'
}
signingConfigs {
config {
keyPassword 'XXXXX'
storeFile file('/XXXXX/XXXXX/XXXXX/android.keystore')
storePassword 'XXXXX'
keyAlias 'XXXXX'
}
}
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "XXXXX"
minSdkVersion 21
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
signingConfig signingConfigs.config
}
}
testOptions {
unitTests.returnDefaultValues = true
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
testCompile 'org.mockito:mockito-core:1.9.5'
apt 'com.google.dagger:dagger-compiler:2.5'
provided 'javax.annotation:jsr250-api:1.0'
compile 'com.android.support:appcompat-v7:24.2.0'
compile 'com.google.android.gms:play-services-auth:9.4.0'
compile 'com.google.dagger:dagger:2.5'
compile 'com.google.firebase:firebase-core:9.4.0'
compile 'com.google.firebase:firebase-database:9.4.0'
compile 'com.google.firebase:firebase-auth:9.4.0'
compile 'com.firebaseui:firebase-ui:0.3.1'
compile 'com.firebase:firebase-client-android:2.4.0'
compile group: 'com.google.guava', name: 'guava', version: '19.0'
}
apply plugin: 'com.google.gms.google-services'
</code></pre>
| <p>Just Remove:</p>
<pre><code>compile fileTree(include: ['*.jar'], dir: 'libs')
</code></pre>
<p>from</p>
<pre><code>dependencies {}
</code></pre>
<p>The <code>jackson-core-2.2.2.jar</code>is already present in your <code>libs/</code> but another dependency is trying to add it again externally. </p>
|
Regex may contains a group or not <p>I have multiple string to parse. This text could be multiline or not.
Also, some part may not be exist. I have some samples to understand what I need.</p>
<p>Samples;<br>
1-singleline) 00026A123456123456789012741852<br>
2-multiline) 00030A789ABC210987654321258369X123</p>
<p>X is seperate groups.<br>
I try to use this regex: <code>(?<group1>.*)(?:[X](?<group2>.*))</code></p>
| <p>If there can be only 1 <code>X</code> separating the groups, or it is the first <code>X</code> that always separates the groups, you may use</p>
<pre><code>^(?<group1>.*?)(?:X(?<group2>.*))?$
</code></pre>
<p>See the <a href="https://regex101.com/r/hpScrj/3" rel="nofollow">regex demo</a>.</p>
<p>The first group pattern should be a lazy dot <code>.*?</code> and the second one should be wrapped with an optional non-capturing group <code>(?:....)?</code>.</p>
<p>When the text has no <code>X...</code>, the second capturing group is considered <em>non-participating</em>, and thus is either <em>null</em> or <em>empty</em> (depending on where you use the regex).</p>
<p><strong>Details</strong>:</p>
<ul>
<li><code>^</code> - start of string</li>
<li><code>(?<group1>.*?)</code> - any 0+ chars (or excluding linebreak symbols, depending on the regex engine) as few as possible up to the first</li>
<li><code>(?:X(?<group2>.*))?</code> - an optional sequence of <code>X</code> followed with any 0+ chars as many as possible up to </li>
<li><code>$</code> - the end of string.</li>
</ul>
|
Hive: external partitioned table from Avro <p>Is it possible to create an external table in Hive based on Avro files that also add columns for the directory partitions:</p>
<p>Let's say I have data stored in <code>/data/demo/dt=2016-02-01</code> and so on. I then tried the following but I get 0 rows when I select from the table:</p>
<pre><code>CREATE EXTERNAL TABLE demo
PARTITIONED BY (date STRING)
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.avro.AvroSerDe'
STORED AS AVRO
LOCATION '/data/demo/'
TBLPROPERTIES ('avro.schema.url' = 'hdfs:///path/to/schema.avsc');
</code></pre>
<p>I tried without the <code>PARTITIONED BY</code> clause and then I get the records but obviously without the <code>key=value</code> directory partitions. Is this at all possible?</p>
| <p>Since the partition name is in your case <code>dt</code>, not <code>date</code>, you have to use <code>PARTITIONED BY (dt string)</code>, and then you still need to add the partitions to the metastore :</p>
<pre><code>ALTER TABLE demo ADD PARTITION (dt='2016-02-01')
</code></pre>
<p>If you have several partitions, you can <a href="https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL#LanguageManualDDL-RecoverPartitions(MSCKREPAIRTABLE)" rel="nofollow">repair</a> the table, and it will add them automatically :</p>
<pre><code>msck repair table demo
</code></pre>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.