input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
How to delegate mouse events to all underlying overlapped panes in JavaFX? <p>I have some top decoration pane, which I want to process/preprocess mouse events, but which should not consume them, i.e. all overlapped panes should work as if they were not overlapped by decoration pane.</p>
<p>How to do this? I failed with several tries.</p>
<p>Below is a code with 3 panes. Green one is "decorating". The task is to make it transparent to mouse events. Yellow and blue panes are worker panes. They should work as if they were not overlapped by green pane.</p>
<p>But green pane should receive mouse events nevertheless.</p>
<p>Commented lines indicate what I tries and comments say what appeared wrong:</p>
<pre><code>import javafx.application.Application;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.event.EventType;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
/**
* Created by dims on 13.10.2016.
*/
public class DelegateEventsToOverlappedNodes extends Application{
@Override
public void start(Stage primaryStage) throws Exception {
StackPane root = new StackPane();
root.setBackground(new Background(new BackgroundFill(Color.RED, CornerRadii.EMPTY, Insets.EMPTY)));
AnchorPane yellowPane = new AnchorPane();
yellowPane.setBackground(new Background(new BackgroundFill(Color.YELLOW, CornerRadii.EMPTY, Insets.EMPTY)));
yellowPane.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
System.out.println("yellowPane clicked");
}
});
root.getChildren().add(yellowPane);
Pane bluePane = new Pane();
bluePane.setBackground(new Background(new BackgroundFill(Color.BLUE, CornerRadii.EMPTY, Insets.EMPTY)));
bluePane.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
System.out.println("bluePane clicked");
}
});
AnchorPane.setLeftAnchor(bluePane, 200.);
AnchorPane.setRightAnchor(bluePane, 200.);
AnchorPane.setTopAnchor(bluePane, 200.);
AnchorPane.setBottomAnchor(bluePane, 200.);
yellowPane.getChildren().add(bluePane);
AnchorPane greenPane = new AnchorPane();
greenPane.setBackground(new Background(new BackgroundFill(Color.rgb(0, 255, 0, 0.9), CornerRadii.EMPTY, Insets.EMPTY)));
greenPane.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
System.out.println("greenPane clicked");
}
});
// greenPane.setVisible(false); // green pane invisible at all
// greenPane.setMouseTransparent(true); // green clicked doesn't occur
// greenPane.addEventHandler(Event.ANY, event -> yellowPane.fireEvent(event)); // works for yellow pane, but not for blue sub pane
root.getChildren().add(greenPane);
Scene scene = new Scene(root, 800, 600);
primaryStage.setScene(scene);
primaryStage.setTitle("DelegateEventsToOverlappedNodes");
primaryStage.show();
}
public static void main(String[] args) {
DelegateEventsToOverlappedNodes.launch(args);
}
}
</code></pre>
| <p>You could set <code>greenPane</code> mouse transparent again and add an event filter to <code>root</code> to preprocess the mouse events here:</p>
<pre class="lang-java prettyprint-override"><code>greenPane.setMouseTransparent(true);
root.addEventFilter(MouseEvent.MOUSE_CLICKED, event -> System.out.println(event));
</code></pre>
<p>Filters receive events during the event capturing phase of event processing, whereas handlers are triggered during the event bubbling phase. You could also use an event handler, but I think a filter is more idiomatic in this case (read more <a href="https://docs.oracle.com/javase/8/javafx/events-tutorial/processing.htm" rel="nofollow">here</a>).</p>
<p>Your code:</p>
<pre class="lang-java prettyprint-override"><code>import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class DelegateEventsToOverlappedNodes extends Application {
public static void main(String[] args) {
DelegateEventsToOverlappedNodes.launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
// Yellow pane.
AnchorPane yellowPane = new AnchorPane();
yellowPane.setBackground(new Background(new BackgroundFill(Color.YELLOW, CornerRadii.EMPTY, Insets.EMPTY)));
yellowPane.setOnMouseClicked(event -> System.out.println("yellowPane clicked"));
// Blue pane.
AnchorPane bluePane = new AnchorPane();
bluePane.setBackground(new Background(new BackgroundFill(Color.BLUE, CornerRadii.EMPTY, Insets.EMPTY)));
bluePane.setOnMouseClicked(event -> System.out.println("bluePane clicked"));
AnchorPane.setLeftAnchor(bluePane, 200.0);
AnchorPane.setRightAnchor(bluePane, 200.0);
AnchorPane.setTopAnchor(bluePane, 200.0);
AnchorPane.setBottomAnchor(bluePane, 200.0);
// Green pane.
AnchorPane greenPane = new AnchorPane();
greenPane.setBackground(new Background(new BackgroundFill(Color.rgb(0, 255, 0, 0.9), CornerRadii.EMPTY, Insets.EMPTY)));
greenPane.setMouseTransparent(true);
// Root pane.
StackPane rootPane = new StackPane();
rootPane.setBackground(new Background(new BackgroundFill(Color.RED, CornerRadii.EMPTY, Insets.EMPTY)));
rootPane.addEventFilter(MouseEvent.MOUSE_CLICKED, event -> System.out.println(event));
// Layout and scene.
yellowPane.getChildren().add(bluePane);
rootPane.getChildren().addAll(yellowPane, greenPane);
primaryStage.setScene(new Scene(rootPane, 800.0, 600.0));
primaryStage.setTitle("DelegateEventsToOverlappedNodes");
primaryStage.show();
}
}
</code></pre>
<p>If you created <code>greenPane</code> only to preprocess events, there's no need for it anymore.</p>
|
Rails - cUrl GET with session cookie information - Getting 401 <p>I am trying to cUrl GET a Rails URL in a hosted application. To test, I want to use a logged in session in my browser. I grabbed the cookies from the browser tab and passed it to cUrl command, but it's giving 401 Not Authorized.</p>
<p>I am using </p>
<pre><code>curl -H 'session: 2asdfjlksfja32asdfuyio24fasdf' http://my-url/some-path
</code></pre>
<p>The session is the key that is sent by browser to the server.</p>
| <p>How are you sending the cookies?
According to the curl documentation you should use the <code>-b, --cookie STRING/FILE Read cookies from STRING/FILE (H)</code> option.</p>
<p>The way you are using the <code>-H</code> is to set a header with "Session:" which is not a <a href="https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Request_fields" rel="nofollow">standard HTTP header</a></p>
<p>From a signed in browser, use developer tools (Network tab) to inspect the raw headers in the request sent to the server, then try to replicate the Headers and Cookies using the curl command.</p>
|
Angular 2: Bind class just to selected element [ngClass] <p>I'm displaying arrows in a header table with icons from bootstrap, the problem is when i make click on a column all the columns get the icon class here is what talking about:
<a href="https://i.stack.imgur.com/CAS81.png" rel="nofollow"><img src="https://i.stack.imgur.com/CAS81.png" alt="enter image description here"></a></p>
<p>This is the code:</p>
<p>HTML -></p>
<pre><code><table class="table table-hover">
<thead>
<th (click)="orderBy('username')">Username<span [ngClass]="displayArrow()"></span></th>
<th (click)="orderBy('email')">Email<span [ngClass]="displayArrow()"></span></th>
<th (click)="orderBy('id')">Id<span [ngClass]="displayArrow()"></span></th>
<th (click)="orderBy('roleId')">Role Id<span [ngClass]="displayArrow()"></span></th>
</thead>
<tbody>
<tr *ngFor="let user of usersListData | orderByController: OrderByParams">
<td (click)="onSelectFilterParam(user.username)">{{user.username}}</td>
<td (click)="onSelectFilterParam(user.email)">{{user.email}}</td>
<td (click)="onSelectFilterParam(user.id)">{{user.id}}</td>
<td (click)="onSelectFilterParam(user.roleId)">{{user.roleId}}</td>
</tr>
</tbody>
</code></pre>
<p></p>
<p>AppComponent -></p>
<pre><code>private toggleArrow = 0;
orderBy(columnName: string) {
this.toggleArrow++;
if(this.toggleArrow > 2) {
this.toggleArrow = 0;
}
console.log(this.toggleArrow);
}
displayArrow() {
if(this.toggleArrow === 0) {
return '';
}
else if(this.toggleArrow === 1) {
return 'glyphicon glyphicon-chevron-up';
}
else if(this.toggleArrow === 2) {
return 'glyphicon glyphicon-chevron-down';
}
}
</code></pre>
<p>It's possible just bind the class to one element?</p>
| <p>This might not be the most elegant of solutions, but you can do something like this by declaring the columns in your component. </p>
<pre><code> columns: any[] = [
{'Name':'username','Direction':0},
{'Name':'email','Direction':0},
{'Name':'id','Direction':0},
{'Name':'roleId','Direction':0}
]
</code></pre>
<p>In your HTML you could do something like this:</p>
<pre><code><table class="table table-hover">
<thead>
<th *ngFor="let col of columns" (click)="orderBy(col.Direction)">{{ col.Name }}<span [ngClass]="displayArrow(col.Direction)"></span></th>
</thead>
<tbody>
<tr *ngFor="let user of usersListData | orderByController: OrderByParams">
<td (click)="onSelectFilterParam(user.username)">{{user.username}}</td>
<td (click)="onSelectFilterParam(user.email)">{{user.email}}</td>
<td (click)="onSelectFilterParam(user.id)">{{user.id}}</td>
<td (click)="onSelectFilterParam(user.roleId)">{{user.roleId}}</td>
</tr>
</tbody>
</code></pre>
<p>OrderBy would then be</p>
<pre><code>orderBy(dir: number) {
dir++;
if(dir > 2) {
dir = 0;
}
console.log(dir);
}
</code></pre>
<p>and finally the displayClass()</p>
<pre><code>displayArrow(dir: number): string {
if(dir === 0) {
return '';
}
else if(dir === 1) {
return 'glyphicon glyphicon-chevron-up';
}
else if(dir === 2) {
return 'glyphicon glyphicon-chevron-down';
}
}
</code></pre>
|
Why is my expression matching something that clearly doesn't meet the expression? <p>I'm using Rails 4.2.7. I want to match the pattern, numbers, an arbitrary number of spaces, and a potential "+" at the end. So I wrote</p>
<pre><code>2.3.0 :013 > /\d+\s*\+?/.match("40+")
=> #<MatchData "40+">
</code></pre>
<p>However, this is also matching</p>
<pre><code>2.3.0 :012 > /\d+\s*\+?/.match("40-50")
=> #<MatchData "40">
</code></pre>
<p>What gives? The string "40-50" doesn't match the expression provided, but clearly I'm not doing something right in my regex.</p>
| <p>If you want it to match only the full string, use the <code>\A</code> and <code>\z</code> markers. Like this:</p>
<pre><code>/\A\d+\s*\+\z$/.match("40-50")
</code></pre>
<p>This will force the regular expression to match only if the full string match it.</p>
<p>Otherwise, the way you have it now, it will stop as soon as it find a match anywhere in your string.</p>
<p><code>\d+</code> means one digit or more.</p>
<p><code>\s*</code> means an optional space.</p>
<p><code>\+?</code> means an optional + sign</p>
<p>So <code>40</code> does match those conditions.</p>
|
Exception in readObject of String <p>I'm trying to read a text file from the server string by string (line by line from the file).</p>
<p>It works good until readObject in the client side has nothing to read and than I get exception and going to "client error".</p>
<p>I have tried to close streams and sockets, ask questions and also I have tried to use scanner but none of the options above helped me.</p>
<p>Can u help me?</p>
<p>client side:</p>
<pre><code>package hit.model;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class MMUClient {
private ArrayList<String> userDetails;
private String fileFromServer =null;
private ObjectOutputStream outToServer;
private ObjectInputStream inFromServer;
private String fileName;
private boolean ERROR = true;
private String messageError = "No Errors";
private PrintWriter printerWriter;
public MMUClient(ArrayList<String> userParameters){
userDetails = userParameters;
};
public MMUClient(String filePath){
fileName = filePath;
};
public ArrayList<String> getUserDetails() {
return userDetails;
}
public void setUserDetails(ArrayList<String> userDetails) {
this.userDetails = userDetails;
clientAuthenticate();
}
public void clientAuthenticate(){
try{
Socket myServer = null;
try {
//1. creating a socket to connect to the server
myServer = new Socket("localhost", 12345);
System.out.println("Connected to localhost in port 12345");
//2. get Input and Output streams
outToServer = new ObjectOutputStream(myServer.getOutputStream());
inFromServer=new ObjectInputStream(myServer.getInputStream());
//3: Communicating with the server
outToServer.writeObject(userDetails);
//4. get server answer
fileFromServer = (String) inFromServer.readObject();
printerWriter = new PrintWriter("logClient.txt");
if(fileFromServer.contains("Error")){
messageError = "Error";
ERROR = true;
}
else{
if (fileFromServer.contains("Wrong")){
messageError = "Wrong";
ERROR = true;
}
else
while(fileFromServer != null){
// messageError = "No Errors";
// ERROR = false;
System.out.println(fileFromServer);
printerWriter.println(fileFromServer);
// writeData(fileFromServer);
fileFromServer = (String) inFromServer.readObject();
}
printerWriter.close();
}
} catch (IOException e) {
System.out.println("Client error");
}finally{
inFromServer.close();
outToServer.close();
myServer.close();
}
}catch (Exception e) {
System.out.println("Client error Details");
}
}
//**********************write into text file from server***************************
/* private void writeData(String lineToWrite) {
FileWriter fileWriter = null;
String filetowrite = "logClient.txt";
try {
PrintWriter printerWriter = new PrintWriter(filetowrite);
printerWriter.println(lineToWrite);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
*/
//************************if there is any error with the client******************************
public boolean getError(){
return ERROR;
}
public String getMessageError() {
return messageError;
}
public void setMessageError(String messageError) {
this.messageError = messageError;
}
}
</code></pre>
<p>server side:</p>
<pre><code>package hit.applicationservice;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
import hit.login.AuthenticationManager;
public class MMULogFileApplicationService implements Runnable {
//MMULogService logService;
AuthenticationManager authenticateDetails;
MMULogFileBrowsing browsing;
ArrayList<String> userDetails;
private Socket someClient = null;
private ObjectOutputStream outToClient;
private ObjectInputStream inFromClient;
String filePath = "/Users/oferg/Desktop/lastVirsion/MMUProject/log.txt";
public MMULogFileApplicationService (Socket socket ){
someClient = socket;
};
@Override
public void run() {
//3. get Input and Output streams
try{
outToClient = new ObjectOutputStream(someClient.getOutputStream());
inFromClient = new ObjectInputStream(someClient.getInputStream());
userDetails = (ArrayList<String>) inFromClient.readObject();
System.out.println("Connection successful ");
}catch(IOException | ClassNotFoundException ioException){
ioException.printStackTrace();
}
boolean userFound = false;
try {
authenticateDetails = new AuthenticationManager();
userFound = authenticateDetails.authenticate(userDetails.get(0), userDetails.get(1));
if(userFound)
{
browsing = new MMULogFileBrowsing(someClient, userDetails.get(2), filePath);
if(!browsing.searchIfFileExist()){
//write object to Socket
String sendMessage = "Wrong FileName the file isn't found";
outToClient.writeObject(sendMessage);
}
else{
getFileToClient();
}
}
else
{
//write object to Socket
String sendMessage = "Error - the user isn't exist";
outToClient.writeObject(sendMessage);
}
} catch (ClassNotFoundException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
inFromClient.close();
outToClient.close();
someClient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void getFileToClient() throws IOException {
FileReader fileReader = null;
String currentLine = null;
try {
fileReader = new FileReader(filePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((currentLine = bufferedReader.readLine())!= null){
if (currentLine.isEmpty() == false ){
outToClient.writeObject(currentLine);
outToClient.flush();
}
}
outToClient.close();
bufferedReader.close();
fileReader.close();
}
}
</code></pre>
| <p>tnx everybody for their answers.
i think i found the way to pass al the text file by the next simple loop code:</p>
<pre><code>String currentLine = "";
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((tempLine = bufferedReader.readLine())!= null){
if (tempLine.isEmpty() == false ){
currentLine = currentLine+tempLine+"\n";
}
}
</code></pre>
<p>in that way i'm copying the text file line by line and send it to the client by 1 string and than i can do whatever i want.</p>
<p>tnx every1.
peace</p>
|
Weird HashMap error on onDataChange() in Firebase <p>I've made this function to check a number of error in a field of my app.
So I've made this code:</p>
<pre><code>private int getSegnalations(final Location location, DatabaseReference ref, final HashMap<Location,String>mapLocation) {
final List<Segnalation> matches = new LinkedList<>();
final String key = mapLocation.get(location);
Query query = ref.child("segnalation");
segnalationDialog = createProgressDialog(getActivity(),segnalationDialog,getString(R.string.download));
query.addValueEventListener(new ValueEventListener()
{
@Override
public void onDataChange(DataSnapshot dataSnapshot)
{
stopProgressDialog(segnalationDialog);
for(DataSnapshot dS : dataSnapshot.getChildren())
{
Segnalation segnalation = dS.getValue(Segnalation.class);
Log.d("keys:",segnalation.getIdPark()+","+mapLocation.get(location));
if(segnalation.getIdPark().equals(key))
{
matches.add(segnalation);
}
}
}
@Override
public void onCancelled(DatabaseError databaseError)
{
stopProgressDialog(segnalationDialog);
showErrorMessage(getActivity(),getString(R.string.dbProblem));
}
});
return matches.size();
}
</code></pre>
<p>the bug is that Log.d show me this lines:</p>
<pre><code>D/keys:: -KTijPwCAd7M7wdZms3S,-KTy7n4WcCx3IUWRsRDX
D/keys:: -KTjJYQGW8_k6Dpi_z7W,-KTy7n4WcCx3IUWRsRDX
D/keys:: -KTjKby31PU7PkJWrb5U,-KTy7n4WcCx3IUWRsRDX
D/keys:: -KTy7n4WcCx3IUWRsRDX,-KTy7n4WcCx3IUWRsRDX
</code></pre>
<p>but if is bypass and returns me size 0 and not 1.</p>
<p>Why? What is the error in this code?</p>
| <p>The problem with you code is due to <code>synchronization</code>. While <code>query.addValueEventListener()</code> starts a new <code>Thread</code> to execute its operation. Your background <code>Thread</code> countinues its execution and ends the method with <code>return matches.size();</code> which is offcourse <code>0</code> because this list is being populated in other thread which executes long after your <code>getSegnalations()</code> method is over.</p>
|
The Error class in node.js <p>Obviously in console core modules(<a href="https://nodejs.org/dist/latest-v4.x/docs/api/console.html" rel="nofollow">https://nodejs.org/dist/latest-v4.x/docs/api/console.html</a>) of node documentation exist below code:</p>
<pre><code>console.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to stderr
</code></pre>
<p>but,when I run test.js which code show below</p>
<pre><code>var err = new Error('a');
console.error(err);
</code></pre>
<p>the terminal print the message like:</p>
<blockquote>
<p>Error: a
at Object. (/Users/suoyong/Express/è¿æ¥æ°æ®åº/error.js:1:73)
at Module._compile (module.js:556:32)
at Object.Module._extensions..js (module.js:565:10)
at Module.load (module.js:473:32)
at tryModuleLoad (module.js:432:12)
at Function.Module._load (module.js:424:3)
at Module.runMain (module.js:590:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3</p>
</blockquote>
<p>As you can see, my code is same with the node doc, and yet the result not.
Please help me with the tiny question.,</p>
| <blockquote>
<pre><code>console.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to stderr
</code></pre>
</blockquote>
<p>This is not to be interpreted in the literal sense. Not in the latest LTS and stable versions anyway. Printing an error like that will actually print a textual representation of the error object, which was referred as <code>[Error: Whoops, something bad happened]</code> in the documentation. The actual intended behaviour is further clarified in the documentation of <a href="https://nodejs.org/dist/latest-v4.x/docs/api/console.html#console_console_error_data" rel="nofollow"><code>Console.error()</code></a>:</p>
<blockquote>
<p>If formatting elements (e.g. %d) are not found in the first string then <code>util.inspect()</code> is called on each argument and the resulting string values are concatenated.</p>
</blockquote>
<p>On the side of <code>util.inspect()</code>, this method "returns a string representation of object that is primarily useful for debugging". For objects of type <code>Error</code>, this will yield a string containing the error's message and stack trace.</p>
<pre><code>> const txt = util.inspect(new Error("I'm on SO"))
undefined
> txt
'Error: I\'m on SO\n at repl:1:26\n at sigintHandlersWrap (vm.js:22:35)\n at sigintHandlersWrap (vm.js:96:12)\n at ContextifyScript.Script.runInThisContext (vm.js:21:12)\n at REPLServer.defaultEval (repl.js:313:29)\n at bound (domain.js:280:14)\n at REPLServer.runBound [as eval] (domain.js:293:12)\n at REPLServer.<anonymous> (repl.js:513:10)\n at emitOne (events.js:101:20)\n at REPLServer.emit (events.js:188:7)'
> console.log(txt)
Error: I'm on SO
at repl:1:26
at sigintHandlersWrap (vm.js:22:35)
at sigintHandlersWrap (vm.js:96:12)
at ContextifyScript.Script.runInThisContext (vm.js:21:12)
at REPLServer.defaultEval (repl.js:313:29)
at bound (domain.js:280:14)
at REPLServer.runBound [as eval] (domain.js:293:12)
at REPLServer.<anonymous> (repl.js:513:10)
at emitOne (events.js:101:20)
at REPLServer.emit (events.js:188:7)
</code></pre>
|
ArrayIndexOutOfBoundException using BigInteger in a for loop and taking values <p>I know there are already solution available for this topic I tried the answers mentioned in the topic but didn't help. So what I am trying here is to get the BigInteger values from the user using BigInteger in a for loop. But that gave me ArrayIndexOutOfBoundException.<br>
Here is my code <br></p>
<pre><code>import java.util.Scanner;
import java.math.*;
class BigForLoop{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
BigInteger m = scan.nextBigInteger();
BigInteger n = scan.nextBigInteger();
BigInteger[] xor = new BigInteger[m.intValue()];
for (BigInteger i = BigInteger.valueOf(m.intValue()); i.compareTo(BigInteger.ZERO) > 0; i = i.subtract(BigInteger.ONE))
xor[i.intValue()] = scan.nextBigInteger();
for (BigInteger i = BigInteger.valueOf(m.intValue()); i.compareTo(BigInteger.ZERO) > 0; i = i.subtract(BigInteger.ONE))
System.out.println(xor[i.intValue()]);
}
}
</code></pre>
<p>Thank you.</p>
| <p>Arrays use 0 based index, so we need to replace <code>xor[i.intValue()]</code> with <code>xor[i.intValue()-1]</code>, below should work:</p>
<pre><code>public static void main(String[] args){
Scanner scan = new Scanner(System.in);
BigInteger m = scan.nextBigInteger();
BigInteger n = scan.nextBigInteger();
BigInteger[] xor = new BigInteger[m.intValue()];
for (BigInteger i = BigInteger.valueOf(m.intValue()); i.compareTo(BigInteger.ZERO) > 0; i = i.subtract(BigInteger.ONE))
xor[i.intValue() - 1] = scan.nextBigInteger();
for (BigInteger i = BigInteger.valueOf(m.intValue()); i.compareTo(BigInteger.ZERO) > 0; i = i.subtract(BigInteger.ONE))
System.out.println(xor[i.intValue() - 1]);
}
</code></pre>
<p>P.S. I have no idea what the solution actually does, but that is not the part of question.</p>
|
Which files or commits does Git consider when calculating differences for cherry-pick, merge and rebase? <p>I've read about the Git internals <a href="https://git-scm.com/book/en/v2/Git-Branching-Branches-in-a-Nutshell" rel="nofollow">here</a> and <a href="https://git-scm.com/book/en/v2/Git-Internals-Git-Objects" rel="nofollow">here</a> and know what a commit is, as well as a tree and a blob.</p>
<p>I know that Git stores individual files instead of file differences (deltas), and that the later ones are calculated in real time as necessary. The documentation also speaks often about the "difference between two commits" (whether they are parent and child, ancestor/descendant or neither of them).</p>
<p>However, it's not clear to me how Git calculates those deltas in various situations (cherry-picking, merge, rebase). And which files (i.e. files from which commit) are considered in each case?</p>
<p>I've read that according to that structure a single commit can be considered a whole branch (i.e. the commit history leading up to that commit) in the sense that for a given file I can reach all of its versions by traversing the branch back (though not necessarily back to its root I suppose; just back to a immediately previous file version may be enough). If my assumption is wrong, please clarify.</p>
| <p>The rules are simple enough conceptually but get complicated in practice.</p>
<ul>
<li><p>A real <code>git merge</code> uses the commit DAG to find the merge base(s). The merge base is defined as the Lowest Common Ancestor (generalized in the obvious way to arbitrary DAGs where there may be multiple LCAs, vs simple trees where there's always a unique LCA). The <code>git merge-base</code> command will, given two commits, find a (default) or all (<code>--all</code>) merge base commits from the DAG.</p>
<p>If there are multiple merge bases, the algorithm depends on the <code>-s</code> (strategy) argument. The default <code>recursive</code> strategy merges the merge-bases using recursion (what else? :-) ). This is currently done the slow-simple-stupid way: if there are 5 merge bases, Git merges two of them (finding the merge base of those two as needed) and makes a "virtual commit" from the result, merges that result with the next (3rd) in the list-of-5, merges <em>that</em> result with the 4th, and merges <em>that</em> with the 5th to get the final virtual merge base. (To make this all work correctly, I believe Git actually makes <em>real</em> commits. There's no reason not to: these unreferenced commits will be garbage-collected automatically later.)</p>
<p>The <code>resolve</code> strategy simply picks one of the multiple merge bases and uses that as the base.</p>
<p>In any case, the two diffs that get combined, once we have a single merge base hash ID <code>$base</code> and the two branch-tips, are the output from:</p>
<pre><code>git diff $base $tip1
git diff $base $tip2
</code></pre>
<p>(more or lessâthere's some tweaking of the <code>--rename-limit</code> value if needed, depending on extra merge command arguments, and all this assumes no special merge drivers; the actual merging happens file-by-file, but the merge base <em>version</em> for each file comes from <code>$base</code>, with any rename detection happening first from the two commit-wide diffs).</p></li>
<li><p>The <code>git cherry-pick</code> command diffs each commit against its parent, and then first tries to apply the resulting delta as a patch. If that fails it falls back on "three way merge", but the merge base is on a file-by-file basis rather than a commit-by-commit basis, because it uses the <code>Index:</code> information in the formatted patch. There's one <code>Index:</code> line per file-in-the-patch, giving the SHA-1 IDs of the two blobs in question.</p>
<p>Thus, the merge base is initially ignored entirely: the cherry-pick just uses the patch as a patch. Only if the patch does not apply (as in <code>git apply</code>) does the cherry-pick fall back to a three-way merge (as in <code>git apply -3</code>). The blob itself must also exist in your repositoryâfor a cherry-pick, it always does; for a literal <code>git apply</code> of an emailed patch, it may not.</p>
<p>At this point the two diffs to be combined are:</p>
<pre><code>git diff $indexbase $file1
the diff in the patch # equivalent to git diff $indexbase $file2
</code></pre>
<p>where <code>$indexbase</code> is the file extracted by the hash ID in the <code>Index:</code> line and <code>$file1</code> is the file in your work-tree. (This file matches the <code>HEAD</code> commit unless you're using <code>git cherry-pick -n</code>.) In an arbitrary (emailed) patch you don't necessarily have <code>$file2</code> at all, just the diff; in a cherry-picked patch, <code>$file2</code> is the version of the file in the commit being cherry-picked (but it's not needed since we already have the diff!).</p>
<p>If you cherry-pick a merge commit, you must tell Git <em>which</em> parent of that merge commit is to be used to produce a changeset-as-patch. This step is completely manual.</p></li>
<li><p>A rebase consists, functionally, of a series of cherry-pick operations. Merge commits are omitted from rebases. (Interactive rebase's <code>--preserve-merges</code> operation makes <em>new</em> merges, completely ignoring the original merge.) An interactive rebase literally runs <code>git cherry-pick</code> (one at a time for each commit to be copied), while a non-interactive rebase attempts to use <code>git format-patch <args> | git am -3</code> if it can (format-patch elides "empty" commits so this is only possible without <code>-k</code>).</p>
<p>The commits to be copied are chosen via an actual <code>git rev-list --cherry-pick</code> on a symmetric difference in some cases, or, for algorithmic purposes, something equivalent.</p></li>
</ul>
|
Select subquery where last row of many-to-many relation is equals to condition <p>I have 3 tables: Inventory, InventoryTransaction, InventoryState.
What im trying to do is select all items from Inventory where last row of InventoryTransaction is in InventoryState euqlas 'SOLD'</p>
<blockquote>
<p>note: 1 Item can have multiple transactions, so i need to get all items that the last transaction item state is SOLD</p>
</blockquote>
<p>Tables:</p>
<pre><code> Inventory
---------------------
id | item_name | date
1 | book | 2016
InventoryTransaction
----------------------------------------------
id | amount | item_id | inventory_state | date
1 | 20.00 | 1 | 1 | 2016
InventoryState
-----------------
id | description
1 | 'SOLD'
</code></pre>
| <p>Try using a correlated sub query to fetch the latest inventory_state from the transaction table, and then join by it to the state table:</p>
<pre><code>SELECT t.id
FROM(
SELECT i.*,
(SELECT it.inventory_state FROM InventoryTransaction it
WHERE it.item_id = i.id
ORDER BY it.id DESC
LIMIT 1) as last_inv_state_id
FROM inventory i) t
JOIN InventoryState invs
ON(t.last_inv_state_id = invs.id AND invs.description = 'SOLD')
</code></pre>
|
How to use ReportViewer in Sensenet <p>I would like to include ReportViewer control in the Parametric Search portlet rendering ASCX file.</p>
<p>I placed RDLC file in the content repository and it is being retrieved properly as binary steam</p>
<pre><code><%
....
//retrieve rdlc file
string Path = "/Root/Global/renderers/ReportFiles/Report1.rdlc"
Node node = Node.LoadNode(Path);
var binaryData = node.GetBinary("Binary");
System.IO.Stream stream = binaryData.GetStream();
//setup report
ReportViewer1.ProcessingMode = ProcessingMode.Local;
ReportViewer1.LocalReport.LoadReportDefinition(stream);
ReportDataSource datasource = new ReportDataSource("Results", dsResults.Tables[0]);
ReportViewer1.LocalReport.DataSources.Add(datasource);
%>
<div id="rptvwr">
<asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server">
</asp:ScriptManagerProxy>
<rsweb:ReportViewer ID="ReportViewer1" runat="server" Width="600">
</rsweb:ReportViewer>
</div>
</code></pre>
<p>This results in 'Illegal characters in path' error message.</p>
<p>After I changed my code around a bit and I now have the following situation:</p>
<ul>
<li><p>when I use <code><asp:Scriptmanager></code> tag required by ReportViewer control, I receive an error message that only one ScriptManager per page is allowed</p></li>
<li><p>when I use <code><asp:ScriptManagerProxy></code> tag, I receive an error message stating </p>
<p>Portlet Error: The Report Viewer Web Control requires a System.Web.UI.ScriptManager on the web form.</p></li>
</ul>
| <p>There can be only one <em>ScriptManager</em> control on the page, and <strong>SenseNet already generates one automatically</strong>, you cannot do much about it. Actually it is a custom control called <em>SNScriptManager</em> (it inherits from the default scriptmanager control) that the pagetemplate manager puts into the generated master page automatically. So you cannot put another one manually in your ascx. </p>
<p>You can still add additional scripts using the ScriptManagerProxy control if you want to, according to <a href="https://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanagerproxy.aspx" rel="nofollow">MSDN</a>. Or you can use the built-in sn:ScriptRequest control that SenseNet offers, it helps with bundling - but of course all this applies only if you know exactly what scripts you have to add.</p>
<p>Maybe the <em>ReportViewer</em> control looks for the <em>default</em> script manager and does not like the custom (inherited) one used by SenseNet (I hope this is not the case).</p>
<p>(it is unclear from your question what happens if you do not add the sm proxy or any other tag, because the last two bullet points both start with "when I use tag..." - which tag do you mean here?)</p>
<p>Is the first error message ('illegal characters in path') still relevant? If yes, can you please add more details, e.g. a stack trace from event viewer?</p>
|
Vue - how to get a file to a hidden input field <p>I am currently previewing an image, but would also like to actually return somehow the file to my form, so that I can later submit it in the backend, but not sure how to do that?</p>
<p>This is my component:</p>
<pre><code><template>
<div>
<div v-if="!image">
<h2>Select an image</h2>
<input type="file" @change="onFileChange">
</div>
<div v-else>
<img :src="image" />
<button @click="removeImage">Remove image</button>
<input type="file" v-bind:value="{ file }" style="display:none">
</div>
</div>
</template>
<script>
export default {
data() {
return {
image: '',
formData:new FormData()
}
},
methods: {
onFileChange: function onFileChange(e) {
var files = e.target.files || e.dataTransfer.files;
if (!files.length)
return;
this.createImage(files[0]);
this.formData.append('file', files[0]);
},
createImage: function createImage(file) {
var image = new Image();
var reader = new FileReader();
var vm = this;
reader.onload = function (e) {
vm.image = e.target.result;
};
reader.readAsDataURL(file);
},
removeImage: function removeImage(e) {
this.image = '';
}
}
}
</script>
</code></pre>
<p>I have tried with adding <code>formData:new FormData()</code> to data function and then appending the file to formData object like this:</p>
<pre><code>this.formData.append('file', files[0]);
</code></pre>
<p>But I get an error: </p>
<blockquote>
<p>formData is not defined</p>
</blockquote>
| <p>Hi I think the error caused by <code>v-bind:value="{ file }</code> , you should remove it, and it will work:</p>
<pre><code><input type="file" style="display:none">
</code></pre>
<p>You can't use <code>v-model = "file"</code> to get the file data, and what you have done with <code>this.formData.append('file', files[0]);</code> is the right way to get the data, if you want to get the data in the scope of your components, you can do something like this:</p>
<pre><code> data() {
return {
image: '',
formData:new FormData(),
file: null
}
},
methods: {
onFileChange: function onFileChange(e) {
var files = e.target.files || e.dataTransfer.files;
if (!files.length)
return;
this.createImage(files[0]);
this.formData.append('file', files[0]);
this.file = files[0];
}
....
</code></pre>
<p>reference:</p>
<ul>
<li><a href="https://laracasts.com/discuss/channels/vue/vuejs-using-v-model-with-input-typefile?page=1" rel="nofollow">https://laracasts.com/discuss/channels/vue/vuejs-using-v-model-with-input-typefile?page=1</a></li>
<li><a href="http://codepen.io/Atinux/pen/qOvawK/" rel="nofollow">http://codepen.io/Atinux/pen/qOvawK/</a></li>
</ul>
|
How to optimize resources (images, json) version management <p>I'm actually working on an AngularJS app which consume a lot of independant resources.
The code and the resources are versioned with Git, and the resources (images, html, json...) are organized in module by theme. </p>
<p><strong>Here is my problem :</strong> The resources use a lot of disk space in our Git repo.</p>
<p>So do you know any free versioning tool more efficient than git to store this type of file ?</p>
<p>Thanks</p>
| <p>Most text based files (HTML, json) should be fine with git. They won't take up too much space. For binary files, such as images, that are changed often you might want to consider using <a href="https://git-lfs.github.com/" rel="nofollow">Git Large File Storage</a>. This should limit the space used by old revisions of binary files to the Large File Storage itself, not the development machines.</p>
|
Access Typescript variable value in javascript inside Angular 2 Component <p>I have written a reusable component in Angular 2 to display the <code>Summernote</code> WYSIWYG editor in my application. That component accepts 3 input parameters which are being set as attributes for a rendered <code>textarea</code> as id, name and last one used as the body. My problem is that within this component I am initializing the Summernote plugin and creating the editor. <strong>Here, I do not want to hard code the selector name and want the dynamic values that the component received as the input parameters to the component.</strong> Relevant code is as follows.</p>
<pre><code>import {Component, ElementRef, OnInit, EventEmitter, Input, Output, Inject, ComponentRef} from '@angular/core';
import {Http} from '@angular/http';
declare var $: any;
@Component({
selector: 'editor',
template: `<textarea id="{{eid}}" name="{{ename}}" class="form-control">{{body}}</textarea>`
})
export class EditorComponent {
@Input() body: string;
@Input() eid: string;
@Input() ename: string;
@Output() onContentChanged: EventEmitter<any>;
constructor(){}
ngAfterViewInit()
{
$(document).on("pageLoaded", function (){
console.log("pageLoaded");
$("#body").summernote({
height: '200px',
callbacks: {
onChange: function(contents, $editable) {
$("#body").val(contents);
}
}
});
});
}
}
</code></pre>
<p>Here, you can see that I have used <code>$("#body")</code> twice inside the <code>ngAfterViewInit</code> block. I want this to be replaced by the <code>eid</code> variable. I have tried <code>{{eid}}</code> but it doesn't work and throws the following error in browser console.</p>
<p><code>EXCEPTION: Syntax error, unrecognized expression: #{{eid}}</code></p>
<p><code>this.eid</code> can't be used here either since we're inside the javascript method and not typescript.</p>
<p>I'm using this component in my other view file as a directive.</p>
<p><code><editor [body]="page.body" eid="body" ename="body"></editor></code></p>
<p>The <code>template</code> block in component is set properly with dynamic values. Only the javascript part is my issue.</p>
<p>Is there any other way I'm missing here?</p>
<p>P.S. So far it works great. I just want to make the initialization fully dynamic, so that I can use it anywhere with different IDs.</p>
| <p>You can try using arrow functions instead of <strong>function</strong> to keep the same context.</p>
<pre class="lang-js prettyprint-override"><code> $(document).on("pageLoaded", () => {
console.log("pageLoaded");
$(this.eid).summernote({
height: '200px',
callbacks: {
onChange: (contents, $editable) => {
$(this.eid).val(contents);
}
}
});
});
}
</code></pre>
|
Why doesn't java.util.Optional implement Iterable? <p>Why doesn't Java 8's <code>Optional</code> implement <code>Iterable</code>?</p>
<p>I assume it's a deliberate language choice but I'm wondering why. Scala's <code>Option</code> and Haskell's <code>Maybe</code> implement traversal methods analogous to <code>Iterable</code>. FWIW, Java 9 will implement <code>Optional.stream()</code> (<a href="https://bugs.openjdk.java.net/browse/JDK-8050820" rel="nofollow">JDK-8050820</a>).</p>
| <p>I'm not an expert on Scala or Haskell, but my belief is that those languages have constructs such as sequence comprehension that make it quite useful for <code>Option</code> or <code>Maybe</code> to be <code>Traversable</code>.</p>
<p>It may be that Java's <code>Iterable</code> is analogous to <code>Traversable</code> but the rest of the Java language doesn't provide very much support around it. The only thing <code>Iterable</code> does in Java is enable its use in an enhanced-for ("for each") loop. Consider for example if Java's <code>Optional</code> were to implement <code>Iterable</code>. That would allow an <code>Optional</code> to be used like this:</p>
<pre><code>Optional<T> opt = ... ;
for (T t : opt) {
doSomethingWith(t);
}
</code></pre>
<p>It's kind of misleading to write this as a loop, since it executes zero or one times. To be less misleading, one might as well write this:</p>
<pre><code>if (opt.isPresent()) {
doSomethingWith(opt.get());
}
</code></pre>
<p>or preferably</p>
<pre><code>opt.ifPresent(this::doSomething);
</code></pre>
<p>I don't know for a fact the reason that <code>Optional</code> was not made <code>Iterable</code>. The Java 8 lambda expert group had several face-to-face meetings where a bunch of things were probably discussed and never written down. I can easily imagine this topic being raised at such a meeting, and dismissed as not being very useful, given the existence of much more useful alternatives such as <code>ifPresent</code>.</p>
|
Manage AD Group members using Powershell, CSV & extensionAttribute1 <p>I have seen various posts that cover similar topics to this. But none that match my exact requirements.</p>
<p>My aim is:</p>
<ul>
<li>Use a CSV containing col 1 (<code>ADGroupName</code>), col 2 (<code>extensionAttirbute1</code>)</li>
<li>Delete users from AD groups based on CSV</li>
<li>Add users to AD groups based on CSV</li>
</ul>
<p>I'm sure this can be done simply however, to get it to work with the <code>extensionAttribute1</code> value, is proving difficult.</p>
<p>Below is some of the code:</p>
<p>So, I have 2 functions. </p>
<ul>
<li>First creates CSVs to work from. (Working). </li>
<li>Second function adds/removes AD groups based on CSV contents. (Working). </li>
</ul>
<p>Below is where I left the final function after wiping out various bits of code after it didn't work.</p>
<pre><code>Function SyncGroups {
$Groups = Import-Csv "C:\Temp\Scripts\GroupMembership.csv"
foreach ($user in $Groups) {
Add-ADGroupMember -Identity $user.Group -Members $user.extensionAttribute1
Get-ADUser -Filter {extensionAttribute1 -eq $user.extensionAttribute1}
}
}
</code></pre>
| <p>The problem you're facing is a common misunderstanding of how the parameter <code>-Filter</code> works (see <a href="http://stackoverflow.com/a/34029622/1630171">this answer</a> to a similar question). It's better to think of the argument to the parameter as a string (because that's essentially what it is, despite the notation), and define it as such.</p>
<p>Either assign <code>$user.extensionAttribute1</code> to a variable and use that variable in the expression:</p>
<pre><code>foreach ($user in $Groups) {
Add-ADGroupMember -Identity $user.Group -Members $user.extensionAttribute1
$attr = $user.extensionAttribute1
Get-ADUser -Filter "extensionAttribute1 -eq '$attr'"
}
</code></pre>
<p>or put <code>$user.extensionAttribute1</code> in a <a href="https://technet.microsoft.com/en-us/library/hh847732.aspx" rel="nofollow">subexpression</a>:</p>
<pre><code>foreach ($user in $Groups) {
Add-ADGroupMember -Identity $user.Group -Members $user.extensionAttribute1
Get-ADUser -Filter "extensionAttribute1 -eq '$($user.extensionAttribute1)'"
}
</code></pre>
|
Having trouble navigating file explorer with python <p>I am building an automated browser with selenium and it is working flawlessly! (thank you selenium (: )
But I am having trouble uploading a file. One of the steps I need to execute is to upload a file.</p>
<p>The code I use to upload, and seems like it works for many people, is:</p>
<pre><code>file_input = driver.find_element_by_id('ImageUploadButton')
file_input.send_keys('C:\\image.jpg')
</code></pre>
<p>Also tried:</p>
<pre><code>driver.find_element_by_id('ImageUploadButton').click()
driver.find_element_by_css_selector('input[type="file"]').clear()
driver.find_element_by_css_selector('input[type="file"]').send_keys('C:\\image.jpg')
</code></pre>
<p>This seems to work for a lot of people, but for me, it just opens the file explorer for me to pick the file I want to upload, and that is it. No error message, just continues to execute the code.</p>
<p>Is anyone aware of maybe another module that I can use to navigate the file explorer and submit the file?</p>
<p>Or am I using selenium inappropriately? </p>
<p>----------- edit ---------------</p>
<p>Added DIV from website:</p>
<pre><code> <div id="FileInputWrapper" class="file-input-wrapper">
<input id="FileUploadInput" type="hidden" name="file">
<button id="ImageUploadButton" class="button-update-cancel short file-upload-button" type="button" style="position: relative; z-index: 1;"> Select Images</button>
</div>
<input type="hidden" name="images">
<div id="html5_1auv7g94u187l1qdq108d1ue5qve3_container" class="moxie-shim moxie-shim-html5" style="position: absolute; top: 518px; left: 0px; width: 155px; height: 45px; overflow: hidden; z-index: 0;">
<input id="html5_1auv7g94u187l1qdq108d1ue5qve3" type="file" accept="image/jpeg,image/png,image/gif,image/bmp" multiple="" style="font-size: 999px; opacity: 0; position: absolute; top: 0px; left: 0px; width: 100%; height: 100%;">
</div>
</code></pre>
| <p>Seems that you use wrong locator to upload file. You should handle <code>input</code> element, not <code>button</code>:</p>
<pre><code>file_input = driver.find_element_by_xpath('//input[@type="file"]')
file_input.send_keys('C:\\image.jpg')
</code></pre>
|
Amazon AWS Error: Missing credentials in config node.js <p>I am just getting started using AWS and I'm trying to use their example code <a href="http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-examples.html" rel="nofollow">here.</a> I am using dotenv to store my keys as environmental variables. Using coffee script my code looks like this:</p>
<pre><code>require('dotenv').config()
express = require 'express'
router = express.Router()
AWS = require('aws-sdk')
AWS.config.region = 'us-west-2'
s3bucket = new (AWS.S3)(params: Bucket: 'new-bucket-name')
s3bucket.createBucket ->
params =
Key: process.env.AWS_ACCESS_KEY_ID
Body: 'Hello!'
s3bucket.upload params, (err, data) ->
if err
console.log 'Error uploading data: ', err
else
console.log 'Successfully uploaded data to myBucket/myKey'
return
return
</code></pre>
<p>But I keep getting the following error: </p>
<pre><code>message: 'Missing credentials in config',
code: 'CredentialsError',
errno: 'EHOSTDOWN',
syscall: 'connect',
address: '169.254.169.254',
port: 80,
time: 2016-10-13T14:14:03.605Z,
originalError:
{ message: 'Could not load credentials from any providers',
code: 'CredentialsError',
errno: 'EHOSTDOWN',
syscall: 'connect',
address: '169.254.169.254',
port: 80,
time: 2016-10-13T14:14:03.605Z,
originalError:
{ message: 'Missing credentials in config',
code: 'CredentialsError',
errno: 'EHOSTDOWN',
syscall: 'connect',
address: '169.254.169.254',
port: 80,
time: 2016-10-13T14:14:03.599Z,
originalError: [Object] } } }
</code></pre>
<p>How do I fix this, do I also need to send my secret key somehow?</p>
<p>UPDATE:
fixed it using </p>
<pre><code>AWS.config = new AWS.Config();
AWS.config.accessKeyId = "accessKey";
AWS.config.secretAccessKey = "secretKey";
</code></pre>
<p>but now I am getting this new error:</p>
<pre><code> message: 'Access Denied',
code: 'AccessDenied',
region: null,
time: 2016-10-13T14:38:19.651Z,
requestId: '958BD7EA261F2DCA',
extendedRequestId: 'xuBSmGL/GC5Tx1osMh9tBFIwXMLy15VtJXniwYVGutTcoBJgrCeOLZpQMlliF1Azrkmj1tsAX7o=',
cfId: undefined,
statusCode: 403,
retryable: false,
retryDelay: 11.225715031927086 }
</code></pre>
| <p><code>Access Denied</code> sounds like your IAM Permissions are not setup correctly. Check that user tied to those credentials can create buckets in your account. </p>
<p>Also usually the AWS SDKs can read out of your actual ENV variables so you probably do not need to use DotEnv in this case. And when you push code to production systems that might be running on EC2 or Lambda you should really be using a IAM Profile which handles the credentials for you. So again.. DotEnv isn't necessary. </p>
|
emacs adding spaces to file <p>I'm loading a text file into emacs and it is displaying a vertical column of slashes as a big blob of slashes with different spacing for each line. It displays correctly in VIM and notepad++, but not in emacs. What could cause this to happen?</p>
<p><a href="https://i.stack.imgur.com/8kUOz.png" rel="nofollow">emacs display error</a></p>
| <p>This is probably because the file contains tabs, and Emacs uses a different tab width than VIM and notepad++.</p>
<p>You can make Emacs show what kind of whitespace there is with <code>M-x whitespace-mode</code>.</p>
<p>To change how Emacs displays tabs, use <code>M-x set-variable</code>, and change <code>tab-width</code>. The Emacs default is 8, but many editors use 4 instead.</p>
|
Can this be made into a sql join <p>I want to find where mydata has a Q value but not at least one corresponding d value. How would I solve using a left join or right join?</p>
<p>If it can not be solved using joins, please give some insight into why not, because I am not seeing it.</p>
<p>Below is the solution that I found which works against data provided.</p>
<pre><code>SELECT distinct tablea.mykey
FROM mytest as tablea
where tablea.mydata = 'Q'
and tablea.mykey not in (select distinct tableb.mykey
FROM mytest as tableb
where tableb.mydata = 'd')
</code></pre>
<pre class="lang-none prettyprint-override"><code>mykey mydata
7 d
5 Q
5 d
5 d
6 Q
6 d
6 a
9 Q
9 a
9 a
</code></pre>
| <p>You can use an outer join and then select only the non-matches</p>
<pre><code>SELECT distinct tablea.mykey
FROM mytest as a
left join mytest as b on a.mykey = b.mykey
and b.mydata = 'd'
where a.mydata = 'Q'
and b.mykey is null
</code></pre>
|
How to set two timeouts? <p>I am trying to have two separate timeout times in my coursel (so that 2 slides are faster than the others). I have all of my images at 7 seconds but I want my "brands1slide" and "brands2slide" to be 3.5 seconds.</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>var slideIndex = 0;
carousel();
function carousel() {
var i;
var x = document.getElementsByClassName("mySlides");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
slideIndex++;
if (slideIndex > x.length) {
slideIndex = 1
}
x[slideIndex - 1].style.display = "block";
setTimeout(carousel, 7000);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="SlidesDiv" style="max-width:1024px">
<img class="mySlides" id="returnsSlide" alt="returnsSlide" src="img/ReturnsOnly.png" />
<img class="mySlides" id="brands1Slide" alt="brands1Slide" src="img/Brands_1.png" />
<img class="mySlides" id="brands2Slide" alt="brands2Slide" src="img/Brands_2.png" />
<img class="mySlides" id="fsaSlide" alt="brands2Slide" src="img/FSAs.png" />
</div></code></pre>
</div>
</div>
</p>
| <p>One way to do it is to have an array of times specifying the timeout for each slide:</p>
<pre><code>var slideTimes = [7000, 3500, 3500, 7000];
</code></pre>
<p>Then you can use that to choose a good timeout for each slide:</p>
<pre><code>setTimeout(carousel, slideTimes[slideIndex - 1]);
</code></pre>
<p>Snippet:</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>var slideTimes = [3500, 3500, 7000, 7000];
var slideIndex = 0;
carousel();
function carousel() {
var i;
var x = document.getElementsByClassName("mySlides");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
slideIndex++;
if (slideIndex > x.length) {
slideIndex = 1
}
x[slideIndex - 1].style.display = "block";
setTimeout(carousel, slideTimes[slideIndex - 1]);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="SlidesDiv" style="max-width:1024px">
<img class="mySlides" id="returnsSlide" alt="returnsSlide" src="img/ReturnsOnly.png" />
<img class="mySlides" id="brands1Slide" alt="brands1Slide" src="img/Brands_1.png" />
<img class="mySlides" id="brands2Slide" alt="brands2Slide" src="img/Brands_2.png" />
<img class="mySlides" id="fsaSlide" alt="brands2Slide" src="img/FSAs.png" />
</div></code></pre>
</div>
</div>
</p>
|
How to search Windows Search Indexed in file <p>I have files indexed by the Windows Search service. I need function, which can find some string in text files. I have script in PowerShell, but it didn't work fine.</p>
<pre><code>function search {
param($path, $word)
$c = $path + "\%"
$query = "SELECT
System.ItemName, System.ItemPathDisplay
FROM SystemIndex
WHERE System.ItemPathDisplay LIKE '$c' AND CONTAINS('$word')"
$ADOCommand = New-Object -ComObject ADODB.Command
$ADOConnection = New-Object -ComObject ADODB.Connection
$RecordSet = New-Object -ComObject ADODB.RecordSet
$ADOConnection.Open("Provider=Search.CollatorDSO;Extended Properties='Application=Windows';")
$RecordSet.Open($query, $ADOConnection)
try { $RecordSet.MoveFirst() }
catch [System.Exception] { "no records returned" }
while (-not($RecordSet.EOF)) {
if ($locatedFile) { Remove-Variable locatedFile }
$locatedFile = New-Object -TypeName PSObject
Add-Member -InputObject $locatedFile -MemberType NoteProperty -Name 'Name' -Value ($RecordSet.Fields.Item("System.ItemName")).Value
Add-Member -InputObject $locatedFile -MemberType NoteProperty -Name 'Path' -Value ($RecordSet.Fields.Item("System.ItemPathDisplay")).Value
$locatedFile
$RecordSet.MoveNext()
}
$RecordSet.Close()
$ADOConnection.Close()
$RecordSet = $null
$ADOConnection = $null
[gc]::Collect()
}
</code></pre>
<p>If <code>$word = "Hello"</code> it works fine for files where we have</p>
<pre>*some text * Hello * some text*</pre>
<p>in the file, but not when we have Hello without spaces like:</p>
<pre>HelloWorld</pre>
<p>We can't also search when <code>$word</code> is a phrase,for example "Hello World".</p>
<p>Anyone know how to fix it? </p>
| <p>I believe the issue is with the <code>CONTAINS</code> in your query. You should add asterisk (*) wildcard character to the word that you search.
So instead of:</p>
<pre><code> WHERE System.ItemPathDisplay LIKE '$c' AND CONTAINS('$word')
</code></pre>
<p>please try:</p>
<pre><code>WHERE System.ItemPathDisplay LIKE '$c' AND CONTAINS('*$word*')
</code></pre>
|
2-Dence neural network accuracy optimization <p>Below you can see the dataset i use"sorted_output" in order to construct an ANN with 2 hidden dense layers and one input, one output layer. My question is why am i getting extremely low accuracy(62,5%)? I have the feeling that the fact that since both my input data (columns A-U) and my output data (column V) are in binary form, this should lead me to 100% accuracy. Am i wrong?</p>
<pre><code>from keras.models import Sequential
from keras.layers import Dense
from sklearn.cross_validation import train_test_split
import numpy
# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)
dataset = numpy.loadtxt("sorted_output.csv", delimiter=",")
# split into input (X) and output (Y) variables
X = dataset[:,0:21]
Y = dataset[:,21]
# split into 67% for train and 33% for test
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.33, random_state=seed)
# create model
model = Sequential()
model.add(Dense(12, input_dim=21, init='orthogonal', activation='relu'))
model.add(Dense(10, init='uniform', activation='relu'))
model.add(Dense(1, init='orthogonal', activation='sigmoid'))
# Compile model
model.compile(loss='binary_crossentropy', optimizer='sgd', metrics=['accuracy'])
# Fit the model
model.fit(X_train, y_train, validation_data=(X_test,y_test), nb_epoch=150, batch_size=10)
</code></pre>
<p><a href="https://i.stack.imgur.com/PNPWb.png" rel="nofollow"><img src="https://i.stack.imgur.com/PNPWb.png" alt="enter image description here"></a></p>
| <p>Accuracy of the network depends on many factors. It is really difficult to understand why the accuracy is so low in your case. It really depends on the underlying data distribution and how good you network is at capturing the relevant information during training.</p>
<p>I suggest you to monitor the loss and see if the model is overfitting the train data. If that is the case, you might have to use some kind of regularization to improve the generalization. Otherwise, you can increase the depth of the network and check if results are better.</p>
<p>These are by no means an exhaustive list of approaches. Sometimes changing the optimizer also helps, depending on how your data distributed.</p>
|
div hover effect on expansion? <p><a href="https://i.stack.imgur.com/kws09.jpg" rel="nofollow">this is how the blocks look like</a></p>
<p><a href="https://i.stack.imgur.com/PQ1T9.jpg" rel="nofollow">if i mouseover on test1 with hover effect ,it covers all block to its right but doesnot maximize full covering all block...i need solution for this</a></p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type=text/javascript src="jquery-1.11.0.min.js"></script>
<script type=text/javascript src="avc.js"></script>
<link href="amcstyle.css" rel="stylesheet" />
</head>
<body>
<div class="twocol">
<div class="inside">test0</div>
</div>
<div class="twocol">
<div class="inside1">Test1</div>
</div>
<div class="twocol">
<div class="inside2">Test3</div>
</div>
<div class="twocol">
<div class="inside3">Test4</div>
</div>
<div style="clear:both"></div>
<div class="twocol">
<div class="inside4">Test5</div>
</div>
<div class="twocol">
<div class="inside5">Test6</div>
</div>
<div class="twocol">
<div class="inside6">Test7</div>
</div>
</body>
</html>
</code></pre>
<p>css</p>
<pre><code>.twocol {
float: left;
width: 150px;
height: 150px;
position: relative;
padding: 10px;
}
.twocol1 {
width: 100px;
height: 100px;
position: relative;
padding: 10px;
background-color:pink;
}
.inside {
position: absolute;
border: 1px solid #000;
width: 150px;
height: 150px;
background: #eee;
z-index: 900;
}
.inside:hover {
position: absolute;
z-index: 999;
transition: 0.5s ease;
}
</code></pre>
<p>script... currently to manage the expansion and size of the div i have written seperate script function for each</p>
<pre><code>$(document).ready(function () {
$('.inside').hover(
function () {
$(this).animate({
height: '320px',
width: '660px'
}, 200);
},
function () {
$(this).animate({
height: '150px',
width: '150px'
}, 200);
});
});
$(document).ready(function () {
$('.inside1').hover(
function () {
$(this).animate({
height: '320px',
width: '500px'
}, 200);
},
function () {
$(this).animate({
height: '150px',
width: '150px',
}, 200);
});
});
$(document).ready(function () {
$('.inside2').hover(
function () {
$(this).animate({
height: '320px',
width: '320px'
}, 200);
},
function () {
$(this).animate({
height: '150px',
width: '150px'
}, 200);
});
});
$(document).ready(function () {
$('.inside3').hover(
function () {
$(this).animate({
height: '320px',
width: '150px'
}, 200);
},
function () {
$(this).animate({
height: '150px',
width: '150px'
}, 200);
});
});
$(document).ready(function () {
$('.inside4').hover(
function () {
$(this).animate({
height: '155px',
width: '500px'
}, 200);
},
function () {
$(this).animate({
height: '150px',
width: '150px'
}, 200);
});
});
$(document).ready(function () {
$('.inside5').hover(
function () {
$(this).animate({
height: '155px',
width: '320px'
}, 200);
},
function () {
$(this).animate({
height: '150px',
width: '150px'
}, 200);
});
});
$(document).ready(function () {
$('.inside6').hover(
function () {
$(this).animate({
height: '150px',
width: '320px'
}, 200);
},
function () {
$(this).animate({
height: '150px',
width: '150px'
}, 200);
});
});
</code></pre>
| <p>Increase <code>Width</code> and <code>Height</code> in animate section add<br>
<code>inside:hover{left:0}</code> to cover from left side and also remove <code>.twocol {position:relative}</code> ..
let me know this is what you looking for</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 () {
$('.inside').hover(
function () {
$(this).animate({
height: '400px',
width: '400px'
}, 200);
},
function () {
$(this).animate({
height: '150px',
width: '150px'
}, 200);
});
});
$(document).ready(function () {
$('.inside1').hover(
function () {
$(this).animate({
height: '500px',
width: '900px'
}, 200);
},
function () {
$(this).animate({
height: '150px',
width: '150px'
}, 200);
});
});
$(document).ready(function () {
$('.inside2').hover(
function () {
$(this).animate({
height: '320px',
width: '320px'
}, 200);
},
function () {
$(this).animate({
height: '150px',
width: '150px'
}, 200);
});
});
$(document).ready(function () {
$('.inside3').hover(
function () {
$(this).animate({
height: '320px',
width: '150px'
}, 200);
},
function () {
$(this).animate({
height: '150px',
width: '150px'
}, 200);
});
});
$(document).ready(function () {
$('.inside4').hover(
function () {
$(this).animate({
height: '155px',
width: '500px'
}, 200);
},
function () {
$(this).animate({
height: '150px',
width: '150px'
}, 200);
});
});
$(document).ready(function () {
$('.inside5').hover(
function () {
$(this).animate({
height: '155px',
width: '320px'
}, 200);
},
function () {
$(this).animate({
height: '150px',
width: '150px'
}, 200);
});
});
$(document).ready(function () {
$('.inside6').hover(
function () {
$(this).animate({
height: '150px',
width: '320px',
left:'0'
}, 200);
},
function () {
$(this).animate({
height: '150px',
width: '150px',
left:'0'
}, 200);
});
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.twocol {
float: left;
width: 150px;
height: 150px;
padding: 10px;
}
.twocol1 {
width: 100px;
height: 100px;
padding: 10px;
background-color:pink;
}
.inside {
position: absolute;
border: 1px solid #000;
width: 150px;
height: 150px;
background: #eee;
z-index: 900;
}
.inside:hover {
position: absolute;
z-index: 999;
transition: 0.5s ease;
}
.inside1 {
position: absolute;
border: 1px solid #000;
width: 150px;
height: 150px;
background: #eee;
z-index: 900;
}
.inside1:hover {
position: absolute;
z-index: 999;
transition: 0.5s ease;
left:18px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type=text/javascript src="jquery-1.11.0.min.js"></script>
<script type=text/javascript src="avc.js"></script>
<link href="amcstyle.css" rel="stylesheet" />
</head>
<body>
<div class="twocol">
<div class="inside">test0</div>
</div>
<div class="twocol">
<div class="inside1">Test1</div>
</div>
<div class="twocol">
<div class="inside2">Test3</div>
</div>
<div class="twocol">
<div class="inside3">Test4</div>
</div>
<div style="clear:both"></div>
<div class="twocol">
<div class="inside4">Test5</div>
</div>
<div class="twocol">
<div class="inside5">Test6</div>
</div>
<div class="twocol">
<div class="inside6">Test7</div>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
|
Not able to take a build using SBT for a Simple spark application <p>I am trying to take a build for a simple spark application using SBT </p>
<p>While taking the build using sbt package from the project directory it simply hangs for few minutes and then i got the below error </p>
<pre><code>n1@edge-node DEV $ pwd
/home/cloudera/test/spark/SimpleSpark
n1@edge-node DEV $ find .
.
./src
./src/main
./src/main/scala
./src/main/scala/SimpleSpark.scala
./build.sbt
n1@edge-node DEV $ sbt package
Getting org.scala-sbt sbt 0.13.8 ...
:: problems summary ::
:::: WARNINGS
module not found: org.scala-sbt#sbt;0.13.8
==== local: tried
/home/cloudera/.ivy2/local/org.scala-sbt/sbt/0.13.8/ivys/ivy.xml
-- artifact org.scala-sbt#sbt;0.13.8!sbt.jar:
/home/cloudera/.ivy2/local/org.scala-sbt/sbt/0.13.8/jars/sbt.jar
==== typesafe-ivy-releases: tried
https://repo.typesafe.com/typesafe/ivy-releases/org.scala- sbt/sbt/0.13.8/ivys/ivy.xml
</code></pre>
<p>Also I tried to get the version of sbt installed in my cluster and I get the below message alone, nothing happens after that </p>
<pre><code>n1@edge-node DEV $ sbt --version
sbt launcher version 0.13.8
</code></pre>
<p>I would like to know what went wrong here .
I am new to sbt .
Could someone help me on this?</p>
| <p>It looks like there is a version mismatch. The SBT version that was available in your desktop needs to be updated. its looking for 0.13.8 version of SBT. Please check donwload include in your PATH and it should resolve the issue.</p>
|
pdb file not generated in visual studio 2015 <p>I am developing a application using <strong>C#-MVC with Entity framework(database first) <em>VS 2015</em></strong>
I have created separate project for<strong>Data Layer Access</strong>. When I build this project, either DEBUG or RELASE mode, debug file not getting generated i.e. "<strong>.pdb</strong>" file.
Due this unable to hit break point.
In all project this file generated except <strong>Data Layer Access</strong> project </p>
<p>Please let me know, how can I generate this <strong>.pdb</strong> file for project in my project?</p>
<p>Thanks in advance!</p>
| <p>(1)Like this document about <a href="http://dotnetnsqlcorner.blogspot.sg/2014/04/how-to-disable-generating-pdb-files.html#!/2014/04/how-to-disable-generating-pdb-files.html" rel="nofollow">how to disable the pdb file</a>, please check your project property "Debug Info" option and output path:</p>
<p><a href="https://i.stack.imgur.com/oPK7B.png" rel="nofollow"><img src="https://i.stack.imgur.com/oPK7B.png" alt="enter image description here"></a></p>
<p>(2)Please also check your build configuration manager, all projects use the default Debug or Release option.</p>
<p>(3)If still no help, you'd better to collect the detailed output/compiled information, and make sure that which dll file or pdb generated this issue.</p>
|
What is the fastest way to xor 2 integers in Ruby? <p>Given an array a of n elements, I should replace <code>a[i]</code> with <code>a[i] XOR a[i+1]</code> and the value of <code>a[n-1]</code> with <code>a[n-1] XOR a[0]</code> for m number of times. The value of m may reach up to 10^18. What is the fastest and best approach?</p>
<pre><code>n, m = gets.chomp.split(" ").map &:to_i
arr = gets.chomp.split(" ")
m -= 1
m.times do
brr = arr.dup
i = 0.to_i
for i in 0..n-2
brr[i] = (arr[i].to_i ^ arr[i+1].to_i)
end
brr[n-1] = (arr[n-1].to_i ^ arr[0].to_i)
arr = brr.dup
p arr
puts ""
end
</code></pre>
<p>Is there a faster way to calculate the XOR value other than ^ operator?</p>
| <p>Stop thinking about it in terms of particular numbers, and consider basic mathematical rules for <code>^</code>:</p>
<ol>
<li>x ^ x = 0.</li>
<li>x ^ 0 = x.</li>
<li><p>^ is associative and commutative, so, for instance:</p>
<p>(x<sub>1</sub> ^ x<sub>2</sub>) ^ (x<sub>3</sub> ^ x<sub>2</sub>) = x<sub>1</sub> ^ (x<sub>2</sub> ^ x<sub>2</sub>) ^ x<sub>3</sub> = x<sub>1</sub> ^ 0 ^ x<sub>3</sub> = x<sub>1</sub> ^ x<sub>3</sub>.</p></li>
</ol>
<p>Write out a small array (n = 3 or 4) in terms of x<sub>i</sub>'s rather than actual specific numbers, and apply those rules through a few (m) iterations of your algorithm. You will see a repeated pattern emerge for m > n.</p>
<h2>ADDENDUM</h2>
<p>Once you see the pattern, Ruby's <a href="https://ruby-doc.org/core-2.2.0/Array.html#method-i-rotate" rel="nofollow">Array#rotate</a> might be incredibly handy (and provide a very fast solution) for you.</p>
|
Swift - Overriding functions with different default parameters <p>Case: A base class (A) with a function (doSomething) that has a default parameter (param: T = foo), and a subclass (B) which overrides that function with a different default parameter (param: T = bar). <strong>But is then called as A.</strong></p>
<p>Edit: Apologies for the original code, so actually what is happening is basically the following:</p>
<pre><code>class Foo
{
func doSomething(a: String = "123")
{
print(a)
}
}
class Bar: Foo
{
override func doSomething(a: String = "abc")
{
print("Using Bar method body... but not Bar's default a value!")
print(a)
}
}
(Bar() as Foo).doSomething()
// Prints:
// Using Bar method body... but not Bar's default a value!
// 123
</code></pre>
<p>Is it a bug or expected behaviour that it uses the functions body but doesn't use the functions default parameter?</p>
| <p>It's being called as Foo (or A) <em>because you tell it to.</em> Because you're instantiating <code>Bar() as Foo</code>, it is doing <strong><em>exactly that.</em></strong> </p>
<p>If you do:</p>
<pre><code>Bar().doSomething()
</code></pre>
<p>Bar's method is what is called:</p>
<pre><code>Using Bar method body...
abc
</code></pre>
<p>Interestingly, as you point out:</p>
<pre><code>(Bar() as Foo).doSomething()
</code></pre>
<p>Yields: </p>
<pre><code>Using Bar method body...
123
</code></pre>
<p>Because Bar is instantiated <strong><em>as</em></strong> Foo, (note emphasis) Bar gets Foo's default parameters, yet still executes Bar's function body.</p>
<p>Interesting observation!</p>
|
redis - display values less than $foo <p>I'm making a simple news website in laravel. I'm almost there, but I would like to add a trending articles option with help of redis. My question is - is there an option in redis to display results with value less than a variable foo. To be more exact, i've added timestamp and id in a hash, and i would like to display only results with timestamp-84600.</p>
<p>Any ideas?</p>
| <p>The best way to do it would be to also add them to a sorted set and then use <a href="http://redis.io/commands/zrangebyscore" rel="nofollow">zrangebyscore</a> to access them.</p>
<p>So you'd add </p>
<pre><code>ZADD articletimes <time> articleID
</code></pre>
<p>to redis and then </p>
<pre><code>ZRANGEBYSCORE articletimes <time-84600> <time>
</code></pre>
<p>to get your results back.</p>
|
Upload a file in ASP? <p>I have a FileUploader ion my website. When I choose a pic, it works fine.
But when I choose another type of file, this error occurs:</p>
<blockquote>
<p>This site canât be reached. The connection was reset.</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/ZJPmZ.png" rel="nofollow"><img src="https://i.stack.imgur.com/ZJPmZ.png" alt="click to see error"></a></p>
<p>Here is my code:</p>
<pre><code>protected void UploadFile_Click(object sender, EventArgs e)
{
if (rb_pic.Checked==true)
{
UploadPic();
}
else if (rb_vid.Checked == true)
{
UploadVideo();
}
else if (rb_picvid.Checked == true)
{
UploadVidPic();
}
}
</code></pre>
<p>As you see, <code>Uploadvideo</code> method is empty:</p>
<pre><code>public void UploadVideo()
{
}
</code></pre>
<p><code>UploadPic();</code> and <code>UploadVidPic();</code> are working fine.</p>
| <p>i just test it again .
it works for some files .
but some files still has an error .</p>
|
How to add source files generated in target folder as library in Intellij Idea <p>I'm trying to checkout a maven project from SubVersion. In the pom.xml file it's specified to generate web service proxy classes in the target folder. Here's the concerned part of the pom.xml file:</p>
<pre><code> <execution>
<goals>
<goal>wsimport</goal>
</goals>
<configuration>
<wsdlUrls>
<wsdlUrl>${basedir}/config/mnpBusinessService.wsdl</wsdlUrl>
</wsdlUrls>
<packageName>com.mnp.services.business</packageName>
<sourceDestDir>${basedir}/target/generated-code/src</sourceDestDir>
</configuration>
<id>ws-import-mnpBusinessService</id>
<phase>generate-sources</phase>
</execution>
</code></pre>
<p>As you can see the maven is instructed to create the generated proxy classes in the <code>${basedir}/target/generated-code/src</code> directory. When I checkout with NetBeans, a seperate GeneratedCode directory is created as part of the project. And any package inside this directory is available to the main source files. But when I checkout with Intellij Idea,</p>
<ol>
<li><p>I have to manually execute install command and second.</p></li>
<li><p>The files are indeed created in the specified directory but main source files can't see those packages.</p></li>
</ol>
<p>I've tried Project Structure|Modules|MyModule|Dependencies|Add Jars or directories and Project Structure|Libraries|Add|Java|Mydiectoryy. But neither helped. I also tried removing the <code>target</code> folder from Exclude list but that didn't help either. What should I do to be able to import generated proxy classes in Intellij Idea. It's the Ultimate version 2016.2.4. </p>
| <p>I ended up creating a module from existing sources, where existing sources folder is my <code>generated-code</code> folder. Then from the Modules|My main module|Dependencies|Add module and chose the just created module. And voila.</p>
<p>Here are the steps I followed:</p>
<p><strong>1.</strong></p>
<p><a href="https://i.stack.imgur.com/6QlYp.png" rel="nofollow"><img src="https://i.stack.imgur.com/6QlYp.png" alt="enter image description here"></a></p>
<p><strong>2.</strong></p>
<p><a href="https://i.stack.imgur.com/NPHQj.png" rel="nofollow"><img src="https://i.stack.imgur.com/NPHQj.png" alt="enter image description here"></a></p>
<p><strong>3</strong></p>
<p><a href="https://i.stack.imgur.com/Aik3w.png" rel="nofollow"><img src="https://i.stack.imgur.com/Aik3w.png" alt="enter image description here"></a></p>
<p><strong>4</strong></p>
<p><a href="https://i.stack.imgur.com/tdcnC.png" rel="nofollow"><img src="https://i.stack.imgur.com/tdcnC.png" alt="enter image description here"></a></p>
|
Laravel Mongo enbedsMany not embedding documents <p>Using the classic Posts and Comments example I am seeing that the embedsMany relation does not seem to be working where as hasMany works just fine. That is with hasMany I see the foreign key and all but with embedsMany I see no embedded document in Posts DB. </p>
<pre><code>class Post extends Moloquent
{
use SoftDeletes;
/**
* The name of the database connection to use.
*
* @var string
*/
protected $connection = 'mongodb';
public function comments()
{
return $this->embedsMany('App\Comment');
}
}
class Comment extends Moloquent
{
use SoftDeletes;
/**
* The name of the database connection to use.
*
* @var string
*/
protected $connection = 'mongodb';
/**
* Get the case that owns the comment.
*/
public function post()
{
return $this->belongsTo('App\Post');
}
}
</code></pre>
<p>My code to save:</p>
<pre><code> $comment = new Comment();
$comment->text = 'This is a comment';
$comment->save();
$post = new Post();
$post->text='some text blah blah';
$post->comments()->save($comment);
</code></pre>
| <p>Figured this out. I shoudln't have saved the comment document. </p>
<pre><code> $comment = new Comment();
$comment->text = 'This is a comment';
// $comment->save();
$post = new Post();
$post->text='some text blah blah';
$post->comments()->save($comment);
</code></pre>
|
Android - custom listview and highlight <p>I've tried a lot to get things working, but without any sort of success.</p>
<p>I have implemented a custom listview that displays 3 textviews, added the custom adapter of my hands and things work correctly, I've done the registerForContextMenu(View of listview) and when I press items displayed, it shows a perfect blue highlight around my item, and when I press it long the same happens and then it shows me the menu. Okay. Then I added a button inside my custom listview displaying one color if certain things happen, displaying another one viceversa. After I modified my custom adapter to include my button and setting the change-color logic, if I long press my items I have no more highlight around, but the context menu is preserved.</p>
<p>Why is this happening?</p>
<p>I tried a lot searching on Stack and Google, but every solution I found was not working with my app. I tried also to insert a custom selector, it works fine when I exclude the button from my listview design, I suppose the button is the culprit, but I can't find out a way to resolve this problem. I suppose is something related to the "background" - "drawable" of the button, but I am here to ask you some help.</p>
<p>Thanks in advance.</p>
<p>Some code if it can interest you:</p>
<p>listviewdesign.xml:</p>
<pre><code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="5dp"
android:layout_centerVertical="true"
android:gravity="center"
/>
<TextView
android:id="@+id/text2"
android:singleLine="false"
android:maxEms="8"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"
android:layout_toLeftOf="@+id/text3"
android:layout_toRightOf="@+id/text1"
android:layout_centerVertical="true"
android:gravity="center"
/>
<TextView
android:id="@+id/text3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"
android:layout_marginRight="5dp"
android:layout_toLeftOf="@+id/btn1"
/>
<Button
android:id="@+id/btn1"
android:layout_width="10px"
android:layout_height="10px"
android:layout_alignParentRight="true"
android:layout_marginTop="20dp"
/>
</RelativeLayout>
</code></pre>
<p>mainactivitylayout.xml:</p>
<pre><code><LinearLayout ...>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@android:id/list"
(when I add selector: android:listSelector="@xml/myselector")
android:clickable="false"
/>
</LinearLayout>
</code></pre>
<p>And my selector for completeness:</p>
<pre><code><selector xmlns:android="http://schemas.android.com/apk/res/android"
class="class of project">
<item android:state_pressed="true"
android:drawable="@drawable/pressed"/>
<item android:state_focused="true"
android:drawable="@drawable/focused"/>
<item android:state_selected="false"
android:state_pressed="false"
android:drawable="@drawable/normal"/>
<item android:drawable="@drawable/normal"/>
</selector>
</code></pre>
<p>Where those drawable items are correctly setup such as:</p>
<pre><code><resources>
<drawable name="pressed">#FF00A5FF</drawable>
<drawable name="focused">#FF0000FF</drawable>
<drawable name="normal">#00000000</drawable>
</resources>
</code></pre>
<p>Thanks!</p>
| <p>You need to place "myselector.xml" in drawable folder.</p>
<pre><code> android:listSelector="@xml/myselector"
</code></pre>
<p>this line should be </p>
<pre><code> android:listSelector="@drawable/myselector"
</code></pre>
|
Read variables from file and loop through them in bash <p>I have a text file containing variables like this:</p>
<pre><code>lane1_pair1="file1"
lane1_pair2="file2"
lane2_pair1="file3"
lane2_pair2="file4"
...
</code></pre>
<p>I'd like to loop through the variables and concatenate all of them in a single file. I am applying the loop as:</p>
<pre><code>. variables
for (( n=1; n<=no_lanes; n++ )) {
cat $"lane"${n}_pair1 >> "$sampleID"_cat1.fq
cat $"lane"${n}_pair2 >> "$sampleID"_cat2.fq
}
"$sampleID"_cat1.fq > fq_align_1
"$sampleID"_cat2.fq > fq_align_2
</code></pre>
<p>The problem here is that, cat command does not work because instead of replacing the <code>"laneX_pairY"</code> with its value, treat it as a string. I was wondering if anyone here has any idea about this.</p>
| <p>As I see it, the problem is you're looping through variables that are named like an array but aren't one. Then you're in the position of trying to evaluate the contents of the variable name created from your other indexing variable, which is a recipe for messy code that breaks easily. I recommend making actual arrays of file names from your <code>variables</code> file:</p>
<pre><code>p1_files=($(grep 'pair1' variables | cut -d '=' -f 2))
p2_files=($(grep 'pair2' variables | cut -d '=' -f 2))
for f in "${p1_files[@]}"; do
cat "${f//\"/}" >> "$sampleID"_cat1.fq
done
for f in "${p2_files[@]}"; do
cat "${f//\"/}" >> "$sampleID"_cat2.fq
done
</code></pre>
<p>I'm not sure how you want your <code>fq_align_n</code> variables to be, but you can read the file contents to variables using:</p>
<pre><code>fq_align_1=$(cat "$sampleID"_cat1.fq)
fq_align_2=$(cat "$sampleID"_cat2.fq)
</code></pre>
<p>Or just skip the file creation altogether and build the variables incrementally in the loops.</p>
|
How to debug reasons of program hanging? <p>I have a program with 2 threads, one of them redrawing display (with ncurses), and another is running inout processing on a serial port, outputting some info in process.</p>
<p>I have found out that at some points second thread hangs for reasons unknown to me. How to get to the bottom of the issue if:</p>
<ol>
<li>I cannot debug what happens in second thread because libthread_db and libpthread do not match on my system and gdb refuses to provide threading debug.</li>
<li>Thread that hangs performs processing with sequential calls to <code>select</code> and <code>read</code> on non-blocking file descriptor.</li>
<li>After dropping into gdb with Cntrl-C and resuming the program, thread is unstuck; moreover, it then processes all data stuck in recieving buffer of serial port.</li>
</ol>
<p>Are there any tips or tricks that will help me get to the bottom of the issue and determine reason for hanging?</p>
<p>Update. Running with strace netted me these lines in trace:</p>
<pre><code>waitpid(-1, 0xbfdcdfd0, 0) = ? ERESTARTSYS (To be restarted)
--- SIGCHLD (Child exited) @ 0 (0) ---
--- SIGCONT (Continued) @ 0 (0) ---
</code></pre>
<p>As far as i can tell, that corresponds to times where i saw a hang in the program, suspended it with <code>C-z</code> and looked at trace file (where nothing new was written until whole program has finished). After every restart thread was unhanged.</p>
<p>So, that means there is a 'rogue' <code>waitpid</code> call. I know for sure that it is not present in bare form anywhere in my code. A pity gdb fails to put a breakpoint on it - must be an issue of stripped symbols somewhere.</p>
| <blockquote>
<p>Are there any tips or tricks that will help me get to the bottom of the issue and determine reason for hanging?</p>
</blockquote>
<p>The obvious answer is to use <code>strace</code> on the hung thread to see what it's doing.</p>
<p>One common mistake is when you expect to read some number of bytes, and loop like this:</p>
<pre><code>while (bytes_remaining > 0) {
int n = read(..., bytes_remaining);
if (n == -1) {
// handle read error ...
break;
}
// save data we just got ...
bytes_remaining -= n;
// loop to read more data
}
</code></pre>
<p>The problem here is that <code>read</code> may return <code>0</code> on <code>EOF</code>, and you'll loop forever. In <code>strace</code> this will immediately be obvious.</p>
<p>If that's not it, the other thing you can do (assuming Linux) is attach GDB to the hung thread instead of the process.</p>
|
Reformat Python's vector list results to a single comma delimitted one <p>How can I <code>reformat</code> the results from a vector array (Python) to a single comma delimitted one?</p>
<p>I have these results:</p>
<pre><code> [ ['44231#0:', '2016/10/11', '11:19:23', '11:19:23', '1', '11:19:24', '11:19:24'
, '0']
['44231#0:', '2016/10/11', '12:20:39', '12:20:58', '12:20:59', '12:20:59', '0']
]
</code></pre>
<p>And I need something like:</p>
<pre><code>44231#0:, 2016/10/11, 11:19:23, 11:19:23, 1, 11:19:24, 11:19:24
44231#0:, 2016/10/11, 12:20:39, 12:20:58, 12:20:59, 12:20:59, 0
</code></pre>
<p>Anyone?</p>
<p>thank you in advance!!</p>
| <p>the simply way will be using two for loop.</p>
<pre><code>for d in data:
s = ''
for l in d:
s += l + ', '
print(s[:-2])
</code></pre>
|
TFS 2015 Copy and Publish Build Artifacts without subdictories <p>I have created a Copy and Publish Build Artifacts build step in TFS 2015 with the following parameters:</p>
<ul>
<li>Copy Root: $(build.sourcesdirectory)\bin\Installers</li>
<li>Contents: **</li>
</ul>
<p>The according to <a href="https://www.visualstudio.com/pl-pl/docs/build/steps/utility/copy-and-publish-build-artifacts" rel="nofollow">https://www.visualstudio.com/pl-pl/docs/build/steps/utility/copy-and-publish-build-artifacts</a> it should not copy the subdirecttories but unfortunately it does it! </p>
<p>How to copy and publish build artifacts whitout subfolders?</p>
| <p>Please add the suffix of the files after **, then you won't get the subdirectories. For example, in the following setting, you'll only get .txt and .dll files under <code>$(build.sourcesdirectory)\bin\Installers</code>, but you won't get .txt and .dll files in any sub folders under <code>$(build.sourcesdirectory)\bin\Installers</code>:</p>
<p><a href="https://i.stack.imgur.com/r0gI7.png" rel="nofollow"><img src="https://i.stack.imgur.com/r0gI7.png" alt="enter image description here"></a></p>
|
Merge Multiple JavaRDD <p>I've attempted to merge multiple JavaRDD but i get only 2 merged can someone kindly help. I've been struggling with this for a while but overall i would like to be able to obtain multiple collections and use sqlContext create a group and print out all results.</p>
<p>here my code</p>
<pre><code> JavaRDD<AppLog> logs = mapCollection(sc, "mongodb://hadoopUser:Pocup1ne9@localhost:27017/hbdata.ppa_logs").union(
mapCollection(sc, "mongodb://hadoopUser:Pocup1ne9@localhost:27017/hbdata.fav_logs").union(
mapCollection(sc, "mongodb://hadoopUser:Pocup1ne9@localhost:27017/hbdata.pps_logs").union(
mapCollection(sc, "mongodb://hadoopUser:Pocup1ne9@localhost:27017/hbdata.dd_logs").union(
mapCollection(sc, "mongodb://hadoopUser:Pocup1ne9@localhost:27017/hbdata.ppt_logs")
)
)
)
);
public JavaRDD<AppLog> mapCollection(JavaSparkContext sc ,String uri){
Configuration mongodbConfig = new Configuration();
mongodbConfig.set("mongo.job.input.format", "com.mongodb.hadoop.MongoInputFormat");
mongodbConfig.set("mongo.input.uri", uri);
JavaPairRDD<Object, BSONObject> documents = sc.newAPIHadoopRDD(
mongodbConfig, // Configuration
MongoInputFormat.class, // InputFormat: read from a live cluster.
Object.class, // Key class
BSONObject.class // Value class
);
return documents.map(
new Function<Tuple2<Object, BSONObject>, AppLog>() {
public AppLog call(final Tuple2<Object, BSONObject> tuple) {
AppLog log = new AppLog();
BSONObject header =
(BSONObject) tuple._2();
log.setTarget((String) header.get("target"));
log.setAction((String) header.get("action"));
return log;
}
}
);
}
</code></pre>
<p>// printing the collections
SQLContext sqlContext = new org.apache.spark.sql.SQLContext(sc);</p>
<pre><code> DataFrame logsSchema = sqlContext.createDataFrame(logs, AppLog.class);
logsSchema.registerTempTable("logs");
DataFrame groupedMessages = sqlContext.sql(
"select * from logs");
// "select target, action, Count(*) from logs group by target, action");
// "SELECT to, body FROM messages WHERE to = \"eric.bass@enron.com\"");
groupedMessages.show();
logsSchema.printSchema();
</code></pre>
| <p>If you wanted to merge multiple <code>JavaRDDs</code> , simply use <code>sc.union(rdd1,rdd2,..)</code> instead <code>rdd1.union(rdd2).union(rdd3)</code>.</p>
<p>Also check this <a href="http://stackoverflow.com/questions/29173160/rdd-union-vs-sparkcontex-union">RDD.union vs SparkContex.union</a></p>
|
Racket: applying filter on a field of a struct in a list of struct <p>Please find my code snippet below:</p>
<pre><code> (define (try los)
(filter (string=? (person-name (first los)) "Mike") los))
</code></pre>
<p>I am getting some syntactical errors here. I am not sure how to apply filter on 1 particular field of struct in a list of structs. (Note: I do not want to use recursion). Can someone give me an example for the same or help me correct what I am trying to do here?</p>
| <p>A simple solution is to make a helper function, <code>mike?</code>, that accepts a person struct <code>s</code> and checks whether the name is <code>"Mike"</code>.</p>
<pre><code>(define (mike? s)
(string=? (person-name s) "Mike")
(define (try los)
(filter mike? los))
</code></pre>
|
Text to Outlook body <p>I have this button which when clicked opens outlook with the details i have provided. I also have a TEXTAREA which is holding certain texts. I'm looking for a way to have this text appear in the body of my outlook. Can this be done.? Please find code below -</p>
<pre><code> <!DOCTYPE html>
<html lang="en">
<head>
<body>
<title>NMUK</title>
<script type=âtext/javascriptâ language=âjavascriptâ src=âMail.jsâ></script>
<script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('.btnSendEmail').click(function (event) {
var email = 'example@email.com';
var subject = 'Creation Checklist';
var emailBody = $('#holdtext').val();
window.location = 'mailto:' + email + '?subject=' + subject + '&body=' + emailBody;
});
});
</script>
</head>
</head>
<br><br><br><br><br><br>
<div id="container">
<TEXTAREA ID="holdtext" rows="15" cols="100">
</TEXTAREA><br><br>
<button class="btnSendEmail" ><span>Send Email</span></button>
</div>
<div>
<style>#container {width:100%; text-align:center;}</style>
<h2></h2><br><br><br>
<p> <SPAN ID="Fetch"> Fetch next</p> <br>
<button class="button2" button onclick="FetchFunction()"><span>Next </span></button>
<p> <SPAN ID="GroupCompanies"> In AD goto Group</p>
<button class="button1" button onclick="GroupCompaniesFunction()"><span>Next </span></button>
<script>
function FetchFunction() {
holdtext.innerText = Fetch.innerText;
}
function GroupCompaniesFunction() {
holdtext.innerText += "\n"+GroupCompanies.innerText;
}
</script>
</body>
</html>
</code></pre>
| <p><strong>Here is an example that I have used with the textarea tag and javascript:</strong></p>
<pre><code><div class="contact-form">
<br>
<div class="alert alert-success hidden" id="contactSuccess">
<strong>Success!</strong> Your message has been sent to us.
</div>
<div class="alert alert-error hidden" id="contactError">
<strong>Error!</strong> There was an error sending your message.
</div>
<form name="sentMessage" id="contactForm" novalidate>
<div class="form-group">
<input type="text" class="form-control" placeholder="Full Name" id="RecipientName"
required name="RecipientName"
data-validation-required-message="Please enter your name" />
</div>
<div class="form-group">
<input type="email" class="form-control" placeholder="Email"
id="RecipientEmail" name="RecipientEmail" required
data-validation-required-message="Please enter your email" />
</div>
<div class="form-group">
<textarea rows="10" cols="100" class="form-control"
placeholder="Please enter your message" id="RecipientMessage" name="RecipientMessage"
required data-validation-required-message="Please enter your message" minlength="5"
data-validation-minlength-message="Min 5 characters" maxlength="999"
style="resize:none">
</textarea>
</div>
<input class="btn btn-primary pull-right" type="submit" id="EmailSendButton"
name="EmailSendButton" value="send message" onclick="EmailData()">
</form><br /><br />
<div id="EmailConfirmation"></div>
</div>
<script>
function EmailData() {
$("#EmailSendButton").attr("disabled", "true");
var url = "/Home/EmailData";
var recipientName = $("#RecipientName").val();
var recipientEmail = $("#RecipientEmail").val();
var recipientMessage = $("#RecipientMessage").val();
var postData = { 'Name': recipientName, 'Email': recipientEmail, 'Message': recipientMessage }
$.post(url, postData, function (result) {
$("#EmailConfirmation").css({ 'display': 'block' });
$("#EmailConfirmation").text(result);
$("#EmailConfirmation").attr({ class: 'alert alert-success' })
$("#RecipientName").val('Your Name *');
$("#RecipientEmail").val('Your E-mail *');
$("#RecipientMessage").val('Your Message *');
})
}</script>
</code></pre>
|
Undesired background color overlay while using brunch/with-react <p>I am not sure this issue is related directly to brunch, but it's the first time I use this framework and first time I see something like this ...</p>
<p>I am trying out brunch/with-react skeleton and there is a little issue with my DOM elements.</p>
<p>I changed my body's background color as follow, in <code>app/styles/application.css</code></p>
<pre><code>body {
background-color: #cfcfcf
}
</code></pre>
<p>Here is the result
<a href="https://i.stack.imgur.com/ZdTjI.png" rel="nofollow">DOM rendering</a></p>
<p>I am using Chrome so I went ahead and inspected every elements.
I cannot find any element responsible for this behavior.</p>
| <p>Your html pages says:</p>
<pre><code><link rel="stylesheet" type="text/css" href="/app.css">
</code></pre>
<p>But your css filename is application.css</p>
|
JVM heap stuck at 2g even when started with -Xmx 3G <p>We have a weird issue with a java process.
It was started with -Xmx3G , and at some point it started throwing :</p>
<pre><code>java.lang.OutOfMemoryError: Java heap space
</code></pre>
<p>Checking the GC logs around the time the error is thrown, the heap size seems stuck at 2G ?</p>
<pre><code>...
12893.533: [Full GC 2248110K->2248109K(2315776K), 0.4723440 secs]
212894.006: [Full GC 2248110K->2248109K(2315776K), 0.4823290 secs]
212894.490: [Full GC 2248110K->2248110K(2315776K), 0.4642130 secs]
212894.955: [Full GC 2248114K->2248112K(2315776K), 0.4866180 secs]
...
</code></pre>
<p>What are the possible reasons that could explain this ?</p>
<p>Many thanks,
George</p>
| <p>This is major GC log, which collects the full heap. </p>
<p>It is reasonable that 3G heap but showing about 2.3G in GC log, because the heap is comprised by many parts not only young and old generations but also perm/virtual which are not collected by GC <a href="http://www.oracle.com/technetwork/java/javase/gc-tuning-6-140523.html#generation_sizing.total_heap" rel="nofollow">hotspot VM generations</a>. </p>
<p>The error is caused by that heap is full but GC cannot collect any objects, so larger heap needed or you may have to resize the heap (so young/old generations have larger space). To verify if there is any setting problems, simply using -Xmx5G to see if heap is still stuck at 2G (which should not happen).</p>
|
Call inferface methods in different order <p>I have one interface with several methods:</p>
<pre><code>interface IExample {
methodA();
methodB();
methodC();
...
methodN();
}
</code></pre>
<p>I also have several implementations of that interface (e.g class A, class B...). I also have HashMap where I put those implementations based on specific key:</p>
<pre><code>commands = new HashMap<String, IExample>();
commands.put("key1", new A());
.
.
commands.put("keyN", new N());
</code></pre>
<p>I use strategy design pattern to fetch each implementation when some event occur:</p>
<pre><code>Event event = ...
IExample example = UtilClass.commands.get(event.getKey());
</code></pre>
<p>and now I am able to call methods on particular implementation:</p>
<pre><code>example.methodA();
...
</code></pre>
<p>The problem is that depending on the event, method call order is different. So, for key1 call order is:</p>
<pre><code>example.methodC();
example.methodA();
...
</code></pre>
<p>but for different key, let's say key2, method call order is:</p>
<pre><code>example.methodA()
example.methodC()
...
</code></pre>
<p>What design pattern or approach I can use in order solve this problem in a easy and clean way? Not to use something like this:</p>
<pre><code> if (example instance of A) { call order for A... }
if (example instance of B) { call order for B... }
</code></pre>
| <p>You just simply add another method to your <code>IExample</code> interface:</p>
<pre><code>interface IExample {
methodA();
methodB();
methodC();
...
methodN();
execute();
}
class A implements IExample {
//...
execute() {
methodA();
methodC();
}
}
...
commands.get("key1").execute();
</code></pre>
<p>In case, if the <code>IExample</code> interface could not be changed, or there are many orders duplicated, you can move the <code>execute()</code> method to another interface <code>IExecutor</code>:</p>
<pre><code>interface IExecutor {
execute();
}
class Executor1 implements IExecutor {
private final IExample example;
public Executor1(IExample example) { this.example = example; }
execute() {
example.methodA();
example.methodC();
}
}
</code></pre>
<p>and manage a hash map of <code>IExecutor</code> instead of <code>IExample</code>:</p>
<pre><code>commands = new HashMap<String, IExecutor>();
commands.put("key1", new Executor1(new ExampleA()));
commands.put("key2", new Executor1(new ExampleB()));
...
commands.get("key1").execute();
</code></pre>
|
Remote server is ahead after pushing from local <p>I asked this yesterday but didn't ask my question right so no one was able to help. So I'll try again.</p>
<p><strong>I add a repo</strong></p>
<pre><code>mkdir test
cd test
git init
git remote add origin git@bitbucket.org:user/test.git
git add .
git commit -m "initial"
git push origin master
</code></pre>
<p><strong>I ssh into my web server and git clone</strong> </p>
<pre><code>git clone git@bitbucket.org:user/test.git
cd test
</code></pre>
<p><strong>I set up my hook in server, add a git checkout then give permission to file</strong></p>
<pre><code>git config receive.denyCurrentBranch ignore
vim .git/hooks/post-recieve
GIT_WORK_TREE=../ git checkout -f
chmod +x .git/hooks/post-recieve
</code></pre>
<p><strong>I add my ssh into server authorized keys.</strong></p>
<p><strong>I then add my remote server from local</strong></p>
<pre><code>git remote add test user@server.com:test
</code></pre>
<p><strong>On git remote -v I get</strong></p>
<pre><code>test user@server.com:test (fetch)
test user@server.com:test (push)
origin git@bitbucket.org:user/test.git (fetch)
origin git@bitbucket.org:user/test.git (push)
</code></pre>
<p><strong>I then add a file</strong></p>
<pre><code>touch test.php
git add test.php
git commit -m "test page"
git push origin master
</code></pre>
<p><strong>I then push to server</strong></p>
<pre><code>git push test master
</code></pre>
<p><strong>In server when ls -l I only get one file index.php
When I do git status I get</strong> </p>
<pre><code># On branch master
# Your branch is ahead of 'origin/master' by 1 commit.
# (use "git push" to publish your local commits)
#
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# deleted: test.php
#
</code></pre>
<p>I then have to run git stash to get all files.</p>
<p>So the head is at the correct position. It's retrived the test.php file but then deleted it? </p>
| <p>Absolutely stupid, wasted a full day yesterday trying to solve this and it was a stupid typo.</p>
<pre><code>vim .git/hooks/post-recieve
</code></pre>
<p>Spelt receive wrong</p>
<pre><code>vim .git/hooks/post-receive
</code></pre>
<p>I'm just going to go kill my self.</p>
|
Query builder isn't execute where = on another column <p>Sorry, my question title isn't very clear but I couldn't figure a way to word this question. </p>
<p>I have the following query builder code.</p>
<pre><code>return self::select(DB::raw('sum(user_points.points) AS points, users.id AS user_id, users.username, users.avatar, users.firstname, users.lastname'))
->join('users', 'users.id', '=', 'user_points.user_id')
$query->where('user_points.artist_id', 0)->orWhere('user_points.artist_id', 'users.favourite_artist_id');
})
->where('user_points.created_at', '>=', $startDate)
->where('user_points.created_at', '<=', $endDate)
->groupBy('users.id')
->orderBy('points', 'DESC')
->orderBy('user_id', 'ASC')
->simplePaginate(100);
</code></pre>
<p>It runs ok but is ignore the inner where query, specifically it's ignoring part of this;</p>
<pre><code>$query->where('user_points.artist_id', 0)->orWhere('user_points.artist_id', 'users.favourite_artist_id');
})
</code></pre>
<p>It's matching 'user_points.artist_id = 0', but it's not matching the 'user_points.artist_id = users.favourite_artist_id', presumable it's got something to do with the way it's handling the bindings? But I can't seem to find a way to get it to work.</p>
<p>The complete query should end up like this;</p>
<pre><code>SELECT SUM(user_points.points) AS points, users.id AS user_id, users.username, users.avatar, users.firstname, users.lastname
FROM user_points
INNER JOIN users ON users.id = user_points.user_id
WHERE (user_points.artist_id = 0 OR user_points.artist_id = users.favourite_artist_id)
AND user_points.created_at >= '$startDate' AND user_points.created_at <= '$endDate'
GROUP BY user_id
ORDER BY points DESC, user_id ASC
</code></pre>
<p>I updated the query builder code to this.</p>
<pre><code>return self::select(DB::raw('sum(user_points.points) AS points, users.id AS user_id, users.username, users.avatar, users.firstname, users.lastname'))
->join('users', 'users.id', '=', 'user_points.user_id')
->where(function($query) {
$query->Where('user_points.artist_id', 0)->orWhere(DB::raw('user_points.artist_id = users.favourite_artist_id'));
})
->where('user_points.created_at', '>=', $startDate)
->where('user_points.created_at', '<=', $endDate)
->groupBy('users.id')
->orderBy('points', 'DESC')
->orderBy('user_id', 'ASC')
->simplePaginate(100);
</code></pre>
<p>That didn't work as the final query ended up looking like this.</p>
<pre><code>select sum(user_points.points) AS points, users.id AS user_id, users.username, users.avatar, users.firstname, users.lastname
from `user_points` inner join `users` on `users`.`id` = `user_points`.`user_id` where (`user_points`.`artist_id` = ? or user_points.artist_id = users.favourite_artist_id is null)
and `user_points`.`created_at` >= ?
and `user_points`.`created_at` <= ?
group by `users`.`id`
order by `points` desc, `user_id` asc
</code></pre>
| <p>You need to add the second where (or) as a raw query. The where method will add the second column as a value so you are actually trying the following:</p>
<pre><code>user_points.artist_id = 'users.favourite_artist_id'
</code></pre>
<p>Try the following:</p>
<pre><code>whereRaw("user_points.artist_id = users.favourite_artist_id")
</code></pre>
|
javascript code prime numbers wont show <p>I am studying JavaScript and right now is Im trying to show the prime numbers. but unfortunately it doesnt display. can someone help Iam stuck with these.</p>
<p>This is my code:</p>
<pre><code>function getPrimes(max) {
var sieve = [], i, j, primes = [];
for (i = 2; i <= max; ++i) {
if (!sieve[i]) {
primes.push(i);
for (j = i << 1; j <= max; j += i) {
sieve[j] = true;
}
}
}
return primes;
}
getPrimes(10);
</code></pre>
<hr>
<p>and also I tried this. but still nothing shows.
second code:</p>
<pre><code>function findeprime(num){
var isPrime;
for (var i = 2; i < num; i++){
isPrime = true;
for (coun = 2; coun < i; coun++) {
if (i % coun == 0) isPrime = false;
}
if (isPrime) document.write(i + " is prime <br/>");
}
}
finderprime(5);
</code></pre>
| <p>What exactly do you mean by "doesn't display"? This code works fine for me in a console. You just don't have any code to actually output or display the returned values.</p>
<p>If you're trying to output to the console, try using <code>console.log()</code>.</p>
<p>If you're trying to make this appear on a webpage, try out <code>document.write();</code>.</p>
|
Paragraph keeps pushing 1 div down <p>Im having an issue with some paragraph text that is pushing one div down. I have 2 rows of 3 divs and its the first div on the first row that is pushing the div below it down on row 2 out of line. I just can work out why it doesnt push the whole row of 3 divs below it down.</p>
<p>Hope someone can shed some light on this for me</p>
<p>Thanks very much</p>
<p><a href="https://jsfiddle.net/8sk3f59m/" rel="nofollow">https://jsfiddle.net/8sk3f59m/</a></p>
<pre><code> <div class="row">
<div class="one-third">
<div class="right-arrow">
<i class="fa fa-arrow-right" aria-hidden="true"></i>
</div>
<div id="wireframe">
<img src="img/wireframe.svg" class="icons" />
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod sed do eiusmod</p>
</div>
</div>
<div class="one-third">
<div class="right-arrow">
<i class="fa fa-arrow-right" aria-hidden="true"></i>
</div>
<div id="develop">
<img src="img/coding.svg" class="icons" />
<p>Lorem ipsum dolor sit amet, consectetur </p>
</div>
</div>
<div class="one-third">
<div id="responsive">
<img src="img/responsive1.svg" class="icons" />
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod</p>
</div>
</div>
<div class="row">
<div class="one-third">
<div id="responsive">
<img src="img/responsive.svg" class="icons" />
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod</p>
</div>
</div>
<div class="one-third">
<div id="responsive">
<img src="img/responsive.svg" class="icons" />
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod!</p>
</div>
</div>
<div class="one-third">
<div id="responsive">
<img src="img/responsive.svg" class="icons" />
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod</p>
</div>
</div>
</div>
</div>
* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
}
body {
font-size: 20px;
font-family: 'Lato', sans-serif;
background-color: #fff;
position: relative;
font-weight: 200;
}
p {
padding: 10px 0;
}
img {
max-width: 100%;
height: auto;
}
h1 {
font-weight: normal;
text-align: center;
padding-bottom: 2%;
}
.justify {
text-align: justify;
}
/*--Basic Setup End--*/
/*--Reusable Content Start--*/
.chart-wrapper {
width: 70%;
margin: 5% auto 3% auto;
}
.clearfix {
zoom: 1
}
.clearfix:after {
content: '.';
clear: both;
display: block;
height: 0;
visibility: hidden;
}
.long-row {
width: 85%;
margin: 0 auto;
position: relative;
}
.row {
max-width: 950px;
margin: 0 auto;
position: relative;
}
.row {
zoom: 1;
/* For IE 6/7 (trigger hasLayout) */
}
.row:before,
.row:after {
content: "";
display: table;
}
.long-row:before,
.long-row:after {
content: "";
display: table;
}
.row:after {
clear: both;
}
.long-row:after {
clear: both;
}
.one-half {
width: 50%;
float: left;
margin: 2% auto;
padding: 0 20px;
}
.one-third {
width: 33.333%;
float: left;
margin: 2% auto;
padding: 0 20px;
position: relative;
}
.two-thirds {
width: 66.667%;
float: left;
margin: 2% auto;
padding: 0 20px;
}
.icon-center {
text-align: center;
}
.icons {
width: 100px;
height: 100px;
opacity: 0.7;
}
.section-wrap {
margin: 4% auto;
}
.icon-heading {
display: block;
font-style: normal !important;
font-weight: 500;
padding: 2% 0;
}
.underline {
border-bottom: 1px solid rgba(0, 0, 0, 0.2);
}
#vision {
margin: 2% 0;
}
.right-arrow {
position: absolute;
display: inline-block;
top: 25%;
right: 0;
opacity: 0.7;
}
#wireframe,
#develop,
#responsive,
i {
text-align: center;
}
</code></pre>
| <p>You're forgetting to include a closing <code></div></code> for your first <code>.row</code>. Including this will fix your height alignment issue.</p>
<p><strong><a href="https://jsfiddle.net/8sk3f59m/2/" rel="nofollow">JSFiddle</a></strong></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-css lang-css prettyprint-override"><code>/*--Colors--/*
#00cc00 - Green
#7fe57b - Green Gradient
/*--Basic Setup Start--*/
* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
}
body {
font-size: 20px;
font-family: 'Lato', sans-serif;
background-color: #fff;
position: relative;
font-weight: 200;
}
p {
padding: 10px 0;
}
img {
max-width: 100%;
height: auto;
}
h1 {
font-weight: normal;
text-align: center;
padding-bottom: 2%;
}
.justify {
text-align: justify;
}
/*--Basic Setup End--*/
/*--Reusable Content Start--*/
.chart-wrapper {
width: 70%;
margin: 5% auto 3% auto;
}
.clearfix {
zoom: 1
}
.clearfix:after {
content: '.';
clear: both;
display: block;
height: 0;
visibility: hidden;
}
.long-row {
width: 85%;
margin: 0 auto;
position: relative;
}
.row {
max-width: 950px;
margin: 0 auto;
position: relative;
}
.row {
zoom: 1;
/* For IE 6/7 (trigger hasLayout) */
}
.row:before,
.row:after {
content: "";
display: table;
}
.long-row:before,
.long-row:after {
content: "";
display: table;
}
.row:after {
clear: both;
}
.long-row:after {
clear: both;
}
.one-half {
width: 50%;
float: left;
margin: 2% auto;
padding: 0 20px;
}
.one-third {
width: 33.333%;
float: left;
margin: 2% auto;
padding: 0 20px;
position: relative;
}
.two-thirds {
width: 66.667%;
float: left;
margin: 2% auto;
padding: 0 20px;
}
.icon-center {
text-align: center;
}
.icons {
width: 100px;
height: 100px;
opacity: 0.7;
}
.section-wrap {
margin: 4% auto;
}
.icon-heading {
display: block;
font-style: normal !important;
font-weight: 500;
padding: 2% 0;
}
.underline {
border-bottom: 1px solid rgba(0, 0, 0, 0.2);
}
#vision {
margin: 2% 0;
}
.right-arrow {
position: absolute;
display: inline-block;
top: 25%;
right: 0;
opacity: 0.7;
}
#wireframe,
#develop,
#responsive,
i {
text-align: center;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row">
<div class="one-third">
<div class="right-arrow">
<i class="fa fa-arrow-right" aria-hidden="true"></i>
</div>
<div id="wireframe">
<img src="img/wireframe.svg" class="icons" />
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod sed do eiusmod</p>
</div>
</div>
<div class="one-third">
<div class="right-arrow">
<i class="fa fa-arrow-right" aria-hidden="true"></i>
</div>
<div id="develop">
<img src="img/coding.svg" class="icons" />
<p>Lorem ipsum dolor sit amet, consectetur </p>
</div>
</div>
<div class="one-third">
<div id="responsive">
<img src="img/responsive1.svg" class="icons" />
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod</p>
</div>
</div>
</div>
<div class="row">
<div class="one-third">
<div id="responsive">
<img src="img/responsive.svg" class="icons" />
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod</p>
</div>
</div>
<div class="one-third">
<div id="responsive">
<img src="img/responsive.svg" class="icons" />
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod!</p>
</div>
</div>
<div class="one-third">
<div id="responsive">
<img src="img/responsive.svg" class="icons" />
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod</p>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
|
shortcut to start script (Excel VBA Drop Down List via Data Validation) <p>Implemented a VBA script (not created by me) to be able to select multiple words from a controlled term list entered into specific cells of an EXCEL spreadsheet. This is based on data validation lists. </p>
<p>The <strong>problems</strong> are the following:</p>
<ul>
<li>If I use data validation in columns for which I don't want to use the script (data validation is needed here, so I can add comments for the user when the cell is selected; comment boxes don't help), overwriting of terms or in-cell deleting doesn't work properly.
So I thought I could refine the script to only work in separate cells/columns. How can I do that?</li>
<li>I'd like to have a shortcut to start the script, rather than (or additional to) a double click.</li>
</ul>
<p>Any suggestions how to change the code to solve these issuese would be highly appreciated!</p>
<p>This is the code used:</p>
<pre><code> Option Explicit
' ...
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim rngDV As Range
Dim oldVal As String
Dim newVal As String
Dim lType As Long
Dim strList As String
Application.EnableEvents = False
On Error Resume Next
lType = Target.Validation.Type
On Error GoTo exitHandler
If lType = 3 Then
'if the cell contains a data validation list
Cancel = True
strList = Target.Validation.Formula1
strList = Right(strList, Len(strList) - 1)
strDVList = strList
frmDVList.Show
End If
exitHandler:
Application.EnableEvents = True
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rngDV As Range
Dim oldVal As String
Dim newVal As String
Dim strSep As String
strSep = ", "
Application.EnableEvents = False
On Error Resume Next
If Target.Count > 1 Then GoTo exitHandler
Set rngDV = Cells.SpecialCells(xlCellTypeAllValidation)
On Error GoTo exitHandler
If rngDV Is Nothing Then GoTo exitHandler
If Intersect(Target, rngDV) Is Nothing Then
'do nothing
Else
newVal = Target.Value
Application.Undo
oldVal = Target.Value
Target.Value = newVal
If newVal = "" Then
'do nothing
Else
If oldVal = "" Then
Target.Value = newVal
Else
Target.Value = oldVal & strSep & newVal
End If
End If
End If
exitHandler:
Application.EnableEvents = True
End Sub
</code></pre>
| <p>You have asked more than one question.<br>This is not a complete answer to all your questions.</p>
<p>Let's say you want to limit the activity to changes to only columns <strong>A</strong> or <strong>B</strong>.</p>
<p>Right after:</p>
<pre><code>strSep = ", "
</code></pre>
<p>include a line like:</p>
<pre><code>If Intersect(Target,Range("A:B")) is Nothing Then Exit Sub
</code></pre>
<p>Modify this line to limit activity to your columns of interest.</p>
|
Simple clojure : Why output of different expressions are same? <pre><code>(map (comp #(- 9 %) *) [2 4 6] [0 0 0])
</code></pre>
<p>output : <code>(9 9 9)</code></p>
<pre><code>(map (comp #(+ 9 %) *) [2 4 6] [0 0 0])
</code></pre>
<p>output : <code>(9 9 9)</code></p>
<p>Why these give same output? <code>#(- 9 %)</code> and <code>#(+ 9 %)</code> are different.</p>
| <p>You are mulitplying each number with zero:</p>
<pre><code>(map * [2 4 6] [0 0 0])
;; -> (0 0 0)
</code></pre>
<p>So what remains: <code>9-0 == 9+0</code></p>
|
MySQL Load Data enclosed character and field terminator on last field <p>I'm having a seemingly basic problem with loading data to MySQL. I'm using:</p>
<pre><code>LOAD DATA LOCAL INFILE 'C:/.../Contrato.txt'
INTO TABLE schema.contrato
FIELDS TERMINATED BY ';' ENCLOSED BY '|' LINES TERMINATED BY '/r/n' IGNORE 0 LINES;
</code></pre>
<p>Each line on the file looks like this, generated by another program:</p>
<pre><code>|abc|;|cde|;|123|;|456|;|name|\r\n
</code></pre>
<p>When executing the load, everything seems to load properly, except the very last field. When I look at the table, the last field actually shows the '|' characters around the name. It's not the end of the world, but it's strange that it would do that. As of now, I'm fixing it by adding a ';' right before the \r\n characters. </p>
<p>Is this the way it's supposed to be done?? Why would I need to add the field terminator before the line terminator in order to delete the field enclosers?</p>
| <p>I can duplicate the effect on a file with a single line in it, with multiple lines I only get a single entry which has the final column entry of "name| |abc" . </p>
<p>I changed '/r/n' to '\r\n' & the load worked correctly for files with a single entry & multiple entries & the surrounding | were correctly removed</p>
<pre><code>LOAD DATA LOCAL INFILE 'C:/.../Contrato.txt'
INTO TABLE schema.contrato
FIELDS TERMINATED BY ';' ENCLOSED BY '|' LINES TERMINATED BY '\r\n' IGNORE 0 LINES;
</code></pre>
|
SpriteKit & Swift: Changing size of scrolling ground node depending on screen size does not work <p>Im working on a game where i have a scrolling ground node, does anyone now how i could change the size of the ground node depending on which device it is running? I have a method to determine on which device the game is running on and changing the size of all the other nodes in my game works great exept for the ground node. I tried to do it but without success. </p>
<p>Thank you in advance.</p>
<p><strong>Method to determine on which device the game is running on:</strong></p>
<pre><code>func determineDevice() {
if view!.bounds.width == 480.0 { //IP4
isIphone4 = true
isIphone5 = false
isIphone6 = false
isIphone6Plus = false
}
if view!.bounds.width == 568.0 { //IP5
isIphone4 = false
isIphone5 = true
isIphone6 = false
isIphone6Plus = false
}
if view!.bounds.width == 667.0 { //IP6
isIphone4 = false
isIphone5 = false
isIphone6 = true
isIphone6Plus = false
}
if view!.bounds.width == 736.0 { //IP6+
isIphone4 = false
isIphone5 = false
isIphone6 = false
isIphone6Plus = true
}
}
</code></pre>
<p><strong>Here's an example how i set the size of all other nodes in my game depending on the screen size:</strong></p>
<pre><code>class GameScene: SKScene, SKPhysicsContactDelegate {
var screenWidth:CGFloat = 0
var screenHeight:CGFloat = 0
override func didMoveToView(view: SKView) {
screenWidth = self.view!.bounds.width
screenHeight = self.view!.bounds.height
node.size = CGSizeMake(screenWidth / 5.5, screenHeight / 6)
}
</code></pre>
<p>}</p>
<p><strong>Last but not least, the ground code:</strong></p>
<pre><code>func initializingScrollingGround() {
for var index = 0; index < 2; index += 1 {
ground = SKSpriteNode(imageNamed:"Ground_Layer")
ground.size = CGSize(width: frame.width, height: frame.height / 6)
ground.position = CGPoint(x: index * Int(ground.size.width), y: Int(screenHeight - 37))
ground.zPosition = 10
ground.anchorPoint = CGPointZero
ground.name = "Ground"
let offsetX = ground.size.width * ground.anchorPoint.x
let offsetY = ground.size.height * ground.anchorPoint.y
let path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, 0 - offsetX, 48 - offsetY)
CGPathAddLineToPoint(path, nil, 0 - offsetX, 0 - offsetY)
CGPathAddLineToPoint(path, nil, 665 - offsetX, 0 - offsetY)
CGPathAddLineToPoint(path, nil, 668 - offsetX, 48 - offsetY)
CGPathCloseSubpath(path)
ground.physicsBody = SKPhysicsBody(polygonFromPath: path)
ground.physicsBody?.categoryBitMask = PhysicsCatagory.ground
ground.physicsBody?.collisionBitMask = PhysicsCatagory.dragon
ground.physicsBody?.contactTestBitMask = PhysicsCatagory.dragon
ground.physicsBody?.affectedByGravity = false
ground.physicsBody?.dynamic = false
ground.physicsBody?.restitution = 0
self.worldNode.addChild(ground)
}
}
</code></pre>
<p><strong>In the update method:</strong></p>
<pre><code> func moveGround() {
self.worldNode.enumerateChildNodesWithName("Ground", usingBlock: { (node, stop) -> Void in
if let Ground = node as? SKSpriteNode {
Ground.position = CGPoint(x: Ground.position.x - self.groundVelocity, y: Ground.position.y)
// Checks if ground node is completely scrolled off the screen, if yes, then puts it at the end of the other node.
if Ground.position.x <= -Ground.size.width {
Ground.position = CGPointMake(Ground.position.x + Ground.size.width * 2, Ground.position.y)
}
}
})
}
</code></pre>
<p>Does anyone now how i could solve my problem?</p>
| <p>One approach to try is with <code>SKCameraNode</code>, then all your nodes will change together. This example uses an extension on <code>SKCameraNode</code> and distinquishes only between iPad and iPhone;</p>
<pre><code>// SKCameraNode+Extensions.swift
extension SKCameraNode {
func updateScaleFor(userInterfaceIdiom: UIUserInterfaceIdiom, isLandscape: Bool) {
switch userInterfaceIdiom {
case .phone:
self.setScale(isLandscape ? 0.75 : 1.0)
case .pad:
self.setScale(isLandscape ? 1.0 : 1.25)
default:
break
}
}
}
</code></pre>
<p>Then when your scene loads;</p>
<pre><code>camera.updateScaleFor(userInterfaceIdiom: UIDevice.current.userInterfaceIdiom, isLandscape: true)
</code></pre>
|
Getting an error on writing a DB output value to a variable in jmeter <p>The syntax I used is <code>props.put("perpetual_id",vars.get("Inventory_id_1"));</code> </p>
<pre><code>Response code: 500
Response message: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced file: inline evaluation of: ``props.put("perpetual_id",vars.get("Inventory_id_1")); System.out.println(vars.ge . . . '' : Method Invocation props.put
</code></pre>
<p>If I am using <code>System.out.println(vars.get("inventoryId_1"));</code>, it's printing fine.</p>
| <p>You probably have a typo, i.e. missing underscore in your <code>props.put...</code> statement. </p>
<p>Given <code>System.out.println(vars.get("inventoryId_1"));</code> works fine my expectation is that you need to change your line to something like:</p>
<pre><code>props.put("perpetual_id",vars.get("inventoryId_1"));
</code></pre>
<p>Few more hints:</p>
<ul>
<li>you can use <a href="http://jmeter.apache.org/usermanual/best-practices.html#bsh_variables" rel="nofollow">bsh.shared namespaces</a> as an alternative to JMeter Properties</li>
<li><p>you can get more human-friendly error message by putting your Beanshell code inside the <a href="https://docs.oracle.com/javase/tutorial/essential/exceptions/try.html" rel="nofollow">try block</a> like:</p>
<pre><code>try {
//your code here
}
catch (Throwable ex) {
log.error("Error in beanshell", ex);
throw ex;
}
</code></pre>
<p>This way you can get the "usual" stacktrace printed to <em>jmeter.log</em> file which will be way more informative and will help you to get to the bottom of the issue much faster and easier. </p></li>
</ul>
<p>See <a href="https://www.blazemeter.com/blog/queen-jmeters-built-componentshow-use-beanshell" rel="nofollow">How to Use BeanShell: JMeter's Favorite Built-in Component</a> guide for more information on using Beanshell in JMeter tests.</p>
|
How to access twig parent for loop inside secondary for <p>I have a basic Silex app running Twig templating, I am trying to display some input fields based on a payment type selected, then in a secondary loop, pre-populating the value based, however I am struggling to reference the inital for loop with the key value from the second loop. </p>
<pre><code>{% for payment in app.paymentTypes %}
{% if payment.name == page.affiliate.payment.PaymentType %}
{% for key, value in payment.fields %}
<div class="form-group">
<label for="{{ key }}" class="col-sm-4 control-label">{{ value }}</label>
<div class="col-sm-6">
<input type="text" id="{{ key }}" class="form-control" value=" {{ page.affiliate.payment.key }} ">
</div>
</div>
{% endfor %}
{% endif %}
{% endfor %}
</code></pre>
<p>The challenge is the: {{ page.affiliate.payment.key }}</p>
<p>The error:</p>
<blockquote>
<p>Twig_Error_Runtime in Template.php line 501:
Key "key" for array with keys "PaymentType, ukbank_bank_name, ukbank_swift, ukbank_account_name, ukbank_account_number" does not exist in "settings/payment.html.twig" at line 61
in Template.php line 501
at Twig_Template->getAttribute(array('PaymentType' => 'UK Bank Transfer', 'ukbank_bank_name' => 'BANK', 'ukbank_swift' => '000000', 'ukbank_account_name' => 'Something Ltd', 'ukbank_account_number' => '00000000'), 'key', array()) in Environment.php(404) : eval()'d code line 145</p>
</blockquote>
<p>Any help is appreciated </p>
| <p><code>'key'</code> does not exit as key in the <code>page.affiliate.payment</code> array.</p>
<p>I guess you want to use the value of <code>key</code> in the <code>page.affiliate.payment</code> array like this:</p>
<pre><code>{{ page.affiliate.payment[key] }}
</code></pre>
|
Bootstrapping sample means in R using boot Package, Creating the Statistic Function for boot() Function <p>I have a data set with 15 density calculations, each from a different transect. I would like to resampled these with replacement, taking 15 randomly selected samples of the 15 transects and then getting the mean of these resamples. Each transect should have its own personal probability of being sampled during this process. This should be done 5000 times. I have a code which does this without using the boot function but if I want to calculate the BCa 95% CI using the boot package it requires the bootstrapping to be done through the boot function first.
I have been trying to create a function but I cant get any that seem to work. I want the bootstrap to select from a certain column (data$xs) and the probabilites to be used are in the column data$prob.</p>
<p>The function I thought might work was;</p>
<pre><code>library(boot)
meanfun <- function (data, i){
d<-data [i,]
return (mean (d)) }
bo<-boot (data$xs, statistic=meanfun, R=5000)
#boot.ci (bo, conf=0.95, type="bca") #obviously `bo` was not made
</code></pre>
<p>But this told me 'incorrect number of dimensions'</p>
<p>I understand how to make a function in the normal sense but it seems strange how the function works in boot. Since the function is only given to boot by name, and no specification of the arguments to pass into the function I seem limited to what boot itself will pass in as arguments (for example I am unable to pass data$xs in as the argument for data, and I am unable to pass in data$prob as an argument for probability, and so on). It seems to really limit what can be done. Perhaps I am missing something though?</p>
<p>Thanks for any and all help</p>
| <p>The reason for this error is, that <code>data$xs</code> returns a vector, which you then try to subset by <code>data [i, ]</code>. </p>
<p>One way to solve this, is by changing it to <code>data[i]</code> or by using <code>data[, "xs", drop = FALSE]</code> instead. The <code>drop = FALSE</code> avoids type coercion, ie. keeps it as a <code>data.frame</code>.</p>
<p>We try</p>
<pre><code>data <- data.frame(xs = rnorm(15, 2))
library(boot)
meanfun <- function(data, i){
d <- data[i, ]
return(mean(d))
}
bo <- boot(data[, "xs", drop = FALSE], statistic=meanfun, R=5000)
boot.ci(bo, conf=0.95, type="bca")
</code></pre>
<p>and obtain:</p>
<pre><code>BOOTSTRAP CONFIDENCE INTERVAL CALCULATIONS
Based on 5000 bootstrap replicates
CALL :
boot.ci(boot.out = bo, conf = 0.95, type = "bca")
Intervals :
Level BCa
95% ( 1.555, 2.534 )
Calculations and Intervals on Original Scale
</code></pre>
|
How to modify button behavior immediately when accounting for Required Field Validators? <p>Trying to disable a Submit button when the user clicks it on a form. The Required Field Validators I'm using on other controls seem to be messing it up.</p>
<p>When I disable the button in the code behind in the method called on button submit, (btnSubmit.Enabled = false), the button doesn't actually change until the rest of the code in the method runs. The code takes about a minute total so the idea was to have it immediately change to disabled to prevent users from submitting multiple times.</p>
<p>Also tried changing the button directly on the page. I added</p>
<pre><code>OnClientClick="this.disabled = true;" UseSubmitBehavior="false"
</code></pre>
<p>to the button markup which worked by disabling it immediately but it didn't account for the required field validators. Even if a field was missing, the button would be disabled and the user wouldn't be able to submit once they filled out the missing field</p>
<p>How do I change the button to disabled immediately only when all of the required fields are there?</p>
| <p>This should work for you:</p>
<pre><code>runat="server" ID="btnSubmit" Text="Submit" OnClick="btnSubmit_Click" OnClientClick="if (!Page_ClientValidate()){ return false; } this.disabled = true; this.value = 'Saving...';" UseSubmitBehavior="false"
</code></pre>
<p>All these attribute inside your <code>asp:button</code>.</p>
|
Find particular column in particular table in all databases at the same time <p>I have many identical databases and I would like to find all databases that have particular entry in the same table.</p>
<p>This is what I have to run agains each databse to get the info I need:</p>
<pre><code>select OrderID, OrderRef
from Orders
where OrderID = '12345'
</code></pre>
<p>I thought that I can run my query against all databses using unsupported <code>sp_MSforeachdb</code>, but I'm not desperate to use this particular method.</p>
<pre><code>CREATE TABLE ##tmpTable(OrderID VARCHAR(MAX), OrderRef VARCHAR(MAX));
DECLARE @command varchar(1000)
SELECT
@command = 'Use ? INSERT INTO ##tmpTable SELECT ''[?]'', OrderID, OrderRef FROM Orders WHERE OrderID = ''12345'';'
EXEC sp_MSforeachdb @command
SELECT * FROM ##tmpTable;
GO
DROP TABLE ##tmpTable;
</code></pre>
<p>When I run it as it is I am getting following error:</p>
<blockquote>
<p>Column name or number of supplied
values does not match table definition.</p>
</blockquote>
<p>Additionally, it doesn't show which database the results come from. What I would like to get is this: </p>
<pre><code>DatabaseName | OrderID | OrderRef
</code></pre>
| <p>Thanks to your comments I was able to modify my query and it works now:</p>
<pre><code>CREATE TABLE ##tmpTable(DB_Name VARCHAR(MAX), OrderID VARCHAR(MAX), OrderRef VARCHAR(MAX));
DECLARE @command varchar(1000)
SELECT @command = 'Use ? INSERT INTO ##tmpTable select ''?'', OrderID, OrderRef from Orders WHERE OrderID = ''12345''
;'
EXEC sp_MSforeachdb @command
SELECT * FROM ##tmpTable;
GO
DROP TABLE ##tmpTable;
</code></pre>
|
Handling multiple fact and multiple entities tables (MySQL) with common fields in Qlikview/QlikSense <p>I resolved my fact table with this post (<a href="http://stackoverflow.com/questions/18337272/handling-multiple-fact-tables-in-qlikview/40025152#40025152">Handling multiple fact tables in Qlikview</a>). But I have a problem with entity tables. I will use the example in this post (<a href="http://stackoverflow.com/questions/18337272/handling-multiple-fact-tables-in-qlikview/40025152#40025152">Handling multiple fact tables in Qlikview</a>) to explain my problem:</p>
<pre><code>test_scores_fact | enrollment_fact | school | gender | student
---------------- | --------------- | ------ | ------ | ---
school_code (FK) | school_code (FK) | school_code (PK) | gender_id (PK) | student_id (PK)
test_code (FK) | grade_id (FK) | school_name (FK) | gender_desc | school_code (FK)
grade_id (FK) | ethnicity_id (FK) | address | ... | gender_id (FK)
gender_id (FK) | gender_id (FK) | ... |
ethnicity_id (FK) | number_enrolled (F) |
student_id(FK) |
test_score (F) |
</code></pre>
<p>In the example i added the student table that have a relation with school table and geneder table. </p>
<p>My problem: </p>
<p>i followed the steps, then i have loaded my sql tables in Qlik Sense. I have also created a report for test_scores_face table with some filters like (student_id, gender_id,...). The problem that when i have selected the filter student_id the report can not filter by it? I think that the problem in the entity tables (school, gender, student) because they have common fields (like school_code, geneder_id). These common fields produce a circular references. </p>
<p>To avoid these circular references I have to do another link table for entity tables or collgate these table to the link table of fact tables? I tired these 2 solution but I also can not filter by student_id!</p>
<p>How can i deal this problem?</p>
| <p>You need to remove the link between the tables, I have assumed that you are manually editing the script?</p>
<p>If the field is not required for link</p>
<ul>
<li>Remove/Rename the field that is causing the circular reference</li>
</ul>
<p>If the fields are required for linking, concatenate the fields in the tables using <code>&'_'&</code></p>
<p>It depends on how you want to organise your data, but for a start it looks to me like grade and gender could be removed from the enrolment fact table as a start as this is covered on the student.</p>
|
Split sql string value based on 7th delimiter <p>Present column value</p>
<p>(Below is column value from temp table, value here is dynamically changing)</p>
<pre><code>45 | 00055 | 9/30/2016 | Vodafone | Randy Singh | Newyork | Test Msg | TBL101 | PC | 1.00 | COMP101 | CS | 1.00.............. etc
</code></pre>
<p>Need to divide based on 7th PIPE i.e after Test Msg</p>
<p>Output should be </p>
<p>String1</p>
<pre><code>45 | 00055 | 9/30/2016 | Vodafone | Randy Singh | Newyork | Test Msg
</code></pre>
<p>and (as a second string)</p>
<p>String 2</p>
<pre><code>TBL101 | PC | 1.00 | COMP101 | CS | 1.00......... etc
</code></pre>
<p>Function </p>
<pre><code>CREATE FUNCTION dbo.SUBSTRING_INDEX
(
@str NVARCHAR(4000),
@delim NVARCHAR(1),
@count INT
)
RETURNS NVARCHAR(4000)
WITH SCHEMABINDING
BEGIN
DECLARE @XmlSourceString XML;
SET @XmlSourceString = (SELECT N'<root><row>' + REPLACE( (SELECT @str AS '*' FOR XML PATH('')) , @delim, N'</row><row>' ) + N'</row></root>');
RETURN STUFF
(
((
SELECT @delim + x.XmlCol.value(N'(text())[1]', N'NVARCHAR(4000)') AS '*'
FROM @XmlSourceString.nodes(N'(root/row)[position() <= sql:variable("@count")]') x(XmlCol)
FOR XML PATH(N''), TYPE
).value(N'.', N'NVARCHAR(4000)')),
1, 1, N''
);
END
</code></pre>
<p>GO</p>
<pre><code>DECLARE @EmpId NVARCHAR(1000)
select @EmpId = temp from OMSOrderTemp
SELECT dbo.SUBSTRING_INDEX(@EmpId, N'|', 7) AS Result;e
</code></pre>
<p>Here in Result only string1 is showing and only first row.</p>
| <p>Spend time for you and happy that come with solution , I have modify the your function with own logic you can try this, This is table value function i.e this function will return Table </p>
<pre><code>CREATE FUNCTION dbo.SUBSTRING_INDEX
(
@str NVARCHAR(4000),
@delim NVARCHAR(1),
@count INT
)RETURNS @rtnTable TABLE
(
FirstString NVARCHAR(2000),
SecondString NVARCHAR(2000)
)
AS
BEGIN
DECLARE @cnt INT=1;
DECLARE @subStringPoint INT = 0
WHILE @cnt <=@count
BEGIN
SET @subStringPoint=CHARINDEX(@delim,@str,@subStringPoint)+1
SET @cnt=@cnt+1
END
INSERT INTO @rtnTable
SELECT SUBSTRING(@str,0,@subStringPoint-1) ,SUBSTRING(@str,@subStringPoint+1,LEN(@str))
RETURN
END
</code></pre>
<p>To call this function</p>
<pre><code>DECLARE @s varchar(MAX)='45 | 00055 | 9/30/2016 | Vodafone | Randy Singh | Newyork | Test Msg | TBL101 | PC | 1.00 | COMP101 | CS | 1.00'
SELECT * FROM dbo.SUBSTRING_INDEX (@s,'|',7)
</code></pre>
<p>This will gives two column output </p>
<pre><code>45 | 00055 | 9/30/2016 | Vodafone | Randy Singh | Newyork | Test Msg TBL101 | PC | 1.00 | COMP101 | CS | 1.00
</code></pre>
|
Atomic RPC calls <p>Could you tell me if an RPC is executed atomically?</p>
<p>For example making a transaction between two accounts, I would have an RPC such:</p>
<pre><code>1. client.rpc.provide('xfer', (data, response) => {
2. var srcWallet = getRecord(data.srcWalletId);
3. var dstWallet = getRecord(data.dstWalletId);
4. if (srcWallet.get('balance') >= data.xferAmount) {
5. srcWallet.set('balance', srcWallet.get('balance') - xferAmount);
6. dstWallet.set('balance', dstWallet.get('balance') + xferAmount);
7. }
</code></pre>
<p>Is it certain that the srcWallet balance cannot change between line 4 and 5?</p>
| <p>Just to clarify: deepstream does RPC's (request/response) using ds.rpc.make/ds.rpc.provide, your example refers to records.</p>
<p>The above example would work temporarily for JavaScript implementations that are single threaded, however you can't be sure that there isn't an incoming transaction on the way to the client that changes the wallet's balance. To enforce rules like the above, use a Valve rule on the server, e.g.</p>
<p><code>_('src-wallet').balance >= data.xferAmount</code></p>
<p>Please find more at </p>
<p><a href="https://deepstream.io/tutorials/core/permission-conf-simple/" rel="nofollow">https://deepstream.io/tutorials/core/permission-conf-simple/</a>
<a href="https://deepstream.io/tutorials/core/permission-conf-advanced/" rel="nofollow">https://deepstream.io/tutorials/core/permission-conf-advanced/</a>
<a href="https://deepstream.io/tutorials/core/permissions-dynamic/" rel="nofollow">https://deepstream.io/tutorials/core/permissions-dynamic/</a></p>
|
In C++, how do I round numbers without displaying them using only iostream, and iomanip? <p>For example, I want 2.22 to round to 2 and 7.8 to round up to 8, and I want to use these values as integers later in my code to print out a certain number of asterisks. Turning them into int values rounds them down automatically, but I need a number to round up, how would I go about doing that?</p>
| <p>You can use a <code>round()</code> function, such as the one below, which works for positive numbers.</p>
<pre><code>double round(double d)
{
return floor(d + 0.5);
}
</code></pre>
<p>You need the <a href="http://www.cplusplus.com/reference/cmath/floor/" rel="nofollow"><code>floor()</code></a> function for this, found in <code><cmath></code>. I honestly cannot think of anything involving JUST <code><iostream></code> and <code><iomanip></code></p>
<p>EDIT: For another approach, use <a href="http://en.cppreference.com/w/cpp/numeric/math/round" rel="nofollow"><code>std::round()</code></a>, from <code><cmath></code></p>
|
Can't send requests to google <p>I am sending a lot of requests per second to google from my web application (my server works on nodeJS). After several attempts google blocks my requests and respond with error. Is there any API for sending a lot of requests ?</p>
| <p>You can try JSON/Atom Custom Search API. It's free verson gives you opportunity of 100 query a day.You must create Key for your API and put it in link below`
<a href="https://www.googleapis.com/customsearch/v1?key=INSERT_YOUR_API_KEY&cx=017576662512468239146:omuauf_lfve&q=lectures" rel="nofollow">https://www.googleapis.com/customsearch/v1?key=INSERT_YOUR_API_KEY&cx=017576662512468239146:omuauf_lfve&q=lectures</a></p>
<p>here is the introduction of API <a href="https://developers.google.com/custom-search/json-api/v1/introduction#identify_your_application_to_google_with_api_key" rel="nofollow">enter link description here</a></p>
|
Express JS: No 'Access-Control-Allow-Origin' header is present on the requested resource <p>I have an API running on a server and a front-end client connecting to it to retrieve data. I did some research on the cross domain problem and has it working. However I've not sure what has changed. I am now getting this error in the console:</p>
<blockquote>
<p>XMLHttpRequest cannot load <a href="https://api.mydomain/api/status" rel="nofollow">https://api.mydomain/api/status</a>. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin '<a href="http://beta.mydomain.com" rel="nofollow">http://beta.mydomain.com</a>' is therefore not allowed
access. The response had HTTP status code 502.</p>
</blockquote>
<p>I have the following route file:</p>
<pre><code>var express = require('express');
var router = express.Router();
var Assessment = require('../app/models/assessment');
router.all('*', function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
router.post('/api/status', function (req, res, next) {
getStatus.getStatus(req, res, Assessment);
});
module.exports = router;
</code></pre>
<p>And the following JavaScript making an Ajax call to that route:</p>
<pre><code>var user = {
'uid' : '12345'
};
$.ajax({
data: user,
method: 'POST',
url: 'https://api.mydomain/api/status',
crossDomain: true,
done: function () {
},
success: function (data) {
console.log(JSON.stringify(data));
},
error: function (xhr, status) {
}
});
</code></pre>
<p>I have tried:
Putting the requesting domain in the 'Access-Control-Allow-Origin' header
Using the cors module for express
Putting my router.all function inside middleware</p>
<p>The requesting domain is HTTP and the api domain is on HTTPS. However, I have had it working while the HTTP was enabled. </p>
<p>Does anyone have any insight into why the 'Access-Control-Allow-Origin' header is not being send?</p>
<p>Thank you</p>
| <p>Instead of setting the request headers to your express route, Can you try setting it to express instance itself like this,</p>
<pre><code>var express = require('express');
var app = express();
var Assessment = require('../app/models/assessment');
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.post('/api/status', function (req, res, next) {
// your code goes here
});
module.exports = app;
</code></pre>
<p>Hope this helps!</p>
|
iteration variable inside for changing its value <p>I'm facing something I don't understand, I've tried many things. The weird thing is that this happens only in some servers, but not on others. So I'm guessing is somehow related to the PHP config. I have this code:</p>
<pre><code>$j = 0 ;
for($m = $days - 1; $m >= 0 ; $m--){
$time1 = strtotime('-'.$m.' DAY');
$date_day = date('Y-m-d', $time1) ;
$$items_var[$j] = new stdClass();
$j++;
}
</code></pre>
<p>The value of $days is 7. So this is for loop where $m goes from 6 to 0. well.. it should be. it starts ok, it does 6,5,4,3... and then it crashes. usually the error I get is
<strong>Catchable fatal error: Object of class stdClass could not be converted to string</strong></p>
<p>so, at some point (and it looks random, because in some servers is after the second iteration), the $m becomes an object...!!</p>
<p>this is somehow related to that assignation you see on the code:</p>
<p>$$items_var[$j] = new stdClass();</p>
<p>Yes, that's a double $$. I have a variable $items_var which value is "items". Therefore I'm trying to create this new stdClass() in an array called $items.</p>
<p>this is what's messing the code, but I don't know why. If I remove this assignation, the code works. the $m goes from 6 to 0. but for some reason, some PHP installations are messing this up and this line of code CHANGES the value of $m to an object.</p>
<p>I am clueless.</p>
| <p>It's EXACTLY this:</p>
<blockquote>
<p>Yes, that's a double $$. I have a variable $items_var which value is "items".</p>
</blockquote>
<p>That means you have:</p>
<pre><code>$items_var = 'items';
</code></pre>
<p>And you're using that string as an array:</p>
<pre><code>$$items_var[$j] = new stdClass();
</code></pre>
<p>When <code>$j</code> = 3, you're effectively running</p>
<pre><code>$m = new stdClass();
</code></pre>
<p>and have now <strong>overwritten</strong> your <code>for</code> loop variable with an object. On the NEXT iteration, you end up doing</p>
<pre><code>stdClass() >= 0
</code></pre>
<p>and produce your exact error.</p>
<p>This is exactly WHY you should <strong>NEVER</strong> use variable-variables. You end up with stupid/impossibly difficult-to-debug errors like this.</p>
<hr>
<p>comment followup:</p>
<p>PHP allows strings to be treated as arrays of characters:</p>
<pre><code>$foo = 'abcdefgh';
echo $foo[3] // outputs 'd'
</code></pre>
<p>Variable variables take the contents of a variable, and use it as the name of some OTHER variable:</p>
<pre><code>$bar = 'hi mom';
$foo = 'bar';
echo $foo; // outputs 'bar'
echo $$foo; // outputs 'hi mom'
</code></pre>
<p>So given:</p>
<pre><code>$items_vars = 'items';
$j = 3;
</code></pre>
<p>This sequence occurs:</p>
<pre><code>$$items_vars[$j] = new stdClass();
^-------------^
|
$ 'items'[3] = new stdClass();
|
$ m = new stdClass();
$m = new stdClass();
</code></pre>
<p>and boom, your <code>$m</code> that you're using in <code>for($m=....)</code> is now trashed.</p>
<hr>
<p>code deconstruction. If you pull apart your loop and write it out longhand:</p>
<pre><code>$items_vars = 'items';
$j = 0;
for($m = $days - 1; $m >= 0 ; $m--){
$$items_var[$j] = new stdClass();
</code></pre>
<p>You end up doing this:</p>
<pre><code> $$items_vars[$j] = new StdClass:
j = 0; m =6 ${'items'[0]} -> $i = new stdClas();
j = 1; m = 5 ${'items'[1]} -> $t = new stdClass();
j = 2; m = 4 ${'items'[2]} -> $e = new stdClass();
j = 3; m = 3 ${'items'[3]} -> $m // BOOM
</code></pre>
<p>You're not putting your new stdClass objects into an array. Your variable-variable is building SINGLE LETTER variable names, and putting a stdClass into each of them. If you want to store your new classes in an array, you'd need something more like</p>
<pre><code>array_push($$items_var, new stdClass());
</code></pre>
<p>which would execute as</p>
<pre><code>array_push($items, new stdClass());
</code></pre>
|
Spring Boot: Is it possible to consume @RequestParam's as json? <p>I have following rest endpoint in spring boot application:</p>
<pre><code> @RequestMapping(method = RequestMethod.POST, value = "/sign-in")
public Client signIn(@RequestParam String username, @RequestParam String password, HttpServletRequest request) {
Client client = authService.signIn(username, password);
return client;
}
</code></pre>
<p>I want accept data as application/json.</p>
<p>Is it possible to do this WITHOUT creating class for this like this?:</p>
<pre><code>public class LoginModel {
private String username;
private String password;
...
}
</code></pre>
<p>Also, without argument of type Map in <strong>signIn</strong> method</p>
<p>I need to accept application/json with this signature:</p>
<pre><code>public Client signIn(@RequestParam String username, @RequestParam String password)
</code></pre>
<p>Is it possible?</p>
| <p>No. I don't think it's possible. </p>
<p>You need to create the intermediary <code>Login</code> object. </p>
<p><code>@RequestParam</code> mandates you have a request param. </p>
|
Table border lines/separate editing <p>I am working on an HTML/CSS project for my school but have run into a problem. On one of my pages I have 3 tables which I want to edit with CSS separately.
I've tried to put class in all of the tables but it still only takes the commands of the second table. Am I supposed to put class in all of the TRs and TDs too?</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>body {
background-color: lightgrey;
}
.tabel1 {
border-color: purple;
width: 400px;
text-align: center;
height: 100px;
}
.tabel2,
tr,
td {
width: 350px;
border-color: grey;
border-style: solid;
border-collapse: collapse;
}
.tabel3 {
border-radius: 25px;
background: purple;
padding-left: 2%;
padding-right: 2%;
padding-bottom: 4%;
padding-top: 4%;
width: 400px;
border-color: purple;
box-shadow: 15px 6px 10px purple;
}
.tr1 {
background-color: purple;
}
.tr2 {
background-color: #9370DB;
}
.tr3 {
background-color: purple;
}
.tr4 {
background-color: #9370DB;
}
.tr5 {
background-color: purple;
}
.tr6 {
background-color: #9370DB;
}
.tr7 {
background-color: purple;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="tabel1" align="center">
<tr>
<td><strong>Film-Favo's</strong>
</td>
</tr>
</table>
<br>
<table class="tabel2" align="center">
<tr class="tr1">
<td>Film</td>
<td>Regisseur</td>
</tr>
<tr class="tr2">
<td>Film 1</td>
<td>Regisseur 1</td>
</tr>
<tr class="tr3">
<td>De noorderlingen</td>
<td>Ales van warmerdam</td>
</tr>
<tr class="tr4">
<td>Film 3</td>
<td>Regisseur 3</td>
</tr>
<tr class="tr5">
<td>Film 4</td>
<td>Regisseur 4</td>
</tr>
<tr class="tr6">
<td>Film 5</td>
<td>Regisseur 5</td>
</tr>
<tr class="tr7">
<td>Film 6</td>
<td>Regisseur 6</td>
</tr>
</table>
<br>
<table align="center" class="tabel3">
<tr>
<td bgcolor="#EE82EE">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium
quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate.</td>
</tr></code></pre>
</div>
</div>
</p>
| <p>If you remove the tr, td specification, your tables will be styled differently. Your CSS should apply to the <code>table</code>, not to the rows or cells.</p>
<p>Here is a <a href="https://jsfiddle.net/zephyr_hex/46dxof6f/" rel="nofollow">Fiddle Demo</a>.</p>
<p><strong>CSS</strong></p>
<pre><code>body {
background-color: lightgrey;
}
.tabel1 {
border-color: purple;
width: 400px;
text-align: center;
height: 100px;
}
.tabel2 {
width: 350px;
border-color: grey;
border-style: solid;
border-collapse: collapse;
}
.tabel3 {
border-radius: 25px;
background: purple;
padding-left: 2%;
padding-right: 2%;
padding-bottom: 4%;
padding-top: 4%;
width: 400px;
border-color: purple;
box-shadow: 15px 6px 10px purple;
}
</code></pre>
<p><strong>HTML</strong></p>
<pre><code><table class="tabel1">
<thead>
<tr>
<th>Col 1</th>
<th>Col 2</th>
<th>Col 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
<td>Cell 3</td>
</tr>
</tbody>
</table>
<table class="tabel2">
<thead>
<tr>
<th>Col 1</th>
<th>Col 2</th>
<th>Col 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
<td>Cell 3</td>
</tr>
</tbody>
</table>
<table class="tabel3">
<thead>
<tr>
<th>Col 1</th>
<th>Col 2</th>
<th>Col 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
<td>Cell 3</td>
</tr>
</tbody>
</table>
</code></pre>
<p><strong>Result</strong></p>
<p><a href="https://i.stack.imgur.com/CdnwD.png" rel="nofollow"><img src="https://i.stack.imgur.com/CdnwD.png" alt="result"></a></p>
|
Oracle query using Xpath to get comma separated List for same node <p><em>Hello Everyone,
I need a help to fetch comma separated list for same node if exists in XML nodes.
My XML is like this which is stored in my database:-</em></p>
<pre><code><Event>
<Detail>
<List>
<Element>
<name>ABC</name>
<salary>150</salary>
</Element>
<Element>
<name>PQR</name>
<salary>250</salary>
</Element>
</List>
</Detail>
</Event>
</code></pre>
<p><em>I need to get comma separated name list (ABC,PQR ) from this using xpath oracle query.
I have tried alot and when i get a way like this :-</em></p>
<pre><code>NVL(VALUE (line).EXTRACT ('/Event/Detail/List/Element/name/text()') .getstringval (),'') Name List
</code></pre>
<p>Then , my output was ABCPQR. </p>
<p>No Space or comma was there. Could anyone please help me out for this .</p>
<p><strong>Expected output is :- ABC,PQR</strong></p>
<p>Thanks in advance :)</p>
| <p>You're pulling a list of values out of an XML document, rather than a single value, so I think you'd be better off selecting them all into a table using <code>XMLTABLE</code> and then joining them together with <code>LISTAGG</code>.</p>
<p>Here's an example:</p>
<pre class="lang-none prettyprint-override"><code>SQL> CREATE TABLE xmltest (id INTEGER, x XMLTYPE);
Table created.
SQL> INSERT INTO xmltest (id, x) VALUES (1, XMLTYPE('<Event>
2 <Detail>
3 <List>
4 <Element>
5 <name>ABC</name>
6 <salary>150</salary>
7 </Element>
8 <Element>
9 <name>PQR</name>
10 <salary>250</salary>
11 </Element>
12 </List>
13 </Detail>
14 </Event>'));
1 row created.
SQL> COMMIT;
Commit complete.
SQL> SELECT t.id, LISTAGG(y.name, ',') WITHIN GROUP (ORDER BY ROWNUM)
2 FROM xmltest t,
3 XMLTABLE('//Element' PASSING t.x COLUMNS name VARCHAR2(1000) PATH 'name') y
4 GROUP BY t.id;
ID
----------
LISTAGG(Y.NAME,',')WITHINGROUP(ORDERBYROWNUM)
--------------------------------------------------------------------------------
1
ABC,PQR
</code></pre>
<p>There is a function in XPath 2.0, <code>string-join</code>, which will join the string values together with commas. It would seem to be just what you need, but alas it seems Oracle doesn't support it.</p>
|
How to make windows slim read writer lock fair? <p>i found out that windows implemented a slim reader-writer-lock (see <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa904937%28v=vs.85%29.aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/windows/desktop/aa904937%28v=vs.85%29.aspx</a> ). Unfortunately (for me) this rw-lock is neither fifo nor is it fair (in any sense).
Is there a possibility to make the windows rw-lock with some workaround fair or fifo?
If not, in which scenarios would you use the windows slim rw-lock?</p>
| <blockquote>
<p>this rw-lock is neither fifo nor is it fair </p>
</blockquote>
<p>I wouldn't expect anything to do with threading to be "fair" or "fifo" unless it said it was explicitly. In this case, I would expect writing locks to take priority, as it might never be able to obtain a lock if there are a lot of reading threads, but then I also wouldn't assume that's the case, and I've not read the MS documentation for a better understanding.</p>
<p>That said, it <em>sounds</em> like your issue is that you have a lot of contention on the lock, caused by write threads; because otherwise your readers would always be able to share the lock. You should probably examine why your writing thread(s) are trying to hold the lock for so long; buffering up adds for example will help mitigate this.</p>
|
Linq to entities with join <p>I'm having some problem with my linqToEntities query. The Product is missing in the query result. Is there any way to return the ProductQuantity with the Product property correctly with a linqToEntities expression?</p>
<pre><code> public class ProductQuantity
{
public string Id { get; set; }
public string SomeProperty { get; set; }
public Product Product { get; set; }
public Guid ProductId { get; set; }
}
public class Product
{
public Guid Id { get; set; }
public string SomeProperty { get; set; }
//...
}
// MyId is the ProductId I need
// The following will return all productQuantity detail but the Product property will be null
var result = myEntities.ProductQuantities.Include(x => x.Product).Where(x => x.ProductId == MyId)
// The following will work but I want to avoid refilling the object like this :
var result = myEntities.ProductQuantities.Include(x => x.Product).Where(x => x.ProductId == MyId)
.Select(y => new ProductQuantity{ SomeProperty = y.SomeProperty, Product = y.Product});
</code></pre>
<p>What is the proper way to do this with linq to entities? Why the product is not just simply returned with the query ?</p>
<p>Thanks</p>
<h1>EDIT 1</h1>
<p>Look like my problem is releated to .Include() when using more than one include. </p>
<p>Just add a Category to ProductQuantity in the preceding example : </p>
<pre><code>//This will return the product but not the category
var result = myEntities.ProductQuantities.Include(x => x.Product).Include(x=> x.Category).Single(x => x.ProductId == MyId)
//This will return the category but not the product
var result = myEntities.ProductQuantities.Include(x => x.Category).Include(x=> x.Product).Single(x => x.ProductId == MyId)
</code></pre>
<p>Why only one include can be used and only the first one is working??????? (a saw tons of similar example on the net?)</p>
<p>Any help?</p>
| <p>Seems like there is a problem when the same entity is used in any other include. (ex: Product.Unit and Product.AlternateUnit cannot be retreived at the same time if the same entity is used ie:unit) I dont really understand why but I use separate query to fetch the data that cannot be retrieved by the include.</p>
|
GET cart.js empty | shopify <p>I am developing a Shopify store using their API. But I have hit a rather large snag that seems simple, but I can't fix. </p>
<p>I have successfully viewed all products and their variants. I can also add a product/variant to the cart. It is "successful" because I am getting a status of 200 AND I can see what products are getting added with my Shopify account. Everything on that end is working. </p>
<p>When I call the cart with GET request I am able to see the cart, but it is completely empty (item_count: 0). I have tried adding different products/variants. It is always empty. </p>
<p>Am I missing something? Do I need to call the cart another way? </p>
<p>Thanks in advance!</p>
| <p>When you GET cart.js, and your item count is zero, it means you failed to place anything in the cart. When you do place items in the cart, and you validate they are actually in the cart, and you do a GET on cart.js, if that call is still empty, then you are really really unlucky and are probably just making a really dumb mistake in your GET call. </p>
|
Images Not Loading With Jekyll <p>Folder layout:</p>
<pre><code>/content
/certificates
/images
picture_name.png
file_trying_to_access_images.md
/jekyll
/_site
/img
picture_name.png
logo.png
/img
picture_name.png
logo.png
</code></pre>
<p>I am having trouble accessing the pictures within my repo on my Jekyll site. "logo.png" is found and works fine, but all the other pictures are not showing up in the "Sources" tab within Chrome's inspector. I originally had the pictures inside an image folder within the content folder, then moved them to the img folder within the jekyll folder, and finally tried within the jekyll/_site/img folder. </p>
<p>I have also built and served it with each change locally. It shows the path being changed, but never updates the actual img folder in Sources.</p>
<p>Any ideas on what I am doing wrong would be great!</p>
<p>I had the images working in the Markdown previewer I was using. The current syntax I have for my images within the jekyll/_site/img folder are:</p>
<p><code></code></p>
<p><code></code></p>
| <p>It appears that you aren't able to move images around using windows explorer. I needed to use the command line to move the images to their new folder and then I was able to access the pictures. </p>
|
Difference between CType and type specific cast (CInt, CBool, CStr)? <p>CInt will succeed with "1.2" while Integer.Parse will fail, are there some values that CType will succeed with where CInt, CDec or CStr will fail? When should CType be used? </p>
| <p>There is no difference between using CType and using CXXXX, in fact they compile to the same IL, e.g. a call to Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger for CInt or CType(,Integer), to Microsoft.VisualBasic.CompilerServices.Conversions.ToDecimal for CDec or Ctype(, Decimal). </p>
<p>CType can be used on more than the primitive types, and can be used in generics, but outside of that, there is no concrete reason to prefer one syntax over the other. They will compile down to the same IL and so produce the same results in the same amount of time.</p>
|
AdMob address verification PIN - wrong letter? <p>I've received a letter from Google today. It should contain PIN which verifies my address, so I could pay out money I've earned from ads on my Android app. Instead it is a business verification code for some company - or at least what I think it is. It says <em>Google My Business</em> on the inside and has 5-letter code as well as these 3 steps:</p>
<ol>
<li>Visit <em>google.com/verifymybusiness</em></li>
<li>Sign in to your Google account.</li>
<li>Enter your verification code and submit!</li>
</ol>
<p>I've typed once already this verification code on AdMob site, but it said it's incorrect. After 3 failed verifications the ads will be suspended, so I just want to be sure - <strong>if that could really be the Google mistake and I should just wait for "Ask for new address verification PIN" link to unlock on AdMob site?</strong> I've sent them an email as well, but I don't even know if the address was correct, because it was so hard to find and it was through some help form...</p>
| <p>Same thing happened to me. Did you contact admob-support about this. Let me know if you were able to get the correct admob pin later.</p>
<p>Edit: I too received a mail from Google Adsense with the correct pin after 2 days I received the verifymybusiness pin. Thanks for your update as well.</p>
|
How can I request the relationships of a resource without using a filter? <p>I have a backend that follows the JSON API specification.</p>
<p>In my Ember app, I do something like this:</p>
<pre><code>model() {
return this.store.query('category', { filter: { forum: 'main' } });
}
</code></pre>
<p>This works well and the request sent to the server is <code>GET /categories?filter[forum]=main</code>. My app gets all the categories from the forum with ID <code>main</code>.</p>
<p>Now, instead of the previous request, I would like to make a <code>GET /forums/main/categories</code> from the model. How can this be done in Ember with Ember Data?</p>
<p>Here's something I tried with Ember AJAX:</p>
<pre><code>ajax: Ember.inject.service(),
model() {
return Ember.RSVP.hash({
categories: this.get('ajax').request('/forums/main/categories'),
});
}
</code></pre>
<p>The request works and the correct data is returned from the server. But Ember Data just doesn't know about it and I can't use the model in my template. How can I make Ember AJAX work with Ember Data?</p>
<p>The Ember AJAX GitHub page proposes to write something like that:</p>
<pre><code>import DS from 'ember-data';
import AjaxServiceSupport from 'ember-ajax/mixins/ajax-support';
export default DS.JSONAPIAdapter.extend(AjaxServiceSupport);
</code></pre>
<p><a href="https://github.com/ember-cli/ember-ajax#usage-with-ember-data" rel="nofollow">https://github.com/ember-cli/ember-ajax#usage-with-ember-data</a></p>
<p>But it doesn't seem to change anything.</p>
| <p>Okay, <code>/forums/main/categories</code> looks a bit like a relationship link. Like <code>forum</code> is a model as well, and has a relationship categories. Is this right?</p>
<p>If yes, probably the best thing is to first fetch the <code>forum</code> and then the relationship. Maybe you already have the <code>forum</code> record? So something like this:</p>
<pre><code>store.findRecord('forum', 'main').then(forum => forum.get('categories'));
</code></pre>
<p>However if you want to filter the <code>categories</code> based on a forum string, this is also possible. So basically you want to do this:</p>
<pre><code>this.store.query('category', { filter: { forum: 'main' } });
</code></pre>
<p>But it should request <code>/forums/main/categories</code> instead of <code>/categories?filter[forum]=main</code>. This can be done with a custom adapter. Probably you just have to override <code>urlForQuery</code>:</p>
<pre><code>urlForQuery(query, modelName) {
if(query.filter.forum)
const forum = query.filter.forum;
delete query.filter.forum;
return `/forums/${forum}/categories`
} else {
return this._super(...arguments);
}
},
</code></pre>
|
Unable to run Excel VSTO Add-ins <p>Trying to run an Excel 2013 VSTO Add-ins project, and I keep on getting an error that says that: </p>
<blockquote>
<p>"System.Security.SecurityException: The solution cannot be installed because it is signed by a publisher whom you have not yet chosen to trust. If you trust the publisher, add the certificate to the Trusted Publisher list." </p>
</blockquote>
<p>The project has a key file with signature algorithm sha256RSA and certificate issued to/by the Windows User. </p>
<p>Any idea how to get around this ?</p>
| <p>Try the solutions from the postings <a href="https://social.msdn.microsoft.com/Forums/vstudio/en-US/cba58bc6-3d57-443e-9982-59d0840b15f8/trying-to-overcome-the-the-solution-cannot-be-installed-because-it-is-signed-by-a-publisher-whom?forum=vsto" rel="nofollow">here</a>.</p>
<p>As for myself, I've developed an Excel VSTO AddIn with a self-signed untrusted certificate that is delivered by a custom Setup.exe which is then installed on machines that belong to some end-users. I have no control over these machines because the end-users just download my Setup.exe from a public website. After setup the path of the .vsto is a local file path so I don't need a web server as a host.</p>
<p>In my case the following code (placed in my Setup.exe) is enough to successfully trust the Excel VSTO:</p>
<pre><code>UserInclusionList.Add(new AddInSecurityEntry(new Uri(vstoFilePath),
"<RSAKeyValue><Modulus>...</Modulus><Exponent>...</Exponent></RSAKeyValue>"));
</code></pre>
<p>The corresponding <code><RSAKeyValue></code> can be found in your .vsto file.</p>
|
Crash With DllImport C# <p>Gang,</p>
<p>I'm using a third-party API written in (what looks like) MFC C++. My application is a WinForms app in C#. The API's company has a C# demo application, and I used their code verbatim. The relevant code looks like this...</p>
<p>API's C++ Function:</p>
<pre><code>int PASCAL CppFunction(BYTE *pbAdapterID, BYTE *pbTargetID, char *pcVendor, char *pcProduct, char *pcRelease, int iMessageBox)
{
// The function definition is all I can see in the API's documentation
}
</code></pre>
<p>The DllImport Statement:</p>
<pre><code>[DllImport("api.dll")]
extern public static int CppFunction(ref byte pbAdapter, ref byte pbTargetID, string pcVendor, string pcProduct, string pcRelease, int iMessageBox);
</code></pre>
<p>My C# Logic:</p>
<pre><code>public void CallCppFunction()
{
try
{
int result = 0;
string strVendorBuffer = string.Empty;
string strProductBuffer = string.Empty;
string strReleaseBuffer = string.Empty;
string strSerial = string.Empty;
byte bAdapt = 0;
byte bTarg = 0;
result = CppFunction(ref bAdapt, ref bTarg, strVendorBuffer, strProductBuffer, strReleaseBuffer, 0);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
</code></pre>
<p>This is the code as it exists in their C# sample. When run, it crashes with a "FatalExecutionEngineError" even in a try/catch. </p>
<p><a href="https://i.stack.imgur.com/7GWfi.png" rel="nofollow"><img src="https://i.stack.imgur.com/7GWfi.png" alt="enter image description here"></a></p>
<p>I don't know PInvoke very well, but don't those variables have to be marshaled as an unmanaged type? Any help would be appreciated.</p>
| <p>I am taking a wild guess here, but I am pretty sure it will be the right answer</p>
<p>Lets take a look to the function definition:</p>
<pre><code>int PASCAL CppFunction(
BYTE *pbAdapterID,
BYTE *pbTargetID,
char *pcVendor,
char *pcProduct,
char *pcRelease,
int iMessageBox);
</code></pre>
<p>And the corresponding DllImport declaration:</p>
<pre><code>[DllImport("api.dll")]
extern public static int CppFunction(
ref byte pbAdapter,
ref byte pbTargetID,
string pcVendor,
string pcProduct,
string pcRelease,
int iMessageBox);
</code></pre>
<p>There are a lot of parameters there, some of them caught my attention:</p>
<pre><code> char *pcVendor,
char *pcProduct,
char *pcRelease,
</code></pre>
<p>They are not passed by reference, are they being modified by the library?</p>
<p>Note: That why I asked you to give details about the function.</p>
<p>I that's the case, you cannot marshal strings because the datatype string is immutable, you must use the <code>StringBuilder</code> class, just make sure the <code>StringBuilder</code>has enough <a href="https://msdn.microsoft.com/en-us/library/system.text.stringbuilder.capacity(v=vs.110).aspx" rel="nofollow">Capacity</a>.</p>
<pre><code>int result = 0;
StringBuilder strVendorBuffer = new StringBuilder(1024); // up to 1024 chars
StringBuilder strProductBuffer = new StringBuilder(1024); // up to 1024 chars
StringBuilder strReleaseBuffer = new StringBuilder(1024); // up to 1024 chars
StringBuilder strSerial = string.Empty;
byte bAdapt = 0;
byte bTarg = 0;
result = CppFunction(ref bAdapt, ref bTarg, strVendorBuffer, strProductBuffer, strReleaseBuffer, 0);
</code></pre>
|
How do I get the three line menu option in iOS? <p>I have seen the button on Android apps and I was curious if such a feature is available on iOS? I've thought about using a split view controller and then trying to trigger the detail via that button, but I am not sure how I would go about that. In short, I don't know how I would get the detail view controller to slide through the master. <a href="https://i.stack.imgur.com/k3ode.png" rel="nofollow">Click here to see what I mean</a>
Any help is greatly appreciated. Thanks!</p>
| <p>You need to add yourself, it's not native option for developer, it's called Hamburger Menu :) </p>
<p>Add your button in view with image you wished <a href="https://www.iconfinder.com/icons/134216/hamburger_lines_menu_icon#size=128" rel="nofollow">menu image</a>. That's it. If you want menu library I recommend to use <a href="https://github.com/Friend-LGA/LGSideMenuController" rel="nofollow">LGSideMenuController</a> </p>
|
Version UIAutomator test package <p>I have a UIAutomator test that interacts with the OS to automate some tasks that I can't do from ADB or another app. Sometimes I release a new version of the tests. I planned on using <code>adb shell dumpsys package my.package.test | grep versionName</code> to parse the version from the test app, and update it if necessary.</p>
<p>However, it appears that <code>dumpsys package</code> returns <code>versionName=null</code> for my UIAutomator test (built using a gradle script near-identical to the <a href="https://github.com/googlesamples/android-testing/blob/master/ui/uiautomator/BasicSample/app/build.gradle" rel="nofollow">sample</a>).</p>
<p>Right now I'm just overwriting the test every time I need it. Is there some way to embed version information in a UIAutomator test APK?</p>
| <p>There's no version information in the default manifest generated for the test APK, then you have to introduce it.</p>
<h1>1.</h1>
<p>add this to your <code>build.gradle</code>:</p>
<pre><code>defaultConfig {
manifestPlaceholders = [ versionName:versionName, versionCode:versionCode]
}
</code></pre>
<h1>2.</h1>
<p>copy your main <code>AndroidManifest.xml</code> to <code>src/androidTest</code></p>
<h1>3.</h1>
<p>edit the test manifest</p>
<pre><code><!--suppress AndroidDomInspection -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="your.package.name"
android:versionCode="${versionCode}"
android:versionName="${versionName}"
>
<application
tools:node="remove"
... >
</application>
</manifest>
</code></pre>
<h1>4.</h1>
<p>Once rebuilt, your test APK will include version information.</p>
|
Why wouldn't I use npm to install yarn? <p>In <a href="https://code.facebook.com/posts/1840075619545360" rel="nofollow">the blog post announcing yarn (an alternative npm client)</a> they say, "The easiest way to get started is to run <code>npm install -g yarn</code>". But if you go to <a href="https://yarnpkg.com/en/docs/install" rel="nofollow">the "install yarn" page in their docs</a>, "npm install yarn" isn't listed on any of the platform-specific installation pages, and it's only offered as the third of three options on the "Alternatives" page. So my question is if <code>npm install</code> is the easiest installation method, why isn't it a recommended method in their docs? Are there disadvantages to installing yarn using <code>npm</code>?</p>
| <p>Because <code>npm</code> is not platform specific and runs on almost any system it is listed as an Alternative. There is no advantage or disadvantage over the platform specific installs. The difference would be the install location but all methods expose the global <code>yarn</code> command to your CLI.</p>
<p>I would argue they listed it as "the easiest way" because most people are already very familiar with <code>npm</code>.</p>
|
Tweet button with tooltip like <p>I would like to create a tweet button similar to this one :</p>
<p><a href="https://i.stack.imgur.com/vho8T.png" rel="nofollow"><img src="https://i.stack.imgur.com/vho8T.png" alt="tweet button"></a></p>
<p>I tried this from the doc : </p>
<pre><code><a href="https://twitter.com/share" class="custom-twitter-widget">Tweet</a><script async src="http://platform.twitter.com/widgets.js" charset="utf-8"></script>
</code></pre>
<p>But it shows only the button like this :</p>
<p><a href="https://i.stack.imgur.com/1QaEZ.png" rel="nofollow"><img src="https://i.stack.imgur.com/1QaEZ.png" alt="enter image description here"></a></p>
| <p>You can't, twitter removed that future so you gotta use this <a href="http://twitcount.com/" rel="nofollow">alternative.</a> As they stated on the website.. <a href="https://i.stack.imgur.com/wq84I.png" rel="nofollow"><img src="https://i.stack.imgur.com/wq84I.png" alt="enter image description here"></a></p>
<p><a href="http://twitcount.com/" rel="nofollow">http://twitcount.com/</a></p>
|
Problems when pandas reading Excel file that has blank top row and left column <p>I tried to read an Excel file that looks like below,
<a href="https://i.stack.imgur.com/vD3Di.png" rel="nofollow"><img src="https://i.stack.imgur.com/vD3Di.png" alt="enter image description here"></a></p>
<p>I was using pandas like this</p>
<pre><code>xls = pd.ExcelFile(file_path)
assets = xls.parse(sheetname="Sheet1", header=1, index_col=1)
</code></pre>
<p>But I got error</p>
<blockquote>
<p>ValueError: Expected 4 fields in line 3, saw 5</p>
</blockquote>
<p>I also tried </p>
<pre><code>assets = xls.parse(sheetname="Sheet1", header=1, index_col=1, parse_cols="B:E")
</code></pre>
<p>But I got misparsed result as follows</p>
<p><a href="https://i.stack.imgur.com/rCP9E.png" rel="nofollow"><img src="https://i.stack.imgur.com/rCP9E.png" alt="enter image description here"></a></p>
<p>Then tried </p>
<pre><code>assets = xls.parse(sheetname="Sheet1", header=1, index_col=0, parse_cols="B:E")
</code></pre>
<p>Finally works, but why index_col=0 and parse_cols="B:E"? This makes me confused becasue based on pandas <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html" rel="nofollow">documents</a>, <code>assets = xls.parse(sheetname="Sheet1", header=1, index_col=1)</code> should just be fine. Have I missed something?</p>
| <p>The <code>read_excel</code> <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html" rel="nofollow">documentation</a> is not clear on a point.</p>
<ul>
<li><code>skiprows=1</code> to skip the first empty row at the top of the file or <code>header=1</code> also works to use the second row has column index.</li>
<li><code>parse_cols='B:E'</code> is a way to skip the first empty column at the left of the file</li>
<li><code>index_col=0</code> is optional and permits to define the first parsed column (B in this example) as the <code>DataFrame</code> index. The mistake is here since <code>index_col</code> is relative to columns selected though the <code>parse_cols</code> parameter.</li>
</ul>
<p>With your example, you can use the following code</p>
<pre><code>pd.read_excel('test.xls', sheetname='Sheet1', skiprows=1,
parse_cols='B:E', index_col=0)
# AA BB CC
# 10/13/16 1 12 -1
# 10/14/16 3 12 -2
# 10/15/16 5 12 -3
# 10/16/16 3 12 -4
# 10/17/16 5 23 -5
</code></pre>
|
C++ Lambda -- String params not working in following function calls <p>I'm having an issue where when I try to access a string that's the main param in a lambda, the compiler doesn't recognize it as so when I try to call functions using that string.</p>
<p>Here is my code:</p>
<pre><code>void removePunctuation(std::vector<std::string> &inTokens,
std::vector<std::string> &outTokens) {
std::for_each(inTokens.begin(), inTokens.end(), [outTokens](std::string s) {
std::string newS = s;
// newS.erase(std::remove_if(newS.begin(), newS.end(), ispunct));
outTokens.push_back(newS);});
}
</code></pre>
<p>And the following error is produced:</p>
<pre><code>a2.cpp:114:19: error: no matching member function for call to 'push_back'
outTokens.push_back(newS);});
</code></pre>
<p>I am also getting this sort of error in other functions, when I try to call a function that uses the lambda's string param in its call.</p>
<p>Any help is much appreciated!</p>
| <p>By default, lambda arguments are <a href="http://stackoverflow.com/q/5501959">passed as read-only</a>, try</p>
<pre><code>[&outTokens](std::string s)
</code></pre>
<p>(It is perhaps what you want anyway, if the <code>outTokens</code> parameter is expected to be modified.)</p>
|
pipe hexdump output to node js program <p>I'm working on an Intel Edison with Yoctoo 3.10, I have a barcode scanner on /dev/hidraw0 and I want to use the exact lines that are output when I run <code>hexdump /dev/hidraw0</code> as the input for a program written in node js. </p>
<p>The node js program is the following:</p>
<pre><code>var readline = require('readline');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
rl.on('line', function(line){
console.log(line);
})
</code></pre>
<p>I have tried piping it normally: </p>
<pre><code>hexdump /dev/hidraw0 | node program.js
</code></pre>
<p>But I get nothing, I think it has to do with the fact that hexdump doesn't write \n so the buffer doesn't write it's content. </p>
<p>I have also tried opening /dev/hidraw0 as a file, like this: </p>
<pre><code>var fs = require('fs');
fs.open('/dev/hidraw0', 'r', function(status, fd) {
if (status) {
console.log(status.message);
return;
}
var buffer = new Buffer(100);
fs.read(fd, buffer, 0, 100, 0, function(err, num) {
console.log(buffer.toString('hex'));
});
});
</code></pre>
<p>And using some hex dumpers like hexy but in this case I get some hex lines but not the same ones as with hexdump, which are the ones I need. </p>
<p>Just using <code>hexdump /dev/hidraw0</code> gives me the following
(when I use a card) </p>
<pre><code>0000000 0000 0020 0000 0000 0000 0000 0000 0000
0000010 0000 0020 0000 0000 0000 001f 0000 0000
0000020 0000 0027 0000 0000 0000 0026 0000 0000
0000030 0000 0025 0000 0000 0000 0000 0000 0000
0000040 0000 0025 0000 0000 0000 0024 0000 0000
0000050 0000 0021 0000 0000 0000 0025 0000 0000
0000060 0000 0028 0000 0000 0000 0000 0000 0000
</code></pre>
| <p>The following works for me:</p>
<pre><code>process.stdin.setEncoding('utf8');
process.stdin.on('readable', function () {
var chunk = process.stdin.read();
if (chunk !== null) {
console.log(chunk);
}
});
</code></pre>
<p>Running:</p>
<pre><code>sudo hexdump /dev/hidraw0 | node this-script.js
</code></pre>
<p>Sample output (when I move a wireless mouse):</p>
<pre><code>0000000 0120 0002 fd00 ffcf 0000 0000 0000 2000
0000010 0201 0000 cffc 00ff 0000 0000 0000 0120
...
</code></pre>
|
Item in loop is undefined <p>I have an issue that I don't understand, and if anyone can help, I would appreciate it.</p>
<p>I am using Ionic2 with Meteor/MongoDb.</p>
<p>I have a cursor:</p>
<pre><code>private messages: Mongo.Cursor<Message>;
</code></pre>
<p>On the server I do an insert:</p>
<pre><code>Messages.insert({
chatId: chatId,
senderId: senderId,
content: content,
readByReceiver: false,
createdAt: new Date()
});
</code></pre>
<p>It triggers an observable as expected:</p>
<pre><code> this.messages.observe({
added: (message) => this.addMessageToLocal(message)
});
private addMessageToLocal(newMessage: Message): void {
// here I print the message, and it is as expected
}
</code></pre>
<p>Also, I do a <code>forEach</code> through the <code>messages</code>, and they are all populated as expected.</p>
<p><strong>Issue</strong></p>
<p>My problem is in the <code>html</code>. I loop trough the <code>messages</code> cursor. It displays each item as expected. Until I add a <code>message</code> (as above). Then the new <code>message</code> from the <code>html</code> is <code>undefined</code>.</p>
<pre><code><template ngFor let-message [ngForOf]="messages">
<div *ngIf="!exists(message)" class="message-wrapper">
<div *ngIf="message.changeDate">
<center><span class="message-datetime">{{message.createdAt | amDateFormat: 'DD MMM YYYY'}}</span></center>
</div>
<div [class]="'message message-' + message.ownership">
<div class="message-content">server:{{message.content}}</div>
<span class="time-tick">
<span *ngIf="message" class="message-timestamp">{{message.createdAt | amDateFormat: 'h:mm a'}}</span>
<div *ngIf="message && message.readByReceiver && senderId == message.senderId">
<span class="checkmark">
<div class="checkmark_stem"></div>
<div class="checkmark_kick"></div>
</span>
</div>
</span>
</div>
</div>
</template>
</code></pre>
<p>The final <code>message</code> item in the loop (the new one added), is <code>undefined</code>. i.e. In the <code>*ngIf="!exists(message)"</code> function called from the <code>html</code>, I print the <code>message</code>, and its's <code>undefined</code>.</p>
<p>So in the <code>html</code> I loop over the <code>messages</code> Cursor, and the new one is <code>undefined</code>. However, if even in the same function (<code>exists()</code>), I loop over the <code>messages</code> Cursor again, just to test it, none of the items are <code>undefined</code>.</p>
<p><strong>Question</strong></p>
<p>Please can anyone suggest what I can do to <strong>not</strong> have the last <code>item</code> in the <code>Cursor</code> as <code>undefined</code>?</p>
<p>Thanks</p>
<p><strong>UPDATE</strong></p>
<p>I am getting something I don't understand.</p>
<p>When I call a function from the <code>html</code> as follows, <code>message</code> is not <code>undefined</code>:</p>
<p><code>{{ formatMessage(message) }}</code></p>
<p>But if I call a function as follows, it is <code>undefined</code>:</p>
<p><code>*ngIf="!exists(message)"</code></p>
| <p>I solved this by using:</p>
<pre><code>changeDetection: ChangeDetectionStrategy.OnPush,
</code></pre>
<p>But I still think there may be a bug in Angular</p>
|
How can I write an EXISTS predicate on a collection attribute in Criteria API? <p>I have these classes:</p>
<pre><code>@Entity
public class Customer {
@Id long id;
String name;
@OneToMany List<Customer> related;
}
</code></pre>
<p>and I'm using this JPQL query:</p>
<pre><code>select c from Customer c where c.name = 'ACME'
or exists( select 1 from c.related r where r.name = 'ACME' )
</code></pre>
<p>How can I write the same query with the Criteria API? I need to use <code>exists</code> with a subquery, like the JPQL, but I don't know how to create a subquery from a collection attribute in the Criteria API.</p>
| <p>Something like this would give <code>EXISTS (subquery)</code></p>
<pre><code>Subquery<Long> sq = cq.subquery(Long.class);
Root<Customer> customerSub = sq.correlate(customer);
Join<Customer,Customer> related = customerSub.join(Customer_.related);
... extra config of subquery
Predicate existsCustomer = cb.exists(sq);
</code></pre>
<p>where <code>cq</code> is the <code>CriteriaQuery</code>, and <code>cb</code> is <code>CriteriaBuilder</code>. This comes from an example in the JPA 2.1 spec p323 Example 4</p>
|
Suppress records from one table that are also in another table <p>List1 is my main table and List2 is a secondary table. Is there a way to display people from List1 that are <em>not</em> on List2? Or suppress if they <em>are</em> on List2?</p>
<p>The common field is <code>personID</code>.</p>
<pre><code>List1:
name;id
Ed Newb;1
John Law;2
Mike Jordan;3
List2:
name;id
Ed Newb; 1
Mike Jordan; 3
Other Guy; 4
</code></pre>
<p>I am seeking a query that will remove data on list2 from list1:</p>
<pre><code>Report:
List1.name;List1.id
John Law; 2
</code></pre>
| <p>Looks like you can filter them out in SQL:</p>
<pre><code>SELECT
l1.id,
l1.name
FROM
list1 l1
LEFT OUTER JOIN list2 l2 ON l1.id = l2.id
WHERE
l2.id IS NULL
</code></pre>
|
Is there a function in python to get the size of an arbitrary precision number? <p>I'm working on a cryptographic scheme in python, so I use arbitrary precision numbers (<code>long</code>) all the time. I'm using python 2.7.</p>
<p>My problem is that I need to get the most significant two bytes (16 bits) of a number and check if they are the padding I inserted. I've tried <code>sys.getsizeof()</code> but that gives the size of the entire object and guess I could also iterate through every few bits of the number until there are only two bytes left, but is there a more pythonian way of doing this?</p>
<p>Thanks in advance.</p>
| <p>This should do it for you:</p>
<pre><code>>>> n = 1 << 1000
>>> n.bit_length()
1001
>>> n >> (n.bit_length() - 16)
32768L
</code></pre>
|
Create dynamic PDF starting from jrxml template in JasperReports <p>I'm trying to generate a PDF with JasperReports starting from a <em>.jrxml</em> template.<br>
The problem is that I'd like to have a sort of dynamic behaviour among the sections of PDF, that are basically subreports. More specifically I need some sections to disappear completely when null (I'm not even sure how to check if a subreport is null) and the other subreports to fill that void moving <strong>only upward</strong>. </p>
<p>Let me give you an example:<br>
1) Situation where everything is filled<br>
<img src="https://i.stack.imgur.com/V9OaI.png" alt="All blocks populated"></p>
<p>2) Now the green block is not shown because it's null, and all the blocks below move upward to fill the void left by that section<br>
<img src="https://i.stack.imgur.com/HuczS.png" alt="enter image description here"></p>
<p>I don't think I can accomplish this with DynamicJasper am I right?</p>
<p>I really need to start from a <em>.jrxml</em> template created and/or customized by other people.</p>
| <p>It is possible with <code>JasperReports</code>. What i recommend is using <code>iReport</code> tool (or some other <code>JasperReport</code> visualizing tool).</p>
<p>Just like each report, a subreport has a <code>dataSource</code>. When it is <code>null/empty</code>, the subreport should not render. In <code>iReport</code>, utilize the scripting language available (usually <code>Groovy</code>) and do conditional rendering of the <code>Detail</code> band that is hosting your subreport.</p>
<p>Hope this give you enough pointers to start.</p>
|
Visual Studio NuGet / Extension Installs Fail with "The process cannot access the file because it is being used by another process" <p>Installing extensions or NuGet packages to Visual Studio fail with the error 'The process cannot access the file because it is being used by another process'.</p>
<p><a href="http://www.paraesthesia.com/archive/2013/07/30/upgrading-nuget-the-process-cannot-access-the-file-because-it.aspx/" rel="nofollow">This link</a> provides a workaround but it's a pain to have to do it each time an Extension / NuGet package needs updating when I'd just like to use the in built functionality if possible.</p>
<p>Does anyone know of a fix for this?</p>
| <p>We found that this was an issue with our corporate McAfee anti-virus software.</p>
<p><a href="https://kc.mcafee.com/corporate/index?page=content&id=KB85636" rel="nofollow">This link</a> from McAfee took us part of the way, however, we had to add three process names to the exclusion list to allow the updates to execute without error.</p>
<ol>
<li><p>Open RegEdit and navigate to:</p>
<p><code>HKLM\System\CurrentControlSet\Services\mfeEEFF</code></p></li>
<li><p>Create a key 'ExemptedProcesses'.</p></li>
<li>Under the HKLM\System\CurrentControlSet\Services\mfeEEFF\ExemptedProcesses multiple String Values can be created.</li>
<li><p>Create the following String Values (listed as <em>Name / Type / Data</em>):</p>
<p>'1' / 'REG_SZ' / 'devenv.exe'</p>
<p>'2' / 'REG_SZ' / 'MSIEXE.exe'</p>
<p>'3' / 'REG_SZ' / 'VSIXInstaller.exe'</p></li>
<li><p>Reboot the machine. </p></li>
</ol>
|
Listing later dates in comparison to another entry in SQL <p>How would I list the students who started later than start year of student with id = 8871?</p>
<p>This is what I have so far:</p>
<pre><code>SELECT sid s1
FROM Student
WHERE s1.started <= sid = '8871';
</code></pre>
<p>I went to this link for some reference but I'm still having issues:
<a href="http://stackoverflow.com/questions/19924236/query-comparing-dates-in-sql">Query comparing dates in SQL</a></p>
<p>Student Table has:
Student (Lastname, Firstname, SID, Started)</p>
<p>any help would be great</p>
| <p>I'd use a <a class='doc-link' href="http://stackoverflow.com/documentation/sql/261/join/940/self-join#t=2016101316295637364">self join</a> where one side of the join contains the students you want and the the reference student 8871:</p>
<pre><code>SELECT a.*
FROM student a
JOIN student b ON b.sid = '8871' AND a.started > b.started
</code></pre>
|
Django: configuring email sending <p>I am in new Django framework. I want to send an e-mail. This is my <code>setting.py</code> file and I want to know what should I put at <code>EMAIL_HOST</code>, <code>EMAIL_HOST_USER</code>, <code>EMAIL_HOST_PASSWORD</code> fields. Could you explain what is this?</p>
<pre><code>ALLOWED_HOSTS = []
EMAIL_HOST = ''
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_PORT = 587
EMAIL_USE_TLS = True
</code></pre>
| <p>Everything depend what email service you want to use. Example for GMAIL you can find here <a href="http://stackoverflow.com/questions/19264907/python-django-gmail-smtp-setup">Python Django Gmail SMTP setup</a></p>
|
CodeIgniter Auto Loading form_validation causes Error with Model files <p>I am using CodeIgniters form_validation library to validate a form in my app. Library loaded here:</p>
<pre><code>$autoload['libraries'] = array('database','form_validation');
</code></pre>
<p>Ever since including the library I cannot load any models in the app. I get the following error in my browser. The form is a registration form for users to sign up to the site. The form gets validated perfectly.</p>
<pre><code> A PHP Error was encountered
Severity: Notice
Message: Undefined property: register_model::$load
Filename: libraries/Form_validation.php
Line Number: 147
</code></pre>
<p>Here is my function that tries to load the model:</p>
<pre><code> public function validateRegForm(){
$this->load->model('register_model');
$this->load->helper('url');
$this->load->helper('form');
$this->form_validation->set_rules('firstname', 'First Name', 'required');
$this->form_validation->set_rules('lastname', 'Last Name', 'required');
$this->form_validation->set_rules('address', 'Address', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('phone', 'Phone', 'required');
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_rules('confirm-password', 'Confirm Password', 'required|matches[password]');
if ($this->form_validation->run() == FALSE){
$data['title'] = 'Sign Up';
$this->load->view('template/header', $data);
$this->load->view('template/navigation');
$this->load->view('register_view');
$this->load->view('template/footer');
} else {
$data = array(
'firstName' => $this->input->post('firstname'),
'lastName' => $this->input->post('lastname'),
'address' => $this->input->post('address'),
'email' => $this->input->post('email'),
'phone' => $this->input->post('phone'),
'username' => $this->input->post('username'),
'password'=> $this->input->post('password')
);
$this->register_model->insertUsers($data);
}
}
</code></pre>
<p>Register model file:</p>
<pre><code> <?php
class register_model extends CI_Controller {
//Insert a new user to users table when registration form submits
function insertUser(){
$query = $this->db->query();
}
}
?>
</code></pre>
<p>Any help is appreciated :)</p>
| <p>Remove form validation library from autoload, and load it inside of controller.</p>
<p>
<pre><code> public function __CONSTRUCT(){
parent::_CONSTRUCT();
$this->load->model('register_model');
$this->load->helper('url');
$this->load->helper('form');
$this->load->library('form_validation'); // load it from controller like this
}
$this->form_validation->set_rules('firstname', 'First Name', 'required');
$this->form_validation->set_rules('lastname', 'Last Name', 'required');
$this->form_validation->set_rules('address', 'Address', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('phone', 'Phone', 'required');
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_rules('confirm-password', 'Confirm Password', 'required|matches[password]');
if ($this->form_validation->run() == FALSE){
$data['title'] = 'Sign Up';
$this->load->view('template/header', $data);
$this->load->view('template/navigation');
$this->load->view('register_view');
$this->load->view('template/footer');
} else {
$data = array(
'firstName' => $this->input->post('firstname'),
'lastName' => $this->input->post('lastname'),
'address' => $this->input->post('address'),
'email' => $this->input->post('email'),
'phone' => $this->input->post('phone'),
'username' => $this->input->post('username'),
'password'=> $this->input->post('password')
);
$this->register_model->insertUsers($data);
}
}
</code></pre>
|
Boost.Asio async_handshake cannot be canceled <p>When initiating an <code>async_handshake</code> with a Boost Asio SSL stream, and then implementing a deadline timer to cancel/close the stream before the handshake completes, the program will crash with a buffer overflow exception (on Windows, I haven't tried Linux yet). The crash is somewhere after the socket is <code>close</code>d, and external handlers finish executing, but before the <code>run()</code> command completes.</p>
<p>Is there a reason why the socket cannot be closed when an SSL handshake is in progress? Or is this a bug in Boost Asio?</p>
<pre><code>class Connection
{
void connect_handler(const boost::system::error_code &err)
{
...
ssock->async_handshake(boost::asio::ssl::stream_base::client,
boost::bind(&Connection::handle_handshake, this, _1));
...
}
void handle_handshake(const boost::system::error_code &err)
{
// CONNECTED SECURELY
}
void handle_timeout()
{
// HANDLE SSL SHUTDOWN IF ALREADY CONNECTED...
...
ssock->shutdown(boost::asio::ip::tcp::socket::shutdown_both);
ssock->close();
delete ssock;
}
...
boost::asio::ssl::stream<boost::asio::ip::tcp::socket> *ssock;
};
</code></pre>
<p>To clarify, calling <code>handle_timeout()</code> before <code>handle_handshake()</code> is called by the IO service will crash in the <code>io_service::run()</code> method.</p>
| <p>The problem is the socket object is being destroyed before the asynchronous handlers complete. To cancel the pending/queued handlers, use <code>io_service::stop()</code> like this:</p>
<pre><code>io_service.stop(); // Stop the IO service to prevent handlers from executing
ssock->shutdown(boost::asio::ip::tcp::socket::shutdown_both);
ssock->close();
delete ssock;
</code></pre>
<p>So no, it is not a bug in Boost.Asio itself.</p>
|
Cant find 'google-play-services_lib' anywhere <p>Right now I'm trying to get Fyber working in my Unity game on Android.</p>
<p>and have run into issues at <a href="http://developer.fyber.com/content/current/unity/integration/building-your-app/#android" rel="nofollow">the following step..</a></p>
<p>"Keep in mind that adding the line above to your manifest will require you to add Google Play Services lib to your project. You copy the google-play-services_lib project from your android sdk path (usually under Android/sdk/extras/google/google_play_services/libproject/google-play-services_lib) to your Unity project under Plugins\Android"</p>
<p>I dont even know if Im looking for a file or a folder but I cant find any file or folder named
"google-play-services_lib" in my Android sdk or in the <a href="https://dl-ssl.google.com/android/repository/google_play_services_8487000_r29.ziphttp://" rel="nofollow">last distributed lib project from google repository</a> they also recommend downloading if your having issues.</p>
<p>Heres the full error I'm getting when I try to build at the moment</p>
<pre><code> CommandInvokationFailure: Failed to re-package resources.
C:\Users\Blar\AppData\Local\Android\sdk\build-tools\24.0.3\aapt.exe package --auto-add-overlay -v -f -m -J gen -M AndroidManifest.xml -S "res" -I "C:/Users/Blar/AppData/Local/Android/sdk\platforms\android-24\android.jar" -F bin/resources.ap_
stderr[
AndroidManifest.xml:17: error: Error: No resource found that matches the given name (at 'value' with value '@integer/google_play_services_version').
]
stdout[
Configurations:
(default)
v14
v21
xhdpi-v4
Files:
drawable\app_banner.png
Src: (xhdpi-v4) res\drawable-xhdpi\app_banner.png
drawable\app_icon.png
Src: () res\drawable\app_icon.png
values\strings.xml
Src: () res\values\strings.xml
values\styles.xml
Src: () res\values\styles.xml
Src: (v14) res\values-v14\styles.xml
Src: (v21) res\values-v21\styles.xml
AndroidManifest.xml
Src: () AndroidManifest.xml
Resource Dirs:
Type drawable
drawable\app_banner.png
Src: (xhdpi-v4) res\drawable-xhdpi\app_banner.png
drawable\app_icon.png
Src: () res\drawable\app_icon.png
Type values
values\strings.xml
Src: () res\values\strings.xml
values\styles.xml
Src: () res\values\styles.xml
Src: (v14) res\values-v14\styles.xml
Src: (v21) res\values-v21\styles.xml
Including resources from package: C:\Users\Blar\AppData\Local\Android\sdk\platforms\android-24\android.jar
applyFileOverlay for drawable
applyFileOverlay for layout
applyFileOverlay for anim
applyFileOverlay for animator
applyFileOverlay for interpolator
applyFileOverlay for transition
applyFileOverlay for xml
applyFileOverlay for raw
applyFileOverlay for color
applyFileOverlay for menu
applyFileOverlay for mipmap
Processing image: res\drawable\app_icon.png
Processing image: res\drawable-xhdpi\app_banner.png
(processed image res\drawable\app_icon.png: 90% size of source)
(processed image res\drawable-xhdpi\app_banner.png: 93% size of source)
(new resource id app_banner from xhdpi-v4\drawable\app_banner.png #generated)
(new resource id app_icon from drawable\app_icon.png #generated)
]
UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.Android.PostProcessor.Tasks.TasksCommon.Exec (System.String command, System.String args, System.String workingdir, System.String errorMsg, Int32 retiresOnFailure)
</code></pre>
| <p>I found a folder called 'google-play-services_lib' in the last distributed lib project from google repository you also recommend downloading, and copied it into Plugins\Android.</p>
<p>But it did not fix my issue. I am still getting the same error when I try to build</p>
|
Python SQLite removes/escapes part of regular expression pattern in user defined function <p>I did a simple replace implementation for regular expressions in python sqlite3:</p>
<pre><code>import sqlite3, re
db = sqlite3.connect(':memory:')
c = db.cursor()
c.executescript("""
create table t2 (n REAL, v TEXT, t TEXT);
insert into t2 VALUES (6, "F", "ef");
insert into t2 VALUES (1, "A", "aa");
insert into t2 VALUES (2, "B", "be");
insert into t2 VALUES (4, "D", "de");
insert into t2 VALUES (5, "E", "ee");
insert into t2 VALUES (3, "C", "ze");
""");
db.commit()
def preg_replace(string, pattern, replace):
return re.sub(pattern, replace, string)
db.create_function('replace',1,preg_replace)
c = db.cursor()
# This does not do anything
c.execute("UPDATE t2 SET t=replace(t,?,?)",('e$','ee'))
db.commit()
c = db.cursor()
c.execute("select * from t2")
print c.fetchall()
// This makes 'be' to 'bee'
print preg_replace("be","e$","ee")
</code></pre>
<p>My problem is now that my UPDATE command does not replace 'e' at the end of the table entries.<br>
If I use just 'e' as a pattern it works fine ('be' ends up as 'bee').<br>
If I manually change 'be' in the table to 'be$', it gets modiefied to 'bee'.</p>
<p>However, I can replace the 'e' at the end of the string if I use the preg_replace function directly.</p>
<p>I do not understand why. is there some string escaping going on when the input for my user defined function goes to sqlite? Thanks a lot in advance.</p>
<p>PS: Running Python 2.7.3</p>
| <p>You must tell <a href="https://docs.python.org/2/library/sqlite3.html#sqlite3.Connection.create_function" rel="nofollow">create_function()</a> how many parameters the function has.</p>
<p>Your <code>preg_replace</code> will be used if the SQL calls <code>replace()</code> with one parameter.</p>
|
Clip-path using svg html element is not working <p>I'm trying to clip an image using a svg but it is not working.</p>
<p>Follows the code:</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>img {
clip-path: url(#svgPath);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<clipPath id="svgPath">
<rect x="286.5" y="95" stroke="#000000" stroke-miterlimit="10" width="274" height="274"></rect>
<rect x="286.5" y="391" stroke="#000000" stroke-miterlimit="10" width="274" height="274"></rect>
<rect x="582.5" y="95" stroke="#000000" stroke-miterlimit="10" width="274" height="274"></rect>
<rect x="582.5" y="391" stroke="#000000" stroke-miterlimit="10" width="274" height="274"></rect>
</clipPath>
</defs>
</svg>
<img src="https://s3-us-west-1.amazonaws.com/powr/defaults/image-slider2.jpg" /></code></pre>
</div>
</div>
</p>
<p>Thank you very much</p>
| <p>You need to use the <code>-webkit-</code> vendor prefix as chrome, opera and safari consider <code>clip-path</code> to be an experimental feature.</p>
<p>More on <code>clip-path</code> browser support can be found on <a href="http://caniuse.com/#feat=css-clip-path" rel="nofollow">caniuse.com</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-css lang-css prettyprint-override"><code>body {
margin: 0;
}
img {
-webkit-clip-path: url(#svgPath);
clip-path: url(#svgPath);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="https://s3-us-west-1.amazonaws.com/powr/defaults/image-slider2.jpg" />
<svg xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<clipPath id="svgPath">
<rect x="286.5" y="95" stroke="#000000" stroke-miterlimit="10" width="274" height="274" fill="#ffffff"></rect>
<rect x="286.5" y="391" stroke="#000000" stroke-miterlimit="10" width="274" height="274"></rect>
<rect x="582.5" y="95" stroke="#000000" stroke-miterlimit="10" width="274" height="274"></rect>
<rect x="582.5" y="391" stroke="#000000" stroke-miterlimit="10" width="274" height="274"></rect>
</clipPath>
</defs>
</svg></code></pre>
</div>
</div>
</p>
|
Android Downgrade Issue <p>I am using Unity to build and create my app. I already have my app in the Play store with this version number:</p>
<p><strong>4220 (4.2.2)</strong></p>
<p>I also have the application installed on my android device.</p>
<p>Now, I have created a new version of my app and added this into my manifest file:</p>
<pre><code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="xxx.xxxxxxxx.xxxxxxx"
android:installLocation="preferExternal"
android:versionCode="5000"
android:versionName="5.0.0">
</code></pre>
<p>(x's is off course my app ID) </p>
<p>Now, when building from Unity I get this error:</p>
<p><strong>Failure [INSTALL_FAILED_VERSION_DOWNGRADE]</strong></p>
<p>Now, I have searched the net for solutions to this, and can't see what I am doing wrong here?!?!? </p>
<p>Please help, and any help is appreciated :-)</p>
| <p>Unity overwrites the values of your custom <strong>AndroidManifest.xml</strong> with the several configurations in the <strong>Player Settings</strong>. </p>
<p>So check your values under Edit > Project Settings > Player > Android > Other Settings > Identification > <strong>Version</strong> and <strong>Bundle Version Code</strong>.</p>
<p>You can inspect the merged AndroidManifest.xml of the APK with a tool like <a href="https://github.com/google/android-classyshark" rel="nofollow">ClassyShark</a></p>
|
Writing a function that take the sum of all numbers in and between two inputs <p>Help! I'm trying to write a function that take the sum of all numbers in and between two inputs. </p>
<p>So far I have, </p>
<pre><code>(define (sum-between x y)
(cond
[(= x y) x]
[((- x y) 0) 0]
[else (+ (+ x y) (sum-between (sub1 x) (sub1 y)))]))
</code></pre>
<p>This should return:</p>
<pre><code>(check-expect (sum-between 0 2) 3)
(check-expect (sum-between -1 1) 0)
(check-expect (sum-between 7 7) 7)
(check-expect (sum-between 1 10) 55)
</code></pre>
<p>I'm not sure how to call the recursive case so it doesn't run in an infinite loop. Any suggestions? Thanks!</p>
| <p>How about using built-in procedures? this is easier:</p>
<pre><code>(define (sum-between x y)
(apply + (range x (add1 y))))
</code></pre>
<p>But I guess you want to implement this from scratch. The main idea here is that one of the values must get closer and closer to the other, your error is that you're decrementing <em>both</em> of them. Try this instead:</p>
<pre><code>(define (sum-between x y)
(cond
[(= x y) x]
[else (+ x (sum-between (add1 x) y))]))
</code></pre>
|
JavaScript Array to MVC Controller <p>I have a simple JavaScript array that I am trying to pass to a controller</p>
<pre><code>function SubmitData()
{
var operationCollection = new Array();
var test1 = { name: "Bill", age: "55", address: "testing" };
operationCollection.push(test1);
var test2 = { name: "Ben", age: "55", address: "testing" };
operationCollection.push(test2);
var test3 = { name: "Flo", age: "55", address: "testing" };
operationCollection.push(test3);
var dataToPost = JSON.stringify(operationCollection);
$.ajax({
type: "POST",
url: "Home/AddPerson",
datatype: JSON,
data: { methodParam: dataToPost },
traditional: true
});
}
</code></pre>
<p>The C# controller has a class</p>
<pre><code>public class newEntry
{
public string name { get; set; }
public string age { get; set; }
public string address { get; set; }
}
</code></pre>
<p>and the method</p>
<pre><code>public void AddPerson(List<newEntry> methodParam)
{
foreach (newEntry item in methodParam)
{
string name = item.age + item.address;
}
}
</code></pre>
<p>When I run the code in debug, the value passed to the controller method is always NULL or 0. I can't seem to get the array to pass correctly. I have read on previous posts that <code>traditional: true</code> will fix this... it doesn't for me though. Has anyone any ideas?</p>
| <p>Try adding this to the signature of your method:</p>
<pre><code>[HttpPost]
public void AddPerson(List<newEntry> methodParam)
</code></pre>
<p>Also as Gavin stated use <code>data: dataToPost</code></p>
|
Is Not A Function Trouble Logging In With Passport <p>Hey I'm new to express and am trying to login as a user. With the following code, I get the error below. I thought since I did module.exports.comparePassword it would work. Is there something I'm missing? Thanks for any help</p>
<blockquote>
<p>events.js:160
throw er; // Unhandled 'error' event
^</p>
<p>TypeError: user.comparePassword is not a function
at /Users/Sam/Desktop/teach/routes/users.js:112:17
at Query. (/Users/Sam/Desktop/teach/node_modules/mongoose/lib/model.js:3343:16)
at /Users/Sam/Desktop/teach/node_modules/kareem/index.js:259:21
at /Users/Sam/Desktop/teach/node_modules/kareem/index.js:127:16
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)</p>
</blockquote>
<p><strong>models/user.js</strong></p>
<pre><code>var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcryptjs')
var userSchema = new Schema({
email: { type: String },
password: { type: String },
type: { type: String }
});
var User = mongoose.model('User', userSchema);
module.exports = User;
//Get a User by id
module.exports.getUserById = function(id, callback){
User.findById(id, callback);
}
//Get a User by email
module.exports.getUserByEmail = function(email, callback){
var query = {email : email}
User.findOne(query, callback);
}
//Save a student
module.exports.saveStudent = function(newUser, newStudent, callback){
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(newUser.password, salt, function(err, hash){
if (err) {throw err}
newUser.password = hash;
//Saves both a user and student
async.parallel([newUser.save, newStudent.save], callback);
})
})
}
//Save a instructor
module.exports.saveInstructor = function(newUser, newInstructor, callback){
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(newUser.password, salt, function(err, hash){
if (err) {throw err}
newUser.password = hash;
//Saves both a user and instructor
async.parallel([newUser.save, newInstructor.save], callback);
})
})
}
//Checks if password matches.
module.exports.comparePassword = function(candidatePassword, hash, callback){
bcrypt.compare(candidatePassword, hash, function(err, isMatch){
if(err) throw err;
callback(null, isMatch);
});
}
</code></pre>
<p><strong>routes/users.js</strong></p>
<pre><code>var express = require('express');
var router = express.Router();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/user');
var Student = require('../models/student');
var Instructor= require('../models/instructor');
router.get('/signup', function(req, res, next) {
res.render('users/signup');
});
router.get('/login', function(req, res, next){
res.render('users/login')
});
//Registering a user
router.post('/signup', function(req, res, next){
var first_name = req.body.first_name;
var last_name = req.body.last_name;
var email = req.body.email;
var password = req.body.password;
var password2 = req.body.password2;
var type = req.body.type;
req.checkBody('first_name', 'First name is required.').notEmpty();
req.checkBody('first_name', 'Please enter a shorter first name.').len(1, 40);
req.checkBody('last_name', 'Last name is required.').notEmpty();
req.checkBody('last_name', 'Please enter a shorter last name.').len(1, 40);
req.checkBody('email', 'Email is required.').notEmpty();
req.checkBody('email', 'Email must be valid.').isEmail();
req.checkBody('email', 'Please enter a shorter email.').len(1, 40);
req.checkBody('password', 'Password is required.').notEmpty();
req.checkBody('password2', 'Passwords must match.').equals(req.body.password);
req.checkBody('password', 'Please choose a password between 6 to 50 characters.').len(6, 50);
var errors = req.validationErrors();
if(errors){
res.render('users/signup', {
errors: errors,
first_name: first_name,
last_name: last_name,
email: email,
password: password,
password2: password2
});
} else {
var newUser = new User({
email: email,
password: password,
type: type
});
var newStudent = new Student({
first_name: first_name,
last_name: last_name,
email: email,
});
var newInstructor = new Instructor({
first_name: first_name,
last_name: last_name,
email: email,
});
if(type == 'student'){
User.saveStudent(newUser, newStudent, function(err, user){
console.log('Student saved');
});
} else {
User.saveInstructor(newUser, newInstructor, function(err, user){
console.log('Instructor saved');
});
}
res.redirect('/classes');
}
});
passport.serializeUser(function(user, done){
done(null, user._id);
});
passport.deserializeUser(function(id, done){
User.getUserByEmail(function(err, user){
done(err, user);
});
});
//Login in a user
router.post('/login',passport.authenticate('local', {
failureRedirect:'/users/login',
failureFlash:'Wrong Username or Password'
}), function(req, res){
var usertype = req.user.type;
res.redirect('/classes');
});
passport.use(new LocalStrategy({
usernameField: 'email'
},
function(email, password, done) {
User.getUserByEmail(email, function(err, user){
if (err) return done(err);
if(!user){
return done(null, false, { message: 'Unregistered email'});
}
if (!user.comparePassword(password)) {
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, user);
});
}
));
module.exports = router;
</code></pre>
| <p>Clearly, it will give an undefined function error since comparePassword is not a function defined for User Schema. You can use it as User.comparePassword since it has the function (in the JS file), but the user (object of the user schema - mongo) has no such function defined. </p>
<p>Do this before you export the User,</p>
<pre><code>userSchema.methods.comparePassword = function(candidatePassword, hash, callback){
bcrypt.compare(candidatePassword, hash, function(err, isMatch){
if(err) throw err;
callback(null, isMatch);
});
};
</code></pre>
<p>Hope it helps.</p>
|
Issues with RecyclerView only updating random cardview text size <p>Im trying to implement a dynamic text size option within my app. For some reason the recycler is only randomly changing text size within my cardviews instead of setting all the text to the desired size. As I scroll the list, the top cardview text will change correctly but the next 3-4 will stay default and randomly down the list another cardview text will display correctly. when i scroll back up the list, the cardview that displays correctly will change at random.</p>
<p>Main Activity....</p>
<pre><code>// Dark Mode Menu
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mDrawer.openDrawer(GravityCompat.START);
return true;
case R.id.menu_night_mode_day:
setNightMode(AppCompatDelegate.MODE_NIGHT_NO);
break;
case R.id.menu_night_mode_night:
setNightMode(AppCompatDelegate.MODE_NIGHT_YES);
break;
case R.id.menu_night_mode_auto:
setNightMode(AppCompatDelegate.MODE_NIGHT_AUTO);
break;
// Text Size Options
case R.id.menu_text_size_small:
setTextSize(18);
break;
case R.id.menu_text_size_medium:
setTextSize(20);
break;
case R.id.menu_text_size_large:
setTextSize(22);
break;
}
return super.onOptionsItemSelected(item);
}
// Dark Mode Menu
private void setNightMode(@AppCompatDelegate.NightMode int nightMode) {
AppCompatDelegate.setDefaultNightMode(nightMode);
if (Build.VERSION.SDK_INT >= 11) {
recreate();
}
}
// Dynamic text size
private void setTextSize(int textSize) {
TextView description = (TextView) findViewById(R.id.cardview_description);
description.setTextSize(textSize);
saveToPreferences(this, "THE_TEXT_SIZE", "" + textSize);
}
</code></pre>
<p>My Adapter.... </p>
<pre><code>public class MyPageAdapter extends Adapter<MyPageHolder> {
public List<MenuPageItems> datas;
private Activity activity;
public String dynamicTextSize;
public MyPageAdapter(Activity activity){
datas = new ArrayList<>();
this.activity = activity;
}
public void add(MenuPageItems dataModel){
datas.add(dataModel);
}
public void add(MenuPageItems dataModel, int position){
datas.add(position, dataModel);
}
public void addAll(List<MenuPageItems> menuPageItems){
datas.addAll(menuPageItems);
}
@Override
public MyPageHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(viewType, parent, false);
return createViewHolder(v, viewType);
}
@Override
public void onBindViewHolder(MyPageHolder holder, int position) {
holder.bind(datas.get(position), activity, position);
dynamicTextSize = "20";
}
@Override
public int getItemCount() {
return datas.size();
}
@Override
public int getItemViewType(int position){
return datas.get(position).getViewResId();
}
public int searchViewTypePosition(int viewType){
int i = 0;
boolean found = false;
while(i < datas.size() && !found){
if(datas.get(i).getViewResId() == viewType){
found = true;
i--;
}
i++;
}
return i;
}
public MyPageHolder createViewHolder(View v, int viewType){
return datas.get(searchViewTypePosition(viewType)).createViewHolder(v, activity, this);
}
}
</code></pre>
<p>Holder....</p>
<pre><code>public abstract class MyPageHolder extends RecyclerView.ViewHolder{
protected final Activity activity;
protected MyPageAdapter adapter;
public TextView txtTitle, txtDescription, txtTheContent;
public ImageView imgImage;
public View view;
public MyPageHolder(View v, Activity activity, MyPageAdapter adapter) {
super(v);
this.activity = activity;
this.adapter = adapter;
imgImage = (ImageView) v.findViewById(R.id.cardview_image);
txtTitle = (TextView) v.findViewById(R.id.cardview_title);
txtDescription = (TextView) v.findViewById(R.id.cardview_description);
view = (CardView) v.findViewById(R.id.card_view);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/*/ this is where the magic happens when clicked /*/
}
});
}
public void bind(MenuPageItems dataModel, Activity activity, final int position) {
final MenuPageItems m = (MenuPageItems)dataModel;
imgImage.setImageResource(m.image);
txtTitle.setText(m.title);
txtDescription.setText(m.description);
//txtTheContent.setText(m.theContent);
view.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v){
Intent cvIntent = new Intent(view.getContext(), EndpageActivity.class);
// header image to pass to endpage activity
cvIntent.putExtra("endpageHeader", m.image);
// text to pass to endpage activity
cvIntent.putExtra("endpageTitle", m.title);
cvIntent.putExtra("endpageTheContent", m.theContent);
view.getContext().startActivity(cvIntent);
}
});
}
}
</code></pre>
<p>Do I need to add something to my adapter or viewholder to update all the text properly?</p>
| <p>I think I get it, but I don't see where you are setting the text size at all, you said it changes in some cards randomly.</p>
<p>As I see it, what needs to be done is to set the size in the Holder's bind method. This gets executed every time the card needs to be redrawn. You can read the shared preferences inside the bind(), but that is terribly inefficient since the holder's bind method will be called many times over when scrolling. You wan to avoid any excess work inside the Holders bind()</p>
<p>Add a dynamicTextSize member variable to the adapter and set the value with either:</p>
<ol>
<li>Add a <code>setText/getText</code> size to the adapter and the activity can set this when needed.</li>
<li>Retrieve the text size inside the adapter's constructor and then override the <code>notifyDataSetChanged()</code> method and pull the value again each time that is called. Then call <code>super.notifyDataSetChanged()</code></li>
</ol>
<p>Example:</p>
<pre><code>@Override
public void notifyDataSetChanged() {
this.dynamicTextSize = // Pull value from shared preferences
super.notifiyDataSetChanged();
}
</code></pre>
<p>What I also don't see is the dynamicTextSize value being passed into the holder. Since the holder has a reference to the adapter, you can add a getTextSize() method to the adapter, then the holder can call into the adapter to get it.</p>
<pre><code>public MyPageHolder(View v, Activity activity, MyPageAdapter adapter) {
...
this.dynamicTextSize = adapter.getTextSize()
}
</code></pre>
<p>Finally, in the setTextSize() method you'll need to call the adapter.notifyDataSetChanged() to update the adapter.</p>
<p><strong>Update 10/17</strong></p>
<p>I've attempted to add some detail to by previous post.</p>
<p><strong>Main Activity</strong></p>
<pre><code>// Dynamic text size
private void setTextSize(int textSize) {
// Add a call to set the text to the adapter's member variable:
mAdapter.setTextSize(textSize);
// I'm not sure what description is here... I don't see what type the member is
description.setTextSize(textSize);
saveToPreferences(this, "THE_TEXT_SIZE", "" + textSize);
}
</code></pre>
<p>In your adapter, add a method to set and get the text size. The set will be called by the main activity, when the text size changes, and the get is called by the holder each time it needs to set the size of the TextView. </p>
<pre><code>public class MyPageAdapter extends Adapter<MyPageHolder> {
...
public String dynamicTextSize;
public void setTextSize(int textSize) {
dynamicTextSize = textSize;
}
// This will be called by the holder
public int getTextSize() {
return dynamicTextSize;
}
...
}
</code></pre>
<p>In your holder:</p>
<pre><code>public abstract class MyPageHolder extends RecyclerView.ViewHolder{
public void bind(MenuPageItems dataModel, Activity activity, final int position) {
...
// Call into the adapter to get the text size.
int textSize = adapter.getTextSize();
txtDescription.setTextSize(textSize);
}
}
</code></pre>
<p><strong>Update 10/19</strong></p>
<p>I was able to get it to work with just a small change. </p>
<ol>
<li>Add a getDynamicTextSize in your MainActivity</li>
<li><p>Add a call to the get from within the MyPageAdapter constructor.</p>
<pre><code>public MyPageAdapter(Activity activity){
datas = new ArrayList<>();
this.activity = activity;
dynamicTextSize = ((MainActivity)activity).getDynamicTextSize();
}
</code></pre></li>
</ol>
<p>While this does work, there is are few things it will not do for you.</p>
<ol>
<li><p>Ties your fragments to always being a child of the MainActivity activity, you can get around this with an interface, but still not pretty.</p></li>
<li><p>Will not update the current activity as soon as the user chooses the new text size. Since the mainActivity takes the menu event, you will need to inform whatever Fragment(s) is/are active, that the text setting has changed and then call notifiyDataSetChanged on the adapter.</p></li>
<li><p>Does not set the size of the text outside of the custom <code>RecyclerView</code>. I see you have a few fragments that do not use you recycler view. These will not take the setting. The setting in the menu would make you think all the text in the app should change.</p></li>
</ol>
<p>The accepted reply in <a href="http://stackoverflow.com/questions/4877153/android-application-wide-font-size-preference">this post</a> seems to be a good way to adjust the text size for the entire app. Some changes in your app almost show that you've seen it.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.