qid
int64 1
74.7M
| question
stringlengths 0
70k
| date
stringlengths 10
10
| metadata
list | response
stringlengths 0
115k
|
---|---|---|---|---|
61,077,570 |
I have a github account with say a username 'abc'. If I create a repository in it and clone it on my system as
`git clone https://github.com/abc/demo.git` it gets cloned.
If I login into my another github account with username say 'xyz' and create a repository in it and if I try to clone the repository on my same system as
`git clone https://github.com/xyz/demo.git` it gives fatal error such as
```
Cloning into 'demo'...
remote: Repository not found.
fatal: repository 'https://github.com/instructor-git/demo.git/' not found
```
I am new to git and not able to diagnose the problem what wrong I am doing. Please help.
|
2020/04/07
|
[
"https://Stackoverflow.com/questions/61077570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3588025/"
] |
`/xyz/` in the url is not enough to tell which user is cloning. you need to be explicit about it: `xyz@`:
```
$ git clone https://[email protected]/xyz/demo.git
```
|
6,276,346 |
I want to print the array index for some purpose. Can anybody tell me about this ?
|
2011/06/08
|
[
"https://Stackoverflow.com/questions/6276346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/762267/"
] |
Get the first index of an elemnt:
```
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
echo $key;
```
For all elemnts
```
foreach($array as $key => $value){
echo "{$key} => {$value}\n";
}
```
will output
```
0 => blue
1 => red
2 => green
3 => red
```
All keys:
```
echo implode(', ',array_keys($array));
```
will output
```
0, 1, 2, 3
```
|
23,411,896 |
I would like to put an arrow image (png) centered under my active item menu instead of having my actual blue border-line. I tried to modified my css with no luck, the image doesn't appear. do you know what I doing wrong ?
**My CSS** :
```
#cssmenu ul {
margin: 0;
padding: 0;
font-size: 12pt;
font-weight: bold;
background: #94adc1;
font-family: Arial, Helvetica, sans-serif;
border-bottom: 1px solid #f2f1f2;
zoom: 1;
text-align:center;
}
#cssmenu ul:before {
content: '';
display: block;
}
#cssmenu ul:after {
content: '';
display: table;
clear: both;
}
#cssmenu li {
float: left;
margin: 0 auto;
padding: 0 4px;
list-style: none;
}
#cssmenu li a {
display: block;
float: left;
color: #123b59;
text-decoration: none;
font-weight: bold;
padding: 10px 20px 7px 20px;
border-bottom: 3px solid transparent;
}
#cssmenu li a:hover {
content: url("images/arrowmenunav.png");
/*color: #6c8cb5;
border-bottom: 3px solid #00b8fd;*/
}
#cssmenu li.active a {
/*display: inline;
border-bottom: 3px solid #00b8fd;
float: left;
margin: 0;*/
content: url("images/arrowmenunav.png");
}
#cssmenu {
width: 100%;
position: fixed;
height:94px;
}
```
**My menu in HTML** :
```
<div id="cssmenu">
<ul id="list">
<li><a href="#home" >home</a></li>
<li><a href="#home2">home2</a></li>
<li><a href="#newsletter">newsletter</a></li>
</ul>
</div>
```
|
2014/05/01
|
[
"https://Stackoverflow.com/questions/23411896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/979974/"
] |
The first thing I can see is this line
```
#cssmenu li.active a {
content: url("images/arrowmenunav.png");
}
```
Should be this:
```
#cssmenu li.active a:after {
content: url("images/arrowmenunav.png");
}
```
**I've setup this jsfiddle to show it in a bit more detail** <http://jsfiddle.net/e3WEs/2/>
In this I've used a 20px by 20px placeholder image. The negative margin should be half of your image width (10px in this case) to centre align it to the parent element.
**Here is a version that will work in older browsers too (IE7 and below)**
<http://jsfiddle.net/e3WEs/3/>
|
38,613,452 |
I need to pass both FormData and JSON object in an ajax call, but I get a 400 Bad Request error.
```
[artifact:mvn] org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Unexpected character ('-' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value
[artifact:mvn] at [Source: java.io.PushbackInputStream@3c0d58f6; line: 1, column: 3]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('-' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value
[artifact:mvn] at [Source: java.io.PushbackInputStream@3c0d58f6; line: 1, column: 3]
```
JS:
```
var formData = new FormData(form[0]);
//form JSON object
var jsonData = JSON.stringify(jcArray);
$.ajax({
type: "POST",
url: postDataUrl,
data: { formData:formData,jsonData:jsonData },
processData: false,
contentType: false,
async: false,
cache: false,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
success: function(data, textStatus, jqXHR) {
}
});
```
Controller:
```
@RequestMapping(value="/processSaveItem",method = RequestMethod.POST")
public @ResponseBody Map<String,String> processSaveItem(
@RequestBody XYZClass result[])
}
```
There is similar question, [jquery sending form data and a json object in an ajax call](https://stackoverflow.com/q/5938544/1793718) and I'm trying the same way.
How can I send both FormData and JSON object in a single ajax request?
|
2016/07/27
|
[
"https://Stackoverflow.com/questions/38613452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1793718/"
] |
Java 6 usage is precisely what causes the issue. It seems that one of the required libraries supports Java 7/8 at minimum - there's no workaround, you might have to migrate to a newer Java version.
|
8,756 |
I am having problems in accessing the address of a new contract generated within another contract acting as Factory.
My code:
```
contract Object {
string name;
function Object(String _name) {
name = _name
}
}
contract ObjectFactory {
function createObject(string name) returns (address objectAddress) {
return address(new Object(name));
}
}
```
when I compile and execute the method `createObject('')`, I expect to be returned the address of the new contract.
Instead, I receive the hash of the transaction.
I use Web3 to execute the function:
```
var address = web3.eth.contract(objectFactoryAbi)
.at(contractFactoryAddress)
.createObject("object", { gas: price, from: accountAddress });
```
I tried also to modify the function to store the address in an array, returning the length of the array, and then retrieve it at a later time, with the same results: always the transaction hash is returned.
Any light on this is welcome.
|
2016/09/20
|
[
"https://ethereum.stackexchange.com/questions/8756",
"https://ethereum.stackexchange.com",
"https://ethereum.stackexchange.com/users/4366/"
] |
Super high-level answer: all nodes, on the road from the changed node to the root, change.
|
34,484,845 |
I have a spinning gear on my website displayed with this code:
```html
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"/>
<i class = "fa fa-cog fa-5x fa-spin"></i>
```
Personally, I think that the speed of the gear is too fast. Can I modify it with CSS?
|
2015/12/27
|
[
"https://Stackoverflow.com/questions/34484845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5661019/"
] |
Short answer
------------
Yes, you can. Replace the `.fa-spin` class on the icon with a new class using your own animation rule:
```css
.slow-spin {
-webkit-animation: fa-spin 6s infinite linear;
animation: fa-spin 6s infinite linear;
}
```
```html
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"/>
<i class = "fa fa-cog fa-5x slow-spin"></i>
```
Longer answer
-------------
If you look at the [`Font Awesome CSS file`](https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.css), you'll see this rule for spinning animation:
```
.fa-spin {
-webkit-animation: fa-spin 2s infinite linear;
animation: fa-spin 2s infinite linear;
}
```
The rule for the `.fa-spin` class refers to the `fa-spin` keyframes:
```
@keyframes fa-spin {
0% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
```
You can use the same keyframes in a different class. For example, you can write the following rule for a class called `.slow-spin`:
```
.slow-spin {
-webkit-animation: fa-spin 6s infinite linear;
animation: fa-spin 6s infinite linear;
}
```
Now you can rotate HTML elements at the speed of your choosing. Instead of applying the class `.fa-spin` to an element, apply the `.slow-spin` class:
```
<i class = "fa fa-cog fa-5x slow-spin"></i>
```
|
31,048 |
How to set the column width in the align environment.
I've got a align environment to demonstrate how to do division by hand so the columns always contain only one number, but the columns are much wider than this.
Following an example only showing the ugly result because of to wide columns:
```
\begin{align}
&1&2&3&4&4\\
& & & &2&4\\
\end{align}
```
|
2011/10/09
|
[
"https://tex.stackexchange.com/questions/31048",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/7875/"
] |
```
\documentclass[leqno]{report}
\usepackage{amsmath}
\begin{document}
\begin{flalign}
1 + 1 &= 2 &\\
1 &= 2 - 1
\end{flalign}
\end{document}
```

|
63,945,343 |
1. This is a extract from a table that i want to clean.
[](https://i.stack.imgur.com/wOogb.png)
2. What i've tried to do:
`df_sb['SB'] = df_sb['SB'].str.replace('-R*', '', df_sb['SB'].shape[0])`
3. I expected this (Without -Rxx):
[](https://i.stack.imgur.com/kGZdz.png)
4. But i've got this (Only dash[-] and character "R" where replaced):
[](https://i.stack.imgur.com/A9TU9.png)
Could you please help me get the desired result from item 4?
|
2020/09/17
|
[
"https://Stackoverflow.com/questions/63945343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11277192/"
] |
An example using `str.partition()`:
```
s = ['A330-22-3123-R-01','A330-22-3123-R-02']
for e in s:
print(e.partition('-R')[0])
```
OUTPUT:
```
A330-22-3123
A330-22-3123
```
EDIT:
Not tested, but in your case:
```
df_sb['SB'] = df_sb['SB'].str.partition('-R')[0]
```
|
554,408 |
I have an application that has been getting strange errors when canceling out of a dialog box. The application can't continue if the box is cancelled out of, so it exits, but it is not working for some reason, and thus it keeps running and crashes.
I debugged this problem, and somehow the application runs right past the Application.Exit call. I'm running in Debug mode, and this is relevant because of a small amount of code that depends on the RELEASE variable being defined. Here is my app exit code. I have traced the code and it entered the ExitApp method, and keeps on going, returning control to the caller and eventually crashing.
This is an application which provides reports over a remote desktop connection, so that's why the exit code is a bit weird. Its trying to terminate the remote session, but only when running under release because I don't want to shut down my dev machine for every test run.
```
private void ExitApp()
{
HardTerminalExit();
Application.Exit();
}
// When in Debug mode running on a development computer, this will not run to avoid shutting down the dev computer
// When in release mode the Remote Connection or other computer this is run on will be shut down.
[Conditional("RELEASE")]
private void HardTerminalExit()
{
WTSLogoffSession(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, false);
}
```
I've run a debugger right past the Application.Exit line and nothing happens, then control returns to the caller after I step past that line.
What's going on? This is a Windows Forms application.
|
2009/02/16
|
[
"https://Stackoverflow.com/questions/554408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26140/"
] |
This is an article which expands on the same train of thought you are going through: <http://www.dev102.com/2008/06/24/how-do-you-exit-your-net-application/>
Basically:
>
> * Environment.Exit - From MSDN: Terminates this process and gives the
> underlying operating system the
> specified exit code. This is the code
> to call when you are using console
> application.
> * Application.Exit - From MSDN: Informs all message pumps that they
> must terminate, and then closes all
> application windows after the messages
> have been processed. This is the code
> to use if you are have called
> Application.Run (WinForms
> applications), this method stops all
> running message loops on all threads
> and closes all windows of the
> application. There are some more
> issues about this method, read about
> it in the MSDN page.
>
>
>
Another discussion of this: [Link](https://web.archive.org/web/20201029173358/http://geekswithblogs.net/mtreadwell/archive/2004/06/06/6123.aspx)
This article points out a good tip:
You can determine if System.Windows.Forms.Application.Run has been called by checking the System.Windows.Forms.Application.MessageLoop property. If true, then Run has been called and you can assume that a WinForms application is executing as follows.
```
if (System.Windows.Forms.Application.MessageLoop)
{
// Use this since we are a WinForms app
System.Windows.Forms.Application.Exit();
}
else
{
// Use this since we are a console app
System.Environment.Exit(1);
}
```
|
57,637,466 |
Please note: this kind of question has been asked on SO, but I believe mine is different, since the solution alone of using partial `struct X*` types doesn't solve this. I have read the other answers and have found no solution, so please bear with me.
I have the following circular-dependency problem (resulting in a compile error) which I'm unable to solve.
`value.h` relies on `chunk.h`, which relies on `value_array.h`, which relies on `value.h`.
Originally - `chunk.h` used to rely directly on `value.h` as well. I have managed to eliminate that dependency by having `addConstant` take a `struct Value*` instead of `Value`.
But I still haven't figured out how I can remove the dependency between `value_array.h` and `value.h`. The problem is that functions in `value_array.c` need to know the `sizeof(Value)`, and so their signature can't take the partial type `struct Value*`.
Suggestions would be welcome.
The slightly simplified code:
**value.h**
```
#ifndef plane_value_h
#define plane_value_h
#include "chunk.h"
typedef enum {
VALUE_NUMBER,
VALUE_BOOLEAN,
VALUE_CHUNK
} ValueType;
typedef struct Value {
ValueType type;
union {
double number;
bool boolean;
Chunk chunk;
} as;
} Value;
#endif
```
**chunk.h**
```
#ifndef plane_chunk_h
#define plane_chunk_h
#include "value_array.h"
typedef struct {
uint8_t* code;
ValueArray constants;
int capacity;
int count;
} Chunk;
void initChunk(Chunk* chunk);
void writeChunk(Chunk* chunk, uint8_t byte);
void setChunk(Chunk* chunk, int position, uint8_t byte);
void freeChunk(Chunk* chunk);
int addConstant(Chunk* chunk, struct Value* constant);
#endif
```
**value\_array.h**
```
#ifndef plane_value_array_h
#define plane_value_array_h
#include "value.h"
typedef struct {
int count;
int capacity;
Value* values;
} ValueArray;
void value_array_init(ValueArray* array);
void value_array_write(ValueArray* array, Value value);
void value_array_free(ValueArray* array);
#endif
```
**value\_array.c**
```
#include "value_array.h"
void value_array_init(ValueArray* array) {
array->values = NULL;
array->count = 0;
array->capacity = 0;
}
void value_array_write(ValueArray* array, Value value) {
if (array->count == array->capacity) {
int oldCapacity = array->capacity;
array->capacity = GROW_CAPACITY(oldCapacity);
array->values = reallocate(array->values, sizeof(Value) * oldCapacity, sizeof(Value) * array->capacity, "Dynamic array buffer");
}
array->values[array->count++] = value;
}
void value_array_free(ValueArray* array) {
deallocate(array->values, array->capacity * sizeof(Value), "Dynamic array buffer");
value_array_init(array);
}
```
|
2019/08/24
|
[
"https://Stackoverflow.com/questions/57637466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3284878/"
] |
Have you tried passing a filtered array to the ForEach. Something like this:
```swift
ForEach(userData.bookList.filter { return !$0.own }) { book in
NavigationLink(destination: BookDetail(book: book)) { BookRow(book: book) }
}
```
**Update**
----------
As it turns out, it is indeed an ugly, ugly bug:
Instead of filtering the array, I just remove the ForEach all together when the switch is flipped, and replace it by a simple `Text("Nothing")` view. The result is the same, it takes 30 secs to do so!
```swift
struct SwiftUIView: View {
@EnvironmentObject var userData: UserData
@State private var show = false
var body: some View {
NavigationView {
List {
Toggle(isOn: $userData.showWantsOnly) {
Text("Show wants")
}
if self.userData.showWantsOnly {
Text("Nothing")
} else {
ForEach(userData.bookList) { book in
NavigationLink(destination: BookDetail(book: book)) {
BookRow(book: book)
}
}
}
}
}.navigationBarTitle(Text("Books"))
}
}
```
**Workaround**
--------------
I did find a workaround that works fast, but it requires some code refactoring. The "magic" happens by encapsulation. The workaround forces SwiftUI to discard the List completely, instead of removing one row at a time. It does so by using two separate lists in two separate encapsualted views: `Filtered` and `NotFiltered`. Below is a full demo with 3000 rows.
```swift
import SwiftUI
class UserData: ObservableObject {
@Published var showWantsOnly = false
@Published var bookList: [Book] = []
init() {
for _ in 0..<3001 {
bookList.append(Book())
}
}
}
struct SwiftUIView: View {
@EnvironmentObject var userData: UserData
@State private var show = false
var body: some View {
NavigationView {
VStack {
Toggle(isOn: $userData.showWantsOnly) {
Text("Show wants")
}
if userData.showWantsOnly {
Filtered()
} else {
NotFiltered()
}
}
}.navigationBarTitle(Text("Books"))
}
}
struct Filtered: View {
@EnvironmentObject var userData: UserData
var body: some View {
List(userData.bookList.filter { $0.own }) { book in
NavigationLink(destination: BookDetail(book: book)) {
BookRow(book: book)
}
}
}
}
struct NotFiltered: View {
@EnvironmentObject var userData: UserData
var body: some View {
List(userData.bookList) { book in
NavigationLink(destination: BookDetail(book: book)) {
BookRow(book: book)
}
}
}
}
struct Book: Identifiable {
let id = UUID()
let own = Bool.random()
}
struct BookRow: View {
let book: Book
var body: some View {
Text("\(String(book.own)) \(book.id)")
}
}
struct BookDetail: View {
let book: Book
var body: some View {
Text("Detail for \(book.id)")
}
}
```
|
58,206,306 |
Suppose I have a local file called "contacts.json" . I want to insert it in react component and create a table . I'll be so glad if anybody can help me .Thanks .
```
{
"contacts": [
{
"id": 1,
"firstName": "hamid",
"lastName": "mohamadi",
"contactType": "Friend",
"birthDate": "2010.10.10",
"phoneNumber": [
"09011019011",
"09120658719"
],
"email": [
"[email protected]",
"[email protected]"
]
}
```
}
|
2019/10/02
|
[
"https://Stackoverflow.com/questions/58206306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11749690/"
] |
When you use the `disabled` property, Material-UI places the `Mui-disabled` class on many different elements. To get the equivalent look, you need to add it to all the same elements.
Below is an example of how to do this. In addition to adding the `Mui-disabled` class, it is also necessary to override the ["focused" styling](https://github.com/mui-org/material-ui/blob/v4.5.0/packages/material-ui/src/Input/Input.js#L30) of the underline (handled via the `:after` pseudo-class).
```
import React from "react";
import ReactDOM from "react-dom";
import TextField from "@material-ui/core/TextField";
import { makeStyles } from "@material-ui/core/styles";
const disabledClassNameProps = { className: "Mui-disabled" };
const useStyles = makeStyles(theme => {
const light = theme.palette.type === "light";
const bottomLineColor = light
? "rgba(0, 0, 0, 0.42)"
: "rgba(255, 255, 255, 0.7)";
return {
underline: {
"&.Mui-disabled:after": {
borderBottom: `1px dotted ${bottomLineColor}`,
transform: "scaleX(0)"
}
}
};
});
function App() {
const classes = useStyles();
return (
<div className="App">
<TextField
{...disabledClassNameProps}
inputProps={{ readOnly: true }}
InputProps={{ ...disabledClassNameProps, classes }}
InputLabelProps={disabledClassNameProps}
FormHelperTextProps={disabledClassNameProps}
label="Test Disabled Look"
defaultValue="Some Text"
helperText="Helper Text"
/>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
```
[](https://codesandbox.io/s/textfield-readonly-looking-disabled-gsktd?fontsize=14)
Related answers:
* [Altering multiple component roots for MUI Textfield](https://stackoverflow.com/questions/57917743/altering-multiple-component-roots-for-mui-textfield/57926379#57926379)
* [How can I remove the underline of TextField from Material-UI?](https://stackoverflow.com/questions/57914368/how-can-i-remove-the-underline-of-textfield-from-material-ui/57915357#57915357)
* [How do I custom style the underline of Material-UI without using theme?](https://stackoverflow.com/questions/56023814/how-do-i-custom-style-the-underline-of-material-ui-without-using-theme/56026253#56026253)
|
20,810,210 |
Consider the following class:
```
public class MyClass
{
private MyObject obj;
public MyClass()
{
obj = new MyObject();
}
public void methodCalledByOtherThreads()
{
obj.doStuff();
}
}
```
Since obj was created on one thread and accessed from another, could obj be null when methodCalledByOtherThread is called? If so, would declaring obj as volatile be the best way to fix this issue? Would declaring obj as final make any difference?
Edit:
For clarity, I think my main question is:
Can other threads see that obj has been initialized by some main thread or could obj be stale (null)?
|
2013/12/28
|
[
"https://Stackoverflow.com/questions/20810210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2605245/"
] |
For the `methodCalledByOtherThreads` to be called by another thread and cause problems, that thread would have to get a reference to a `MyClass` object whose `obj` field is not initialized, ie. where the constructor has not yet returned.
This would be possible if you leaked the `this` reference from the constructor. For example
```
public MyClass()
{
SomeClass.leak(this);
obj = new MyObject();
}
```
If the `SomeClass.leak()` method starts a separate thread that calls `methodCalledByOtherThreads()` on the `this` reference, then you would have problems, but this is true regardless of the `volatile`.
Since you don't have what I'm describing above, your code is fine.
|
29,317 |
I have two network interfaces (one wired & one wireless). I have two internet accounts too (each 256 kBps; one from a modem that I use as wired connection & the other from a wireless network).
Is it possible to connect to both networks and merge them and get twice the speed (512 kBps)?
How?
I'm using Ubuntu 10.04 (Lucid Lynx).
Thanks
|
2012/01/17
|
[
"https://unix.stackexchange.com/questions/29317",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/11920/"
] |
This is definitely feasible. Many of us were running mixed, load-balanced broadband configs for corporate years ago and they worked really well. Many probably still do!
You can do it in a number of ways, including using `iptables` rules and/or `iproute2` (`ip(8)` command) to setup policy routing.
The load balancing is not done at the packet level, but at the *connection* level. That is, all packets of a connection go out of one interface. Which interface this is depends on the routing policy. Without the co-operation of your the first routers just beyond your own infrastructure, this is the only way you can do it. Remote computers have no way to tell that your two IP addresses actually belong to the same computer. In TCP, a connection is uniquely identified by a 4-tuple (Remote-IP, Remote-Port, Local-IP, Local-Port). If you send packets from different IPs, the remote server thinks they belong to two different connections and gets hopelessly confused.
Obviously, this sort of thing makes more sense in a corporate environment, or one with lots of users sharing a single connection. At work, we were combining a 256 kbps ADSL line with a 512 kbps cable line (yes, back then) and the whole thing worked remarkably well, with the added benefit of high availability.
For some actual practical help, [here's one way of doing it with `iproute2`](http://www.debian-administration.org/articles/377). It's meant for Debian, but it works on Ubuntu too, of course.
|
50,717,476 |
Fiddle: <http://sqlfiddle.com/#!18/5d05a/3>
I have tables:
```
CREATE TABLE Table1(
Date Date,
Figure int
);
INSERT INTO Table1 (Date, Figure)
VALUES ('06-06-18','25'),
('05-12-18','30'),
('05-27-17','30');
```
I am using this query to return the previous months data
```
DECLARE @PrevMonth int = MONTH(getdate()) -1,
@Year int = YEAR(getdate())
SELECT @Year AS [Year], @PrevMonth AS [Month], Figure
FROM Table1
WHERE MONTH([Date]) = @PrevMonth
AND YEAR([Date]) = @Year
```
Which returns:
```
| Year | Month | Figure |
|------|-------|--------|
| 2018 | 5 | 30 |
```
However, this wont work once i hit Jan of a new year. In Jan of that new year i would be looking for December of the previous year. Can anyone advise me on a better method to use which would cover Jan in a new year. Thanks
|
2018/06/06
|
[
"https://Stackoverflow.com/questions/50717476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8412784/"
] |
Querying the month and year parts of a query is a great way to slow it down. You're far better off with the date manipulation on the input parameter (in this case `GETDATE()`) not the column:
```
SELECT *
FROM Table1
WHERE [Date] >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1,0)
AND [date] < DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()),0);
```
|
14,320,215 |
I was wondering if there is a way to create a black transparent overlay to basically cover the entire contents of the webpage?
```
<body>
<div class="main-container">
<!--many more divs here to create webpage-->
</div>
</body>
```
|
2013/01/14
|
[
"https://Stackoverflow.com/questions/14320215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1316524/"
] |
use this css on a div to create a black transparent overlay:
```
#overlay {
width: 100%;
height: 100%;
background: rgba(0,0,0,0.6);
position: fixed;
top:0;
left: 0;
}
```
|
2,349,006 |
$A$ be $3\times3$ matrix with $\operatorname{trace}(A)=3$ and $\det(A)=2$. If $1$ is an eigenvalue of $A$ find eigenvalues for matrix $A^2-2I$?
In this question I got eigenvalues of $A=1,1+i,1-i$ . I was thinking to change $\lambda$ to $\lambda^2-2$ in characteristic equation of $A$ to get eigenvalues of required matrix. I m getting characteristic equation $x^6-9x^4+28x^2-30=0$. Let $x=\lambda$. Can anyone tell me why I m wrong? I m not getting results.
|
2017/07/06
|
[
"https://math.stackexchange.com/questions/2349006",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/453977/"
] |
If $p(x)$ is a polynomial, the eigenvalues of $p(A)$ are the numbers $p(\lambda)$ for each eigenvalue $\lambda$ of $A$. What you are doing is instead taking the polynomial $f(p(x))$ where $f(x)$ is the characteristic polynomial of $A$, which is a totally different operation. The roots of $f(p(x))$ are numbers $a$ such that $p(a)$ is an eigenvalue of $A$, not numbers of the form $p(\lambda)$ such that $\lambda$ is an eigenvalue of $A$.
|
38,014,675 |
I'm trying to modify a minecraft mod (gravisuite) that puts "Gravitation Engine OFF/ON" whenever I press F, however I want to change this string, I started with replacing "Gravitation Engine OFF" with "Gravitation Engine Turned OFF" by using a hex editor but the file was no longer valid afterwards :/ I tried to use tools like jbe and cjbe and rej and that string is in the constant pool but it will only let me delete it...
Is there any way to change a string in a compiled java class without destroying it?
Thanks
|
2016/06/24
|
[
"https://Stackoverflow.com/questions/38014675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4931748/"
] |
I compiled the same class twice with a minor tweak, firstly with "foo" and then with "foo-bar"
```
public class HelloWorld {
public static final String HELLO = "foo-bar";
}
```
With "foo"
```
000000b0 74 01 00 **03** 66 6f 6f 00 21 00 02 00 03 00 00 00 |t...foo.!.......|
000000c0 01 00 19 00 04 00 05 00 01 00 06 00 00 00 02 00 |................|
000000d0 07 00 01 00 01 00 08 00 09 00 01 00 0a 00 00 00 |................|
000000e0 1d 00 01 00 01 00 00 00 05 2a b7 00 01 b1 00 00 |.........*......|
000000f0 00 01 00 0b 00 00 00 06 00 01 00 00 00 01 00 01 |................|
00000100 00 0c 00 00 00 02 00 0d |........|
```
With "foo-bar"
```
000000b0 74 01 00 **07** 66 6f 6f 2d 62 61 72 00 21 00 02 00 |t...foo-bar.!...|
000000c0 03 00 00 00 01 00 19 00 04 00 05 00 01 00 06 00 |................|
000000d0 00 00 02 00 07 00 01 00 01 00 08 00 09 00 01 00 |................|
000000e0 0a 00 00 00 1d 00 01 00 01 00 00 00 05 2a b7 00 |.............*..|
000000f0 01 b1 00 00 00 01 00 0b 00 00 00 06 00 01 00 00 |................|
00000100 00 01 00 01 00 0c 00 00 00 02 00 0d |............|
```
It seems that the length is also encoded in the structure. Note the 3 and the 7... There is [more information on this structure](https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html)
And with a String of 300 characters the preceding two bytes were 01 2c.
So given "Gravitation Engine Turned OFF" is 29 characters long, I'd make sure you change the byte immediately before the string to 1D, it should currently be 19 (25 characters for "Gravitation Engine OFF/ON")
|
644,043 |
I was sifting through some stuff I got from a friend whose uncle was a professor of electrical engineering and found a few of these 2.54 mm pitch prototyping cables (commonly known as 'Dupont' cables) which are female-to-female but have a removable male pin.
I've looked for variations of the cable name with the word 'removable' but have had no luck. I can find plenty of male-to-male cables but I believe all those male pins are part of the crimped connector and not removable, but I may be wrong.
I can probably get regular female-to-female cables and get the pins separately as well.
How can I find and purchase either the female-to-female cables with the detachable pins, or the detachable pins alone?
[](https://i.stack.imgur.com/l4Rct.jpg)
[](https://i.stack.imgur.com/22Z0I.jpg)
|
2022/11/26
|
[
"https://electronics.stackexchange.com/questions/644043",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/10065/"
] |
I believe this is a female single-pin connector along with a single 25 mil square pin, probably taken out of a pin header like this one:
[](https://i.stack.imgur.com/RDACD.png)
([image source](https://www.digikey.com/en/products/detail/harwin-inc/M20-9990345/3728227), just a random part on digikey)
They don't come out easily, but with pliers and a bit of force you can pull the individual pins out.
As an aside, I'm not sure why people call these Dupont connectors. As far as I can determine, Dupont never actually made them. The largest manufacturer of them today is probably either Amphenol, TE Connectivity, or maybe Molex.
|
38,714,238 |
As a part of learning process, I am roaming around angular js routing concepts. For this, I created one inner folder inside app with two sample test html pages ..
When i run the app it should load first page from that folder but it does not not happening .. I am not sure where i have done wrong in this code...
I am getting error like this **'angular.js:4640Uncaught Error: [$injector:modulerr]'**
Below is my controller code
```
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'Pages/main.html',
controller: 'mainController'
})
.when('/second', {
templateUrl: 'Pages/second.html',
controller: 'secondController'
})
});
myApp.controller('mainController', ['$scope','$log', function($scope,$log) {
}]);
myApp.controller('secondController', ['$scope','$log', function($scope,$log) {
}]);
```
and html code goes here
```
<!DOCTYPE html>
<html lang="en-us" ng-app="myApp">
<head>
<title>Learn and Understand AngularJS</title>
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta charset="UTF-8">
<!-- load bootstrap and fontawesome via CDN -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<style>
html, body, input, select, textarea
{
font-size: 1.05em;
}
</style>
<!-- load angular via CDN -->
<script src="https://code.angularjs.org/1.5.8/angular.min.js"></script>
<script src="https://code.angularjs.org/1.5.8/angular-route.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<header>
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/">AngularJS</a>
</div>
<ul class="nav navbar-nav navbar-right">
<li><a href="#"><i class="fa fa-home"></i>Home</a></li>
<li><a href="#/second"><i></i>second</a></li>
</ul>
</div>
</nav>
</header>
<div class="container">
<div ng-view></div>
</div>
</body>
</html>
```
and for main.html
```
<h1>this is main page</h1>
```
and for second.html
```
<h1>this is second page</h1>
```
Would any one please help on this query,
many thanks in advance..
|
2016/08/02
|
[
"https://Stackoverflow.com/questions/38714238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/899271/"
] |
`BrowserDomAdapter` is not supposed to be used. It's for Angular internal use only.
I assume you want to query elements passed as children because you use `ngAfterContentInit`:
```ts
@Component({
...
template: `
...
<div #wrapper>
<ng-content></ng-content>
</div>
...
`
})
export class MyComponent {
@ViewChild('wrapper') wrapper:ElementRef;
ngAfterContentInit(){
this.lightboxImages();
}
lightboxImages(){
let images = this.wrapper.nativeElement.querySelector('img','.post-body');
console.log(images);
}
}
```
|
1,435,766 |
Here is a particular scenario that I have been unclear about (in terms of scope) for a long time.
consider the code
```
#include <stdio.h>
typedef struct _t_t{
int x;
int y;
} t_t;
typedef struct _s_t{
int a;
int b;
t_t t;
}s_t;
void test(s_t & s){
t_t x = {502, 100};
s.t = x;
}
int main(){
s_t s;
test(s);
printf("value is %d, %d\n", s.t.x, s.t.y);
return 0;
}
```
the output is
```
value is 502, 100
```
What is a bit confusing to me is the following. The declaration
```
t_t x
```
is declared in the scope of the function test. So from what I have read about C programming, it should be garbage out of this scope. Yet it returns a correct result. Is it because the "=" on the line
s.t = x;
copies the values of x into s.t?
edit---
after some experimentation
```
#include <stdio.h>
typedef struct _t_t{
int x;
int y;
} t_t;
typedef struct _s_t{
int a;
int b;
t_t t;
}s_t;
void test(s_t & s){
t_t x = {502, 100};
t_t * pt = &(s.t);
pt = &x;
}
int main(){
s_t s;
test(s);
printf("value is %d, %d\n", s.t.x, s.t.y);
return 0;
}
```
actually outputs
```
value is 134513915, 7446516
```
as expected.
|
2009/09/16
|
[
"https://Stackoverflow.com/questions/1435766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/177931/"
] |
>
> Is it because the "=" on the line s.t = x; copies the values of x into s.t?
>
>
>
Yes.
By the way, this is C++. You've passed the "s" local to main as a reference to the function, which modifies it. Because it's a reference, and not a copy, it affects the caller's "s".
|
24,208,909 |
I have a runtime error that is happening at this line of code:
```
_searchresults = [_beerNames filteredArrayUsingPredicate:resultPredicate];
```
serchresuls is a NSArray (nil objects)
beerNames is a NSArray M (196 objects)
and result predicate is a NScomparison predicate and I don't really understand what that means
Here is my code for the result predicate
```
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"name contains[c] %@", searchText];
```
and searchText is a NSCF string, but it only fills up with one letter before the program crashes.
The error it is giving me is this:
NSCFString 0x8cbce80> valueForUndefinedKey:]: this class is not key value coding-compliant for the key name.
Any ideas on what is going on?
|
2014/06/13
|
[
"https://Stackoverflow.com/questions/24208909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3307446/"
] |
In order to turn on numbered-sections in latex output you need to use `numbersections` in your YAML block. If you ever want to "discover" things like this with pandoc just poke around the templates:
```
$ grep -i number default.latex
$if(numbersections)$
$ grep -i number default.html*
$
```
As you can see this option does not work with html.
Markdown and YAML I tested with:
```
---
title: Test
numbersections: true
---
# blah
Text is here.
## Double Blah
Twice the text is here
```
If you need it to work with more than beamer,latex,context,opendoc you will need to file a bug at github.
|
21,049,090 |
I just installed Git + TortoiseGit, created a new local repository on my PC, added a file, and now I'm trying to commit it (I guess that's Commit -> "master").
However it says: "User name and email must be set before commit. Do you want to set these now?"
Ehh, this is supposed to be a local repository. What does any email address have to do with this?
Or am I misunderstanding the way Git works? Note that I'm not using GitHub or BitBucket or whatever. Just a local repository.
|
2014/01/10
|
[
"https://Stackoverflow.com/questions/21049090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1072269/"
] |
The name and email are added to the commit by Git. It's not related to login credentials. It's useful to set at least the name, even if you don't want to set your email.
If you want to leave them blank then you can enter these commands in a terminal:
```
git config --global user.name ""
git config --global user.email ""
```
which should create a `~/.gitconfig` file at your system's $HOME, which will look like:
```
[user]
name =
email =
```
Alternatively, just create or edit your current ~/.gitconfig file to look like this.
|
29,682,561 |
I have an app in which markers can be added to the map using the Google Maps API, I'm trying to send a notification to all devices with the app installed when a new marker is added, this works for the device that is currently using the app but not my other device which does not have the app loaded, is there something else I have to do to register it with other devices?
Here is the code for connecting to the server and adding the marker, which calls the showNotification method:
```
try
{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://***.***.***.**/markerLocation/save.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
String msg = "Data entered successfully";
//The method call that makes the alert notification
ShowNotification(name);
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
```
and here is the code for creating the alert:
```
public void ShowNotification(String name)
{
// define sound URI, the sound to be played when there's a notification
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// intent triggered, you can add other intent for other actions
Intent intent = new Intent(GoogleMapsActivity.this, NotificationReceiver.class);
PendingIntent pIntent = PendingIntent.getActivity(GoogleMapsActivity.this, 0, intent, 0);
// this is it, we'll build the notification!
// in the addAction method, if you don't want any icon, just set the first param to 0
Notification mNotification = new Notification.Builder(this)
.setContentTitle(name)
.setContentText(name + " has added a marker in your area")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent)
.setSound(soundUri)
.addAction(0, "View", pIntent)
.addAction(0, "Remind", pIntent)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// If you want to hide the notification after it was selected, do the code below
mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, mNotification);
}
```
|
2015/04/16
|
[
"https://Stackoverflow.com/questions/29682561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2757842/"
] |
First you will need a Push service to warn other devices of your new marker, then you will need a BroadCastReceiver to receive the push message and emit the Notification on all devices that received it, I would love to explain this and write some example code for you but its widely explained in Android Docus so why reinvent the wheel?
Look at this page, it has everything u need:
[Google Cloud Messaging GCM](https://developer.android.com/google/gcm/index.html)
|
5,400,733 |
I've been building a static library to share between multiple iOS projects, and I want to use gcov (or any code coverage analysis tool) to tell me where I'm missing my tests. However, when I enable gcov by following these directions: <http://supermegaultragroovy.com/blog/2005/11/03/unit-testing-and-code-coverage-with-xcode/>
I get this error from Libtool:
>
>
> ```
> /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/libtool: can't locate file for: -lgcov
> /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/libtool: file: -lgcov is not an object file (not allowed in a library)
>
> ```
>
>
For some reason XCode4 can't find the libgcov.a file. It is in many places on my system but for some reason it can't be found. I'm fairly new to XCode, and gcc based programming in general, so I'm not sure how I can fix this, my guess is that I just have to tell it specifically where to find libgcov.a but I'm not sure how to go about that.
|
2011/03/23
|
[
"https://Stackoverflow.com/questions/5400733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16445/"
] |
Looks like I found a solution. Crazy XCode seems to treat static libraries completely different when invoking gcc. And I thought MSBuild was a build system from hell... it's a snap and at least there are books about it.
Anyway, here's how you do it:
Add `$(PLATFORM_DEVELOPER_USR_DIR)/lib` to your "Library Search Paths" build setting for your static library and tick the "Recursive" check box.
Works for me, let me know if it works for you.
|
12,071,679 |
I am trying to edit `SharedPreferences` of one app through another app, my code goes like this
```
try {
Context plutoContext = getApplicationContext().createPackageContext("me.test",Context.MODE_WORLD_WRITEABLE);
SharedPreferences plutoPreferences = PreferenceManager.getDefaultSharedPreferences(plutoContext);
Editor plutoPrefEditor = plutoPreferences.edit();
plutoPrefEditor.putString("country", "India");
plutoPrefEditor.commit();
}
```
I am getting an error
`E/SharedPreferencesImpl( 304): Couldn't create directory for SharedPreferences file /data/data/me.test/shared_prefs/me.test_preferences.xml`
where `me.test` is my another project
in me.test proj I can edit and retrieve `SharedPreferences` with no pain
I am testing it on Nexus S android 4.0.4 (Samsung), can any one help me
|
2012/08/22
|
[
"https://Stackoverflow.com/questions/12071679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1501118/"
] |
You need to add the permissions in your AndroidManifest.xml:
```
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
```
I have the same problem with you, and I solved it with the above solution.
|
64,121,826 |
I have a table of accounts that contains an edit option. When the edit option is clicked, an account edit modal dialog is displayed. The user has the option to close or cancel the edit by clicking the "X" in the top right corner or clicking a Close button. When the modal closes there are state properties that i would like to clear, both dialog properties and parent component properties. The dialog properties are updated without any issues but i receive this error when the parent properties are attempted to be updated:
>
> Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.
>
>
>
This is the parent component:
```
export class Accounts extends Component {
constructor(props, context) {
super(props);
this.state = {
loading: true,
showEditUserModal: false,
userId: null,
redraw: false,
}
this.handleAccountEdit = this.handleAccountEdit.bind(this);
}
handleAccountEdit(cell, row, rowIndex) {
this.setState({ userId: cell },
this.setState({ showEditUserModal: true }));
}
//This is parent function being called from dialog close Error occurs here
handleAccountEditClose() {
this.setState({ userId: null, showEditUserModal: false, redraw: true });
}
render() {
return (
<div className='container-fluid'>
{this.state.showEditUserModal ?
<AccountEditModal userId={this.state.userId}
parentCloseAccountEditModal={() => this.handleAccountEditClose()}></AccountEditModal>
</div>
)
}
```
AccountEditModal:
```
export default class AccountEditModal extends React.Component {
constructor(props, context) {
super(props);
this.state = {
uId: null,
userName: '',
showModal: true,
}
}
handleClose = (e) => {
this.setState({ showModal: false, uId: null, userName: '' });
}
render() {
return (
<div >
<Modal show={this.state.showModal} onHide={() => { this.handleClose(); this.props.parentCloseAccountEditModal() }} centered >
<Modal.Header closeButton>
<Modal.Title>Account Edit</Modal.Title>
</Modal.Header>
<Modal.Body>
<div className="row">
<div className="row pad-top float-right">
<div className='col-md-2 my-auto'>
<span id='btnCloseAccountEdit' onClick={() => { this.handleClose(); this.props.parentCloseAccountEditModal() }}
className='btn btn-success'>Close</span>
</div>
</div>
</div>
</Modal.Body>
</Modal>
</div>
)
}
```
How can i update the parent component properties without getting this error?
The suggested solution does not call a parent component function. I changed the handleClose to a lambda in the AccountEditModal but still receive the same error.
|
2020/09/29
|
[
"https://Stackoverflow.com/questions/64121826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2370664/"
] |
I am nit sure what you are doing different than I am but based on your code and explanation I created this demo application and it is working as expected without any errors. May be you might want to compare it to your application and check what is different in your app.
Find working [codesandbox](https://codesandbox.io/s/fancy-wind-x3prr) here.
**Accounts.js**
```
import React, { Component } from "react";
import { AccountEditModal } from "./AccountEditModal";
export class Accounts extends Component {
constructor(props, context) {
super(props);
this.state = {
loading: true,
showEditUserModal: false,
userId: null,
redraw: false
};
this.handleAccountEdit = this.handleAccountEdit.bind(this);
}
handleAccountEdit(cell) {
this.setState({ userId: cell }, this.setState({ showEditUserModal: true }));
}
//This is parent function being called from dialog close Error occurs here
handleAccountEditClose() {
this.setState({ userId: null, showEditUserModal: false, redraw: true });
}
render() {
return (
<div className="container-fluid">
{this.state.showEditUserModal ? (
<AccountEditModal
userId={this.state.userId}
parentCloseAccountEditModal={() => this.handleAccountEditClose()}
></AccountEditModal>
) : (
<table>
{this.props.users.map((uId) => {
return (
<tr>
<td>
<button onClick={() => this.handleAccountEdit(uId)}>
{uId}
</button>
</td>
</tr>
);
})}
</table>
)}
</div>
);
}
}
```
**AccountEditModal.js**
```
import React, { Component } from "react";
import { Modal } from "react-bootstrap";
export class AccountEditModal extends Component {
constructor(props, context) {
super(props);
this.state = {
uId: null,
userName: "",
showModal: true
};
}
handleClose = (e) => {
this.setState({ showModal: false, uId: null, userName: "" });
};
render() {
return (
<div>
<Modal
show={this.state.showModal}
onHide={() => {
this.handleClose();
this.props.parentCloseAccountEditModal();
}}
centered
>
<Modal.Header closeButton>
<Modal.Title>Account Edit: {this.props.userId}</Modal.Title>
</Modal.Header>
<Modal.Body>
<div className="row">
<div className="row pad-top float-right">
<div className="col-md-2 my-auto">
<span
id="btnCloseAccountEdit"
onClick={() => {
this.handleClose();
this.props.parentCloseAccountEditModal();
}}
className="btn btn-success"
>
Close
</span>
</div>
</div>
</div>
</Modal.Body>
</Modal>
</div>
);
}
}
```
I have added dummy application data in **App.js**:
```
import React, { useState } from "react";
import { Accounts } from "./Accounts";
import "./styles.css";
export default function App() {
const [users] = useState([
"User1",
"User2",
"User3",
"User4",
"User5",
"User6",
"User7",
"User8",
"User9",
"User10"
]);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<Accounts users={users}></Accounts>
</div>
);
}
```
|
25,038,980 |
i'm building a traffic schedule application using Neo4J, NodeJS and GTFS-data; currently, i'm trying to get
things working for the traffic on a single day on the Berlin subway network. these are the grand totals
i've collected so far:
`10 routes
211 stops
4096 trips
83322 stoptimes`
to put it simply, GTFS (General Transit Feed Specification) has the concept of a `stoptime` which denotes the
event of a given train or bus stopping for passengers to board and alight. `stoptime`s happen on a `trip`,
which is a series of `stoptimes`, they happen on a specific date and time, and they happen on a given
`stop` for a given `route` (or 'line') in a transit network. so there's a lot of references here.
the problem i'm running into is the amount of data and the time it takes to build the database. in order
to speed up things, i've already (1) cut down the data to a single day, (2) deleted the database files
and have the server create a fresh one (very effective!), (3) searched a lot to get better queries. alas,
with the figures as given above, it still takes 30~50 minutes to get all the edges of the graph.
these are the indexes i'm building:
```
CREATE CONSTRAINT ON (n:trip) ASSERT n.id IS UNIQUE;
CREATE CONSTRAINT ON (n:stop) ASSERT n.id IS UNIQUE;
CREATE CONSTRAINT ON (n:route) ASSERT n.id IS UNIQUE;
CREATE CONSTRAINT ON (n:stoptime) ASSERT n.id IS UNIQUE;
CREATE INDEX ON :trip(`route-id`);
CREATE INDEX ON :stop(`name`);
CREATE INDEX ON :stoptime(`trip-id`);
CREATE INDEX ON :stoptime(`stop-id`);
CREATE INDEX ON :route(`name`);
```
i'd guess the unique primary keys should be most important.
and here are the queries that take up like 80% of the running time (with 10% that are unrelated to Neo4J,
and 10% needed to feed the node data using plain HTTP post requests):
```
MATCH (trip:`trip`), (route:`route`)
WHERE trip.`route-id` = route.id
CREATE UNIQUE (trip)-[:`trip/route` {`~label`: 'trip/route'}]-(route);
MATCH (stoptime:`stoptime`), (trip:`trip`)
WHERE stoptime.`trip-id` = trip.id
CREATE UNIQUE (trip)-[:`trip/stoptime` {`~label`: 'trip/stoptime'}]-(stoptime);
MATCH (stoptime:`stoptime`), (stop:`stop`)
WHERE stoptime.`stop-id` = stop.id
CREATE UNIQUE (stop)-[:`stop/stoptime` {`~label`: 'stop/stoptime'}]-(stoptime);
MATCH (a:stoptime), (b:stoptime)
WHERE a.`trip-id` = b.`trip-id`
AND ( a.idx + 1 = b.idx OR a.idx - 1 = b.idx )
CREATE UNIQUE (a)-[:linked]-(b);
MATCH (stop1:stop)-->(a:stoptime)-[:next]->(b:stoptime)-->(stop2:stop)
CREATE UNIQUE (stop1)-[:distance {`~label`: 'distance', value: 0}]-(stop2);
```
the first query is still in the range of some minutes which i find longish given that there are only
thousands (not hundreds of thousands or millions) of `trips` in the database. the subsequent queries that
involve `stoptime`s take several ten minutes each on my desktop machine.
(i've also calculated whether the schedule really contains 83322 stoptimes each day, and yes, it's plausible:
in Berlin, subway trains run on 10 lines for 20 hours a day with 6 or 12 trips per hour, and there are 173
subway stations: 10 lines x 2 directions x 17.3 stops per line x 20 hours x 9 trips per hour gives 62280,
close enough. there *are* some faulty? / double / extra stop nodes in the data (211
stops instead of 173), but those are few.)
frankly, **if i don't find a way to speed up things at least tenfold (rather more), it'll make little sense to use Neo4J
for this project**. just in order to cover the single city of Berlin *many*, *many* more stoptimes have to be added,
as the subway is just a tiny fraction of the overall public transport here (e.g. bus and tramway have like
170 routes with 7,000 stops, so expect around 7,000,000 stoptimes each day).
**Update** the above edge creation queries, which i perform one by one, have now been running for over an hour and not yet finished, meaning that—if things scale in a linear fashion—the time needed to feed the Berlin public transport data for a single day would consume something like a week. therefore, the code currently performs *several* orders of magnitude too slow to be viable.
**Update** @MichaelHunger's solution did work; see my response below.
|
2014/07/30
|
[
"https://Stackoverflow.com/questions/25038980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/256361/"
] |
I just imported 12M nodes and 12M rels into Neo4j in 10 minutes using LOAD CSV.
You should see your issues when you run profiling on your queries in the shell.
Prefix your query with `profile` and look a the profile output if it mentions to use the index or rather just label-scan.
Do you use parameters for your insert queries? So that Neo4j can re-use built queries?
For queries like this:
```
MATCH (trip:`trip`), (route:`route`)
WHERE trip.`route-id` = route.id
CREATE UNIQUE (trip)-[:`trip/route` {`~label`: 'trip/route'}]-(route);
```
It will very probably not use your index.
Can you perhaps point to your datasource? We can convert it into CSV if it isn't and then import even more quickly.
Perhaps we can create a graph gist for your model?
I would rather use:
```
MATCH (route:`route`)
MATCH (trip:`trip` {`route-id` = route.id)
CREATE (trip)-[:`trip/route` {`~label`: 'trip/route'}]-(route);
```
For your initial import you also don't need create unique as you match every trip only once.
And I'm not sure what your "~label" is good for?
Similar for your other queries.
As the data is public it would be cool to work together on this.
Something I'd love to hear more about is how you plan do express your query use-cases.
I had a really great discussion about timetables for public transport with training attendees last time in Leipzig. You can also email me on michael at neo4j.org
Also perhaps you want to check out these links:
### Tramchester
* <http://www.thoughtworks.com/de/insights/blog/transforming-travel-and-transport-industry-one-graph-time>
* <http://de.slideshare.net/neo4j/graph-connect-v5>
* <https://www.youtube.com/watch?v=AhvECxOhEX0>
### London Tube Graph
* <http://blog.bruggen.com/2013/11/meet-this-tubular-graph.html>
* <http://www.markhneedham.com/blog/2014/03/03/neo4j-2-1-0-m01-load-csv-with-rik-van-bruggens-tube-graph/>
* <http://www.markhneedham.com/blog/2014/02/13/neo4j-value-in-relationships-but-value-in-nodes-too/>
|
19,321,925 |
I have a query which I get as:
```
var query = Data.Items
.Where(x => criteria.IsMatch(x))
.ToList<Item>();
```
This works fine.
However now I want to break up this list into x number of lists, for example 3. Each list will therefore contain 1/3 the amount of elements from query.
Can it be done using LINQ?
|
2013/10/11
|
[
"https://Stackoverflow.com/questions/19321925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/524861/"
] |
You can use PLINQ partitioners to break the results into separate enumerables.
```
var partitioner = Partitioner.Create<Item>(query);
var partitions = partitioner.GetPartitions(3);
```
You'll need to reference the System.Collections.Concurrent namespace. `partitions` will be a list of `IEnumerable<Item>` where each enumerable returns a portion of the query.
|
23,282,318 |
I need to disable the "Say something about this" popup box that is displayed after clicking the Facebook Like button.
The simple solution to this is to use the iFrame version of the Like button. However, my like page is hosted with woobox. I cannot change the like button from HTML5 to the iframe version but I do have access to add additional CSS and Javascript.
There have been a number of solutions posted to Stackoverflow but some users have pointed out that they no longer work [Facebook Like Button - how to disable Comment pop up?](https://stackoverflow.com/questions/3247855/facebook-like-button-how-to-disable-comment-pop-up) I have tried all of these solutions and can confirm this.
|
2014/04/25
|
[
"https://Stackoverflow.com/questions/23282318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3505865/"
] |
Okay, I was able to create something that might help you.
Here's the JSFiddle: [JSFiddle](http://jsfiddle.net/4vuDD/)
What I basically did was I wrapped the like button in a div with hidden overflow. Only problem is, the comment box appears for a second right after loading the page, but goes away after. (it's still contained inside the div, but it covers up the like buttons for a second)
Another approach could be something like this: [Changing iFrame elements](https://forum.jquery.com/topic/changing-elements-in-an-iframe)
Where you would need to view the source and check Facebook's element id for the comment box. (looks like it's `div#u_0_6._56zz._56z`) Once you have the id you can try to `.hide()` or `.css('display', 'none')` Unfortunately, this id is really obscure and looks to me like it changes on a regular basis. So if it does change, your code obviously won't work.
The JSFiddle does seems to work. And it looks like your only sure option.
|
47,348 |
Since for my [last question](https://buddhism.stackexchange.com/q/47334/16806), I did not get a satisfactory answer I am reducing the question to its barebones.
What is the difference between 'Witnessing' and 'Mindfulness' from the context of meditation? I mean when I am looking at the sunset without any thoughts in mind and feel a oneness, am I witnessing the sunset or I am being mindful of the eye-consciousness?
In the [Mahāsatipaṭṭhānasutta MN 10](https://suttacentral.net/mn10/en/sujato?layout=plain&reference=none¬es=asterisk&highlight=false&script=latin#mn10:2.1) the word mindfulness is used, can I replace it with the word, 'Witnessing' without changing the meaning?
|
2022/06/01
|
[
"https://buddhism.stackexchange.com/questions/47348",
"https://buddhism.stackexchange.com",
"https://buddhism.stackexchange.com/users/16806/"
] |
sati ("mindfulness") is one of the most commonly misunderstood teachings.
It's been distorted by psychotherapy agendas, and even experienced Buddhist teachers have wildly divergent understandings.
If you want the perspective from the original suttas:
There's an implicit object of sati, and that's the Dharma, the Buddha's teaching that leads to nirvana.
One always remembers to apply the Dharma. All the time.
The fourth frame of sati, seeing Dharma as Dharma, is commonly misunderstood to be seeing thoughts (the dhamma that the mind/mano cognizes/viññāna).
But the primary role of seeing Dharma as Dharma, is living each moment in accordance with the Buddha's Dharma, and the dhamma-thoughts cognized by the mind are subservient to that primary objective.
More detail here:
<http://notesonthedhamma.blogspot.com/2022/12/two-ways-in-which-sati-mindfulness-is.html>
|
412,304 |
A few days after installing 6.1.1 some pages started redirecting to the homepage. I renamed .htaccess, disabled all plugins, and am using the 2022 default theme to try to locate the source of the 301 with no luck. So I checked curl, and found the source of the redirect was labeled "Wordpress". So I stopped the redirect and dumped the debug\_backtrace in order to finally locate this thing. I'm guessing there is a canonical URL set up, but for the life of me, I can't figure it out.
Any page with the URL [https://stgtrulite.wpengine.com/platform/[anything]](https://stgtrulite.wpengine.com/platform/%5Banything%5D) gets a 301 to <https://stgtrulite.wpengine.com>. The rest of the site works, and I can change the URL of the affected pages, but google has already crawled them with the URL.
Can someone please help me out?
Here is the dump:
```
Redirect attempted to location: https://stgtrulite.wpengine.com/
Array
(
[0] => Array
(
[file] => /nas/content/live/stgtrulite/wp-includes/canonical.php
[line] => 801
[function] => wp_redirect
[args] => Array
(
[0] => https://stgtrulite.wpengine.com/
[1] => 301
)
)
[1] => Array
(
[file] => /nas/content/live/stgtrulite/wp-includes/class-wp-hook.php
[line] => 308
[function] => redirect_canonical
[args] => Array
(
[0] => https://stgtrulite.wpengine.com/platform/xxx
)
)
[2] => Array
(
[file] => /nas/content/live/stgtrulite/wp-includes/class-wp-hook.php
[line] => 332
[function] => apply_filters
[class] => WP_Hook
[object] => WP_Hook Object
(
[callbacks] => Array
(
[0] => Array
(
[_wp_admin_bar_init] => Array
(
[function] => _wp_admin_bar_init
[accepted_args] => 1
)
)
[10] => Array
(
[wp_old_slug_redirect] => Array
(
[function] => wp_old_slug_redirect
[accepted_args] => 1
)
[redirect_canonical] => Array
(
[function] => redirect_canonical
[accepted_args] => 1
)
[0000000026d0f2cb000000001a0eef68render_sitemaps] => Array
(
[function] => Array
(
[0] => WP_Sitemaps Object
(
[index] => WP_Sitemaps_Index Object
(
[registry:protected] => WP_Sitemaps_Registry Object
(
[providers:WP_Sitemaps_Registry:private] => Array
(
[posts] => WP_Sitemaps_Posts Object
(
[name:protected] => posts
[object_type:protected] => post
)
[taxonomies] => WP_Sitemaps_Taxonomies Object
(
[name:protected] => taxonomies
[object_type:protected] => term
)
[users] => WP_Sitemaps_Users Object
(
[name:protected] => users
[object_type:protected] => user
)
)
)
[max_sitemaps:WP_Sitemaps_Index:private] => 50000
)
[registry] => WP_Sitemaps_Registry Object
(
[providers:WP_Sitemaps_Registry:private] => Array
(
[posts] => WP_Sitemaps_Posts Object
(
[name:protected] => posts
[object_type:protected] => post
)
[taxonomies] => WP_Sitemaps_Taxonomies Object
(
[name:protected] => taxonomies
[object_type:protected] => term
)
[users] => WP_Sitemaps_Users Object
(
[name:protected] => users
[object_type:protected] => user
)
)
)
[renderer] => WP_Sitemaps_Renderer Object
(
[stylesheet:protected] =>
[stylesheet_index:protected] =>
)
)
[1] => render_sitemaps
)
[accepted_args] => 1
)
)
[11] => Array
(
[rest_output_link_header] => Array
(
[function] => rest_output_link_header
[accepted_args] => 0
)
[wp_shortlink_header] => Array
(
[function] => wp_shortlink_header
[accepted_args] => 0
)
)
[1000] => Array
(
[wp_redirect_admin_locations] => Array
(
[function] => wp_redirect_admin_locations
[accepted_args] => 1
)
)
[99999] => Array
(
[0000000026d0f112000000001a0eef68is_404] => Array
(
[function] => Array
(
[0] => WpeCommon Object
(
[options:protected] =>
)
[1] => is_404
)
[accepted_args] => 1
)
)
)
[iterations:WP_Hook:private] => Array
(
[0] => Array
(
[0] => 0
[1] => 10
[2] => 11
[3] => 1000
[4] => 99999
)
)
[current_priority:WP_Hook:private] => Array
(
[0] => 10
)
[nesting_level:WP_Hook:private] => 1
[doing_action:WP_Hook:private] => 1
)
[type] => ->
[args] => Array
(
[0] =>
[1] => Array
(
[0] =>
)
)
)
[3] => Array
(
[file] => /nas/content/live/stgtrulite/wp-includes/plugin.php
[line] => 517
[function] => do_action
[class] => WP_Hook
[object] => WP_Hook Object
(
[callbacks] => Array
(
[0] => Array
(
[_wp_admin_bar_init] => Array
(
[function] => _wp_admin_bar_init
[accepted_args] => 1
)
)
[10] => Array
(
[wp_old_slug_redirect] => Array
(
[function] => wp_old_slug_redirect
[accepted_args] => 1
)
[redirect_canonical] => Array
(
[function] => redirect_canonical
[accepted_args] => 1
)
[0000000026d0f2cb000000001a0eef68render_sitemaps] => Array
(
[function] => Array
(
[0] => WP_Sitemaps Object
(
[index] => WP_Sitemaps_Index Object
(
[registry:protected] => WP_Sitemaps_Registry Object
(
[providers:WP_Sitemaps_Registry:private] => Array
(
[posts] => WP_Sitemaps_Posts Object
(
[name:protected] => posts
[object_type:protected] => post
)
[taxonomies] => WP_Sitemaps_Taxonomies Object
(
[name:protected] => taxonomies
[object_type:protected] => term
)
[users] => WP_Sitemaps_Users Object
(
[name:protected] => users
[object_type:protected] => user
)
)
)
[max_sitemaps:WP_Sitemaps_Index:private] => 50000
)
[registry] => WP_Sitemaps_Registry Object
(
[providers:WP_Sitemaps_Registry:private] => Array
(
[posts] => WP_Sitemaps_Posts Object
(
[name:protected] => posts
[object_type:protected] => post
)
[taxonomies] => WP_Sitemaps_Taxonomies Object
(
[name:protected] => taxonomies
[object_type:protected] => term
)
[users] => WP_Sitemaps_Users Object
(
[name:protected] => users
[object_type:protected] => user
)
)
)
[renderer] => WP_Sitemaps_Renderer Object
(
[stylesheet:protected] =>
[stylesheet_index:protected] =>
)
)
[1] => render_sitemaps
)
[accepted_args] => 1
)
)
[11] => Array
(
[rest_output_link_header] => Array
(
[function] => rest_output_link_header
[accepted_args] => 0
)
[wp_shortlink_header] => Array
(
[function] => wp_shortlink_header
[accepted_args] => 0
)
)
[1000] => Array
(
[wp_redirect_admin_locations] => Array
(
[function] => wp_redirect_admin_locations
[accepted_args] => 1
)
)
[99999] => Array
(
[0000000026d0f112000000001a0eef68is_404] => Array
(
[function] => Array
(
[0] => WpeCommon Object
(
[options:protected] =>
)
[1] => is_404
)
[accepted_args] => 1
)
)
)
[iterations:WP_Hook:private] => Array
(
[0] => Array
(
[0] => 0
[1] => 10
[2] => 11
[3] => 1000
[4] => 99999
)
)
[current_priority:WP_Hook:private] => Array
(
[0] => 10
)
[nesting_level:WP_Hook:private] => 1
[doing_action:WP_Hook:private] => 1
)
[type] => ->
[args] => Array
(
[0] => Array
(
[0] =>
)
)
)
[4] => Array
(
[file] => /nas/content/live/stgtrulite/wp-includes/template-loader.php
[line] => 13
[function] => do_action
[args] => Array
(
[0] => template_redirect
)
)
[5] => Array
(
[file] => /nas/content/live/stgtrulite/wp-blog-header.php
[line] => 19
[args] => Array
(
[0] => /nas/content/live/stgtrulite/wp-includes/template-loader.php
)
[function] => require_once
)
[6] => Array
(
[file] => /nas/content/live/stgtrulite/index.php
[line] => 17
[args] => Array
(
[0] => /nas/content/live/stgtrulite/wp-blog-header.php
)
[function] => require
)
)
```
|
2022/12/24
|
[
"https://wordpress.stackexchange.com/questions/412304",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/206120/"
] |
In WordPress, there is no concept of "super admins" in the same way that there is in a multisite installation. However, there may be users with the "administrator" role who have access to all areas of the site, including the WordPress settings.
If you are an administrator and you are unable to access the WordPress settings, it could be due to a number of reasons. Here are a few things you could try:
* Check that you are logged in with an account that has the "administrator" role.
* Check if there are any plugins or themes that may be blocking access to the settings. You can try deactivating all plugins and switching to a default theme to see if this resolves the issue.
* Check if there are any errors in your site's `wp-config.php` file that may be preventing access to the settings.
* If you are using a caching plugin, try clearing the cache to see if that resolves the issue.
If none of these suggestions helps, you may need to access the site's database and check via your Host cpanel for any issues there. You can use a tool like `phpMyAdmin` to access the database `wp_users` table and check for any problems.
while on `PHPMyAdmin`, Check if there are any issues with the user roles: The user roles in WordPress determine what permissions users have on the site. If your user role has been changed or there are any issues with the user roles, it could prevent you from accessing the dashboard. You can check the `wp_usermeta` table to see if there are any issues with the user roles.
To change user roles in the wp\_usermeta table in WordPress using phpMyAdmin, you can follow these steps:
1. Log in to your hosting account and open the phpMyAdmin tool.
2. Select the WordPress database from the list of databases on the left side of the page.
3. Click on the `wp_usermeta` table to open it.
4. Click on the "Browse" tab to view the contents of the table.
5. Find the row corresponding to the user whose role you want to change. The `user_id` column will contain the ID of the user, and the `meta_key` column will contain the string "`wp_capabilities`".
6. Click on the "Edit" link for the row you want to modify.
7. In the "meta\_value" field, enter the desired role for the user. The role should be specified as a serialized array, with the key corresponding to the role and the value set to true. For example, to set the user's role to "administrator", you would enter the following value in the "meta\_value" field: `a:1:{s:13:"administrator";b:1;}`.
if a user has the "administrator" role, the `wp_capabilities` field for that user might contain the following value: `a:1:{s:13:"administrator";b:1;}`. This value indicates that the user has the "administrator" role, with the key `s:13:"administrator"` corresponding to the role and the value `b:1;` indicating that the `role is enabled`.
8. Click the "Go" button to save the changes.
Please note that changing user roles in the database can have serious consequences if not done carefully. It is important to make sure you understand the implications of modifying the database before making any changes. If you are not comfortable working with databases, it is best to seek the help of a developer or database administrator.
I hope this helps! Let me know if you have any other questions.
|
21,169,968 |
I set up a new Ghost 0.4 blog, created numerous posts, then switched to production mode before setting the site live. To my surprise, the posts I created no longer showed up. Since setting up Ghost 0.3.3, I had forgotten that Ghost uses separate database stores for the production and development environments, and I failed to switch to production mode before creating content.
How can I migrate content from Ghost's development environment to its production environment?
|
2014/01/16
|
[
"https://Stackoverflow.com/questions/21169968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/705157/"
] |
Ghost uses SQLite databases, which stores content in a single file for each content, so it's easy to back-up, move or copy an entire database in one go.
To solve the problem of having posts only in my development database, I simply shut down Ghost, and switched the production and development SQLite database files. The files are stored in the Ghost `content/data` sub-folder:
* `ghost-dev.db` is the development database
* `ghost.db` is the production database
If you're in the Ghost folder, the following commands will swap the two environment databases:
```
$ mv content/data/ghost-dev.db content/data/ghost-dev.db-tmp
$ mv content/data/ghost.db content/data/ghost-dev.db
$ mv content/data/ghost-dev.db-tmp content/data/ghost.db
```
Restart Ghost in either mode to see the changes.
It's even easier to just copy everything from development to production:
```
$ cp content/data/ghost-dev.db content/data/ghost.db
```
|
30,737,541 |
I want to use enumeration type in C. I know how to use them but I have a question. I have an example like this
```
enum S { A,B,C,G };
```
I know this works but can i do something like this?
```
enum S {^,*,/,%};
```
Thanks for your time.
|
2015/06/09
|
[
"https://Stackoverflow.com/questions/30737541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3161625/"
] |
No. You can only use alphanumeric characters and underscores in identifiers (variable, function, and type names) in C. And the identifier cannot start with a number. Also, you can't use certain reserved keywords.
*<http://www.cprogrammingexpert.com/C/Tutorial/fundamentals/identifiers.aspx>* (link broken)
UPDATE: Newer link that's not broken:
<https://www.w3schools.in/c-programming/identifiers>
|
27,530,000 |
There seem to be at at least **two or three major ways** of building **apps** that communicate with `bokeh-server` in Bokeh. They correspond to the [folders](https://github.com/bokeh/bokeh/tree/master/examples) [`app`](https://github.com/bokeh/bokeh/tree/master/examples/app), [`embed`](https://github.com/bokeh/bokeh/tree/master/examples/embed) and [`plotting`](https://github.com/bokeh/bokeh/tree/master/examples/plotting)/[`glyphs`](https://github.com/bokeh/bokeh/tree/master/examples/glyphs) under the [examples](https://github.com/bokeh/bokeh/tree/master/examples) directory in Bokeh.
On the differences between them, I read [here](https://groups.google.com/a/continuum.io/forum/?utm_medium=email&utm_source=footer#!msg/bokeh/NClF-837DMc/hCfy8tnyFDUJ) the following:
>
> On the [`stock_app.py`](https://github.com/bokeh/bokeh/blob/master/examples/app/stock_applet/stock_app.py) ([`app`](https://github.com/bokeh/bokeh/tree/master/examples/app) folder) example you are using `bokeh-server` to **embed an
> applet** and serve it from the url you specify. That's why you crate a
> new `StockApp` class and create a function that creates a new instance
> of it and decorates it with @`bokeh_app.route("/bokeh/stocks/")` and
> `@object_page("stocks")`. You can follow the **[`app`](https://github.com/bokeh/bokeh/tree/master/examples/app) examples** (sliders,
> stock and crossfilter) and use bokeh `@object_page` and `@bokeh_app.route`
> decorators to create your custom url.
>
>
> On the [`taylor_server.py`](https://github.com/bokeh/bokeh/blob/master/examples/glyphs/taylor_server.py) example ([`glyphs`](https://github.com/bokeh/bokeh/tree/master/examples/glyphs) folder) it is the **session object** that
> is taking care of creating everything on `bokeh-server` for you. From
> this interface is not possible to customize urls or create alias.
>
>
>
But this confused me, what is meant by an "applet" & "embedding" in Bokeh terminology, and what is
**exactly** he difference between applets (presumably [`app`](https://github.com/bokeh/bokeh/tree/master/examples/app) and [`embed`](https://github.com/bokeh/bokeh/tree/master/examples/embed)) and [`plotting`](https://github.com/bokeh/bokeh/tree/master/examples/plotting)/[`glyphs`](https://github.com/bokeh/bokeh/tree/master/examples/glyphs)?
Also I thought that the notion of "embedding" only referred to the design pattern that we see in the `embed` folder as in the example [`animated.py`](https://github.com/bokeh/bokeh/blob/master/examples/embed/animated.py), where we embed a `tag` in the body of an HTML file. I don't see that in the [`stock_app.py`](https://github.com/bokeh/bokeh/blob/master/examples/app/stock_applet/stock_app.py), so why is it an embedding example?
|
2014/12/17
|
[
"https://Stackoverflow.com/questions/27530000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/283296/"
] |
>
> But this confused me, what is meant by an "applet" & "embedding" in
> Bokeh terminology
>
>
>
There is clearly a mistake in the answer you have pasted here (that probably doesn't help you on understanding, sorry). The stock app example `stock_app.py` is in examples\app\stock\_applet\stock\_app.py not embed folder. Also, the terminology used does not help either. On that example you create an applet that can be served in 2 different ways:
1. running directly on a bokeh-server
2. embedded (or integrated if you prefer) into a separate application (a Flask application in that case)
You may find more information at the `examples\app\stock_applet\README.md` file.
Also, you can find info about applets and bokeh server [examples documentation](http://bokeh.pydata.org/docs/user_guide/examples.html#id2) and [userguide](http://bokeh.pydata.org/docs/user_guide/server.html)
Regarding what does embedding means, you can find more info at the user\_guide/embedding section of bokeh docs. To summarize, you can generate code that you can insert on your own web application code to display bokeh components. Examples in examples\embed are also useful to understand this pattern.
Finally, the usage of bokeh-server you see in `taylor_server.py` is just using bokeh server to serve you plot (instead of saving it to a static html file).
Hope this helps ;-)
|
71,547,975 |
I have tried a lot but still can't solve this..
How can I render a tetrahedron with different texture on each face?
At beginning I was trying this way.
```js
import * as THREE from 'three';
window.onload = () => {
const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
const renderer = new THREE.WebGLRenderer({ antialias: true })
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)
var geometry = new THREE.CylinderGeometry(0, 2, 3, 3, 3, false)
var materials = [
new THREE.MeshBasicMaterial({ color: 0xff00ff }),
new THREE.MeshBasicMaterial({ color: 0xff0000 }),
new THREE.MeshBasicMaterial({ color: 0x0000ff }),
new THREE.MeshBasicMaterial({ color: 0x5100ff })
]
var tetra = new THREE.Mesh(geometry, materials)
scene.add(tetra)
renderer.render(scene, camera)
camera.position.z = 5;
var ambientLight = new THREE.AmbientLight(0xffffff, 0.5)
scene.add(ambientLight)
function animate() {
requestAnimationFrame(animate)
tetra.rotation.x += 0.04;
tetra.rotation.y += 0.04;
renderer.render(scene, camera)
}
animate()
}
```
I use a cylinder geometry to "make" a fake tetrahedron.
But I found that I can't texturing each face of this "tetrahedron", bc cylinder geometry actually have only 3 faces.
Does anyone know how to do it?
P.S. I have also tried TetrahedronGeometry but it just didn't work, I guessed it was because TetrahedronGeometry is basically BufferGeometry and there are no faces property on it.
|
2022/03/20
|
[
"https://Stackoverflow.com/questions/71547975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4752143/"
] |
You can build your own geometry or modify an existing one. To have different materials on sides, use `groups`.
```css
body{
overflow: hidden;
margin: 0;
}
```
```html
<script type="module">
import * as THREE from "https://cdn.skypack.dev/[email protected]";
import {OrbitControls} from "https://cdn.skypack.dev/[email protected]/examples/jsm/controls/OrbitControls"
let scene = new THREE.Scene();
let camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 1, 1000);
camera.position.set(0, 5, 10).setLength(3);
let renderer = new THREE.WebGLRenderer();
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
window.addEventListener("resize", event => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
rendrer.setSize(innerWidth, innerHeight);
})
let controls = new OrbitControls(camera, renderer.domElement);
// https://discourse.threejs.org/t/tetrahedron-non-indexed-buffer-geometry/12542
// tetrahedron
// ---------------------------------------------------------------------------------------
var pts = [ // https://en.wikipedia.org/wiki/Tetrahedron#Coordinates_for_a_regular_tetrahedron
new THREE.Vector3(Math.sqrt(8 / 9), 0, -(1 / 3)),
new THREE.Vector3(-Math.sqrt(2 / 9), Math.sqrt(2 / 3), -(1 / 3)),
new THREE.Vector3(-Math.sqrt(2 / 9), -Math.sqrt(2 / 3), -(1 / 3)),
new THREE.Vector3(0, 0, 1)
];
var faces = [ // triangle soup
pts[0].clone(), pts[2].clone(), pts[1].clone(),
pts[0].clone(), pts[1].clone(), pts[3].clone(),
pts[1].clone(), pts[2].clone(), pts[3].clone(),
pts[2].clone(), pts[0].clone(), pts[3].clone()
];
var geom = new THREE.BufferGeometry().setFromPoints(faces);
geom.rotateX(-Math.PI * 0.5);
geom.computeVertexNormals();
geom.setAttribute("uv", new THREE.Float32BufferAttribute([ // UVs
0.5, 1, 0.06698729810778059, 0.2500000000000001, 0.9330127018922194, 0.2500000000000001,
0.06698729810778059, 0.2500000000000001, 0.9330127018922194, 0.2500000000000001, 0.5, 1,
0.06698729810778059, 0.2500000000000001, 0.9330127018922194, 0.2500000000000001, 0.5, 1,
0.06698729810778059, 0.2500000000000001, 0.9330127018922194, 0.2500000000000001, 0.5, 1
], 2));
geom.addGroup(0, 3, 0);
geom.addGroup(3, 3, 1);
geom.addGroup(6, 3, 2);
geom.addGroup(9, 3, 3);
// ---------------------------------------------------------------------------------------
let tl = new THREE.TextureLoader();
let tp = "https://threejs.org/examples/textures/";
let tetra = new THREE.Mesh(geom, [
new THREE.MeshBasicMaterial({map: tl.load(tp + "uv_grid_opengl.jpg")}),
new THREE.MeshBasicMaterial({map: tl.load(tp + "colors.png")}),
new THREE.MeshBasicMaterial({map: tl.load(tp + "brick_diffuse.jpg")}),
new THREE.MeshBasicMaterial({map: tl.load(tp + "758px-Canestra_di_frutta_(Caravaggio).jpg")})
])
scene.add(tetra);
renderer.setAnimationLoop(()=> {
renderer.render(scene, camera);
});
</script>
```
|
735,915 |
Is it possible to use the built in ASP.NET membership provider to secure a web service?
I have a SQL Server database already setup with my membership and now I want to provide a web service that only members are allowed to use. Is it possible to authenticate against this (if so how?) or do I need to have a seperate type of authentication for the web services?
|
2009/04/09
|
[
"https://Stackoverflow.com/questions/735915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/53020/"
] |
There actually is a solution, it turns out: WebRequest.PreAuthenticate
Check out an [article](http://www.west-wind.com/Weblog/posts/243915.aspx) by Rick Strahl.
|
22,850,061 |
**<http://codepen.io/leongaban/pen/talGc/>**
So having an interesting problem here.
I've got a left and right div
The left div has 3 elements in it:
1) Person 1
2) WANTS TO MEET sign
3) Person 2
The right div just a paragraph, both divs are close to 50% width each.
Now if you shrink the browser window, the items inside of the left div will start to wrap. If I know exactly how wide the contents inside of the left div will always be this wouldn't be a problem, I could just solve it with media queries.
So here is my problem, the elements inside the left div will always change so I can't find the perfect media query to break on and remove the floats.
I believe I can fix this problem in jQuery by calculating the width of all the elements inside the left div, and check to see if it matches the width of their container on window resize then remove the floats. However that seems like doing too much and using too much to solve this problem.
Is there a CSS solution to this?
All my code is in the CodePen link above, here is the mediaQuery I'm using to remove the floats at 1205px. But again I will never know the correct size to break everytime since the widths will change:
```
@media all and (max-width: 1205px) {
.the_requestor, .the_requested, .wants_to_meet {
float: none;
}
.the_requestor {
margin: 0 0 10px 0;
}
.request_details_left {
margin-top: 0;
border-right: 1px solid #e0e0e0;
}
.request_details_right {
width: 40%;
border: 0;
}
}
```
**Screenshots:**
Large Desktop - correct look

Resizing the window - problematic look (This is what I want to avoid)

Resized small Desktop - correct look

|
2014/04/03
|
[
"https://Stackoverflow.com/questions/22850061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/168738/"
] |
I suspect what you're *really* trying to do is to show the parent of any `li` with class `active` within a `.cn_submenu`. Your current code looks to see if the **first** `li` of the **first** `.cn_submenu` has the class `active` (ignoring all other `.cn_submenu` and `li` elements), and then uses `this` incorrectly if so.
To show the parent of any `li` with class `active` that's inside a `.cn_submenu`:
```
$(document).ready(function(){
$(".cn_submenu li.active").parent().show();
});
```
How that works:
* `$(".cn_submenu li.active")` selects any `li` elements with the class `active` that are descendants of a `.cn_submenu`.
* `.parent()` finds the (unique) set of immediate parents of those elements.
* `.show()` shows them (if any).
|
64,685,502 |
I have two differents dataframes
```
DF1 = data.frame("A"= c("a","a","b","b","c","c"), "B"= c(1,2,3,4,5,6))
DF2 = data.frame("A"=c("a","b","c"), "C"=c(10,11,12))
```
I want to add the column `C` to `DF1` grouping by column `A`
The expected result is
```
A B C
1 a 1 10
2 a 2 10
3 b 3 11
4 b 4 11
5 c 5 12
6 c 6 12
```
note: In this example all the groups have the same size but it won't be necessarily the case
|
2020/11/04
|
[
"https://Stackoverflow.com/questions/64685502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14578930/"
] |
Welcome to stackoverflow. As @KarthikS commented, what you want is a join.
'Joining' is the name of the operation for connecting two tables together. 'Grouping by' a column is mainly used when summarizing a table: For example, group by state and sum number of votes would give the total number of votes by each state (summing without grouping first would give the grand total number of votes).
The syntax for joins in dplyr is:
```r
output = left_join(df1, df2, by = "shared column")
```
or equivalently
```r
output = df1 %>% left_join(df2, by = "shared column")
```
Key reference [here](https://dplyr.tidyverse.org/reference/join.html).
In your example, the shared column is `"A"`.
|
43,338,055 |
I have a loop of ICommands (well, RelayCommand which is inherited from ICommand) and I don't know how to give information to each ICommand.
What I'm actually doing is creating a WPF context menu and each menu item has an ICommand. Each menu item needs to do a different thing. It needs to add the item clicked on (Character) to a group of items (Scene).
It'll be clearer if I show the loop itself I think:
```
foreach (Scene s in Database.Instance.Scenes)
{
SceneAddMenu.Add(new ContextMenuVM()
{
DisplayName = s.SceneName,
ContextMenuCommand = new RelayCommand(
() =>
{
MessageBox.Show("Clicked " + s.SceneID.ToString());
})
});
}
```
ContextMenuVM holds a String (the menu item display text) and ContextMenuCommand, which is a RelayCommand (inherited from ICommand).
At the moment, the code always runs with the final Scene ID from the list. I think this is because the expression is evaluated at runtime (I might be totally wrong there) and so it's at the end of the loop anyway.
What I want is to get information from outside each loop (the Scene 's') to inside the loop.
I don't know enough about the question to find anymore. I've searched 'ICommand loops' until I was blue in the face on Google, but I don't think those are the right keywords for my problem.
Any help would be appreciated, even just the right terms to use to search.
|
2017/04/11
|
[
"https://Stackoverflow.com/questions/43338055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1096196/"
] |
During page load the accordions appeared with the **open** (or *minus*) sign because, it expects a bootstrap class `collapsed` in the `a` tag which has this attribute -> `data-toggle="collapse"`. The `collapsed` class has been missed in your code.
So it will look like:
```
<a class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapse1">
Agronomija</a>
```
[**Demo**](https://jsfiddle.net/shashank2691/eqhaq8uf/)
|
42,563,429 |
I have data coming in and am trying to display the rows it fills with ng-repeat. Here is how the data looks coming in:
[](https://i.stack.imgur.com/98EpM.png)
SO I am trying to display it on the view:
```
<tbody data-ng-repeat="contract in contracts">
<tr>
<td><div data-strat-form-control data-field-display-id="1" data-vmformreadonly="true" data-strat-model="contract" data-field="contracts[0].ndc_id"></div></td>
</tr>
</tbody>
```
Typing `{{contract.ndc_id}}` or `{{contracts.ndc_id}}` returns nothing.
However, `{{contracts[0].ndc_id}}` returns the expected data.
But There will be multiple contracts in the array and this will only account for the 1st one it looks like.
Why isn't ng-repeat iterating using (contract in contracts)? How do I fix this?
|
2017/03/02
|
[
"https://Stackoverflow.com/questions/42563429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1524210/"
] |
```
<div ng-repeat="(key, value) in contracts[0]">
{{contracts[0][key]}} | {{value}}
<div ng-if="$index === 1"> This is the second value {{value}}</div>
<div ng-if="$index === 2"> This is the thrid value {{value}}</div>
<div ng-if="$last"> This is the last value {{value}}</div>
</div>
```
|
28,913,473 |
This is image : <http://oi60.tinypic.com/118iq7r.jpg>
I have a similar database structure to that shown in the table above. However, I have additional columns for the login times. I would like to take the data from the columns and display them on a page.
```
ID | txtName | txtEmail | txtPasswd
-------------------------------------------
1 | Ahmet | [email protected] | 123123
2 | Ali | [email protected] | 312 321
<?php
session_start();
ob_start();
include 'connect.php';
$email = $_POST['txtEmail'];
$password = $_POST['txtPasswd'];
$cryptpass = md5($password);
$login = mysql_query("select * from users where txtEmail='".$email."' and txtPasswd='".$cryptpass."' ") or die(mysql_error());
if(mysql_num_rows($login)) {
$_SESSION["login"] = true;
$_SESSION["user"] = $password;
$_SESSION["pass"] = $password;
$_SESSION["email"] = $emailadress;
header("location:index.php");
}
else
{
if($email=="" or $password=="") {
echo "";
} else {
header('Location:index.php?error=1');
exit;
}
}
ob_end_flush();
?>
```
This is my profile page.
```
<?php
if (empty($_SESSION["fullname"])) {
$fullnamequery = "";
}
if(!empty($_SESSION['login'])) {
echo '<li class="user logged">
<a href="http://www.petkod.com/hesabim/bilgilerim" title="'.$_SESSION['fullname'].'">'.$_SESSION['fullname'].'<span class="arrow"></span></a>
<div class="subMenu">
<ul>
<li><a href="http://www.petkod.com/hesabim/bilgilerim" class="info">Bilgilerim</a></li>
<li><a href="http://www.petkod.com/hesabim/petlerim" class="pet">Petlerim</a></li>
<li><a href="http://www.petkod.com/hesabim/adreslerim" class="address">Adreslerim</a></li>
<li><a href="http://www.petkod.com/hesabim/siparisler" class="order">Siparişlerim</a></li>
<li><a href="logout.php" class="logout">Çıkış</a></li>
</ul>
</div>
</li>';
}else{echo '<li class="user"><a href="popup-login.php" data-width="520" data-height="556" class="iframe">Giriş Yap</a></li>';};
?>
```
|
2015/03/07
|
[
"https://Stackoverflow.com/questions/28913473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4643769/"
] |
Your suggestion is the good choice to make.
You can't catch the Router in a Meteor method because it's server side. You have to do it in the **callback function**, exactly like you suggested :
```
Meteor.call('createNewItinerary',itinerary, function(err, data){
if(err){
console.log(err);
}
Router.go('confirmation');
});
```
To check that the work has correctly been done on the server, just throw errors, for example:
```
throw new Meteor.Error( 500, 'There was an error processing your request' );
```
Then if error is thrown, it will be logged in your client side.
Hope it helps you :)
|
54,886,421 |
I have this code:
```
new Thread(new Runnable() {
@Override
public void run() {
//implement
}
});
```
My IDE(intellij) suggest to use:
```
new Thread(() -> {
//implement
});
```
This guarantee is the same thing? I ask this because class [Thread](https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#Thread()) has multiple constructors.
|
2019/02/26
|
[
"https://Stackoverflow.com/questions/54886421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9011164/"
] |
Yes, that is equivalent, trust your IDE!
Regarding multiple constructors:
* you have exactly one constructor argument -> two possible constructor implementations
* is `() -> { //implement }` a `String`? - **no** -> only one possible constructor to call -> the one for `Runnable`, which you would call on your own as well.
|
69,238,124 |
From an image made up of 9 smaller images arranged as a 3x3-grid like
```
AAA
BBB
CCC
```
i want to automatically generate all possible variations as .pngs, where the position of the smaller images does matter, no position can be empty and and each small image must be present three times. I managed to get a list of these permutations with python:
```
from sympy.utilities.iterables import multiset_permutations
from pprint import pprint
pprint(list(multiset_permutations(['A','A','A','B','B','B','C','C','C'])))
```
resulting in 1680 variations:
```
[['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'],
['A', 'A', 'A', 'B', 'B', 'C', 'B', 'C', 'C'],
['A', 'A', 'A', 'B', 'B', 'C', 'C', 'B', 'C'],
['A', 'A', 'A', 'B', 'B', 'C', 'C', 'C', 'B'],
['A', 'A', 'A', 'B', 'C', 'B', 'B', 'C', 'C'],
['A', 'A', 'A', 'B', 'C', 'B', 'C', 'B', 'C'],
...
['C', 'C', 'C', 'B', 'B', 'B', 'A', 'A', 'A']]
```
How can i replace each letter for each line with the respective small images A.png, B.png and C.png, which are all square 1000 x 1000 px, with the first three 1000 px apart, and two more rows below?
Thank you for your help!
|
2021/09/18
|
[
"https://Stackoverflow.com/questions/69238124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9338851/"
] |
You can achieve this using `flex` and javascript:
```js
document.addEventListener("DOMContentLoaded", function() {
var btn1= document.getElementById("btn1");
var btn2= document.getElementById("btn2");
var maxWidth = btn1.offsetWidth;
if(maxWidth<btn2.offsetWidth)maxWidth=btn2.offsetWidth;
maxWidth+=1;
btn1.style.width = maxWidth+"px";
btn2.style.width = maxWidth+"px";
});
```
```css
.container {
display:flex;
align-items: flex-start;
justify-content: space-between;
width: 1000px;
height: 100px;
border: 1px solid black;
}
```
```html
<div class="container">
<button id="btn1">Little text (very left)</button>
<button id="btn2">This text is way more long than the other (very right)</button>
</div>
```
|
846,748 |
I'm running an openLDAP server version 2.4.40 on CentOS 7. LDAP is going to be configured using online conf option (olc). Thanks to this [question](https://stackoverflow.com/questions/17669586/where-is-my-data-directories-store-by-slapd-openldap-on-ubuntu), I know that slapd's database files are in `/var/lib/ldap`.
I'm trying to run an openLDAP server on a linux box as read-only OS partition and another partition for persistent data. I will be able to install and configure openLDAP on the OS partition, but will lose access to it after configuring it.
**Question:** Is it possible to change the location LDAP reads/writes data from */var/lib/ldap* to somewhere on the persistent data partition?
|
2017/04/26
|
[
"https://serverfault.com/questions/846748",
"https://serverfault.com",
"https://serverfault.com/users/405449/"
] |
I used to move the default database of openldap after each new setup.
The steps I do when I want to move a database :
* Stop `slapd`
```
sudo service slapd stop
```
* `slapcat` the content of the `cn=config` branch in a LDIF file
```
sudo slapcat -b cn=config > /tmp/config.ldif
```
* Copy the `/var/lib/ldap` directory wherever you want it
* Make sure the user `openldap` owns the new directory and all the files inside
* Edit the previously exported LDIF to modify the `olcDbDirectory` to the new location
* Import the LDIF (Make sure the `/etc/ldap/slapd.d` is empty before doing this)
```
sudo rm -r /etc/ldap/slapd.d/*
sudo slapadd -F /etc/ldap/slapd.d -b cn=config -l /tmp/config.ldif
```
* Make sure the `/etc/ldap/slapd.d` and all its content is owned by `openldap`
```
sudo chown -R openldap:openldap /etc/ldap/slapd.d/
```
* Edit needed configuration to allow Slapd to use this new database directory
For example, with `apparmor`, edit the file `/etc/apparmor.d/usr.sbin.slapd` and add the following lines:
```
/path/to/new/db/ r,
/path/to/new/db/** rwk,
```
* Restart apparmor and slapd
```
sudo service apparmor restart
sudo service slapd start
```
Usually it does the trick. It's also how I backup the configuration of my openldap instances.
|
1,539,772 |
I am trying to `move` folder and files from one location to another on the same mapped network drive.
I have used ROBOCOPY and XCOPY. However, they copy and then delete the files. My files can be over 50GB, thus I want to MOVE.
```
move "P:\public\video\recording\123\*.*" "P:\public\video\recording\"
move /S "P:\public\video\recording\123\*.*" "P:\public\video\recording\"
move "P:\public\video\recording\123\*" "P:\public\video\recording\"
move "P:\public\video\recording\123\*" "P:\public\video\recording."
```
**None of the above work**.
I am not sure if it is possible?
I have tried so many different variations with no success.
Additional information
Okay, reading the comments, this command working on a network share?
I have noticed the follow:
1. When moving only files, the script moves them, not copies them. Tested with a 40GB file.
2. When you have folders with files, it copies and then deletes them after.
These are my observations thus far.
|
2020/04/07
|
[
"https://superuser.com/questions/1539772",
"https://superuser.com",
"https://superuser.com/users/118319/"
] |
In case you are using the Skype App, removing the context menu item is trickier.
One way is to delete `DllPath` under
```
HKEY_CLASSES_ROOT\PackagedCom\Package\Microsoft.SkypeApp_15.61.100.0_x86__kzf8qxf38zg5c\Class\{776DBC8D-7347-478C-8D71-791E12EF49D8}
```
However updates to the app will probably restore this. Adding the following `REG_SZ` key
`"{776DBC8D-7347-478C-8D71-791E12EF49D8}"="Skype"`
to
`[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked]`
is probably a good idea. Restart Windows to take effect.
[](https://i.stack.imgur.com/FCk0d.png)
---
|
59,729,547 |
I have a series of bat files that I want to run in parallel, for example:
```
start program1_1.bat
start program1_2.bat
start program1_3.bat
wait until program1 finished then
start program2_1.bat
start program2_2.bat
start program2_3.bat
wait until program2 finished then
...
```
So far, what I've tried is this [function](https://stackoverflow.com/questions/41584281/how-to-run-three-batch-files-in-parallel-and-run-another-three-batch-files-after):
```
:waitForFinish
set counter=0
for /f %%i in ('tasklist /NH /FI "Imagename eq cmd.exe') do set /a counter=counter+1
if counter GTR 2 Goto waitForFinish
```
But it just launched the first 3 bat files and stop... How can I solve this problem?
Thanks,
EDIT: This is the content of `program1_i.bat` file:
```
program1.exe input_i.txt
```
It will run program1.exe for each input file. The same for `program2_i.bat`.
|
2020/01/14
|
[
"https://Stackoverflow.com/questions/59729547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11369131/"
] |
Your question is a little vague on the exact expected results.
I am however assuming that you want to do something like this.
```
start /wait program1_1.bat | start /wait program1_2.bat | start /wait program1_3.bat
start /wait program2_1.bat | start /wait program2_2.bat | start /wait program2_3.bat
```
The single pipe separators let's us launch the first three commands in parallel and only start the next three commands once the first three has all completed, simply because the next 3 commands are in the next `batch` line the use of `start /wait`
|
208,002 |
I'm new to LaTeX and I have a question about the LaTeX code (which I have to do for my essay), for the inner product of vectors on an exponential\*,how can I fix the problem that the two vektors k and x have their vectors taht are not parallel . *The vector of k is much higher that the vector in x* ( I use the command \overrightarrow for the vector, and I have also use the \displaystyle for a sum that exist in the same equation).
How can I fix that?
Thanks cheers :)
|
2014/10/19
|
[
"https://tex.stackexchange.com/questions/208002",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/64448/"
] |
Actually, X11 is not erased but moved to /opt/X11.
So, the simplest solution would probably be to manually add the symbolic link from /usr/X11 to /opt/X11:
```
sudo ln -s /opt/X11 /usr/X11
```
|
14,580,615 |
I have installed Drush-5.4-2012-06-04-Installer-v1.0.18.msi in the location C:\ProgramData\Drush by default. I run the program and moved to drupal working directory.
When I type drush it is showing "drush is not recognized as an internal or external command " error. Do I need to configure anything before run? Please help.
|
2013/01/29
|
[
"https://Stackoverflow.com/questions/14580615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1679480/"
] |
You need to set the path variable :
* right click on **computer**
* go to **properties**
* click **advanced system settings** then
* click on **environment variable**, then
* find the variable **path**
* and edit it
add this to end of the variable value **C:ProgramData\Propeople\Drush** and restart the drush, It should work.
|
46,598,234 |
i'm new to java and am trying to return the value of commission to be printed out in the last line. but i keep getting the incompatible types: unexpected return value error.
```
import java.util.Scanner;
public class retail {
public static void main (String[] args){
char code;
double commission;
String enumber;
double retail_price=0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter employee number: ");
enumber= scan.nextLine();
System.out.println("Enter retail price: ");
retail_price= scan.nextDouble();
System.out.println("Enter code:");
code=scan.next().charAt(0);
if (code == 'A'){ commission = (retail_price/100)*6;}
else if (code == 'a') {commission = (retail_price/100)*6;}
else if (code == 'B') {commission = (retail_price/100)*8;}
else if (code == 'b') {commission = (retail_price/100)*8;}
else if (code == 'C') {commission = (retail_price/100)*10;}
else if (code == 'c') {commission = (retail_price/100)*10;}
else{System.out.println("Invalid code");}
return commission;
System.out.println("Employee number: "+enumber);
System.out.println("Retail price: "+retail_price);
System.out.println("Commission: "+commission);
}
}
```
|
2017/10/06
|
[
"https://Stackoverflow.com/questions/46598234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8730148/"
] |
Extending your code:
```
from datetime import datetime, date,timedelta
from pytz import timezone
tz1 = timezone('utc')
tz2 = timezone('Asia/Kolkata')
tz3 = timezone('America/Los_Angeles')
dt1 = datetime.now(tz=tz1)
dt2 = datetime.now(tz=tz2)
print(dt1)
print(dt2)
start_of_week = dt1+timedelta(days=0-dt1.weekday())
end_of_week = dt1+timedelta(days=6-dt1.weekday())
print(start_of_week)
print(end_of_week)
```
|
211,310 |
We have a message queue on our queue server to which no-one has access. During a test we removed all the users from the queue. Now no-one can access it at all.
|
2010/11/16
|
[
"https://superuser.com/questions/211310",
"https://superuser.com",
"https://superuser.com/users/25713/"
] |
There is a file in the system32\msmq\storage\lqs directory that contains the configuration for this queue. Find the file that contains the name of the queue you are talking about. If you delete the file and restart MSMQ, the queue has gone. Obviously don't delete any of the other files!
|
71,116,939 |
currently, I am struggling with how the MongoDB document system works. I want to fetch array elements with an auto-generated id but how to fetch that specific data that I don't know.
my current schema is
```
const ItemPricesSchema = new mongoose.Schema({
_id : {
type: String
},
ItemsPrices: {
type: [{
barcode : {
type: String
},
itemName : {
type: String
},
price : {
type: String
}
}]
}
});
```
current data is stored in this way
```
{
"_id": "[email protected]",
"ItemsPrices": [
{
"barcode": "345345",
"itemName": "maggie",
"price": "45",
"_id": "620a971e11120abbde5f4c3a"
},
{
"barcode": "356345",
"itemName": "monster",
"price": "70",
"_id": "620a971e11120abbde5f4c3b"
}
],
"__v": 0
}
```
what I want to achieve is that I want to find array elements through ids
if I want a specific array element with id "620a971e11120abbde5f4c3b" what should I do??
I have tried $unwind , $in, $match...
the result should be like
```
{
"_id": "[email protected]",
"ItemsPrices": [
{
"barcode": "356345",
"itemName": "monster",
"price": "70",
"_id": "620a971e11120abbde5f4c3b"
}
],
"__v": 0
}
```
what I tried is like this from the answer
```
router.get('/filter/:id', async (req, res) => {
try {
const item = await ItemPricesSchema.aggregate([
{$project: {
"ItemsPrices": {
$filter: {
input: "$ItemsPrices",
as: "item",
cond: {
$eq: [
"$$item._id",
"620a8dd1c88ae3eb88a8107a"
]
}
}
}
}
}
])
res.json(item);
console.log(item);
} catch (error) {
res.status(500).json({message: error.message});
}
})
```
and returns something like this (Empty arrays)
```
[
{
"_id": "[email protected]",
"ItemsPrices": []
},
{
"_id": "[email protected]",
"ItemsPrices: []
},
{
"_id": "[email protected]",
"ItemsPrices": []
},
{
"_id": "[email protected]",
"ItemsPrices": []
}
]
```
but If I search for price $$item.price
```
cond: {
$eq: [
"$$item.price",
"30"
]
}
```
it returns the perfect output
```
[
{
"_id": "[email protected]",
"ItemsPrices": []
},
{
"_id": "[email protected]",
"ItemsPrices: []
},
{
"_id": "[email protected]",
"ItemsPrices": []
},
{
"_id": "[email protected]",
"ItemsPrices": [
{
"barcode":"234456345",
"price":"30",
"itemName":"monster",
"_id":"620a8dd1c88ae3eb88a8107a"
}
]
}
]
```
|
2022/02/14
|
[
"https://Stackoverflow.com/questions/71116939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13931640/"
] |
You can do an aggregation with `$project` and apply `$filter` on the array part. In mongoose you can apply the aggregation query in a more or less similar way <https://mongoosejs.com/docs/api/aggregate.html>
```js
db.collection.aggregate([
{
$project: {
"ItemsPrices": {
$filter: {
input: "$ItemsPrices",
as: "item",
cond: {
$eq: [
"$$item._id",
mongoose.Types.ObjectId("620a971e11120abbde5f4c3b")
]
}
}
},
"__v": 1 //when projecting 1 means in the final result this field appears
}
}
])
```
[more examples](https://stackoverflow.com/questions/15117030/how-to-filter-array-in-subdocument-with-mongodb)
[demo](https://mongoplayground.net/p/ZUinQ3EMgpc)
|
174,835 |
I am playing Minecraft with the [Oceancraft](http://www.minecraftmods.com/oceancraft/) mod installed. Among other things, this adds quicksand, which if you step in you begin to sink and slowly suffocate.
Once you have stepped in quicksand - is there any way to avoid your untimely demise? I've tried walking out of it but when I get to the last block I can't jump over it. I've also tried digging up the neighboring blocks and the offending quicksand itself but I still drown.
Is there any way to avoid drowning in quicksand if you haven't managed to avoid it?
|
2014/07/04
|
[
"https://gaming.stackexchange.com/questions/174835",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/16659/"
] |
If I meet Quicksand on any map, it mostly appears like

So if you stepped in it you can easily dig the 2 neighboring blocks in a depth of 2, kinda like this.

And the you can easily walk off the quicksand the direction you dug.
The most important part is the depth of two blocks to dig, if you just dig one block, it's too high to walk off.
|
20,330,154 |
I need to display in excel a matrix, but my last column display special caracteres in excel.
I want to convert this last column in number or String, to be display correctly.
My matrix
```
data
= 'A1' [48]
'A2' [44]
'A3' [45]
'A4' [46]
```
This last column (with brackets) seems to be double.
I want something as this :
```
data
= 'A1' 48
'A2' 44
'A3' 45
'A4' 46
```
|
2013/12/02
|
[
"https://Stackoverflow.com/questions/20330154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/359706/"
] |
Try like this:
```
Class<String[]> cls = String[].class;
```
|
18,226,346 |
i need to make a div position absolute and make it in center but i used does not make it happen. i have gone crazy trying to make it to the center.
i have tried using left and right value to 0. it should have made the div to the center automatically.
need to figure out what went wrong?
help please!
here is the code that i have tried and stuck
```
.slider-wrap {
width: 1000px;
height: 500px;
left: 0;
right: 0;
top: 100px;
background: #096;
z-index: 99;
margin: 0 auto;
}
```
|
2013/08/14
|
[
"https://Stackoverflow.com/questions/18226346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2427498/"
] |
You forgot to set the position to absolute
```
.slider-wrap {
width: 1000px;
height: 500px;
left:0; right:0;
top:100px;
background:#096;
z-index:99;
margin:0px auto;
}
```
Add `position:absolute;`
```
.slider-wrap {
position:absolute;
width: 1000px;
height: 500px;
left:0; right:0;
top:100px;
background:#096;
z-index:99;
margin:0px auto;
}
```
|
71,783,339 |
I'm trying to replace symbols from object in python, I used
```
df_summary.replace('\(|\)!,"-', '', regex=True)
```
[](https://i.stack.imgur.com/vozsS.jpg)
but it didn't change anything.
|
2022/04/07
|
[
"https://Stackoverflow.com/questions/71783339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18737194/"
] |
The replace function is not *in place*. This means that your dataframe will be unchanged, and the result is returned as the return value of the replac function.
You can the the inplace parameter of replace:
```
df_summary.replace('\(|\)!,"-', '', regex=True, inplace=True)
```
Most of the pandas functions are note in place and require if needed either the inplace argument, or the assignement of the result to a new dataframe.
|
14,870,665 |
I'm developing a web solution to run in the clients existing portal. In this portal they already handle F1 differently from the default behaviour.
I would like to add a "Help" icon to my solution that when clicked simulates pressing F1. Of course I would like the solution to be as cross browser compatible as possible but the final version will run solely in Internet Explorer 8 (and actually with the compatibility button pressed - GRRRR).
I have found numerous functions to handle pressing F1 but non that describes how to simulate pressing F1 programmatically.
I'm using jQuery 1.8.2 if that helps...
Thanks in advance
|
2013/02/14
|
[
"https://Stackoverflow.com/questions/14870665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1480182/"
] |
You can use this to catch the event in IE:
* [Internet Explorer or any Browser F1 keypress displays your own help](https://stackoverflow.com/questions/3405412/internet-explorer-or-any-browser-f1-keypress-displays-your-own-help)
and use these to fire the event:
* [Is it possible to simulate key press events programmatically?](https://stackoverflow.com/questions/596481/simulate-javascript-key-events)
* <http://openwritings.net/public/javascript/simulate-pressing-key>
|
13,647 |
I am attempting to complete some *simple* homework examples my Russian teacher has given me. (I am learning Russian in my free time, whilst I work full-time)
The example given in my textbook is:
>
> Given: Наша квартира была приватизирована пять лет назад.
>
>
> Desired: *Нашу квартиру приватизировали* пять лет назад.
>
>
>
I require the following clarifications:
1. Is my assumption that the sentence is going from the *active voice* in the *given* sentence, to the *passive voice* in the *desired* sentence, correct?
2. What part of speech is the word *«приватизирована»*? (My usual search source, [Wiktionary](https://wiktionary.org) is failing me.)
3. What is happening to the above mentioned word when it moves from the *given* sentence to the *desired* sentence?
4. Why does the above mentioned word decline into the plural past tense form, whereas in the first sentence *«быть»* is in its feminine form?
5. How does it happen? What topic or topics must I read, to elaborate this topic further?
6. Are there any rules regarding this?
|
2016/12/09
|
[
"https://russian.stackexchange.com/questions/13647",
"https://russian.stackexchange.com",
"https://russian.stackexchange.com/users/8075/"
] |
>
> Наша квартира *была приватизирована* пять лет назад.
>
>
>
The sentence is in the **passive voice** in the past formed with *быть* which agrees with the subject наша квартира in gender(feminine ) = была + приватизирована (past passive participle, short form) also agreeing in gender with the subject.The topic is *страдательный залог*.
>
> Нашу квартиру приватизировали пять лет назад.
>
>
>
The sentence is in the **active voice**, impersonal, past tense,formed with the verb which agrees with the "dummy" **they** (приватизировали), which is left out. The object is нашу квартиру (accusative sing).The topic is *безличные предложения*.
Both sentences mean the same and have a "hidden" agent.
|
6,402,339 |
I would like to implement a robust IPC solution between a single JVM applet and a C++ application running on the same machine. What is the best approach for doing so?
Any suggestions will be greatly appreciated! Thanks!
|
2011/06/19
|
[
"https://Stackoverflow.com/questions/6402339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/805320/"
] |
sockets are about your best (only reasonable?) choice. although if you are running an applet, you will have to deal with access permissions issues (signing the applet will probably solve these).
|
35,815,261 |
Hybrid apps are obviously a bit new, so it's hard to find good information on this. I know that I need to allow cross origin resource sharing on my server side pages, but this clearly adds a security flaw. On a phonegap/cordova app, I only have client-side control with ajax calls to my server-side page. This means that anyone can access my php pages. This means that anyone can essentially mimic my app by accessing all my data like account info, etc. My question is how can I confirm that only my app is accessing these pages? Please provide specific coding examples.
|
2016/03/05
|
[
"https://Stackoverflow.com/questions/35815261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3822526/"
] |
I answered your question, and many others like it, in this blog post: [Client authenticity is not the server's problem](https://paragonie.com/blog/2016/03/client-authenticity-is-not-server-s-problem).
>
> One of the most basic rules of application security is **input validation**. The reason this rule is so fundamental is because your server only has control (and visibility) over the software running on itself. Every other device on the Internet is a black box that you can communicate with over networking protocols. You can't see what it's doing, you only see the messages that it sends.
>
>
>
...
>
> The server should remain agnostic to the client.
>
>
> The software on the client and the software on the server should have a mutual distrust towards each other. Any messages that the server receives should be validated for correctness and handled with care. Data should never be mixed with code if you can help it.
>
>
>
...
>
> The take-away is: Instead of trying to control your users, focus on making their misbehavior inconsequential to the stability and integrity of your server.
>
>
>
|
918,667 |
I cannot connect to my server via ssh using my computer, but I can connect to this server via my cell phone using termius app. I have checked `/etc/hosts.allow` and `/etc/hosts.deny` and my iptables, and I have alse searched google, it seems no answer fits this problem. I don't know how to solve it , here is `ssh -v 183.17.228.80` output
```
debug1: Connecting to 183.17.228.80 [183.17.228.80] port 22.
debug1: Connection established.=======================
debug1: permanently_set_uid: 0/0
debug1: SELinux support disabled
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_rsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_rsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_dsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_dsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_ecdsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_ecdsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_ed25519 type -1
debug1: key_load_public: No such file or directory
debug1: identity file /root/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.2p2 Ubuntu-4ubuntu2.2
ssh_exchange_identification: read: Connection reset by peer
```
I can ping this server, here is telnet
```
telnet 183.17.228.29 22
Trying 183.17.228.29...
Connected to 183.17.228.29.
Escape character is '^]'.
Connection closed by foreign host.
```
|
2017/05/25
|
[
"https://askubuntu.com/questions/918667",
"https://askubuntu.com",
"https://askubuntu.com/users/673328/"
] |
Just **reboot your server** which you want to ssh. It worked for me, previously I was facing the same issue.
|
39,529,824 |
We have a requirement, that we want to select k random rows from a database.
So, our intial thought was going like this :-
```
table.objects.filter(..).order_by('?')[:k]
```
but then we read over the internet that this is highly inefficient solution so we came up with this (not so innovative):-
```
random.sample(table.objects.filter(..), k)
```
But this seems to be more slower than previous.
So, we want to know what is correct approach for selection exactly *k* rows from the database, which in our case is postgres.
|
2016/09/16
|
[
"https://Stackoverflow.com/questions/39529824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3596887/"
] |
You can do it like this:
```
<tr ng-repeat="(key, value) in data.Test">
<td> {{value.Testing.static.name}} </td>
</tr>
```
<https://jsfiddle.net/nh5zxoka/3/>
|
29,458,096 |
I'm using Bootstrap v3.3.4.
I want to implement a footer in my web page. But, it doesn't work.
The code of my page:
```
<!DOCTYPE html>
<html>
<head>
<title>Web site</title>
<link href='css/main.css' rel='stylesheet'>
<!-- Library -->
<link rel="stylesheet" href="Bootstrap/bootstrap.min.css">
<link rel="stylesheet" href="Bootstrap/bootstrap-theme.min.css">
<script src="Script/jquery.min.js"></script>
<script src="Script/bootstrap.min.js"></script>
</head>
<body>
<div class='container'>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12 text-center">
<h2><b> My first web site!</b></h2>
<div style="padding-bottom: 10px;"></div>
</div>
</div>
<div class="row well">
<div class="col-md-6 col-sm-6 col-xs-6">
<p>This is my first web site, I'm trying to learn Bootstrap.</p>
<button type='button'>Take the Tour</button>
<button type='button'>Book Tickets Now</button>
</div>
<div class="col-md-6 col-sm-6 col-xs-6">
<img src="Images/universe.jpg" alt="Blasting Off"/>
</div>
</div>
<div class="row well">
<div class="col-md-4 col-sm-4 col-xs-4">
<h3><b>I am 20 years old!</b></h3>
<p>I was born in 1994.</p>
</div>
<div class="col-md-4 col-sm-4 col-xs-4">
<h3><b>I live in Rome!</b></h3>
<p>Rome is a beautiful city.</p>
</div>
<div class="col-md-4 col-sm-4 col-xs-4">
<h3><b>I am a programmer!</b></h3>
<p>I am a front-end developer, I started to do this work recently.</p>
</div>
</div>
</div>
<div class="footer">
<div class="container">
<p class="text-muted">Place sticky footer content here.</p>
</div>
</div>
</body>
```
NetBeans says **Class footer not found**
I have included **bootstrap.min.css** and **bootstrap-theme.min.css**
If I open the page with a browser (Chrome, im my case) the footer doesn't work..
Why? Thanks.
|
2015/04/05
|
[
"https://Stackoverflow.com/questions/29458096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4559577/"
] |
I don't know exactly what you are asking for but this may help.
If you want the footer to be fixed at bottom, then try adding this to your CSS code.
**CSS:**
```
.footer {
position: fixed;
bottom: 0;
width: 100%;
height: 60px;
background-color: #f5f5f5;
}
```
I hope this will help you?
|
532,879 |
$$\int\frac{\mathrm dx}{\sqrt x \cos(1-\sqrt x)}$$
please provide a hint about the substitution. The website gives a long answer [See here.](http://www.wolframalpha.com/input/?i=int%201/%28x%5E%281/2%29cos%281-x%5E%281/2%29%29)
Wondering if there is a simplification.
|
2013/10/20
|
[
"https://math.stackexchange.com/questions/532879",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/100812/"
] |
**Hint**:
$$u = 1 - \sqrt{x} \implies du = -\frac{1}{2 \sqrt{x}} dx$$
so the integral can be written as
$$\int \frac{1}{\cos(1 - \sqrt{x})} \frac{dx}{\sqrt{x}} = \int \frac{1}{\cos{u}} \frac{du}{-2} = -\frac{1}{2} \int \sec{u} du$$
|
53,288,831 |
Ruby's json library defaults to converting Time objects to Strings
```
require 'json'
Time.at(1000).utc.to_json # => "\"1970-01-01 00:16:40 UTC\""
```
The problem with this is that we lose precision. I'd like to\_json to produce a float instead.
I also know there are some workarounds using `oj` or requiring `json/add/time`, but both of these add excess data to the output and aren't the most portable.
A straightforward approach is to monkey patch Time, although I'm not fond of doing that, especially to core classes
```
class Time
def to_json(*a)
self.to_f.to_json(*a)
end
end
```
Are there any better approaches?
|
2018/11/13
|
[
"https://Stackoverflow.com/questions/53288831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1449987/"
] |
>
> *A straightforward approach is to monkey patch Time, although I'm not fond of doing that, especially to core classes*
>
>
>
There's no JSON format for dates, as far as JSON cares they're just strings. Most languages understand [ISO 8601](https://github.com/ruby/ruby/blob/4444025d16ae1a586eee6a0ac9bdd09e33833f3c/ext/json/lib/json/add/time.rb), and that's what `Time#to_json` produces. So long as `Time#to_json` continues to produce an ISO 8601 datetime you'll remain backwards compatible.
```
require 'json'
require 'time' # for Time#iso8601 and Time.parse
class Time
def to_json
return self.iso8601(6).to_json
end
end
time = Time.at(1000.123456)
puts "Before: #{time.iso8601(6)}"
json_time = Time.at(1000.123456).to_json
puts "As JSON: #{json_time}"
# Demonstrate round tripping.
puts "Round trip: #{Time.parse(JSON.parse(json_time)).iso8601(6)}"
```
```
Before: 1969-12-31T16:16:40.123456-08:00
As JSON: "1969-12-31T16:16:40.123456-08:00"
Round trip: 1969-12-31T16:16:40.123456-08:00
```
---
If you're not comfortable with monkey patching globally, you can monkey patch in isolation by implementing `around`.
```
class Time
require 'time'
require 'json'
def precise_to_json(*args)
return iso8601(6).to_json(*args)
end
alias_method :original_to_json, :to_json
end
module PreciseJson
def self.around
# Swap in our precise_to_json as Time#to_json
Time.class_eval {
alias_method :to_json, :precise_to_json
}
# This block will use Time#precise_to_json as Time#to_json
yield
# Always put the original Time#to_json back.
ensure
Time.class_eval {
alias_method :to_json, :original_to_json
}
end
end
obj = {
time: Time.at(1000.123456),
string: "Basset Hounds Got Long Ears"
}
puts "Before: #{obj.to_json}"
PreciseJson.around {
puts "Around: #{obj.to_json}"
}
puts "After: #{obj.to_json}"
begin
PreciseJson.around {
raise Exception
}
rescue Exception
end
puts "After exception: #{obj.to_json}"
```
```
Before: {"time":"1969-12-31 16:16:40 -0800","string":"Basset Hounds Got Long Ears"}
Around: {"time":"1969-12-31T16:16:40.123456-08:00","string":"Basset Hounds Got Long Ears"}
After: {"time":"1969-12-31 16:16:40 -0800","string":"Basset Hounds Got Long Ears"}
After exception: {"time":"1969-12-31 16:16:40 -0800","string":"Basset Hounds Got Long Ears"}
```
|
39,379,637 |
I would like to use multiple `geom_smooth` layers in a single ggplot2 chart. When I try to do that, the color scheme gets screwed up. Here is an example demonstrating what is happening.
We construct a simple dataframe we want to visualize.
```
df = data.frame(x = c("a", "b", "c"),
y1 = seq(1, 3),
y1_upr = seq(2, 4),
y1_lwr = seq(0, 2),
y2 = seq(2, 4),
y2_upr = seq(2.5, 4.5),
y2_lwr = seq(1.5, 3.5))
```
We can visualize y1 and y2 easily.
```
plot_obj = ggplot(data = df, aes(x = x, group = 1)) +
geom_line(aes(y = y1, colour = "y1")) +
geom_line(aes(y = y2, colour = "y2")) +
scale_colour_manual("", breaks = c("y1", "y2"), values = c("blue", "red"))
plot_obj
```
[](https://i.stack.imgur.com/s1og5.png)
If we add one `geom_smooth`, the behavior is still as expected.
```
plot_obj +
geom_smooth(aes(y = y1, ymin = y1_lwr, ymax = y1_upr), stat="identity", fill="blue", alpha=0.2)
```
[](https://i.stack.imgur.com/vzztE.png)
Lastly, we add the second `geom_smooth` layer.
```
plot_obj +
geom_smooth(aes(y = y1, ymin = y1_lwr, ymax = y1_upr), stat="identity", fill="blue", alpha=0.2) +
geom_smooth(aes(y = y2, ymin = y2_lwr, ymax = y2_upr), stat="identity", fill="red", alpha=0.2)
```
[](https://i.stack.imgur.com/cxFhg.png)
Notice that the top line is no longer red in the last chart. Why is this happening and how can it be fixed? Thank you!
|
2016/09/07
|
[
"https://Stackoverflow.com/questions/39379637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2252852/"
] |
Certainly reshaping your dataset will make things easier, and is the recommended approach. However, if you want to keep using separate layers:
As you haven't mapped a `color` for `geom_smooth`, it uses the default color of blue for the smoothed lines it drew. If you want just the ribbon, use `geom_ribbon` instead.
```
ggplot(data = df, aes(x = x, group = 1)) +
geom_line(aes(y = y1, colour = "y1")) +
geom_line(aes(y = y2, colour = "y2")) +
scale_colour_manual("", breaks = c("y1", "y2"), values = c("blue", "red")) +
geom_ribbon(aes(ymin = y1_lwr, ymax = y1_upr), stat="identity", fill="blue", alpha=0.2) +
geom_ribbon(aes(ymin = y2_lwr, ymax = y2_upr), stat="identity", fill="red", alpha=0.2)
```
[](https://i.stack.imgur.com/7cOAy.png)
Otherwise you'll need to map your colors for each smooth layer within `aes` or set them manually to red and blue or NA outside of `aes`.
```
ggplot(data = df, aes(x = x, group = 1)) +
geom_line(aes(y = y1, colour = "y1")) +
geom_line(aes(y = y2, colour = "y2")) +
scale_colour_manual("", breaks = c("y1", "y2"), values = c("blue", "red")) +
geom_smooth(aes(y = y1, ymin = y1_lwr, ymax = y1_upr, colour = "y1"),
stat="identity", fill="blue", alpha=0.2) +
geom_smooth(aes(y = y2, ymin = y2_lwr, ymax = y2_upr, colour = "y2"),
stat="identity", fill="red", alpha=0.2)
```
[](https://i.stack.imgur.com/G6qgf.png)
|
44,392,223 |
I am trying to perform two processes using bean, my problem is that I can not find the way these processes are performed continuously. The first process is to send an object and the second process is the response of the object.
```
@Component
public class Proceso implements InitializingBean{
private static final String XML_SCHEMA_LOCATION = "/proceso/model/schema/proceso.xsd";
private Envio envio;
private Respuesta respuesta;
public void Proceso_envio(Proceso proceso, OutputStream outputstream) throws JAXBException{
envio.marshal(proceso, outputstream);}
public void Proceso_respuesta(InputStream inputstream) throws JAXBException, FileNotFoundException{
Object obj = unmarshaller.unmarshal(inputStream);
return (Proceso_respuesta) obj;}
@Override
public void afterPropertiesSet() throws Exception{
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(getClass().getResource(XML_SCHEMA_LOCATION));
JAXBContext jc = JAXBContext.newInstance(Envio.class, Respuesta.class);
this.marshaller = jc.createMarshaller();
this.marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
this.marshaller.setProperty(Marshaller.JAXB_ENCODING, StandardCharsets.UTF_8.displayName());
this.marshaller.setSchema(schema);
this.unmarshaller = jc.createUnmarshaller();
this.unmarshaller.setSchema(schema);
}
```
I imagine that with the code my question becomes clearer.
|
2017/06/06
|
[
"https://Stackoverflow.com/questions/44392223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7708486/"
] |
```
$(function(myFunction()){
if (document.getElementById("study-phase").value == "pri") {
document.getElementById("a").style.display = "block";
}});
```
give error
```
Uncaught SyntaxError: Unexpected token (
```
apart if you revised your code as below it works, as it is vanillaJs you dont need jquery
```js
function myFunction() {
if (document.getElementById("study-phase").value == "pri") {
document.getElementById("a").style.display = "block";
}
};
```
```html
<select name="study-phase" onchange="myFunction()" id="study-phase" class="sp-input">
<option value=""></option>
<option id="pri" value="pri">Primary</option>
<option id="pre" value="pre">Prep</option>
<option id="sec" value="sec">Secondary</option>
</select>
<select name="study-year" id="study-year" class="sp-input">
<option value=""></option>
<option id="a" value="aa">Grade 1</option>
<option id="b" value="">Grade 2</option>
<option id="c" value="">Grade 3</option>
<option id="d" value="">Grade 4</option>
<option id="e" value="">Grade 5</option>
<option id="f" value="">Grade 6</option>
<option id="g" value="">Grade 7</option>
<option id="h" value="">Grade 8</option>
<option id="i" value="">Grade 9</option>
<option id="j" value="">Grade 10</option>
</select>
<style type="text/css">
#a,
#b,
#c,
#d,
#f,
#g,
#h,
#j,
#k,
#e,
#i {
display: none;
}
</style>
```
|
54,531,287 |
I would like to be able to push each **|** into an array
Here is my function:
```
def pyramide(lines):
k = 1 * lines - 1
for i in range(0, lines):
for j in range(0, k):
print(end=" ")
k = k - 1
for j in range(0, i+1):
print("|", end=" ")
print("\r")
lines = 5
pyramide(lines)
```
What I tried:
```
for j in range(0, i+1):
each = print("|", end=" ")
array.push(each)
print("\r")
```
But it doesn't seem to add it into an array, my question is how I can push each **|** into an array so I can delete it later
Edit:
expected input:
```
pyramide(5)
```
expected output:
```
|
| |
| | |
| | | |
```
Then I should be able to remove a **|** from each line by
```
stickDelete(3, 2) # first paramater is the line, second is how much | would like to delete
|
| |
| | | |
```
|
2019/02/05
|
[
"https://Stackoverflow.com/questions/54531287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11013215/"
] |
Split it in 2:
* a list of arrays holding the '|' 's (or other character)
* a function to print the 'pyramid' arrays
Wrapped in a class you get something like:
```
class CPyramide(object):
def __init__(self, lines):
self.pir = []
# construct the array of arrays for the pyramid
# each one holding the n-bars for a row
for i in range(lines):
# construct the array using a listcomprehension
bars = ['|' for j in range(i+1)]
self.pir.append(bars)
def __str__(self):
"""print the pyramid"""
o = ""
# loop through all the rows that represent the pyramid
# and use enumerate to have them numerical from 0 to len(pir)
for i, L in enumerate(self.pir):
# spaces decrease with increase of rows ...
spaces = (len(self.pir) - i) * ' '
# so, a line starts with the n-spaces
o += spaces
# appended with the bars of that row all in L
o += ' '.join(L)
# and a newline, which is definitely something else
# then '\r' (on unix \r will show only one line when
# using '\r'!)
o += "\n"
return o
def stickDelete(self, line, n):
self.pir[line] = self.pir[line][n:]
print("===============")
cpir = CPyramide(5)
print(cpir)
cpir.stickDelete(3, 2)
print(cpir)
```
Output:
```
===============
|
| |
| | |
| | | |
| | | | |
|
| |
| | |
| |
| | | | |
```
|
31,119,709 |
I am trying to develop server-side using loopback with database connector.
However, I am quite confused with installing loopback on AWS.
[reference for installing loopback on AWS](http://docs.strongloop.com/display/SL/Amazon+EC2)
This website mentioned that only loopback of version 2.0 could be installed.
Yet, when I browse through loopback website, <https://strongloop.com/strongblog/how-to-setup-push-notifications-private-mbaas-amazon-aws-part-1/>, this website shows that it seems possible to install loopback of version higher than 2.0 on AWS. Since there are some features only available after version 2.1x, it would be nice if AWS allows installation of loopback of version higher than 2.0. Could anyone help me solve the problem? BTW, I am only using free tier of AWS and do not intend to pay at this moment.
|
2015/06/29
|
[
"https://Stackoverflow.com/questions/31119709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5009672/"
] |
Even if you install the image that comes preconfigured with Loopback 2, you should be able to upgrade to newer versions using npm as you normally would (`sudo npm install -g strongloop` and the like). Imagine if there's a security issue that you'd need that wasn't backported for whatever reason...Loopback is just files and the image is just linux. You have free reign to update/upgrade whatever you need.
My recommendation would be to start out with a minimal Ubuntu image and install everything with npm. You'll understand the ecosystem better and won't be surprised by something you don't remember installing specifically.
One caveat that a bunch of preconfigured images have is they are only available on older instance types (m1 for instance--*pun not intended ;)*). They are slower and more expensive than newer instances.
|
6,478,496 |
I have a google site search
<http://www.google.com/cse/manage/create>
Which gives me the following working code:
```
<div id="cse" style="width: 100%;">Loading</div>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load('search', '1', { language: 'en' });
google.setOnLoadCallback(function () {
var customSearchControl = new google.search.CustomSearchControl('013080392637799242034:ichqh_hal4w');
customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
customSearchControl.draw('cse');
}, true);
</script>
```
On some of my pages, I have a search box. Can I make the text entered in that search box, post to this site search script and load?
For example:
* User is on Home.html
* They enter text in a search box
* Redirects them to Search.html
* Search.html takes the text they entered and does a search with it, without them needing to retype it in the empty box
At the moment I have:
```
// Temporary measure
SearchBox.click(function (event) {
SearchBox.attr('disabled', 'disabled');
SearchBox.css("background", "#efefef");
window.location.replace(Domainroot + "/search");
});
```
Which is less than ideal, but works OK. When a user clicks the search box it redirects them to the search page to save them double entering the query.
Thanks for any help!
|
2011/06/25
|
[
"https://Stackoverflow.com/questions/6478496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/356635/"
] |
Have a look at <http://code.google.com/apis/customsearch/docs/js/cselement-reference.html#_methods-el>
It looks like the control you create comes with methods. It seems you are looking for the .execute(query) method.
|
399,768 |
Here is the MWE:
```
\documentclass{article}
\usepackage[shortlabels]{enumitem}
\begin{document}
\begin{enumerate}[label={Q.\arabic*.}]
\item This is 1
\item This is 2
\item This is 3A
\item This is 3B
\item This is 4
\end{enumerate}
\end{document}
```
How do I get labels to match the items details? So, it should Q.1., Q.2., Q.3.A, Q.3.B, Q.4, etc. instead of Q.1., Q.2., ..., Q.5., etc.?
|
2017/11/05
|
[
"https://tex.stackexchange.com/questions/399768",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/18495/"
] |
If you don't mind doing the special cases semi-manually, you could do the following:
```
\documentclass{article}
\usepackage[shortlabels]{enumitem}
\newlength{\aw}
\settowidth{\aw}{A}
\begin{document}
\begin{enumerate}[label={Q.\arabic*.\hspace*{\aw}}]
\item This is 1
\item This is 2
\addtocounter{enumi}{1}
\item[Q.\arabic{enumi}A.] This is 3A
\item[Q.\arabic{enumi}B.] This is 3B
\item This is 4
\item This is 5
\end{enumerate}
\end{document}
```
[](https://i.stack.imgur.com/ZFh5t.png)
|
31,243,845 |
I just created a basic html page layout and im currently trying to get it work on wordpress, created the header.php, index.php, footer.php, called them with php, well i followed this guide: <https://thethemefoundry.com/blog/html-wordpress/>
Did all thats on there, after i uploaded the theme and actived it i get this:

No divs, no images, just the text
I will include my code bellow of the original html/ css and the php files:
```css
/*
Theme Name: SSK theme
Theme URI:
Description: Tema para o site da ssk
Version: 1.0
Author: DA
Author URI: www
*/
body, div, h1, h2, h3, h4, h5, h6, p, ul, ol, li, dl, dt, dd, img, form, fieldset, input, blockquote {
margin: 0; padding: 0; border: 0;
}
body {
font-family: Helvetica, Arial, Sans-Serif;
line-height: 24px;
background: #eee url(images/body-bg.jpg) center top no-repeat;
width:100%;
height: 100%;
}
#container {
width: 80%;
margin: 0 auto;
height:1100px;
margin-top: -75px;
}
#container p {
margin-bottom: -50px;
color: #0066FF;
font-size: 25px;
}
#languages {
background-color: red;
height:22px;
width: 200px;
position: absolute;
top:60px; right: 125px;
}
#destaques {
margin-top: 75px;
width:100%;
background-color: grey;
}
#main_page_holder {
border-top: 2px solid blue;
position: relative;
margin-top: 110px;
width: 100%;
height: 30%;
}
#home_navigation_link {
margin-left: 1.7%;
margin-right: 1%;
margin-top: 2%;
width: 30%;
height: 35%;
display: inline-block;
background-color: #f2f2f2;
}
#Projetos {
margin-top: 110px;
width: 100%;
height: 20%;
background-color: orange;
}
#projsquare {
border-top: 2px solid blue;
margin-top: -0px;
height: 30%;
}
.squa {
width: 125px;
float:left;
height:125px;
background:magenta;
margin:10px;
margin-top: 90px;
}
#logo2 {
float: right;
width: 30%;
height: 100%;
background-color: red;
}
#logo2 img {
background-repeat: no-repeat;
width: 100%;
height: 30%;
}
.ima {
background-image: url("img/logo.png");
background-repeat: no-repeat;
width:35%;
height:100%;
background-color: blue;
float: left;
-moz-border-radius: 60%;
-webkit-border-radius: 60%;
border-radius: 60%;
border-color:white;
}
.ima img {
width:100%;
height:100%;
-moz-border-radius: 60%;
-webkit-border-radius: 60%;
border-radius: 60%;
border-color:white;
}
.tit {
color: #0066FF;;
float:left;
width:65%;
height:15%;
}
.tito {
width:65%;
height:15%;
background-color: black;
}
#categories {
list-style: none;
position: absolute;
top: 125px;
right: 125px;
font-size: 0;
/* Permalink - use to edit and share this gradient: http://colorzilla.com/gradient-editor/#1b75b1+0,529282+47,71ac4a+100 */
background: rgb(27, 117, 177);
/* Old browsers */
/* IE9 SVG, needs conditional override of 'filter' to 'none' */
background: url(data:image/svg+xml;
base64, PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgdmlld0JveD0iMCAwIDEgMSIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSI+CiAgPGxpbmVhckdyYWRpZW50IGlkPSJncmFkLXVjZ2ctZ2VuZXJhdGVkIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeDE9IjAlIiB5MT0iMCUiIHgyPSIxMDAlIiB5Mj0iMCUiPgogICAgPHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iIzFiNzViMSIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjQ3JSIgc3RvcC1jb2xvcj0iIzUyOTI4MiIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjEwMCUiIHN0b3AtY29sb3I9IiM3MWFjNGEiIHN0b3Atb3BhY2l0eT0iMSIvPgogIDwvbGluZWFyR3JhZGllbnQ+CiAgPHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEiIGhlaWdodD0iMSIgZmlsbD0idXJsKCNncmFkLXVjZ2ctZ2VuZXJhdGVkKSIgLz4KPC9zdmc+);
background: -moz-linear-gradient(left, rgb(27, 117, 177) 0%, rgb(82, 146, 130) 47%, rgb(113, 172, 74) 100%);
/* FF3.6+ */
background: -webkit-gradient(linear, left top, right top, color-stop(0%, rgb(27, 117, 177)), color-stop(47%, rgb(82, 146, 130)), color-stop(100%, rgb(113, 172, 74)));
/* Chrome,Safari4+ */
background: -webkit-linear-gradient(left, rgb(27, 117, 177) 0%, rgb(82, 146, 130) 47%, rgb(113, 172, 74) 100%);
/* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(left, rgb(27, 117, 177) 0%, rgb(82, 146, 130) 47%, rgb(113, 172, 74) 100%);
/* Opera 11.10+ */
background: -ms-linear-gradient(left, rgb(27, 117, 177) 0%, rgb(82, 146, 130) 47%, rgb(113, 172, 74) 100%);
/* IE10+ */
background: linear-gradient(to right, rgb(27, 117, 177) 0%, rgb(82, 146, 130) 47%, rgb(113, 172, 74) 100%);
/* W3C */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#1b75b1', endColorstr='#71ac4a', GradientType=1);
/* IE6-8 */
}
#categories li {
display: inline-block;
vertical-align: top;
position: relative;
}
#categories li a {
font-size: 15px;
color: white;
text-decoration: none;
padding: 6px 22px;
display: block;
}
#categories li:before{
content: '';
width: 1px;
height: 15px;
background: #fff;
position: absolute; top: 0; left: 0;
}
#categories li:first-child:before{
background: none;
}
#header {
overflow: hidden;
padding: 0 0 50px 0;
}
#mllcont {
height:40vh;
background-image: url("img/header.png");
background-repeat: no-repeat;
}
#slidecont {
background-image: url("img/back.jpg");
height:100vh;
background-color: red;
background-size: cover;
background-repeat: no-repeat;
}
#slidecont img {
width: 100%;
position: absolute;
left: 0;
bottom: 0;
}
#squares {
width:100%;
height:250px;
position: relative;
}
#divs p {
position: absolute;
bottom: -100px;
color: #0066FF;
font-size: 25px;
}
#divs div {
height: 300px;
width: 20%;
border: 0px solid red;
margin-left: 2.5%;
margin-right: 2.5%;
float: left; /*Here you can also use display: inline-block instead of float:left*/
background: white;
opacity: 0.7;
}
.circle{
border:1px solid red;
height:20px;
width:20px;
-webkit-border-radius: 40px;
-moz-border-radius: 40px;
border-radius: 40px;
position: relative;
}
#header h1 {
float: left;
}
#content, #footer, #header {
height: 100%;
}
```
```html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Particle</title>
<link href="style.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<!--1 parte-->
<div id="slidecont">
<img src="img/banner.png"/>
<div id="mllcont">
<div id="logo">
</div>
<div id="languages">
</div>
<ul id="categories">
<li><a href="#">Menu1</a></li>
<li><a href="#">Menu2</a></li>
<li><a href="#">Menu3</a></li>
<li><a href="#">Menu4</a></li>
</ul>
</div>
</div>
<!--1 parte-->
<!--2 parte-->
<div id="container">
<div id="squares">
<div id="divs">
<div> <div class="tito"> </div> </div>
<div> <div class="tito"> </div> </div>
<div> <div class="tito"> </div> </div>
<div> <div class="tito"> </div> </div>
<p> Destaques </p>
</div>
</div>
<div id="main_page_holder">
<div id ="destaquetex">
</div>
<div id="home_navigation_link">
<div class="ima"> </div>
<div class="tit"> Nova liderança SKK </div>
</div>
<div id="home_navigation_link">
<div class="ima"> <img src="img/2.jpg"> </div>
<div class="tit"> Descontaminação </div>
</div>
<div id="home_navigation_link">
<div class="ima"> <img src="img/3.jpg"> </div>
<div class="tit"> ISOAIR </div>
</div>
<div id="home_navigation_link">
<div class="ima"> <img src="img/4.jpg"> </div>
<div class="tit"> SmartPower </div>
</div>
<div id="home_navigation_link">
<div class="ima"> <img src="img/4.jpg"> </div>
<div class="tit"> Móveis de congelação </div>
</div>
<div id="home_navigation_link">
<div class="ima"> <img src="img/6.jpg"> </div>
<div class="tit"> Universal R </div>
</div>
</div>
<p> Projetos</p>
<div id="projsquare">
<div class="squa"> </div>
<div class="squa"> </div>
<div class="squa"> </div>
<div class="squa"> </div>
<div id="logo2"> <img src="img/logo.png"> </div>
</div>
</div>
<!--2 parte-->
<!--3 parte-->
<div id="footer">
</div>
<!--3 parte-->
</body>
</html>
```
The files from the theme:
**INDEX.PHP**
```
<?php get_header(); ?>
<div id="container">
<div id="squares">
<div id="divs">
<div> <div class="tito"> </div> </div>
<div> <div class="tito"> </div> </div>
<div> <div class="tito"> </div> </div>
<div> <div class="tito"> </div> </div>
<p> Destaques </p>
</div>
</div>
<div id="main_page_holder">
<?php if ( have_posts() ) : ?>
<?php while ( have_posts() ) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<div class="post-header">
<div class="date"><?php the_time( 'M j y' ); ?></div>
<h2><a href="<?php the_permalink(); ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
<div class="author"><?php the_author(); ?></div>
</div><!--end post header-->
<div class="entry clear">
<?php if ( function_exists( 'add_theme_support' ) ) the_post_thumbnail(); ?>
<?php the_content(); ?>
<?php edit_post_link(); ?>
<?php wp_link_pages(); ?>
</div><!--end entry-->
<div class="post-footer">
<div class="comments"><?php comments_popup_link( 'Leave a Comment', '1 Comment', '% Comments' ); ?></div>
</div><!--end post footer-->
</div><!--end post-->
<?php endwhile; /* rewind or continue if all posts have been fetched */ ?>
<div class="navigation index">
<div class="alignleft"><?php next_posts_link( 'Older Entries' ); ?></div>
<div class="alignright"><?php previous_posts_link( 'Newer Entries' ); ?></div>
</div><!--end navigation-->
<?php else : ?>
<?php endif; ?>
<div id ="destaquetex">
</div>
<div id="home_navigation_link">
<div class="ima"> </div>
<div class="tit"> Nova liderança SKK </div>
</div>
<div id="home_navigation_link">
<div class="ima"> <img src="img/2.jpg"> </div>
<div class="tit"> Descontaminação </div>
</div>
<div id="home_navigation_link">
<div class="ima"> <img src="img/3.jpg"> </div>
<div class="tit"> ISOAIR </div>
</div>
<div id="home_navigation_link">
<div class="ima"> <img src="img/4.jpg"> </div>
<div class="tit"> SmartPower </div>
</div>
<div id="home_navigation_link">
<div class="ima"> <img src="img/4.jpg"> </div>
<div class="tit"> Móveis de congelação </div>
</div>
<div id="home_navigation_link">
<div class="ima"> <img src="img/6.jpg"> </div>
<div class="tit"> Universal R </div>
</div>
</div>
<p> Projetos</p>
<div id="projsquare">
<div class="squa"> </div>
<div class="squa"> </div>
<div class="squa"> </div>
<div class="squa"> </div>
<div id="logo2"> <img src="img/logo.png"> </div>
</div>
</div>
<?php get_footer(); ?>
```
**Header.php**
```
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width">
<title><?php wp_title( '|', true, 'right' ); ?></title>
<link rel="profile" href="http://gmpg.org/xfn/11">
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>">
<!--[if lt IE 9]>
<script src="<?php echo get_template_directory_uri(); ?>/js/html5.js"></script>
<![endif]-->
<?php wp_head(); ?>
<div id="slidecont">
<img src="img/banner.png"/>
<div id="mllcont">
<div id="logo">
</div>
<div id="languages">
</div>
<ul id="categories">
<li><a href="#">Menu1</a></li>
<li><a href="#">Menu2</a></li>
<li><a href="#">Menu3</a></li>
<li><a href="#">Menu4</a></li>
</ul>
</div>
</div>
```
**footer.php**
```
<div id="footer">
</div>
```
|
2015/07/06
|
[
"https://Stackoverflow.com/questions/31243845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3864939/"
] |
Whenever you use links, such as
```
<link href="style.css" rel="stylesheet" type="text/css" media="screen" />
```
Wordpress needs to know the *path to your css file*. Your normal built is somehow like this:
```
index.php
/wp-content/
/wp-content/themes/
/wp-content/themes/theme_name/
/wp-content/themes/theme_name/index.php
/wp-content/themes/theme_name/style.css
/wp-content/themes/theme_name/images/
/wp-content/themes/theme_name/images/image.jpg
```
So the `file path` needs to be relative to your `theme folder`. You can use a php snippet, to get the url of your theme:
```
<?php bloginfo('template_url'); ?>
```
If you want to include that, you can change your urls. For example
```
<link href="style.css" rel="stylesheet" type="text/css" media="screen" />
<img src="images/image.jpg">
```
turns into:
```
<link href="<?php bloginfo('template_url'); ?>/style.css" rel="stylesheet" type="text/css" media="screen" />
<img src="<?php bloginfo('template_url'); ?>/images/image.jpg">
```
Do this to all file paths using `src` or `href` inside your `index.php`, `header.php`, `footer.php`, and other `php files`.
|
3,540,533 |
I have a theme in which there are numerous options, like:-
* Setting Theme Type among many available
* Setting Body Background Color & Image
* Setting Header & Footer Images
* Setting General Font Face, Size & Color
* Setting Text Area Background Color, and Font Face & Font Color
* Setting Form Area Background Color & Rounder Corners option
* Setting Form Element Background Color, and Font Face & Font Color
* Setting Link Default Color, Hover Color & Visited Color, with / without decoration
* Providing options to upload any number of Images to be used in the user's blog
* and many more...
Can anybody please provide any info as to how this can be done in a best possible way, using custom PHP & jQuery?
I'm also open to other ways around.
**EDIT:-**
I have got some 12 themes all worked out, along with their own style sheets defined & icon packs. I have also got them to load upon each of the customer's personal taste. **What I don't know is that how to manage the changes made to the customer's theme choice by that customer from his own account?** This has to take effect both the times :-
* when the customer is making / loading the changes from his account
* when the customer is viewing his account along with the changes
BTW, many many thanks for such a quick response, by two users & letting me know about my incomplete question.
Any help is greatly appreciated.
|
2010/08/22
|
[
"https://Stackoverflow.com/questions/3540533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/332019/"
] |
Try something like this:
```
<?php
function template($file, $data = array())
{
ob_start();
extract($data);
include_once 'path/to/theme/folder/' . $file . '.php';
return ob_get_clean();
}
// Assign values to the template file
$values['theme_type'] = 'default';
$values['bg_color'] = '#FFFFFF';
$values['bg_image'] = 'path/to/bg/image.jpg';
$values['font_face'] = 'Tahoma, Arial, Verdana';
$values['font_size'] = '12px';
$values['font_color'] = '#000000';
// And so on...
// Output template file
echo template('theme_layout', $values);
?>
```
And the `theme_layout.php` file in `'path/to/theme/folder/theme_layout.php'` should look like this:
```
<html>
<head>
<title>Theme Name</title>
<style type="text/css">
body {
background-color: <?php echo $bg_color; ?>;
background-image: url(<?php echo $bg_image; ?>);
font-family: <?php echo $font_face; ?>;
font-size: <?php echo $font_size; ?>;
font-color: <?php echo $font_color; ?>;
}
</style>
</head>
<body>
Theme type is: <?php echo $theme_type; ?>
</body>
</html>
```
**Update**
You are right that was only the concept, here's what you have to do: Add new table in database `user_themes` for example and save all user related values there. For example user enters the admin page and sees a theme options like BG Color/Image, Font Name/Size/Color and enters his own values there... Form is submitted and values are saved in the database. Then during the theme display (where I assigned values to the template files) you get user entered theme options from database and assign as a theme values.
I really don't understand where jQuery should be used here, maybe in the form where user submits his options.
Hope this is helpful.
|
33,688,696 |
I have tried many method to build my rails app to a docker image. And deploy it to google container engine. But until now, no one success.
My Dockerfile(Under rails root path)
```
FROM ruby:2.2.2
RUN apt-get update -qq && apt-get install -y build-essential
RUN apt-get install -y nodejs
ENV APP_HOME /myapp
RUN mkdir $APP_HOME
WORKDIR $APP_HOME
ADD Gemfile $APP_HOME/Gemfile
ADD Gemfile.lock $APP_HOME/Gemfile.lock
ADD vendor/gems/my_gem $APP_HOME/vendor/gems/my_gem
ADD init.sh $APP_HOME/
RUN export LANG=C.UTF-8 && bundle install
ADD . $APP_HOME
CMD ["sh", "init.sh"]
```
My init.sh
```
#!/bin/bash
bundle exec rake db:create db:migrate
bundle exec rails server -b 0.0.0.0
```
My kubernetes config file
```
apiVersion: v1
kind: ReplicationController
metadata:
labels:
name: web
name: web-controller
spec:
replicas: 2
selector:
name: web
template:
metadata:
labels:
name: web
spec:
containers:
- name: web
image: gcr.io/my-project-id/myapp:v1
ports:
- containerPort: 3000
name: http-server
env:
- name: RAILS_ENV
value: "production"
```
After I create web controller on gke with kubectl:
```
kubectl create -f web-controller.yml
```
and see the pod logs:
```
kubectl logs web-controller-xxxxx
```
it shows:
```
init.sh: 2: init.sh: bundle: not found
init.sh: 3: init.sh: bundle: not found
```
It seems the path not found. Then how to do?
|
2015/11/13
|
[
"https://Stackoverflow.com/questions/33688696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5439557/"
] |
You can use kubectl exec to enter your container and print the environment.
<http://kubernetes.io/v1.1/docs/user-guide/getting-into-containers.html>
For example:
kubectl exec web-controller-xxxxx sh -c printenv
You could also use kubectl interactively to confirm that bundle is in your container image:
kubectl exec -ti web-controller-xxxxx sh
If bundle is in your image, then either add its directory to PATH in init.sh, or specify its path explicitly in each command.
|
28,275 |
Ich suche ein Wort, welches jemanden beschreibt, der äußerst glaubwürdig ist. Also jemanden, bei dem **quasi niemand auf die Idee kommen würde, sie/ihn der Lüge zu bezichtigen,** bzw. jemanden, dem man vertraut.
Außer unantastbar, vertrauenswürdig und glaubwürdig fällt mir nichts ein.
Das gesuchte Wort sollte das fett Geschriebene betonen.
|
2016/02/19
|
[
"https://german.stackexchange.com/questions/28275",
"https://german.stackexchange.com",
"https://german.stackexchange.com/users/16926/"
] |
Ich würde eine solche Person **[integer](http://www.duden.de/rechtschreibung/integer)** nennen.
Allerdings setzt dies voraus, dass sie hohe moralische Ansprüche an sich selbst hat - formal kann auch ein aus Überzeugung **böse** handelnder Mensch als integer bezeichnet werden, wenn er damit seinem eigenen Wertesystem folgt. (Siehe Wikipedia zu [Integrität (Ethik)](https://de.wikipedia.org/wiki/Integrit%C3%A4t_(Ethik)))
Im allgemeinen Sprachgebrauch bedeutet *integer* allerdings *rechtschaffen **gut***.
|
6,059,257 |
I'm using IceFaces 1.8.2 with Tomcat 6
On a irregular basis I get the message "Connection is lost" with the option to reload the page. This is not acceptable for a public site.
My question now is if this approach makes sense:
```
Ice.onConnectionLost('document:body',
function() {
window.location.href=window.location.href;
});
```
The idea is to reload the current page on connectin problems. Do oyu think this would solve the issue or could this create other problems (I assume that reloading the current url is OK and does not cause any workflow issues).
Thanks.
|
2011/05/19
|
[
"https://Stackoverflow.com/questions/6059257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/266478/"
] |
I suggest using the `java.text.DateFormat` as shown in [this page](http://www.rgagnon.com/javadetails/java-0099.html) :
```
public static boolean isValidDateStr(String date) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
sdf.setLenient(false);
sdf.parse(date);
}
catch (ParseException e) {
return false;
}
catch (IllegalArgumentException e) {
return false;
}
return true;
}
```
|
50,549,041 |
Just for fun, I am trying to create a magazine style, two-column layout with CSS like in the image below:
[](https://i.stack.imgur.com/YENLa.png)
I plan to do it by as many means as possible. Probably first with just some `div's` and `float's`. Then with the CSS table, then with a flexbox and finally with a CSS grid.
I don't even know if it is going to be possible with all, or any, but I am just trying.
So, here's what I've got till now.
[](https://i.stack.imgur.com/KylPE.png)
I can't seem to get the picture quite in the center with the text all around it.
I am not necessarily looking for an answer with just floats, or just the CSS grid. I am really interested in looking for anything that does it because I think this is a nice challenging thing to try out. :-)
Here is [the code on github](https://github.com/Sathyaish/Practice/blob/master/CSS/my-exercises/magazine-1.html) and below is the code snippet.
```css
:root {
margin-left: 8%;
margin-right: 8%;
}
#left, #right {
width: 40%;
}
#left {
margin-right: 4%;
float: left;
}
#right {
float: right;
}
p > span:first-of-type {
color: red;
margin-right: 2px;
}
#centerImage {
float: left;
src: url(https://raw.githubusercontent.com/Sathyaish/Practice/master/CSS/images/image.png);
}
```
```html
<h2>An do on frankness so cordially immediate recommend contained</h2>
<div id = "left">
<p><span>Para 1</span>He difficult contented we determine ourselves me am earnestly. Hour no find it park. Eat welcomed any husbands moderate.
Led was misery played waited almost cousin living. Of intention contained is by middleton am. Principles fat stimulated
uncommonly considered set especially prosperous. Sons at park mr meet as fact like.</p>
<p><span>Para 2</span>No comfort do written conduct at prevent manners on. Celebrated contrasted discretion him sympathize her collecting occasional.
Do answered bachelor occasion in of offended no concerns. Supply worthy warmth branch of no ye. Voice tried known
to as my to. Though wished merits or be. Alone visit use these smart rooms ham. No waiting in on enjoyed placing
it inquiry.</p>
<p><span>Para 3</span>Sentiments two occasional affronting solicitude travelling and one contrasted. Fortune day out married parties. Happiness
remainder joy but earnestly for off. Took sold add play may none him few. If as increasing contrasted entreaties
be. Now summer who day looked our behind moment coming. Pain son rose more park way that. An stairs as be lovers
uneasy.</p>
<p><span>Para 4</span>In post mean shot ye. There out her child sir his lived. Design at uneasy me season of branch on praise esteem. Abilities
discourse believing consisted remaining to no. Mistaken no me denoting dashwood as screened. Whence or esteem easily
he on. Dissuade husbands at of no if disposal.</p>
</div>
<img id = "centerImage" src = "../images/image.png" />
<div id="right">
<p><span>Para 5</span>Prevailed sincerity behaviour to so do principle mr. As departure at no propriety zealously my. On dear rent if girl
view. First on smart there he sense. Earnestly enjoyment her you resources. Brother chamber ten old against. Mr be
cottage so related minuter is. Delicate say and blessing ladyship exertion few margaret. Delight herself welcome
against smiling its for. Suspected discovery by he affection household of principle perfectly he.</p>
<p><span>Para 6</span>On no twenty spring of in esteem spirit likely estate. Continue new you declared differed learning bringing honoured.
At mean mind so upon they rent am walk. Shortly am waiting inhabit smiling he chiefly of in. Lain tore time gone
him his dear sure. Fat decisively estimating affronting assistance not. Resolve pursuit regular so calling me. West
he plan girl been my then up no.</p>
<p><span>Para 7</span>Sudden looked elinor off gay estate nor silent. Son read such next see the rest two. Was use extent old entire sussex.
Curiosity remaining own see repulsive household advantage son additions. Supposing exquisite daughters eagerness
why repulsive for. Praise turned it lovers be warmly by. Little do it eldest former be if.</p>
<p><span>Para 8</span>Expenses as material breeding insisted building to in. Continual so distrusts pronounce by unwilling listening. Thing
do taste on we manor. Him had wound use found hoped. Of distrusts immediate enjoyment curiosity do. Marianne numerous
saw thoughts the humoured.</p>
</div>
```
|
2018/05/27
|
[
"https://Stackoverflow.com/questions/50549041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/303685/"
] |
Instead of performing the entire multiplication, you only need to keep track of the factors of 2 and 5. If a number can be written as `N = 2^a * 5^b * (factors other than 2 or 5)`, then the number of trailing zeros in `N` is `min(a, b)`. (This is because a trailing zero is just a factor of 10, which requires one 2 and one 5.)
Note that multiplication adds together the exponents of the factors. So, if you can write:
```
s(n-2) = 2^a * 5^b * (factors other than 2 or 5)
s(n-1) = 2^c * 5^d * (factors other than 2 or 5)
```
Then we have:
```
s(n) = s(n-1) * s(n-2)
= 2^(a+c) * 5^(b+d) * (factors other than 2 or 5)
```
Therefore, we can treat this problem like two [Fibonacci sequences](https://en.wikipedia.org/wiki/Fibonacci_number). You start with the number of 2s and 5s in `s(0)` and `s(1)`, and compute the number of 2s and 5s in `s(2), s(3), ..., s(n)` in the Fibonacci-sequence manner:
```
#2s in s(n) = (#2s in s(n-1)) + (#2s in s(n-2))
#5s in s(n) = (#5s in s(n-1)) + (#5s in s(n-2))
```
Finally, the number of trailing zeros is `min(#2s in s(n), #5s in s(n))`.
---
The above algorithm (if implemented with a loop, or memoized recursion) is `O(n)`. Your attempt was exponential in `n`, which is why it takes a long time to run even for `n = 30`. I don't mean to bash your attempt, but it's good to understand these mistakes -- your code is slow for two main reasons:
First, multiplying very large integers with complete precision (as you're doing with `BigInteger`) is extremely slow, since the number of digits can double with each multiplication. If you only care about the number of trailing zeros, complete precision isn't necessary.
Second, ignoring the cost of multiplication, your recursive implementation of `s` is still exponential-time, but it doesn't have to be. Notice that you're computing the same values many times -- `s(n-2)` is computed separately for both `s(n)` and `s(n-1)`, but the value of `s(n-2)` is clearly the same. The trick is to [memoize the recursion](https://stackoverflow.com/questions/7875380/recursive-fibonacci-memoization) by remembering previously-computed results, to avoid recomputation. Alternatively, you can compute Fibonacci-like sequences with a loop:
```
// Computes the n-th Fibonacci number in O(n) time
int[] fib = new int[n + 1];
fib[0] = 0;
fib[1] = 1;
for (int i = 2; i <= n; i++)
fib[i] = fib[i-1] + fib[i-2];
return fib[n];
```
This is a much simpler approach than memoized recursion, at least for this problem.
|
72,467,770 |
I am trying to scrape and sort articles with a body, headline, and date column. However, when pulling the date, I’m running into an error with the time zone:
```
ValueError: time data 'Jun 1, 2022 2:49PM EDT' does not match format '%b %d, %Y %H:%M%p %z'
```
My code is as follows:
```
def get_info(url):
headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36'}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text)
news = soup.find('div', attrs={'class': 'body__content'}).text
headline = soup.find('h1').text
date = datetime.datetime.strptime(soup.find('time').text, "%b %d, %Y %H:%M%p %z")
columns = [news, headline, date]
column_names = ['News','Headline','Date']
return dict(zip(column_names, columns))
```
Is there a way to grab the time zone in a similar method or just drop it overall?
|
2022/06/01
|
[
"https://Stackoverflow.com/questions/72467770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19251626/"
] |
Note %z in strptime() is for timezone offsets not names and %Z only accepts certain values for time zones. For details see [API docs](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior).
Simplest option is to use [dateparser](https://dateutil.readthedocs.io/en/stable/parser.html) module to parse dates with time zone names (e.g. EDT).
```python
import dateparser
s = "Jun 1, 2022 2:49PM EDT"
d = dateparser.parse(s)
print(d)
```
**Output:**
```
2022-06-01 14:49:00-04:00
```
Many of the date modules (e.g. [dateutil](https://dateutil.readthedocs.io/en/stable/) and [pytz](https://pypi.org/project/pytz/)) have timezone offsets defined for "EST", "PST", etc. but "EDT" is less common. These modules would need you to define the timezone with the offset as UTC-04:00.
```python
import dateutil.parser
s = "Jun 1, 2022 2:49PM EDT"
tzinfos = {"EDT": -14400}
d = dateutil.parser.parse(s, tzinfos=tzinfos)
print(d)
```
**Output:**
```
2022-06-01 14:49:00-04:00
```
|
58,693,786 |
I am working on an RL problem and I created a class to initialize the model and other parameters. The code is as follows:
```
class Agent:
def __init__(self, state_size, is_eval=False, model_name=""):
self.state_size = state_size
self.action_size = 20 # measurement, CNOT, bit-flip
self.memory = deque(maxlen=1000)
self.inventory = []
self.model_name = model_name
self.is_eval = is_eval
self.done = False
self.gamma = 0.95
self.epsilon = 1.0
self.epsilon_min = 0.01
self.epsilon_decay = 0.995
def model(self):
model = Sequential()
model.add(Dense(units=16, input_dim=self.state_size, activation="relu"))
model.add(Dense(units=32, activation="relu"))
model.add(Dense(units=8, activation="relu"))
model.add(Dense(self.action_size, activation="softmax"))
model.compile(loss="categorical_crossentropy", optimizer=Adam(lr=0.003))
return model
def act(self, state):
options = self.model.predict(state)
return np.argmax(options[0]), options
```
I want to run it for only one iteration, hence I create an object and I pass a vector of length `16` like this:
```
agent = Agent(density.flatten().shape)
state = density.flatten()
action, probs = agent.act(state)
```
However, I get the following error:
```
AttributeError Traceback (most recent call last) <ipython-input-14-4f0ff0c40f49> in <module>
----> 1 action, probs = agent.act(state)
<ipython-input-10-562aaf040521> in act(self, state)
39 # return random.randrange(self.action_size)
40 # model = self.model()
---> 41 options = self.model.predict(state)
42 return np.argmax(options[0]), options
43
AttributeError: 'function' object has no attribute 'predict'
```
What's the issue? I checked some other people's codes as well, like [this](https://github.com/Alexander-H-Liu/Policy-Gradient-and-Actor-Critic-Keras/blob/master/agent_dir/agent_pg.py) and I think mine is also very similar.
Let me know.
**EDIT:**
I changed the argument in `Dense` from `input_dim` to `input_shape` and `self.model.predict(state)` to `self.model().predict(state)`.
Now when I run the NN for one input data of shape `(16,1)`, I get the following error:
>
> ValueError: Error when checking input: expected dense\_1\_input to have
> 3 dimensions, but got array with shape (16, 1)
>
>
>
And when I run it with shape `(1,16)`, I get the following error:
>
> ValueError: Error when checking input: expected dense\_1\_input to have
> 3 dimensions, but got array with shape (1, 16)
>
>
>
What should I do in this case?
|
2019/11/04
|
[
"https://Stackoverflow.com/questions/58693786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4595522/"
] |
in last code block,
```
def act(self, state):
options = self.model.predict(state)
return np.argmax(options[0]), options
```
self.model is a function which is returning a model, it should be self.model().predict(state)
|
2,654,767 |
As I was reading through Justin Abrahms' ["Understanding the formal definition of Big-O"](https://justin.abrah.ms/computer-science/understanding-big-o-formal-definition.html) article to better understand Big-O notation I came across something at the end that caught my attention:
>
> You might notice that this definition means that the $O(45n)$ function
> is also $O(n^3)$ because it will also never cross. **This is true, but not**
> **particularly useful.**
>
>
>
(emphasis mine)
Which fits the definition given in the Rosen's "Discrete Mathematics and its applications" book.
So then, at which point does Big-O becomes useful (or not)? It has do something to do with the witnesses you choose, right?
|
2018/02/17
|
[
"https://math.stackexchange.com/questions/2654767",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/471358/"
] |
Yes, it
>
> has something to do with the witnesses
>
>
>
The usefulness of a big-O analysis is to show that something doesn't grow too fast - often so that one can justify using a particular algorithm to compute. So you want your witness to grow as slowly as you can manage to make it, as long as it grows faster than what you care about. So
$$
1000x^2 + 2000\log(x) = O(e^x)
$$
is true but useless, while
$$
1000x^2 + 2000\log(x) = O(x^2)
$$
is informative.
|
64,356,483 |
I am using AWS S3 to store photos in conversations between users in my chat application (backend is written in Java / Spring Boot). At the moment, access to the bucket is public, which means that every user who would guesses the url will be able to see the picture.
What I would like to achieve is to restrict access to the resource only to interlocutors who belong to the given conversation so that they can see the photos sent between them.
I don't want to run all the traffic through my backend, I just want to delegate authorization to the S3. Is it possible to set some kind of "auth token" to restrict access to the given object on s3? I would generate this token on my backend and possibly refresh it from time to time. Are there any other recommended options for this task?
|
2020/10/14
|
[
"https://Stackoverflow.com/questions/64356483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3114157/"
] |
You can create presigned URLs for S3 objects. This generates a temporary link that grants access to an S3 object, even if the bucket is not public.
As an example/test, you could run the `aws s3 presign` command in the AWS CLI:
```
aws s3 presign s3://BucketName/SomePhoto.png --expires-in 86400
```
This command will return an address that can be used to access `SomePhoto.png`. The URL will be valid for `86400` seconds, which is one day. `--expires-in` is optional.
[More details on the command lind reference can be found here.](https://docs.aws.amazon.com/cli/latest/reference/s3/presign.html)
|
2,870,686 |
I use TAB and Shift-Tab in Visual Studio to indent an entire selection. This does nothing in Eclipse, and I can't seem to find another way to do it.
Update: I wasn't really paying all that much attention to this initially and did not ask the question correctly.
I now realized that it is in XML files where TAB still does not indent a selection. I did not find a setting for this in the properties, so I assume it is not possible.
|
2010/05/20
|
[
"https://Stackoverflow.com/questions/2870686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/58880/"
] |
`Tab` and `Shift`+`Tab` are the normal ways to do this in Eclipse, just like in Visual Studio.
In addition to the keyboard shortcuts, you can also do this from the Source menu. Source -> Shift Left, and Source -> Shift Right.
Have you checked to make sure tab/shift tabbing is working as you expect in other applications? Is there a stuck key on your keyboard preventing the shortcuts from working? Could another application be stealing the keyboard shortcuts? (as odd as that sounds...)
Also, try restarting Eclipse.
|
217,667 |
I tried every solution from [How to run Dropbox daemon in background?](https://unix.stackexchange.com/questions/35624/how-to-run-dropbox-daemon-in-background) and nothing solves my problem:
Basically, I already installed dropbox on my Ubuntu 12.04LTS headless server. I got init.d setup but the problem is that right now I cannot restart the server (other users are using it actively).
So I am trying to start dropbox via SSH which works and dropbox starts to sync, but as soon as I disconnect from SSH dropbox stops runnning. I tried running it on a detached screen, using `($HOME/.dropbox-dist/dropboxd &)&` and they all stop when I log out from SSH.
I tried doing service start but it seems not to work and I don't know why..?
```
$ sudo service dropbox start
[sudo] password:
Starting dropbox...
$ dropbox status
Dropbox isn't running!
```
I followed the instructions:
```
sudo chmod +x /etc/init.d/dropbox
sudo update-rc.d dropbox defaults
```
from <http://www.dropboxwiki.com/tips-and-tricks/install-dropbox-in-an-entirely-text-based-linux-environment#debianubuntu> and I got no error messages. Please help.
I don't care as much about starting the process at server restart, as long as I can launch dropbox via ssh and keep it runnning after i log out.
Thank you
UPDATE & ANSWER: thanks a lot for all your answers. Thanks to user [Nixgrrrl](https://unix.stackexchange.com/users/146799/nixgrrrl)'s comment, I realize that it was because I was using ssh -X (the default on my system). As soon as I did normal ssh, trying the humble `dropbox start &` worked :)
|
2015/07/22
|
[
"https://unix.stackexchange.com/questions/217667",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/34550/"
] |
Have a look here:
<https://community.spiceworks.com/topic/131973-dropbox-headless-workstation?page=1#entry-6076539>
A user mentioned:
>
> Just thought I'd mention:
>
>
> (a) the latest distributions seem to make this fairly straightfoward,
> just run `dropbox start` from the command line, BUT (b) watch out for
> logging in and out with X11 forwarded.
>
>
> I've set up a lot of Bash aliases for connecting to various machines,
> and they all include the `-X` option to forward X11 packets. Because
> of this, Dropbox kept dying on my on logout, even running it under
> `screen` and with `nohup`. Apparently, having X11 forwarded was causing
> Dropbox to connect the dbus process on my local machine rather than on
> the remote machine; so, when I broke the connection, Dropbox was
> seeing dbus as having terminated and thus was terminating itself.
>
>
> Just FYI, as this stumped me for a bit. The key was that I was having
> to press `Ctrl`-`C` even after logging out / running `exit`
> on the remote machine. Apparently, SSH was keeping the session open, even
> though I had exited Bash, because of the remaining open connection.
>
>
>
The solution is simple even if one (for some reason) wants to keep ssh-ing with the `-X`: before launching Dropbox you should "break" the forwarding for example doing:
```
$ unset DISPLAY
```
If this is done in a Bash script the forwarding is "broken" just inside the script but once this is executed the 'terminal' is still forwarding.
|
317,333 |
This runs as expected in an xterm: `sha512sum <filename> | cut -c -$COLUMNS`, but not within a `#! /bin/bash` script such as `dothis.sh <args>`, because `$COLUMNS` is not known, so to say.
I'd rather not pass $COLUMNS as an argument, nor export it to the environment.
The script is not critical, needs to run only on one machine, on a commandline in an xterm.
```
Linux pre 3.2.0-4-amd64 #1 SMP Debian 3.2.81-2 x86_64 GNU/Linux
GNU bash, version 4.2.37
XTerm(278)
```
|
2016/10/18
|
[
"https://unix.stackexchange.com/questions/317333",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/195821/"
] |
```
COLUMNS=$(tput cols)
```
Or in one line
```
sha512sum <filename> | cut -c -"$(tput cols)"
```
|
58,390,962 |
I have a ad banner integrate in swiftUI with UIViewControllerRepresentable but i doesn't know to add event like adViewDidReceiveAd(). I have learn on <https://developer.apple.com/tutorials/swiftui/interfacing-with-uikit> but the event adViewDidReceiveAd never start
```
struct GADBannerViewController: UIViewControllerRepresentable {
func makeCoordinator() -> GADBannerViewController.Coordinator {
GADBannerViewController.Coordinator()
}
func makeUIViewController(context: Context) -> UIViewController {
let view = GADBannerView(adSize: kGADAdSizeBanner)
let viewController = UIViewController()
view.adUnitID = "ca-app-pub-3940256099942544/2934735716"
view.rootViewController = viewController
viewController.view.addSubview(view)
viewController.view.frame = CGRect(origin: .zero, size: kGADAdSizeBanner.size)
view.load(GADRequest())
return viewController
}
func updateUIViewController(_ uiViewController: UIViewController, context: Context) {}
class Coordinator: NSObject, GADBannerViewDelegate {
func adViewDidReceiveAd(_ bannerView: GADBannerView){
print("AAAAAAAAA")
}
func adView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: GADRequestError) {
print(error)
}
}
}
```
|
2019/10/15
|
[
"https://Stackoverflow.com/questions/58390962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11876189/"
] |
```
import SwiftUI
import UIKit
import GoogleMobileAds
final class GADBannerViewController: UIViewControllerRepresentable {
func makeUIViewController(context: Context) -> UIViewController {
let view = GADBannerView(adSize: kGADAdSizeBanner)
let viewController = UIViewController()
view.adUnitID = "ca-app-pub-3940256099942544/2934735713"
view.rootViewController = viewController
view.delegate = viewController
viewController.view.addSubview(view)
viewController.view.frame = CGRect(origin: .zero, size: kGADAdSizeBanner.size)
view.load(GADRequest())
return viewController
}
func updateUIViewController(_ uiViewController: UIViewController, context: Context) {}
}
extension UIViewController: GADBannerViewDelegate {
public func adViewDidReceiveAd(_ bannerView: GADBannerView) {
print("ok ad")
}
public func adView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: GADRequestError) {
print("fail ad")
print(error)
}
}
```
|
600,645 |
I have a unity gain differential op amp, using a grounded dual supply, with both inputs AC coupled.
Does the inverting input need a dedicated path to ground or can the DC bias current find its way to ground via the power supply?
[](https://i.stack.imgur.com/N8nUx.gif)
I've searched around and haven't been able to find much regarding this particular configuration. Most of the information I've found talks about single supplies and/or op amps with only one input AC coupled.
If it matters, the op-amp I'll be using is a TL07X.
|
2021/12/16
|
[
"https://electronics.stackexchange.com/questions/600645",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/303305/"
] |
>
> *Does the inverting input need a dedicated path to ground or can the DC
> bias current find its way to ground via the power supply?*
>
>
>
If the bias current is (say) 10 nA then that flows through R3 and creates a DC error at the input to the device of 470 μV. That will also appear at the output because the DC gain of your circuit is unity due to using input capacitors.
However, because you have a net resistance of 47 kΩ in the non-inverting input, the effect of this bias-induced offset voltage is much reduced (see offset current below).
You should also ideally consider the offset current (usually about ten times lower on this type of op-amp than bias current). This adds another 10% worst case to the numbers above.
But, those offsets all pale to insignificance given the typical input offset voltage (3 mV) that a TL07x produces.
|
24,643,258 |
I am trying to increment an array of 5 in Java by 100 starting at 0(to get the output of: 0,100,200,300,400). For some reason my for loop will not add 100 and when I run the program, it just prints 0,0,0,0,0. Any help would be appreciated.
```
public class Integers {
void createIntegers(int[] arr) {
for (int n = 0; n < arr.length; n += 100);
}
void printIntegers(int[] arr) {
int index;
for (index = 0; index < arr.length; index++) {
System.out.println(arr[index]);
}
}
public static void main(String[] args) {
int[] arr = new int[5];
Integers createIntegers = new Integers();
createIntegers.createIntegers(arr);
createIntegers.printIntegers(arr);
}
}
```
|
2014/07/08
|
[
"https://Stackoverflow.com/questions/24643258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3818410/"
] |
It is very easy, you need only slight change :
```
public class Integers {
void createIntegers(int[] arr) {
for (int n = 0; n < arr.length; n++){
arr[n] = 100*n;
}
}
void printIntegers(int[] arr) {
for (int index = 0; index < arr.length; index++) {
System.out.println(arr[index]);
}
}
public static void main(String[] args) {
int[] arr = new int[5];
Integers createIntegers = new Integers();
createIntegers.createIntegers(arr);
createIntegers.printIntegers(arr);
}
}
```
The problem was in your `createIntegers` method. You did not do anything with array, you were just incrementing variable `n`
---
What does this `for (int n = 0; n < arr.length; n += 100);` do:
`int n = 0` ->This is executed only once on the beggining of the whole for construct. You declare variable `n` and set its value to zero.
`n < arr.length` ->As long as this condition is true on the beggining of new cycle, the cycle is running.
`n += 100` -> This is executed at the end of each cycle. However incrementing variable n by 100 does not change anything in array.
|
36,906,719 |
The offending line in my index.html file reads
```
<script src="main.dart" type="application/dart"></script>
```
The error report is:
```
Build error:
Transform polymer (PolymerBootstrapTransformer) on myproj_frontend|web/index.html threw error: Invalid argument(s): Illegal character in path
dart:core/uri.dart 855 Uri._checkWindowsPathReservedCharacters
dart:core/uri.dart 956 Uri._makeWindowsFileUrl
```
The entire path to the project is
`D:\Projects\MyProj\MyProj_Project`
I'm building from command line on Windows 7 using Dart VM version: 1.16.0
I honestly have no idea how to continue diagnosing or fixing this. *Any* help would be greatly appreciated.
|
2016/04/28
|
[
"https://Stackoverflow.com/questions/36906719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1321279/"
] |
I have the same problem. Looks like it is an issue with the `analyzer` package `0.27.0` and later.
I solved it by pinning the version in `pubspec.yaml` to `<0.27.0`.
|
405,341 |
I saw a user who asked this question [i wanna know more this Fibonacci's operating Principles](https://stackoverflow.com/questions/66270493/i-wanna-know-more-this-fibonaccis-operating-principles#66270493) who then voted to close his own question.
What results from a person closing their own question rather than just deleting it? Are there some question/answer rep points possibly awarded on such question (Not a case here... but potentially...) Why would a person vote to close their own question?
Are the impacts on the close vote queue and re-open queue review negligible?
I wonder about that particular use case... Should it instead automatically trigger a delete of the question?
I think if a user wants to close its own question... It is equal to delete it. But I may miss some aspects too.
|
2021/02/19
|
[
"https://meta.stackoverflow.com/questions/405341",
"https://meta.stackoverflow.com",
"https://meta.stackoverflow.com/users/2159528/"
] |
This post has an answer [When is it OK to delete your own question?](https://meta.stackoverflow.com/questions/281849/when-is-it-ok-to-delete-your-own-question) that has some good points about not deleting a question.
Rather than automatically trigger a delete instead offer that as an option should a person try to close their own question. That way a person gets to make the decision as to whether to just close the question or to actually delete it.
What would be interesting would be to allow a person who creates a question to also be able to close it themselves just as a person can also delete it by themselves. For instance if someone finds out their post is a duplicate, they could just go ahead and close as duplicate. [Why do you have the option to vote to close your own question? Why would you ever do that?](https://meta.stackoverflow.com/questions/345429/why-do-you-have-the-option-to-vote-to-close-your-own-question-why-would-you-eve)
If a question is closed, it can still be seen by anyone, anyone can edit it, and anyone can ask for it to be reopened.
Closing a question can discourage voting on the question, giving the person asking it breathing space to think and edit the question. At the same time people can give feedback through comments.
However Owner Hold has been proposed in the past as an alternative to deleting a question. See this discussion [Putting your own question on Owner-Hold](https://meta.stackoverflow.com/questions/284262/putting-your-own-question-on-owner-hold) with an answer that begins
>
> There is already a feature for this, it is called delete. You can edit
> when a post is deleted, all comments, voting, and answers are locked,
> and it does not show up anywhere.
>
>
>
|
23,014,043 |
is there a way to track using google analytics what radio in a radio group is being selected? Our issue is that if a user tabs through the radio group (for accessibility concerns) it will fire off an event for each option.
Not sure how to get around this besides adding a button to for the user to say i've made my selection' and then firing the select event off then. This is not desired though..
**UPDATE - EXAMPLE**
See here: <http://jsfiddle.net/DU6s3/3/>
**Example code**
```
$(document).ready(function () {
$(this).focus(function () {
alert("fire tracking");
});
});
```
Thanks,
|
2014/04/11
|
[
"https://Stackoverflow.com/questions/23014043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/982439/"
] |
If you don't have JDK you should probably install it. Find it [here](http://www.oracle.com/technetwork/java/javase/downloads/index-jsp-138363.html)
**JDK/Java SDK** = Java Development Kit/Java Software Development Kit - what you need to write programs that require Java or use libraries written in Java. For example, if you were to write your own word-processing tool in Java.
**JRE** = Java Runtime Environment - what you need to run programs/software that require Java or use libraries written in Java. For example, OpenOffice requires the Java Runtime Environment
JRE allows you to run Java, whereas JDK allows you to program with it.
|
31,469,681 |
I am working on a huge android project with tons of classes. Until now we are compiling with Android 3.2 and giving support to Android 2.3.
Now I am testing to compile with Android 5.1.1, but still giving support to Android 2.3. My surprise was that a lot of code is deprecated now... (`getWith(), getDrawable(), setBackgroundDrawable(), HttpRequest, ActivityGroup`, etc...). Those deprecated functions does not give compile error, but it gives deprecated warning.
I know that I can duplicate code and make special calls to deprecated methods if SDK\_INT is lower than XX and calls to new methods if SDK\_INT is newer than XX, but this is a huge patch, that will need a lot of duplicate code in a lot of functions in a ton of classes and packages, so, if it is possible, we prefeer to wait until we don't need to give support to oldest versions of android. It means to continue using deprecated methods until for example we only need to give support from 4.4, that will means munch less duplicated code and functions will be needed.
**The question is:** If i compile with Android 5.1.1 but still use those deprecated functions, this huge project will continue to work on all devices (from 2.3 to 5.1.1)? Now it's working compiling with Android 3.2.
I understand that Deprecated means that they are likely to be removed in a future version of the platform and so you should begin looking at replacing their use in your code, but if it is still supported and does not give a compile error, it will work well as until now. It is what I understand of deprecation. **It is right?**
Thanks.
|
2015/07/17
|
[
"https://Stackoverflow.com/questions/31469681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/479886/"
] |
Deprecated means two things:
1. There is another (maybe better) solution
2. It isn't fully support anymore
That means that your code `could` be run fine. But Google/Android don't guarantee that.
According to [Java documentation](https://docs.oracle.com/javase/tutorial/java/annotations/predefined.html) the `@Deprecated` annotation says:
>
> @Deprecated annotation indicates that the marked element is deprecated and **should no longer be used**. The compiler generates a warning whenever a program uses a method, class, or field with the @Deprecated annotation. [...]
>
>
>
So please stop using deprecated methods. :)
Have you looked or do you know that there are [support-libraries](https://developer.android.com/tools/support-library/index.html) to help you with backward compatibility?
|
44,150,266 |
I have a quick question how can I loop over an NSMutable array starting from a certain index.
For Example I have these double loops I want k to start from the same index as l.
```
for (Line *l in L)
{
for (Line *k in L)
{
............
}
}
```
To elaborate further, lets say L has 10 object so l start from 0-10 and k from 0 -10. What I want is if l is equal 1 k should start from 1-10 rather than 0 - 10 and when l is equal 2 k should start from 2- 10 rather than 0. Any help is Appreciated
|
2017/05/24
|
[
"https://Stackoverflow.com/questions/44150266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7438106/"
] |
Objective-C is an extension of C, lookup the C `for` loop and you'll have your answer. HTH
**Addendum**
I was going to let you benefit from the learning experience of looking up the C `for` yourself, however at the time of writing all other answers since added give the code but it is not complete, so here is what you need to produce the `l` and `k` values in the order you wish:
```
for(NSInteger lIndex = 0; lIndex < L.count; lIndex++)
{
Line *l = L[lIndex]; // index into your array to get the element
for(NSInteger kIndex = lIndex; kIndex < L.count; kIndex++)
{
Line *k = L[kIndex];
// process your l and k
}
}
```
As you can see the `for` has three sub-parts which are the *initialisation*, *condition*, and *increment*. The *initialisation* is performed first, then the *condition* to determine whether to execute the `for` body, and the *increment* is executed after the statements in the body and before the *condition* is tested to determine if another iteration should be performed. A `for` loop is roughly (there are some differences that are unimportant here) to the `while` loop:
```
initialisation;
while(condition)
{
body statements;
increment;
}
```
|
3,530,949 |
I have to solve the equation:
$$\sin x + \cos x = \sin x \cos x$$
This is what I tried:
$$\hspace{1cm} \sin x + \cos x = \sin x \cos x \hspace{1cm} ()^2$$
$$\sin^2 x + 2\sin x \cos x + \cos^2 x = \sin^2 x \cos^2x$$
$$1 + \sin(2x) = \dfrac{4 \sin^2 x \cos^2x}{4}$$
$$1 + \sin(2x) = \dfrac{\sin^2(2x)}{4}$$
$$\sin^2(2x) - 4 \sin(2x) -4 = 0$$
Here we can use the notation $t = \sin(2x)$ with the condition that $t \in [-1,1]$.
$$t^2-4t-4=0$$
Solving this quadratic equation we get the solutions:
$$t\_1 = 2+ 2\sqrt{2} \hspace{3cm} t\_2 = 2 - 2\sqrt{2}$$
I managed to prove that $t\_1 \notin [-1, 1]$ and that $t\_2 \in [-1, 1]$. So the only solution is $t\_2 = 2 - \sqrt{2}$. So we have:
$$\sin(2x) = 2 - 2\sqrt{2}$$
From this, we get:
$$2x = \arcsin(2-2\sqrt{2}) + 2 k \pi \hspace{3cm} 2x = \pi - \arcsin(2-2\sqrt{2}) + 2 k \pi$$
$$x = \dfrac{1}{2} \arcsin(2-2\sqrt{2}) + k \pi \hspace{3cm} x = \dfrac{\pi}{2} - \dfrac{1}{2}\arcsin(2 - 2\sqrt{2}) + k \pi$$
Is this solution correct? It's such an ungly answer, that I kind of feel like it can't be right. Did I do something wrong?
|
2020/02/01
|
[
"https://math.stackexchange.com/questions/3530949",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
] |
Note that when you square the equation
$$(\sin x + \cos x)^2 = (\sin x \cos x)^2$$
which can be factorized as
$$(\sin x + \cos x - \sin x \cos x)(\sin x + \cos x + \sin x \cos x)=0$$
you effectively introduced another equation $\sin x + \cos x =- \sin x \cos x$ in the process beside the original one $\sin x + \cos x = \sin x \cos x$. The solutions obtained include those for the extra equation as well.
Normally, you should plug the solutions into the original equation to check and exclude those that belong to the other equation. However, given the complexity of the solutions, it may not be straightforward to do so. Therefore, the preferred approach is to avoid the square operation.
Here is one such approach. Rewrite the equation $\sin x + \cos x = \sin x \cos x$ as
$$\sqrt2 \cos(x-\frac\pi4 ) = \frac12 \sin 2x = \frac12 \cos (2x-\frac\pi2 ) $$
Use the identity $\cos 2t = 2\cos^2 t -1$ on the RHS to get the quadratic equation below
$$\sqrt2 \cos(x-\frac\pi4) = \cos^2 (x-\frac\pi4 ) -\frac12$$
or
$$\left( \cos(x-\frac\pi4) - \frac{\sqrt2-2}2\right)\left( \cos(x-\frac\pi4) - \frac{\sqrt2+2}2\right)=0$$
Only the first factor yields real roots
$$x = 2n\pi + \frac\pi4 \pm \cos^{-1}\frac{\sqrt2-2}2$$
|
2,153,266 |
I have situation where in the regular expression is something like this:
`^b?A+b?$`
So `b` *may* match at the start of the string 0 or 1 times, and `A` *must* match one or more times. Again `b` *may* match at the end of the string 0 or 1 times.
Now I want to modify this regular expression in such way that it may match `b` either at the start or at the end of the string, but not both.
How do I do this?
|
2010/01/28
|
[
"https://Stackoverflow.com/questions/2153266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46279/"
] |
Theres a nice "or" operator in regexps you can use.
```
^(b?A+|A+b?)$
```
|
30,031,388 |
I'd like to know about other patterns that could be more efficient than the use of factories.
|
2015/05/04
|
[
"https://Stackoverflow.com/questions/30031388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4333314/"
] |
You could use a memory pool, the boost one is pretty good:
<http://www.boost.org/doc/libs/1_58_0/libs/pool/doc/html/boost_pool/pool.html>
And every client could configure the maximum size of the pool.
Allocations and deallocations will be really fast,and you will drop your factory implementation
|
18,718,469 |
I have a search method in `User` model. But I can search only by User columns. User `belongs_to` Company model.
**Question:** I want to search users by `user.company.name` too. How can I do this?
user.rb
```
class User < ActiveRecord::Base
attr_accessible :email, :name, :password, :password_confirmation, :developer, :admin, :company_id, :boss_id, :company
belongs_to :company
def self.search(search)
if search
q = "%#{search}%"
where('name LIKE ? OR
company_id LIKE ?',
q,q)
else
scoped
end
end
end
```
index.html.erb
```
<% provide(:title, 'Users') %>
<h1>Users</h1>
<%= form_tag users_path, :method => 'get' do %>
<%= hidden_field_tag :direction, params[:direction] %>
<%= hidden_field_tag :sort, params[:sort] %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
```
users\_controller.rb
```
class UsersController < ApplicationController
def index
@users = User.where(:developer => false, :admin => false).search(params[:search]).order(sort_column + ' ' + sort_direction).paginate(:per_page => 10, :page => params[:page])
end
end
```
|
2013/09/10
|
[
"https://Stackoverflow.com/questions/18718469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2702786/"
] |
Try This
```
def self.search(search)
if search
q = "%#{search}%"
joins(:company).where('users.name LIKE ? OR
companies.name LIKE ?',q,q)
else
scoped
end
end
```
|
21,154,462 |
I want to rename a series of .jpg but i want to append the string at the end of file name. Please help me how can I achive this as I am new to batch file coding.
**Series of jpg files** -
CurDt\_S1, CurDt\_S2, CurDt\_S3 etc.. uptill S20.
**I want to replace CurDt\_S1 with CurDt\_1\_S1 as -**
CurDt\_1\_S1, CurDt\_1\_S2, CurDt\_1\_S3 uptill S20.
**Here is the code I am using -**
```
setlocal enabledelayedexpansion
set str=_1
for %%a in (CurDt_S*.jpg) do (
set oldName=%%a
set newName=oldname+str
call :Action
echo.
echo back in For loop
)
echo.
echo For loop completed
echo !oldName!
echo !newName!
endlocal
goto:eof
:Action
echo.
echo start of Action loop
echo !oldName!
echo !newName!
ren "!oldName!" "!newName!"
echo end of Action loop
```
Thanks,
Sneha
|
2014/01/16
|
[
"https://Stackoverflow.com/questions/21154462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2742601/"
] |
```
for /L %%x in (1,1,20) do ECHO ren CurDt_S%%x.jpg CurDt_1_S%%x.jpg
```
should work for you.
The required commands are merely `ECHO`ed for testing purposes. After you've verified that the commands are correct, change `ECHO REN` to `REN` to actually rename the files.
|
865,466 |
I was on Office 2010 and got asked to be in the pilot group for Office 365. After this period O365 went live and I deemed it a good idea to uninstall Office 2010.
After this was done all Office related filetypes lost their association with office and excel woorkbooks were always opened as a blank file.
Since repairing the installation did not resolve the issue I tried uninstalling. Since Office 365 is installed as 10 different products (1 for each language) on my machine I have to uninstall one by one.
After I uninstalled to de-DE version, which is my native locale, everyting worked again in en-US. Here comes my problem: How can I re-install the German language pack or uninstall Office 365 in a one-click manner completly to get it re-installed from the system center from scratch?
I can't just go to the System center configruation manager and click install. The system then will tell me, that office is already installed. If I uninstall everything by hand, I have to calculate about 2 hours per language pack at current performance of my hard drive.
|
2015/01/16
|
[
"https://superuser.com/questions/865466",
"https://superuser.com",
"https://superuser.com/users/275822/"
] |
You can open `viber.db` in `C:\Users\USERNAME\AppData\Roaming\ViberPC\YourNumber` with WordPad and somewhere in the beginning of the file you will find contacts phone numbers. Just enter them manually in your new phone and they will appear on you contacts list in Viber.
Or download [command-line shell for accessing and modifying SQLite databases](http://www.sqlite.org/download.html) and copy `sqlite3.exe` , `viber.db` and `data.db` to `C:\`. Then in CMD(start -> run -> cmd.exe) position yourself on `C:\` and enter `sqlite3.exe viber.db`
Then enter:
```
SELECT ContactRelation.Number, Contact.FirstName, Contact.SecondName FROM Contact INNER JOIN ContactRelation ON Contact.ContactID = ContactRelation.ContactID ORDER BY Contact.FirstName;
```
There you go! You got all contacts listed, phone number first and then the name!
|
68,464,729 |
Goodday,
I have 2 sheets. For each ID on sheet1 I need to verify if that ID is also on sheet2 AND if Date Processed is blank.
If both condition are true > today's date should be set in Date Processed.
[](https://i.stack.imgur.com/Wvet0.png)
I've managed to do so for just 1 value (A2) from sheet1.
What I need is a way to go through all the values in sheet1. Ideally the row in sheet1 would also get deleted (not sure if that is possible)
This is my code till now
```
function myMatch(){
var file = SpreadsheetApp.getActiveSpreadsheet();
var ss = file.getSheetByName("Sheet1");
var ws = file.getSheetByName("Sheet2");
var wsData = ws.getDataRange().getValues();
var mySearch = ss.getRange("A2").getValue();
for(var i = 0; i < wsData.length; i++){
if(wsData[i][1] == mySearch && wsData[i][2] == "")
{
ws.getRange(i+1,3).setNumberFormat('dd"-"mmm"-"yyyy').setValue(new Date());
}
}
}
```
Your help is really appreciated as I have been trying and searching for a solution for 2 days now. Thank you
|
2021/07/21
|
[
"https://Stackoverflow.com/questions/68464729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15972586/"
] |
I know it doesn't makes much sense. Muhammet's code works and looks just fine. But, rather for fun and educational purposes, here is another "functional" solution:
```
function myFunction() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const s1 = ss.getSheetByName('Sheet1');
const s2 = ss.getSheetByName('Sheet2');
// get data from Sheet1 and Sheet2
const s1_data = s1.getDataRange().getValues().slice(1,);
const s2_data = s2.getDataRange().getValues().slice(1,);
// get IDs from data of Sheet1
const IDs = s1_data.map(x => x[0]);
const IDs_to_delete = []; // here will be IDs to delete
// function checks and fill a row and adds ID to array to delete
const write_date = (id,row) => {
if (row[1] == id && row[2] == '') {
IDs_to_delete.push(id);
row[2] = new Date();
}
}
// change rows within data of Sheet 2
IDs.forEach(id => s2_data.forEach(row => row = write_date(id,row)));
// clear and fill Sheet 2
s2.getDataRange().offset(1,0).clearContent();
s2.getRange(2,1,s2_data.length,s2_data[0].length).setValues(s2_data);
// remove rows from data of Sheet 1
const s1_data_new = s1_data.filter(row => !IDs_to_delete.includes(row[0]));
// clear and fill Sheet 1 with new data
s1.getDataRange().offset(1,0).clearContent();
s1.getRange(2,1,s1_data_new.length,s1_data_new[0].length).setValues(s1_data_new);
}
```
The only improvements over Muhamed's code is that this implementation removes processed rows from Sheet1. And, I believe, it will work faster for huge lists, because it doesn't use `getRange()` and `setValue()` on every found cell but fills all cells of the sheet at once with `setValues()` method.
|
33,316,924 |
I am trying to make a slider which scrolls over 3 div elements on to 3 new scroll elements. I am looking for a manual slider with an arrow pointing right on the right side and left on the left side. The slider should slide right when right arrow clicked and display the 3 remaining div elements. If the left arrow is clicked first, nothing should happen. if it is clicked after the right arrow has been clicked it should slide back to the three previous div elements. If the right arrow is clicked twice in a row the second click should slide back to the initial 3 div elements. Basically, I want to end up with something like the slider on the unity website. Link: <http://unity3d.com/unity>
Here is my HTML code so far. It displays the boxes on 3 columns and 2 rows:
```
<div class="categories">
<div class="category">
<div class="rect">
<img src="stuff.gif">
</div>
<h3>Stuff</h3>
<p>Stuff.</p>
</div>
<div class="category">
<div class="rect">
<img src="stuff.gif">
</div>
<h3>Stuff</h3>
<p>Stuff.</p>
</div>
<div class="category">
<div class="rect">
<img src="stuff.gif">
</div>
<h3>Stuff</h3>
<p>Stuff.</p>
</div>
<div class="category">
<div class="rect">
<img src="stuff.gif">
</div>
<h3>Stuff</h3>
<p>Stuff.</p>
</div>
<div class="category">
<div class="rect">
<img src="stuff.gif">
</div>
<h3>Stuff</h3>
<p>Stuff.</p>
</div>
<div class="category">
<div class="rect">
<img src="stuff.gif">
</div>
<h3>Stuff</h3>
<p>Stuff.</p>
</div>
</div>
```
Here are the CSS styles for the boxes:
```
/**********************
*******CATEGORIES******
**********************/
.categories {
width: 90%;
margin: 3% 9%;
clear: left;
}
.category {
padding: 7% 5% 3% 5%;
width: 20%;
border: 1px solid #E0E0E0;
float: left;
cursor: pointer;
text-align: center;
}
.category:hover {
border: 1px solid #4F8E64;
}
.category h3 {
color: #3F7250;
margin: 6% 0;
}
.category p {
text-align: center;
}
```
Make sure that the padding and margin and width stays in percentages. Feel free to modify the code and share it with me on fiddle or something.
|
2015/10/24
|
[
"https://Stackoverflow.com/questions/33316924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5393006/"
] |
Here's a start to see if we're headed in the right direction:
```
>> M = [1 2 3 4;
1 2 8 10;
4 5 7 9;
2 3 6 4;
1 2 4 7];
>> N = M; %// copy M into a new matrix so we can modify it
>> idx = ismember(N(:,1:2), N(1,1:2), 'rows')
idx =
1
1
0
0
1
>> N(idx, :)
ans =
1 2 3 4
1 2 8 10
1 2 4 7
```
Then you can remove those rows from the original matrix and repeat.
```
>> N = N(~idx,:)
N =
4 5 7 9
2 3 6 4
```
|
13,134,230 |
I have the following column values in my crystal report:
```
|Code |Unit |
|A |2 |
|B |3 |
|C |2 |
|D |3 |
|E |1 |
|F |1 |
|G |4 |
|H |(3) |
```
I want to summarize the Unit except the Units which has Code H,J,K, and L.
The Codes: H,J,K, and L contains units which has parenthesis.
Is there a way to do this?
|
2012/10/30
|
[
"https://Stackoverflow.com/questions/13134230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/925063/"
] |
I use a FSM machine to change the state of the application. Each states shows and hides the appropriate view. My views use transition to animate in and out, so changing the state is more complex, then simple show/hide - it animates in and out from one state into another. I have forked <https://github.com/fschaefer/Stately.js> to fit my needs.
|