_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d2401 | train | The current implementation of the streaming interface does not provide this. So in order to achieve this you will need to copy the code of the underlying XSSFSheetXMLHandler and adjust it so that the cell-content is not formatted. | unknown | |
d2402 | train | You can loop over all fields and skip the record if any of the fields are empty:
$ awk -F'|' '{ for (i=1; i<=NF; ++i) { if (!$i) next } }1' foo.dat
A|A|A|B
if (!$i) is "if field i is not non-empty", and 1 is short for "print the line", but it is only hit if next was not executed for any of the fields of the current line.
A: Another in awk:
$ awk -F\| 'gsub(/[^|]+(\||$)/,"&")==NF' file
A|A|A|B
print record if there are NF times | terminating (non-empty, |-excluding) strings.
A: awk '!/\|\|/&&!/\|$/&&!/^\|/' file
A|A|A|B | unknown | |
d2403 | train | This is more or less expected due to the way that BigQuery streaming servers cache the table generation id (an internal name for the table).
Can you provide more information about the use case? It seems strange to delete the table then to write to the same table again.
One workaround could be to truncate the table, instead of deleting the it. You can do this by running SELECT * FROM <table> LIMIT 0, and the table as a destination table (you might want to use allow_large_results = true and disable flattening, which will help if you have nested data), then using write_disposition=WRITE_TRUNCATE. This will empty out the table but preserve the schema. Then any rows streamed afterwards will get applied to the same table. | unknown | |
d2404 | train | As noted by Alateros in the comments, since [email protected] you can use index signatures for template literals.
Though you still have to ensure type field must be required and may have the type that is not compatible with lowercased keys type. So you may write Spec type like that:
type Spec = {
[K in RefKey | PropKey]: 'type' extends K
? string
: K extends RefKey
? SomeRefType
: K extends PropKey
? SomePropType
: never
} & {
type: string
}
playground link
A: I removed
type RefKey = `${UppercaseLetters}${string}`
type PropKey = `${LowercaseLetters}${string}`
and replaced with UppercaseLetters and LowercaseLetters types
Is it what are you looking for? | unknown | |
d2405 | train | for i in (n, n+1)
Iterates over two numbers, n and n + 1, not all divisors. You need to use range to iterate from 1 to n
for i in range(1, n + 1)
A: Your current richNumber function will always return False because sum1 will
always be 0. Try the following code:
def richNumber(n):
nb = []
n = int(n)
sum1 = 0
for i in range(1, n):
if n % i == 0:
nb.append(i)
sum1 = sum(nb)
if sum1 > n:
return True
else:
return False | unknown | |
d2406 | train | The problem is with the scope, currently the query the altered user.pswrd is outside of the scope of the query so it falls back to the value assigned at the top.
By moving the query inside the 'crypto.pbkdf2'... block the user.pswrd value will work as intended. I've updated your code (and made the salt generation asynchronous, as you have used the async version of pbkdf2 anyway).
var tobi = new User({
usrnm: 'sp',
pswrd: 'an'
});
module.exports = User;
function User(obj) {
for (var key in obj) {
this[key] = obj[key];
}
}
User.prototype.save = function(fn) {
var user = this;
// Changed salt generation to async version
// See: https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback
crypto.randomBytes(50, function(ex, buf) {
if (ex) throw ex;
salt = buf.toString('base64');
// password, salt, iterations, keylen[, digest], callback
crypto.pbkdf2(user.pswrd, salt, 10000, 150, 'sha512', function(err, derivedKey) {
user.pswrd = derivedKey.toString('hex');
// Moved the query within the hash function
var query = client.query('INSERT INTO mytable(usrnm,pswrd)VALUES($1,$2) RETURNING mytable_id', [user.usrnm, user.pswrd], function(err, result) {
if (err) {
console.log(err)
} else {
var newlyCreatedId = result.rows[0].mytable_id;
}
});
query.on("end", function(result) {
console.log(result);
client.end();
});
});
});
}
tobi.save(function(err) {
if (err) throw error;
console.log("yo");
})
A: To answer your edit, I think you just need to understand that crypto.pbkdf2 is an asynchronous function that has a callback function as it's last parameter.
So within that callback function, you can access the psw variable, and you are able to do something like psw = newlyCreatedId. However, in your code the query is most likely called before the callback is. Therefore, you cannot make use of the psw variable in the query as your code stands.
What Ashley B did is to put your query function within the callback, to ensure that the query is not called until after the crypto function. You could also structure your code to use events, or promises if you didn't wish to nest the functions.
A: This is to answer your EDIT and to help you understand the passing of data between internal and external functions:
I've modified your code slightly to demonstrate the point. What you must understand is the scope and context of the calling function and how your function gets invoked. Crypto.pbkdf2 function accepts a function as a callback. This function is not part of the regular/sequential flow of control. The pbkdf2 function is an 'asynchronous' function - it returns immediately, but the processing can continue on background. This is why the code marked with '//Output 1: This will be undefined' below, will output 'undefined'. The main thread continues while pbkdf2 continues processing in background.
When the system is done processing, it calls the function you specified as the callback to let you know its done processing. Think of it as an SMS you send to someone vs. making a phone call. They reply back with an SMS whenever they get a chance.
However, when the system invokes the callback function, the "scope" or the "context" is different (think of it as an external entity calling your callback function). Therefore, it does not know what the scope/variables/functions in your context. In order to pass data between callback function and your objects, you can use the 'bind' method along with 'this' keyword:
var tobi = new User({
usrnm:'sp',
pswrd:'an'
});
module.exports = User;
function User(obj){
for(var key in obj){
this[key] = obj[key];
}
}
User.prototype.save = function (fn){
var user=this;
var psw ; //Change this to this.psw to pass changes back.
var crypto = require('crypto');
var salt = crypto.randomBytes(50).toString('base64');
crypto.pbkdf2(user.pswrd, salt, 10000, 150, 'sha512',function(err, derivedKey) {
var justCrypted = derivedKey.toString('hex');
console.log('Finished crypting' + justCrypted);
this.psw = justCrypted;
//When we use 'this' here, we set the value in the right scope/context.
//The var psw does not exist outside the scope of this function, so the
//external function will not know about it. By defining it in the current
// (this) scope, we ensure that external function is also aware of it.
this.externalFunction(justCrypted);
//Bind the callback function to the current context - it will remember
//this when the callback gets invoked. Think of it as explicitly specifying
//the 'context' of the call/method.
}.bind(this));
//Output 1: This will be undefined as callback has not returned yet.
console.log('New psw' + this.psw);
/*var query=client.query('INSERT INTO mytable(usrnm,pswrd)VALUES($1,$2) RETURNING mytable_id',[user.usrnm,user.pswrd], function(err, result) {
if(err) {console.log(err)}
else {
var newlyCreatedId = result.rows[0].mytable_id;
}
});
query.on("end", function (result) {console.log(result);client.end();}); */
}
User.prototype.externalFunction = function (someData) {
console.log('Data passed from an internal function');
console.log('New PSW: ' + this.psw);
console.log('Data from external function: ' + someData);
}
tobi.save(function (err){
if (err)throw error;
console.log("yo");
})
If I run the above, I see the following output. Note that data is now being passed between internal and external functions via the callback:
C:\temp\node\npm-test>node index.js
New pswundefined
3f9219ae14f9246622973724ace5cb66b190a4b5e86abf482fce5d7889e6aff870741d672ff78e7765fada25f150c70e5e61
c13b5bcdec634d03830668348b5a7d06cf75f426259dcf804241eb2f4362d10f1ebf23a1aecca28072a3f38fb8a39eba88c9
f055e9e7ccabafcd8caed25d8b26f3726022973175545f77e4024bcbcc657081ea5d1f2baf5e9080cbb20696135f2be8834c
Data passed from an internal function
New PSW: 3f9219ae14f9246622973724ace5cb66b190a4b5e86abf482fce5d7889e6aff870741d672ff78e7765fada25f15
0c70e5e61c13b5bcdec634d03830668348b5a7d06cf75f426259dcf804241eb2f4362d10f1ebf23a1aecca28072a3f38fb8a
39eba88c9f055e9e7ccabafcd8caed25d8b26f3726022973175545f77e4024bcbcc657081ea5d1f2baf5e9080cbb20696135
f2be8834c
Data from external function: 3f9219ae14f9246622973724ace5cb66b190a4b5e86abf482fce5d7889e6aff870741d6
72ff78e7765fada25f150c70e5e61c13b5bcdec634d03830668348b5a7d06cf75f426259dcf804241eb2f4362d10f1ebf23a
1aecca28072a3f38fb8a39eba88c9f055e9e7ccabafcd8caed25d8b26f3726022973175545f77e4024bcbcc657081ea5d1f2
baf5e9080cbb20696135f2be8834c
Have a look here to understand how bind works and here to understand the concept of this and context in javascript.
EDIT: In response to your latest, comment.
if you just wanted to pass the justCrypted from pbkdf2 to the var psw of User.prototype.save, you can use the synchronous version of the same method:
crypto.pbkdf2Sync(password, salt, iterations, keylen[, digest])
Your method will then look like:
User.prototype.save = function (fn){
var user=this;
var psw ;
var crypto = require('crypto');
var salt = crypto.randomBytes(50).toString('base64');
psw = crypto.pbkdf2Sync(user.pswrd, salt, 10000, 150, 'sha512');
var justCrypted = psw.toString('hex');
console.log(justCrypted);
....
....
}
The important difference here is that this is an synchronous method and the code will wait for crypto.pbkdf2Sync to finish returning a value before it moves to the next line, thus following a sequential flow.
Hope that helps.
EDIT 2: Here is a little diagram of how async works:
Unfortunately, you just can't do it the way you want without using an external function or a synchronous function. | unknown | |
d2407 | train | The problem is that the following piece of code is a definition, not a declaration:
std::ostream& operator<<(std::ostream& o, const Complex& Cplx) {
return o << Cplx.m_Real << " i" << Cplx.m_Imaginary;
}
You can either mark the function above and make it "inline" so that multiple translation units may define it:
inline std::ostream& operator<<(std::ostream& o, const Complex& Cplx) {
return o << Cplx.m_Real << " i" << Cplx.m_Imaginary;
}
Or you can simply move the original definition of the function to the "complex.cpp" source file.
The compiler does not complain about "real()" because it is implicitly inlined (any member function whose body is given in the class declaration is interpreted as if it had been declared "inline"). The preprocessor guards prevent your header from being included more than once from a single translation unit ("*.cpp" source file"). However, both translation units see the same header file. Basically, the compiler compiles "main.cpp" to "main.o" (including any definitions given in the headers included by "main.cpp"), and the compiler separately compiles "complex.cpp" to "complex.o" (including any definitions given in the headers included by "complex.cpp"). Then the linker merges "main.o" and "complex.o" into a single binary file; it is at this point that the linker finds two definitions for a function of the same name. It is also at this point that the linker attempts to resolve external references (e.g. "main.o" refers to "Complex::Complex" but does not have a definition for that function... the linker locates the definition from "complex.o", and resolves that reference).
A: Move implementation to complex.cpp
Right now after including this file implementation is being compiled to every file.
Later during linking there's a obvious conflict because of duplicate implementations.
::real() is not reported because it's inline implicitly (implementation inside class definition)
A: I was having this problem, even after my source and header file were correct.
It turned out Eclipse was using stale artifacts from a previous (failed) build.
To fix, use Project > Clean then rebuild.
A: An alternative to designating a function definition in a header file as inline is to define it as static. This will also avoid the multiple definition error. | unknown | |
d2408 | train | You are doing the comparison i < 5 and incrementing i in the for loop without initializing it first causing undefined behavior (the value of i at that point is a random garbage value)
If you try this instead
#include<stdio.h>
int main()
{
int i = 0;
goto l;
for(i = 0 ; i < 5 ; i++)
l: printf("Hi\n");
return 0;
}
it will have defined behavior and this program will print Hi 5 times.
And to see what is going on try
#include<stdio.h>
int main()
{
int i = 4;
goto l;
for(i = 0 ; i < 5 ; i++)
l: printf("Hi\n");
return 0;
}
and Hi will be printed only once, becase once you enter the for loop, i == 4.
So basicaly you are jumping this line
for(i = 0 ; i < 5 ; i++)
failing to initialize i and thus having undefined behavior for the reasons explained above.
Using goto is not always bad, but when it's used to control the flow of program, it makes it hard to follow the code and understand what it does, and generally it wont be necessary for that, but it's surely useful in some situations, for example consider this case
FILE *file;
int *x;
int *y;
file = fopen("/path/to/some/file", "r");
if (file == NULL)
return IO_ERROR_CODE;
x = malloc(SomeSize * sizeof(int));
if (x == NULL)
{
fclose(file);
return MEMORY_EXHAUST_ERROR_CODE;
}
y = malloc(SomeSize * sizeof(int));
if (y == NULL)
{
free(x);
fclose(file);
return MEMORY_EXHAUST_ERROR_CODE;
}
return SUCESS_CODE;
so you have to add more and more code at each function exit point, but you could do this instead
FILE *file = NULL;
int *x = NULL;
int *y = NULL;
file = fopen("/path/to/some/file", "r");
if (file == NULL)
return SOME_ERROR_CODE;
x = malloc(SomeSize * sizeof(int));
if (x == NULL)
goto abort;
y = malloc(SomeSize * sizeof(int));
if (y == NULL)
goto abort;
return SUCCESS_CODE;
abort:
if (x != NULL)
free(x);
if (y != NULL)
free(y);
if (file != NULL)
fclose(file);
return MEMORY_EXHAUST_ERROR_CODE;
of course in your example, there is absolutely no reason to use goto.
A: Your code exhibits Undefined Behavior. This is because when the execution of the program reaches the goto statement, the execution of the program jumps inside the body of the for loop, thus skipping the initialization part of the for loop. Thus,i is uninitialized and it contains a "garbage value".
As a side note: Using gotos are considered to be bad practice as it makes reading/maintaining your code much harder. | unknown | |
d2409 | train | Seeing your XSLT would help understand why you get unsorted output. But in any case, try <xsl:sort select="col/text()"/>.
A: The following XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" indent="yes"/>
<xsl:template match="/table">
<xsl:copy>
<xsl:apply-templates select="row">
<xsl:sort select="col[1]"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
<xsl:template match="row">
<tr>
<td>
<xsl:value-of select="col[1]"/>
</td>
<td>
<a href="{col[3]}">
<xsl:value-of select="col[2]"/>
</a>
</td>
<td>
<xsl:value-of select="col[5]"/>
</td>
</tr>
</xsl:template>
</xsl:stylesheet>
When applied to the following input XML
<table>
<row>
<col>1</col>
<col>name1</col>
<col>link1</col>
<col>junk1</col>
<col>value1</col>
</row>
<row>
<col>2</col>
<col>name2</col>
<col>link2</col>
<col>junk2</col>
<col>value2</col>
</row>
</table>
will produce the following output
<table>
<tr>
<td>1</td>
<td>
<a href="link1">name1</a>
</td>
<td>value1</td>
</tr>
<tr>
<td>2</td>
<td>
<a href="link2">name2</a>
</td>
<td>value2</td>
</tr>
</table>
Do note the use of Attribute Value Templates (AVT) to set the href attribute for the a tag:
<a href="{col[3]}">
You can also do away with the xsl:sort should you just wish the order of the rows in the output to be the same as the order in input XML. | unknown | |
d2410 | train | lmList in nlme can run multiple regressions at once:
library(nlme)
DF <- data.frame(A = 1:10, X = 1:5, Y = 11:15, Z = 1:10)
DF2 <- cbind(A = DF$A, stack(DF[c("X", "Y")]))
lmList(A ~ values | ind, DF2)
A: Here is an alternative using formulas() from package modelr :
df <- data.frame(A = 1:10, X = 1:5, Y = 11:15, Z = 1:10)
library(modelr)
ll <- formulas(~ A,
m1 = ~ X,
m2 = ~ Y
)
results_list <- lapply(ll, lm, data = df) | unknown | |
d2411 | train | With dplyr, you can sort the data by dates decreasingly and then select the first non-NA value in each column.
library(dplyr)
df %>%
group_by(country, continent) %>%
arrange(desc(date), .by_group = TRUE) %>%
summarise(across(everything(), ~ .x[!is.na(.x)][1])) %>%
ungroup()
# # A tibble: 2 × 7
# country continent date n_case Ex TD TC
# <chr> <chr> <date> <int> <int> <int> <int>
# 1 Italy Europe 2022-02-24 6 87 2 90
# 2 USA America 2022-02-23 6 7 3 65
Data
df <- structure(list(country = c("Italy", "Italy", "USA", "USA", "USA"),
continent = c("Europe", "Europe", "America", "America", "America"),
date = structure(c(19047, 19009, 19046, 19000, 18996), class = "Date"),
n_case = c(6L, 12L, NA, 6L, 6L), Ex = c(NA, 87L, NA, NA, 7L),
TD = c(2L, 2L, 3L, 5L, 7L), TC = c(90L, 86L, 65L, 67L, 87L)),
row.names = c(NA, -5L), class = "data.frame") | unknown | |
d2412 | train | Go to Window in Eclipse and then to Preferences.
Click on the arrow beside Android and you will find Lint Error Checking.
Uncheck the second checkbox which says "Run full error check when exporting the app and abort if fatal errors are found."
And you are good to go. | unknown | |
d2413 | train | Terraform is not aware of the resources deployed in the arm template, so it detects the state change and tries to "fix" that. I dont see any CF resources for logic app connections, so seeing how it detects that parameters.connections changed from 0 to 1 adding your connection directly to the workflow resource might work, but CF mentions : Any parameters specified must exist in the Schema defined in workflow_schema, but I dont see connections in the schema, which is a bit weird, but I assume I'm misreading the schema
you can also use ignore_changes:
lifecycle {
ignore_changes = [
"parameters.$connections"
]
}
according to the comments and this
reading:
https://www.terraform.io/docs/configuration/resources.html#ignore_changes | unknown | |
d2414 | train | You have to specifically select the results you want to be hydrated. The problem you're seeing is that you're just selecting activity.
Then when you call $activity->getMembers() members are lazy loaded, and this doesn't take into account your query.
You can avoid this like so:
public function getCollectiveActivities($selfId)
{
$qb = $this->createQueryBuilder('a');
$qb->addSelect('m');
$qb->join('a.members', 'm')
->where('m.id != :selfId')
->setParameter('selfId', $selfId);
return $qb
->getQuery()
->getResult();
}
This means your fetched activity will already have its members hydrated and restricted by your query condition.
A: public function getCollectiveActivities($selfId)
{
return $this->createQueryBuilder('a')
->join('a.members', 'm')
->where($qb->expr()->neq('c.selfId', $selfId))
->getQuery()
->getResult();
}
A: I ended up adapting a solution posted by @NtskX.
public function getCollectiveActivities($selfId)
{
$qbMyCollectives = $this->createQueryBuilder('ca');
$qbMyCollectives
->select('ca.id')
->leftJoin('ca.members', 'm')
->where('m.id = :selfId')
->setParameter('selfId', $selfId);
$qb = $this->createQueryBuilder('a');
$qb
->where($qb->expr()->notIn('a.id', $qbMyCollectives->getDQL()))
->setParameter('selfId', $selfId); // I had to declare the parameter one more time
return $qb
->getQuery()
->getResult();
}
I really thought someone would show up with a better way to do the join, so any other answer is much welcome. | unknown | |
d2415 | train | battery's answer is ok, but i would do this way:
recievers = []
for user in Users.objects.all():
recievers.append(user.email)
send_mail(subject, message, from_email, recievers)
this way, you will open only once connection to mail server rather than opening for each email.
A: Sending email is very simple.
For your Users model this would be:
for user in Users.objects.all():
send_mail(subject, message, from_email,
user.Email)
Checkout Django's Documentation on send emails for more details.
Would be useful if you mention what problem you are facing if you've tried this.
Also note, IntegerField does not have a max_length argument.
A: for user in Users.objects.all():
send_mail(subject, message, from_email,
user.Email)
This is the best solutions and it works well | unknown | |
d2416 | train | Copied from a Disord conversation: The answer is to include a setting for the calendar table css within the calendar invocation JS. See snippet below where I have added the second, inverted calendar to illustrate.
Notes: It appears that the ccalendar > className > table CSS setting is an entire replacement for the table css class settings. As a benefit, this could allow more refined tweaking. As a negative, if the component CSS were altered and our code remained unaltered then this might be a breaking change case.
$('#standard_calendar')
.calendar();
$('#inverted_calendar')
.calendar({
className: {
table: 'ui inverted celled center aligned unstackable table'
}
});
<link href="https://fomantic-ui.com/dist/semantic.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://fomantic-ui.com/dist/semantic.js"></script>
<body>
<div class='daContent'>
<p>
The first calendar is using standard colors, the second is inverted.
</p>
<span>Standard colors calendar</span>
<div class="ui calendar" id="standard_calendar">
<div class="ui input left icon">
<i class="calendar icon"></i>
<input type="text" placeholder="Date/Time">
</div>
</div>
</p>
<p>
<span>Inverted colors calendar</span>
<div class="ui calendar" id="inverted_calendar">
<div class="ui input left icon">
<i class="calendar icon"></i>
<input type="text" placeholder="Date/Time">
</div>
</div>
</p>
</body> | unknown | |
d2417 | train | I've never actually seen something that does this specifically but it would be quite easy to knock such a utility out in C\C#\VB or any other language that gives easy access to the Service API. Here's a sample of something in C#.
using System;
using System.ComponentModel;
using System.ServiceProcess;
namespace SCSync
{
class Program
{
private const int ERROR_SUCCESS = 0;
private const int ERROR_INVALID_COMMAND_LINE = 1;
private const int ERROR_NO_ACCESS = 2;
private const int ERROR_COMMAND_TIMEOUT = 3;
private const int ERROR_NO_SERVICE = 4;
private const int ERROR_NO_SERVER = 5;
private const int ERROR_INVALID_STATE = 6;
private const int ERROR_UNSPECIFIED = 7;
static int Main(string[] args)
{
if (args.Length < 2 || args.Length > 4)
{
ShowUsage();
return ERROR_INVALID_COMMAND_LINE;
}
string serviceName = args[0];
string command = args[1].ToUpper();
string serverName = ".";
string timeoutString = "30";
int timeout;
if (args.Length > 2)
{
if (args[2].StartsWith(@"\\"))
{
serverName = args[2].Substring(2);
if (args.Length > 3)
{
timeoutString = args[3];
}
}
else
{
timeoutString = args[2];
}
}
if (!int.TryParse(timeoutString, out timeout))
{
Console.WriteLine("Invalid timeout value.\n");
ShowUsage();
return ERROR_INVALID_COMMAND_LINE;
}
try
{
ServiceController sc = new ServiceController(serviceName, serverName);
switch (command)
{
case "START":
sc.Start();
sc.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 0, timeout));
break;
case "STOP":
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 0, timeout));
break;
case "PAUSE":
sc.Pause();
sc.WaitForStatus(ServiceControllerStatus.Paused, new TimeSpan(0, 0, 0, timeout));
break;
case "CONTINUE":
sc.Continue();
sc.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 0, timeout));
break;
default:
Console.WriteLine("Invalid command value.\n");
ShowUsage();
return ERROR_INVALID_COMMAND_LINE;
}
}
catch (System.ServiceProcess.TimeoutException)
{
Console.WriteLine("Operation timed out.\n");
return ERROR_COMMAND_TIMEOUT;
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("You are not authorized to perform this action.\n");
return ERROR_NO_ACCESS;
}
catch (InvalidOperationException opEx)
{
Win32Exception winEx = opEx.InnerException as Win32Exception;
if (winEx != null)
{
switch (winEx.NativeErrorCode)
{
case 5: //ERROR_ACCESS_DENIED
Console.WriteLine("You are not authorized to perform this action.\n");
return ERROR_NO_ACCESS;
case 1722: //RPC_S_SERVER_UNAVAILABLE
Console.WriteLine("The server is unavailable or does not exist.\n");
return ERROR_NO_SERVER;
case 1060: //ERROR_SERVICE_DOES_NOT_EXIST
Console.WriteLine("The service does not exist.\n");
return ERROR_NO_SERVICE;
case 1056: //ERROR_SERVICE_ALREADY_RUNNING
Console.WriteLine("The service is already running.\n");
return ERROR_INVALID_STATE;
case 1062: //ERROR_SERVICE_NOT_ACTIVE
Console.WriteLine("The service is not running.\n");
return ERROR_INVALID_STATE;
default:
break;
}
}
Console.WriteLine(opEx.ToString());
return ERROR_UNSPECIFIED;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return ERROR_UNSPECIFIED;
}
return ERROR_SUCCESS;
}
private static void ShowUsage()
{
Console.WriteLine("SCSync usage:\n");
Console.WriteLine("SCSync.exe service command <server> <timeout>\n");
Console.WriteLine(" service The name of the service upon which the command will act. (Required)");
Console.WriteLine(" command The command to execute - one of: start|stop|pause|continue. (Required)");
Console.WriteLine(" server The name of the server on which the target service runs. This must start with \\. (Optional)");
Console.WriteLine(" timeout The timeout period in seconds in which the command should finish. The default is 30 seconds. (Optional)");
Console.WriteLine("\n");
}
}
}
The WaitForStatus is just a polling loop and could be easily replaced in any other language. The rest is just OpenService and ControlService.
A: Eric Falsken's solution works perfectly. +1.
But I'd like to add that the timeout command would sometimes fail with error:
"Input redirection is not supported, exiting the process immediately"
To fix this I've had to replace the timeout command:
timeout /t 2 /nobreak >NUL
with the following:
ping -n 2 127.0.0.1 1>NUL
A: Edit on 10/20/2011 - updated my code. I posted it before fully debugging.
Many thanks to Eric Falsken. What a great solution. I tweaked Eric's code (BTW look for a couple of typographical errors if you intend to use it). I added logging and some additional error-checking for some conditions Eric didn't account for. Since I'm most interested in a service restart (not just stopping and/or starting), I only built upon Eric's restart code. Anyway, I'm posting my version, hope you like it!
@ECHO off
:: This script originally authored by Eric Falsken http://stackoverflow.com/
:: Revised for by George Perkins 10/20/2011
IF [%1]==[] GOTO Usage
IF [%2]==[] GOTO Usage
:SetLocalVariables
SET /A MyDelay=0
SET MyHours=%time:~0,2%
IF %MyHours%==0 SET MyHours=00
IF %MyHours%==1 SET MyHours=01
IF %MyHours%==2 SET MyHours=02
IF %MyHours%==3 SET MyHours=03
IF %MyHours%==4 SET MyHours=04
IF %MyHours%==5 SET MyHours=05
IF %MyHours%==6 SET MyHours=06
IF %MyHours%==7 SET MyHours=07
IF %MyHours%==8 SET MyHours=08
IF %MyHours%==9 SET MyHours=09
SET MyMinutes=%time:~3,2%
SET MySeconds=%time:~6,2%
SET MyHundredths=%time:~9,2%
SET MyMonth=%date:~4,2%
SET MyDay=%date:~-7,2%
SET MyCentury=%date:~-4,4%
SET MyTimeStamp=%MyCentury%%MyMonth%%MyDay%%MyHours%%MyMinutes%%MySeconds%
IF "%3" == "" (
SET MyLog=C:\Temp
) ELSE (
SET MyLog=%3
)
SET MyLogFile=%MyLog%\ServiceRestart%MyTimeStamp%.log
ECHO.
ECHO. >> %MyLogFile%
ECHO ------------- ------------- %MyHours%:%MyMinutes%:%MySeconds%.%MyHundredths% %MyMonth%/%MyDay%/%MyCentury% ------------- -------------
ECHO ------------- ------------- %MyHours%:%MyMinutes%:%MySeconds%.%MyHundredths% %MyMonth%/%MyDay%/%MyCentury% ------------- ------------- >> %MyLogFile%
ECHO Begin batch program %0.
ECHO Begin batch program %0. >> %MyLogFile%
ECHO Logging to file %MyLogFile%.
ECHO Logging to file %MyLogFile%. >> %MyLogFile%
ECHO Attempting to restart service %2 on computer %1.
ECHO Attempting to restart service %2 on computer %1. >> %MyLogFile%
PING -n 1 %1 | FIND "TTL=" >> %MyLogFile%
IF errorlevel 1 IF NOT errorlevel 2 GOTO SystemOffline
SC \\%1 query %2 | FIND "FAILED 1060" >> %MyLogFile%
IF errorlevel 0 IF NOT errorlevel 1 GOTO InvalidServiceName
SC \\%1 query %2 | FIND "STATE" >> %MyLogFile%
IF errorlevel 1 IF NOT errorlevel 2 GOTO SystemOffline
:ResolveInitialState
SET /A MyDelay+=1
SC \\%1 query %2 | FIND "STATE" | FIND "RUNNING" >> %MyLogFile%
IF errorlevel 0 IF NOT errorlevel 1 GOTO StopService
SC \\%1 query %2 | FIND "STATE" | FIND "STOPPED" >> %MyLogFile%
IF errorlevel 0 IF NOT errorlevel 1 GOTO StartService
SC \\%1 query %2 | FIND "STATE" | FIND "PAUSED" >> %MyLogFile%
IF errorlevel 0 IF NOT errorlevel 1 GOTO SystemOffline
ECHO Service State is changing, waiting %MyDelay% seconds for service to resolve its state before making changes.
ECHO Service State is changing, waiting %MyDelay% seconds for service to resolve its state before making changes. >> %MyLogFile%
TIMEOUT /t %MyDelay% /nobreak >> %MyLogFile%
GOTO ResolveInitialState
:StopService
SET /A MyDelay=0
ECHO Stopping %2 on \\%1.
ECHO Stopping %2 on \\%1. >> %MyLogFile%
SC \\%1 stop %2 | FIND "FAILED" >> %MyLogFile%
IF errorlevel 0 IF NOT errorlevel 1 GOTO Unstoppable
:StoppingServiceDelay
SET /A MyDelay+=1
IF %MyDelay%==21 GOTO MaybeUnStoppable
ECHO Waiting %MyDelay% seconds for %2 to stop.
ECHO Waiting %MyDelay% seconds for %2 to stop. >> %MyLogFile%
TIMEOUT /t %MyDelay% /nobreak >> %MyLogFile%
:StoppingService
SC \\%1 query %2 | FIND "STATE" | FIND "STOPPED" >> %MyLogFile%
IF errorlevel 0 IF NOT errorlevel 1 GOTO StoppedService
SC \\%1 query %2 | FIND "STATE" | FIND "STOP_PENDING" >> %MyLogFile%
IF errorlevel 0 IF NOT errorlevel 1 GOTO StoppingServiceDelay
GOTO StoppingServiceDelay
:MaybeUnStoppable
:: If we got here we waited approximately 3 mintues and the service has not stopped.
SC \\%1 query %2 | FIND "NOT_STOPPABLE" >> %MyLogFile%
IF errorlevel 0 IF NOT errorlevel 1 GOTO OneLastChance
GOTO Unstoppable
:OneLastChance
SC \\%1 stop %2 >> %MyLogFile%
SET /A MyDelay+=1
ECHO Waiting %MyDelay% seconds for %2 to stop.
ECHO Waiting %MyDelay% seconds for %2 to stop. >> %MyLogFile%
TIMEOUT /t %MyDelay% /nobreak >> %MyLogFile%
SC \\%1 query %2 | FIND "STATE" | FIND "STOPPED" >> %MyLogFile%
IF errorlevel 0 IF NOT errorlevel 1 GOTO StoppedService
SC \\%1 query %2 | FIND "STATE" | FIND "RUNNING" >> %MyLogFile%
IF errorlevel 1 IF NOT errorlevel 2 GOTO UnknownState
SC \\%1 query %2 | FIND "NOT_STOPPABLE" >> %MyLogFile%
IF errorlevel 0 IF NOT errorlevel 1 GOTO Unstoppable
GOTO StoppingServiceDelay
:StoppedService
ECHO %2 on \\%1 is stopped.
ECHO %2 on \\%1 is stopped. >> %MyLogFile%
GOTO StartService
:StartService
SET /A MyDelay=0
ECHO Starting %2 on \\%1.
ECHO Starting %2 on \\%1. >> %MyLogFile%
SC \\%1 start %2 >> %MyLogFile%
GOTO StartingService
:StartingServiceDelay
SET /A MyDelay+=1
ECHO Waiting %MyDelay% seconds for %2 to start.
ECHO Waiting %MyDelay% seconds for %2 to start. >> %MyLogFile%
TIMEOUT /t %MyDelay% /nobreak >> %MyLogFile%
:StartingService
SC \\%1 query %2 | FIND "STATE" | FIND "RUNNING" >> %MyLogFile%
IF errorlevel 1 IF NOT errorlevel 2 GOTO StartingServiceDelay
:StartedService
ECHO %2 on \\%1 is started.
ECHO %2 on \\%1 is started. >> %MyLogFile%
GOTO EndExit
:SystemOffline
ECHO Failure! Server \\%1 or service %2 is not accessible or is offline!
ECHO Failure! Server \\%1 or service %2 is not accessible or is offline! >> %MyLogFile%
ECHO See log file %MyLogFile% for details!
GOTO EndExit
:InvalidServiceName
ECHO Failure! Service %2 is not valid!
ECHO Failure! Service %2 is not valid! >> %MyLogFile%
ECHO See log file %MyLogFile% for details!
GOTO EndExit
:UnknownState
ECHO Failure! Service %2 in an unknown state and cannot be stopped!
ECHO Failure! Service %2 in an unknown state and cannot be stopped! >> %MyLogFile%
ECHO See log file %MyLogFile% for details!
GOTO EndExit
:UnStoppable
ECHO Failure! Service %2 cannot be stopped! Check dependencies or system state.
ECHO Failure! Service %2 cannot be stopped! Check dependencies or system state. >> %MyLogFile%
ECHO See log file %MyLogFile% for details!
GOTO EndExit
:Usage
ECHO Will restart a remote service, waiting for the service to stop/start (if necessary).
ECHO.
ECHO Usage:
ECHO %0 [system name] [service name] [logfile path]
ECHO Example: %0 server1 MyService C:\Temp\Log
ECHO.
GOTO EndExit
:EndExit
ECHO.
ECHO %0 Ended.
ECHO.
A: What about PowerShell and Restart-Service commandlet? :)
Get-Service W3SVC -computer myserver | Restart-Service
A: Eric Falsken's scripts are fantastic for this purpose. But note that they use the timeout command which is only available in Vista/Server2003 and newer. For an XP machine you can use sleep.exe from the NT Resource Kit instead. (This should be a commment to Eric's answer but not enough rep to do that).
A: I improved the script of Eric Falsken and revised by Gerorge Perkins.
Changes:
*
*now it is not only a restart script. The script can start, stop and restart a local or remote service;
*removed logging (if you want this, you can use it simply by launching SCRIPT_NAME.bat > logfile.txt);
*sparse optimizations.
@ECHO off
:: This script originally authored by Eric Falsken http://stackoverflow.com/
:: Revised by George Perkins 10/20/2011
:: Revised by Armando Contestabile 02/23/2015
IF "%1"=="" GOTO Usage
IF "%2"=="" GOTO Usage
SET ACTION=%1
SET SERVICENAME=%2
IF "%3"=="" (
SET SYSTEMNAME=%COMPUTERNAME%
) ELSE (
SET SYSTEMNAME=%3
)
IF "%ACTION%" == "stop" (
SET ACTION=STOP
) ELSE IF "%ACTION%" == "STOP" (
SET ACTION=STOP
) ELSE IF "%ACTION%" == "start" (
SET ACTION=START
) ELSE IF "%ACTION%" == "START" (
SET ACTION=START
) ELSE IF "%ACTION%" == "restart" (
SET ACTION=RESTART
) ELSE IF "%ACTION%" == "RESTART" (
SET ACTION=RESTART
) ELSE GOTO Usage
SET STATE=
SET CURRENT_STATUS=
SET /A DEFAULT_DELAY=5
SET /A SLEEP_COUNT=0
SET /A RESTARTED=0
SET /A MAX_WAIT_PERIODS=5
ECHO.
ECHO Attempting to %ACTION% service %SERVICENAME% on computer %SYSTEMNAME%.
PING -n 1 %SYSTEMNAME% | FIND "TTL=" >nul 2>&1
IF ERRORLEVEL 1 IF NOT ERRORLEVEL 2 (
ECHO Failure! Server \\%SYSTEMNAME% or service %SERVICENAME% is not accessible or is offline!
EXIT /B 1
)
SC \\%SYSTEMNAME% query %SERVICENAME% | FIND "FAILED 1060" >nul 2>&1
IF ERRORLEVEL 0 IF NOT ERRORLEVEL 1 (
ECHO Failure! Service %SERVICENAME% is not valid!
EXIT /B 2
)
SC \\%SYSTEMNAME% query %SERVICENAME% | FIND "STATE" >nul 2>&1
IF ERRORLEVEL 1 IF NOT ERRORLEVEL 2 (
ECHO Failure! Server \\%SYSTEMNAME% or service %SERVICENAME% is not accessible or is offline!
EXIT /B 3
)
:Dispatch
FOR /f "tokens=*" %%i IN ('SC \\%SYSTEMNAME% query %SERVICENAME% ^| FIND "STATE"') DO SET STATE=%%i
ECHO %STATE% | FINDSTR /C:"1" >nul
IF %ERRORLEVEL%==0 SET CURRENT_STATUS=STOPPED
ECHO %STATE% | FINDSTR /C:"2" >nul
IF %ERRORLEVEL%==0 SET CURRENT_STATUS=START_PENDING
ECHO %STATE% | FINDSTR /C:"3" >nul
IF %ERRORLEVEL%==0 SET CURRENT_STATUS=STOP_PENDING
ECHO %STATE% | FINDSTR /C:"4" >nul
IF %ERRORLEVEL%==0 SET CURRENT_STATUS=RUNNING
ECHO %STATE% | FINDSTR /C:"5" >nul
IF %ERRORLEVEL%==0 SET CURRENT_STATUS=CONTINUE_PENDING
ECHO %STATE% | FINDSTR /C:"6" >nul
IF %ERRORLEVEL%==0 SET CURRENT_STATUS=PAUSE_PENDING
ECHO %STATE% | FINDSTR /C:"7" >nul
IF %ERRORLEVEL%==0 SET CURRENT_STATUS=PAUSED
ECHO Current status of service is %CURRENT_STATUS%
IF NOT "%CURRENT_STATUS%"=="RUNNING" IF NOT "%CURRENT_STATUS%"=="STOPPED" IF NOT "%CURRENT_STATUS%"=="PAUSED" (
IF "%SLEEP_COUNT%"=="%MAX_WAIT_PERIODS%" (
ECHO Service state won't change. Script exececution is canceled.
EXIT /B 4
)
ECHO Service State is changing, waiting %DEFAULT_DELAY% seconds...
SLEEP %DEFAULT_DELAY%
SET /A SLEEP_COUNT+=1
GOTO Dispatch
)
IF "%ACTION%"=="START" (
IF "%CURRENT_STATUS%"=="RUNNING" (
ECHO Service %SERVICENAME% is running.
GOTO EndExit
) ELSE (
GOTO StartService
)
) ELSE IF "%ACTION%"=="RESTART" (
IF "%CURRENT_STATUS%"=="RUNNING" (
IF %RESTARTED%==1 (
ECHO Service %SERVICENAME% restarted.
GOTO EndExit
)
SET /A SLEEP_COUNT=0
GOTO StopService
) ELSE (
SET /A RESTARTED=1
GOTO StartService
)
) ELSE IF "%ACTION%"=="STOP" (
IF "%CURRENT_STATUS%"=="STOPPED" (
ECHO Service %SERVICENAME% is stopped.
GOTO EndExit
) ELSE (
GOTO StopService
)
)
:StartService
ECHO Starting %SERVICENAME% on \\%SYSTEMNAME%
SC \\%SYSTEMNAME% start %SERVICENAME% >nul 2>&1
SET SLEEP_COUNT=0
GOTO Dispatch
:StopService
ECHO Stopping %SERVICENAME% on \\%SYSTEMNAME%
SC \\%SYSTEMNAME% stop %SERVICENAME% >nul 2>&1
SET SLEEP_COUNT=0
GOTO Dispatch
:Usage
ECHO This script can start/stop/restart a local or remote service, waiting for the service to stop/start ^(if necessary^).
ECHO.
ECHO Usage:
ECHO %0 ^<start^|stop^|restart^> ^<SERVICE^> [SYSTEM]
ECHO.
ECHO If no SYSTEM is provided, the script attempts to execute on the local system.
EXIT /B 5
:EndExit
ECHO.
EXIT /B 0
A: I created a set of batch scripts that use sc.exe to do just this. They are attached below. To run these scripts, you should be a user with administration rights on the target machine and running this from a computer that is a member of the same domain. It's possible to set it up to be able to run from outside of the domain (like from a VPN) but there are a lot of layers of security to work through involving firewalls, DCOM and security credentials.
One of these days, I'm going to figure out the PowerShell equivalent, which should be much easier.
safeServiceStart.bat
@echo off
:: This script originally authored by Eric Falsken
IF [%1]==[] GOTO usage
IF [%2]==[] GOTO usage
ping -n 1 %1 | FIND "TTL=" >NUL
IF errorlevel 1 GOTO SystemOffline
SC \\%1 query %2 | FIND "STATE" >NUL
IF errorlevel 1 GOTO SystemOffline
:ResolveInitialState
SC \\%1 query %2 | FIND "STATE" | FIND "STOPPED" >NUL
IF errorlevel 0 IF NOT errorlevel 1 GOTO StartService
SC \\%1 query %2 | FIND "STATE" | FIND "RUNNING" >NUL
IF errorlevel 0 IF NOT errorlevel 1 GOTO StartedService
SC \\%1 query %2 | FIND "STATE" | FIND "PAUSED" >NUL
IF errorlevel 0 IF NOT errorlevel 1 GOTO SystemOffline
echo Service State is changing, waiting for service to resolve its state before making changes
sc \\%1 query %2 | Find "STATE"
timeout /t 2 /nobreak >NUL
GOTO ResolveInitialState
:StartService
echo Starting %2 on \\%1
sc \\%1 start %2 >NUL
GOTO StartingService
:StartingServiceDelay
echo Waiting for %2 to start
timeout /t 2 /nobreak >NUL
:StartingService
SC \\%1 query %2 | FIND "STATE" | FIND "RUNNING" >NUL
IF errorlevel 1 GOTO StartingServiceDelay
:StartedService
echo %2 on \\%1 is started
GOTO:eof
:SystemOffline
echo Server \\%1 is not accessible or is offline
GOTO:eof
:usage
echo %0 [system name] [service name]
echo Example: %0 server1 MyService
echo.
GOTO:eof
safeServiceStop.bat
@echo off
:: This script originally authored by Eric Falsken
IF [%1]==[] GOTO usage
IF [%2]==[] GOTO usage
ping -n 1 %1 | FIND "TTL=" >NUL
IF errorlevel 1 GOTO SystemOffline
SC \\%1 query %2 | FIND "STATE" >NUL
IF errorlevel 1 GOTO SystemOffline
:ResolveInitialState
SC \\%1 query %2 | FIND "STATE" | FIND "RUNNING" >NUL
IF errorlevel 0 IF NOT errorlevel 1 GOTO StopService
SC \\%1 query %2 | FIND "STATE" | FIND "STOPPED" >NUL
IF errorlevel 0 IF NOT errorlevel 1 GOTO StopedService
SC \\%1 query %2 | FIND "STATE" | FIND "PAUSED" >NUL
IF errorlevel 0 IF NOT errorlevel 1 GOTO SystemOffline
echo Service State is changing, waiting for service to resolve its state before making changes
sc \\%1 query %2 | Find "STATE"
timeout /t 2 /nobreak >NUL
GOTO ResolveInitialState
:StopService
echo Stopping %2 on \\%1
sc \\%1 stop %2 %3 >NUL
GOTO StopingService
:StopingServiceDelay
echo Waiting for %2 to stop
timeout /t 2 /nobreak >NUL
:StopingService
SC \\%1 query %2 | FIND "STATE" | FIND "STOPPED" >NUL
IF errorlevel 1 GOTO StopingServiceDelay
:StopedService
echo %2 on \\%1 is stopped
GOTO:eof
:SystemOffline
echo Server \\%1 or service %2 is not accessible or is offline
GOTO:eof
:usage
echo Will cause a remote service to STOP (if not already stopped).
echo This script will waiting for the service to enter the stopped state if necessary.
echo.
echo %0 [system name] [service name] {reason}
echo Example: %0 server1 MyService
echo.
echo For reason codes, run "sc stop"
GOTO:eof
safeServiceRestart.bat
@echo off
:: This script originally authored by Eric Falsken
if [%1]==[] GOTO usage
if [%2]==[] GOTO usage
ping -n 1 %1 | FIND "TTL=" >NUL
IF errorlevel 1 GOTO SystemOffline
SC \\%1 query %2 | FIND "STATE" >NUL
IF errorlevel 1 GOTO SystemOffline
:ResolveInitialState
SC \\%1 query %2 | FIND "STATE" | FIND "RUNNING" >NUL
IF errorlevel 0 IF NOT errorlevel 1 GOTO StopService
SC \\%1 query %2 | FIND "STATE" | FIND "STOPPED" >NUL
IF errorlevel 0 IF NOT errorlevel 1 GOTO StartService
SC \\%1 query %2 | FIND "STATE" | FIND "PAUSED" >NUL
IF errorlevel 0 IF NOT errorlevel 1 GOTO SystemOffline
echo Service State is changing, waiting for service to resolve its state before making changes
sc \\%1 query %2 | Find "STATE"
timeout /t 2 /nobreak >NUL
GOTO ResolveInitialState
:StopService
echo Stopping %2 on \\%1
sc \\%1 stop %2 %3 >NUL
GOTO StopingService
:StopingServiceDelay
echo Waiting for %2 to stop
timeout /t 2 /nobreak >NUL
:StopingService
SC \\%1 query %2 | FIND "STATE" | FIND "STOPPED" >NUL
IF errorlevel 1 GOTO StopingServiceDelay
:StopedService
echo %2 on \\%1 is stopped
GOTO StartService
:StartService
echo Starting %2 on \\%1
sc \\%1 start %2 >NUL
GOTO StartingService
:StartingServiceDelay
echo Waiting for %2 to start
timeout /t 2 /nobreak >NUL
:StartingService
SC \\%1 query %2 | FIND "STATE" | FIND "RUNNING" >NUL
IF errorlevel 1 GOTO StartingServiceDelay
:StartedService
echo %2 on \\%1 is started
GOTO:eof
:SystemOffline
echo Server \\%1 or service %2 is not accessible or is offline
GOTO:eof
:usage
echo Will restart a remote service, waiting for the service to stop/start (if necessary)
echo.
echo %0 [system name] [service name] {reason}
echo Example: %0 server1 MyService
echo.
echo For reason codes, run "sc stop"
GOTO:eof
A: What about powershell and WaitForStatus? Eg, the script below would restart SQL Server on a remote machine:
$computer = "COMPUTER_NAME"
$me = new-object -typename System.Management.Automation.PSCredential -argumentlist "DOMAIN\user", (convertto-securestring "password" -asplaintext -force)
$restartSqlServer = {
$sqlServer = get-service mssqlserver
$waitInterval = new-timespan -seconds 5
if (-not ($sqlServer.Status -eq "Stopped")) {
$sqlServer.Stop()
$sqlServer.WaitForStatus('Stopped', $waitInterval)
}
$sqlServer.Start()
$sqlServer.WaitForStatus('Running', $waitInterval)
}
icm -ComputerName $computer -ScriptBlock $restartSqlServer -Credential $me
A: I've made a minor change to the script, so that it is running under Windows 10 or similar Versions.
The command "sleep" was replaced with the command "timeout".
@ECHO off
:: This script originally authored by Eric Falsken http://stackoverflow.com/
:: Revised by George Perkins 10/20/2011
:: Revised by Armando Contestabile 02/23/2015
:: Revised by Sascha Jelinek 11/13/2020
IF "%1"=="" GOTO Usage
IF "%2"=="" GOTO Usage
SET ACTION=%1
SET SERVICENAME=%2
IF "%3"=="" (
SET SYSTEMNAME=%COMPUTERNAME%
) ELSE (
SET SYSTEMNAME=%3
)
IF "%ACTION%" == "stop" (
SET ACTION=STOP
) ELSE IF "%ACTION%" == "STOP" (
SET ACTION=STOP
) ELSE IF "%ACTION%" == "start" (
SET ACTION=START
) ELSE IF "%ACTION%" == "START" (
SET ACTION=START
) ELSE IF "%ACTION%" == "restart" (
SET ACTION=RESTART
) ELSE IF "%ACTION%" == "RESTART" (
SET ACTION=RESTART
) ELSE GOTO Usage
SET STATE=
SET CURRENT_STATUS=
SET /A DEFAULT_DELAY=5
SET /A SLEEP_COUNT=0
SET /A RESTARTED=0
SET /A MAX_WAIT_PERIODS=5
ECHO.
ECHO Attempting to %ACTION% service %SERVICENAME% on computer %SYSTEMNAME%.
PING -n 1 %SYSTEMNAME% | FIND "Antwort von" >nul 2>&1
IF ERRORLEVEL 1 IF NOT ERRORLEVEL 2 (
ECHO Failure!! Server \\%SYSTEMNAME% or service %SERVICENAME% is not accessible or is offline!
EXIT /B 1
)
SC \\%SYSTEMNAME% query %SERVICENAME% | FIND "FAILED 1060" >nul 2>&1
IF ERRORLEVEL 0 IF NOT ERRORLEVEL 1 (
ECHO Failure! Service %SERVICENAME% is not valid!
EXIT /B 2
)
SC \\%SYSTEMNAME% query %SERVICENAME% | FIND "STATE" >nul 2>&1
IF ERRORLEVEL 1 IF NOT ERRORLEVEL 2 (
ECHO Failure! Server \\%SYSTEMNAME% or service %SERVICENAME% is not accessible or is offline!
EXIT /B 3
)
:Dispatch
FOR /f "tokens=*" %%i IN ('SC \\%SYSTEMNAME% query %SERVICENAME% ^| FIND "STATE"') DO SET STATE=%%i
ECHO %STATE% | FINDSTR /C:"1" >nul
IF %ERRORLEVEL%==0 SET CURRENT_STATUS=STOPPED
ECHO %STATE% | FINDSTR /C:"2" >nul
IF %ERRORLEVEL%==0 SET CURRENT_STATUS=START_PENDING
ECHO %STATE% | FINDSTR /C:"3" >nul
IF %ERRORLEVEL%==0 SET CURRENT_STATUS=STOP_PENDING
ECHO %STATE% | FINDSTR /C:"4" >nul
IF %ERRORLEVEL%==0 SET CURRENT_STATUS=RUNNING
ECHO %STATE% | FINDSTR /C:"5" >nul
IF %ERRORLEVEL%==0 SET CURRENT_STATUS=CONTINUE_PENDING
ECHO %STATE% | FINDSTR /C:"6" >nul
IF %ERRORLEVEL%==0 SET CURRENT_STATUS=PAUSE_PENDING
ECHO %STATE% | FINDSTR /C:"7" >nul
IF %ERRORLEVEL%==0 SET CURRENT_STATUS=PAUSED
ECHO Current status of service is %CURRENT_STATUS%
IF NOT "%CURRENT_STATUS%"=="RUNNING" IF NOT "%CURRENT_STATUS%"=="STOPPED" IF NOT "%CURRENT_STATUS%"=="PAUSED" (
IF "%SLEEP_COUNT%"=="%MAX_WAIT_PERIODS%" (
ECHO Service state won't change. Script exececution is canceled.
EXIT /B 4
)
ECHO Service State is changing, waiting %DEFAULT_DELAY% seconds...
TIMEOUT /t %DEFAULT_DELAY% /NOBREAK
SET /A SLEEP_COUNT+=1
GOTO Dispatch
)
IF "%ACTION%"=="START" (
IF "%CURRENT_STATUS%"=="RUNNING" (
ECHO Service %SERVICENAME% is running.
GOTO EndExit
) ELSE (
GOTO StartService
)
) ELSE IF "%ACTION%"=="RESTART" (
IF "%CURRENT_STATUS%"=="RUNNING" (
IF %RESTARTED%==1 (
ECHO Service %SERVICENAME% restarted.
GOTO EndExit
)
SET /A SLEEP_COUNT=0
GOTO StopService
) ELSE (
SET /A RESTARTED=1
GOTO StartService
)
) ELSE IF "%ACTION%"=="STOP" (
IF "%CURRENT_STATUS%"=="STOPPED" (
ECHO Service %SERVICENAME% is stopped.
GOTO EndExit
) ELSE (
GOTO StopService
)
)
:StartService
ECHO Starting %SERVICENAME% on \\%SYSTEMNAME%
SC \\%SYSTEMNAME% start %SERVICENAME% >nul 2>&1
SET SLEEP_COUNT=0
GOTO Dispatch
:StopService
ECHO Stopping %SERVICENAME% on \\%SYSTEMNAME%
SC \\%SYSTEMNAME% stop %SERVICENAME% >nul 2>&1
SET SLEEP_COUNT=0
GOTO Dispatch
:Usage
ECHO This script can start/stop/restart a local or remote service, waiting for the service to stop/start ^(if necessary^).
ECHO.
ECHO Usage:
ECHO %0 ^<start^|stop^|restart^> ^<SERVICE^> [SYSTEM]
ECHO.
ECHO If no SYSTEM is provided, the script attempts to execute on the local system.
EXIT /B 5
:EndExit
ECHO.
EXIT /B 0
A: NET START and NET STOP shouldn't return until the service has indicated that the service has started or stopped successfully.
A: I don't believe you can do this with a straight dos command. You might check Code Project or other similar sites to see if there's a custom solution for this already.
If not, you could write a secondary Windows service that does this for you by exposing the start/stop functionality through a WCF endpoint. To access this secondary service remotely, you could write a simple console app that connects to this service to start/stop the Windows service in question. Since it's a console app, it would mimic the desired behavior of working from the command line and not returning until complete (or an error occurred). It's not the straightforward, simple solution you're looking for, but I'll throw it out there for consideration. | unknown | |
d2418 | train | This is the perfect scenario for refetchQueries(): https://www.apollographql.com/docs/angular/features/cache-updates/#refetchqueries
In your scenario, you could pass this prop to your Login mutation component to refetch the GET_USER query after login. Export the GET USER from your _app.js (or wherever you're moving it to if you're putting it in a User Hoc). Then in your login mutation:
import { GET_USER } from '...'
<Mutation
mutation={LOGIN}
onError={error => {
this.setState({error: "Incorrect email or password"})
}}
onCompleted={() => {
window.location.reload() // temp solution to cause app to re-render
}}
// takes an array of queries to refetch after the mutation is complete
refetchQueries={[{ query: GET_USER }]}
>
{(login, {loading}) => (
<Login
{...this.props}
login={login}
loading={loading}
error={error}
/>
)}
</Mutation>
The other alternative is to use the update method to manually set it to the cache and then keep a reference to that data or retrieve it from the cache with a cache id so you don't have to fetch more data, but the refetchQueries is perfect for simple login mutations like this that aren't too expensive to retrieve. | unknown | |
d2419 | train | Using a class for the pairs of integers should be the first. Or is this a coincidence, that all arrays containing a bunch of pairs?
The second thing is, that these initialization-data could be read from a configuration-file.
Edit: As I looked again on this code, I realized that Doubles as keys in a Map is somewhat risky. If you produce Doubles as a result of an mathematical operation, it is not clear, if they will be equal for the computer (even if they are equal in a mathematical sense). Floating-point-numbers are represented as approximation in computers. Most likely you want to associate the values with the interval (example 0.0-0.3) and not the value itself. You may avoid trouble, if you always use the same constants as keys in the array. But in this case you could use an enum as well, and no new programmer runs into trouble, if he uses his calculated doubles as keys in the map.
A: Create another class to hold your pairs of integers, and store them using a list:
Map<Double,List<MyPair>>
Are these to be arbitrary pairs of integers, or will the represent something? If the latter, then name appropriately. New classes are cheap in Java, and good naming will reduce maintenance costs.
Edit: why are you creating an anonymous subclass of HashMap?
A: using a static initializer would be slightly better in my opinion, although it does nothing about the verbosity:
private static final Map<Double, int[][]> rules;
static {
rules = new HashMap<Double, int[][]>();
rules.put(-0.6, new int[][] { { 1, 3 } });
rules.put(-0.3, new int[][] { { 2, 2 } });
rules.put(0.0, new int[][] { { 2, 4 }, { 3, 3 }, { 4, 2 } });
rules.put(0.3, new int[][] { { 4, 4 } });
rules.put(0.6, new int[][] { { 5, 3 } });
}
Another option using a special Pair class and Arrays.asList:
class Pair<A, B> {
A a;
B b;
public Pair(A fst, B snd) {
}
// getters and setters here
}
private static final Map<Double, List<Pair<Integer, Integer>>> rules;
static {
rules = new HashMap<Double, List<Pair<Integer, Integer>>>();
rules.put(-0.6, Arrays.asList(new Pair(1, 3)));
rules.put(-0.3, Arrays.asList(new Pair(2, 2)));
rules.put(0.0, Arrays.asList(new Pair(2, 4), new Pair(3, 3), new Pair(4, 2));
// etc
}
A: Can you wrap a class around Integer[][] called, say Point?
That would make you have a
HashMap<Double, List<Point>>
A: I would start with a MultiValueMap. http://larvalabs.com/collections/.
This way you can do:
private static final MultiValueMap<Double, Integer[]> rules;
static {
MultiValueMap<Double, Integer[]> map = new MultiValueMap <Double, Integer[]>();
map.put(-0.6, new Integer[] { 1, 3 });
map.put(-0.3, new Integer[] { 2, 2 });
map.put(0.0, new Integer[] { 2, 4 }, new Integer[]{ 3, 3 }, new Integer[]{ 4, 2 } );
map.put(0.3, new Integer[] { 4, 4 } );
map.put(0.6, new Integer[] { 5, 3 } );
rules = map;
};
It looks also like you are aways using pairs of integers as the list of Keys. It would probably clean your interface up if you refered to that as a RulePair or some other specified object. Thus 'typing' your Integer array more specificially.
A: you could try also with a Builder; Java is not good as other languages for this kind of uses.. but here is FYI:
First shot
class RuleBuilder {
private Map<Double, Integer[][]> rules;
public RuleBuilder() {
rules = new HashMap<Double, Integer[][]>();
}
public RuleBuilder rule(double key, Integer[]... rows) {
rules.put(key, rows);
return this;
}
public Integer[] row(Integer... ints) {
return ints;
}
public Map<Double, Integer[][]> build() {
return rules;
}
}
sample usage:
private static final Map<Double, Integer[][]> rules =
new RuleBuilder() {{
rule(-0.6, row(1, 3));
rule(-0.3, row(2, 2));
rule(0.0, row(2, 4), row(3,3), row(4, 2));
rule(0.3, row(4, 4));
rule(0.6, row(5, 3));
}}.build();
Second shot
In order to elimate the final "build()" call and double brace init you could try with:
class RuleBuilder2 extends HashMap<Double, Integer[][]> {
public RuleBuilder2 rule(double key, Integer[]... rows) {
put(key, rows);
return this;
}
public Integer[] row(Integer... ints) {
return ints;
}
}
in this case the code is a little better:
private static final Map<Double, Integer[][]> rules2 =
new RuleBuilder2().
rule(-0.6, row(1, 3)).
rule(-0.3, row(2, 2)).
rule(0.0, row(2, 4), row(3,3), row(4, 2)).
rule(0.3, row(4, 4)).
rule(0.6, row(5, 3));
EDIT
Probably the names that I've used are not so meaningful; boxed/unboxed conversion is still a problem but this is a problem of Java
A: There's not much you can do here. The warnings have to be suppressed; in practice, you never have to worry about serialVersionUID unless you are in fact planning to serialize this object.
The boxing can (and probably should) be removed by using a typed collection as described in other answers here. To remove the boilerplate, you'll have to use a method. For example:
private static void put (double key, int x, int y) {
rules.put(key, new Point(x,y));
} | unknown | |
d2420 | train | I also would like to know the answer. I am trying to figure a way to have "persistent time" in my android game where "time passes" in game even when closed. Best solution I figure so far is getting the unix time on the games first start and check against it when reopening the app. My problem is finding a way to save that original unix time to call upon for checks. | unknown | |
d2421 | train | Generally, "namespaces" are like directories ... meaning all WMIs (Windows Management Instrumentations) will be associated to a namespace. This allows us to logically group/associate WMI together with higher level concepts.
From https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-wmiobject?view=powershell-5.1
The -Namespace parameter:
When used with the Class parameter, the Namespace parameter specifies the WMI repository namespace where the specified WMI class is located. When used with the List parameter, it specifies the namespace from which to gather WMI class information.
The WmiMonitorID is described as such (here --> https://learn.microsoft.com/en-us/windows/desktop/wmicoreprov/wmimonitorid):
The WmiMonitorID WMI class represents the identifying information about a video monitor, such as manufacturer name, year of manufacture, or serial number. The data in this class correspond to data in the Vendor/Product Identification block of Video Input Definition of the Video Electronics Standard Association (VESA) Enhanced Extended Display Identification Data (E-EDID) standard. | unknown | |
d2422 | train | Change your connection setting to the following:
class dbConnection
{
protected $db_conn;
public $db_name = "todo";
public $db_user = "root";
public $db_pass = "";
public $db_host = "localhost";
function connect()
{
try {
$this->db_conn = new PDO("mysql:host={$this->db_host};{$this->db_name}", $this->db_user, $this->db_pass); //note that $this->$db_host was wrong
return $this->db_conn;
}
catch (PDOException $e) {
//handle exception here or throw $e and let PHP handle it
}
}
}
In addition, returning values in a constructor has no side-effects (and should be prosecuted by law).
A: Please follow below code , its tested on my server and running fine .
class Config
{
var $host = '';
var $user = '';
var $password = '';
var $database = '';
function Config()
{
$this->host = "localhost";
$this->user = "root";
$this->password = "";
$this->database = "test";
}
}
function Database()
{
$config = new Config();
$this->host = $config->host;
$this->user = $config->user;
$this->password = $config->password;
$this->database = $config->database;
}
function open()
{
//Connect to the MySQL server
$this->conn = new PDO('mysql:host='.$this->host.';dbname='.$this->database, $this->user,$this->password);
if (!$this->conn)
{
header("Location: error.html");
exit;
}
return true;
} | unknown | |
d2423 | train | You can just use if() on CellEndEdit event handler
A: The easiest way to do this, if possible, is to validate the value at the entity level.
For instance, say we have the following simplified Foo entity;
public class Foo
{
private readonly int id;
private int type;
private string name;
public Foo(int id, int type, string name)
{
this.id = id;
this.type = type;
this.name = name;
}
public int Id { get { return this.id; } }
public int Type
{
get
{
return this.type;
}
set
{
if (this.type != value)
{
if (value >= 0 && value <= 5) //Validation rule
{
this.type = value;
}
}
}
}
public string Name
{
get
{
return this.name;
}
set
{
if (this.name != value)
{
this.name = value;
}
}
}
}
Now we can bind to our DataGridView a List<Foo> foos and we will be effectively masking any input in the "Type" DataGridViewColumn.
If this isn't a valid path, then simply handle the CellEndEdit event and validate the input. | unknown | |
d2424 | train | I am making some assumptions here.
*
*The first name and last name is known (eg: Steve Smith)
*You can identify the target table without any issues.
You can use the following XPath. This Xpath will find the tr which has text Steve Smith and then navigate to the td containing Edit.
//tr[./td[.='Steve']][./td[.='Smith']]/td[.='Edit']
All this is based on the HTML you posted. Hope this helps you. | unknown | |
d2425 | train | If request.method is not "POST", then final_result isn't assigned to before it is used the the call to render.
A: You should initialize final_result before
final_result = 0
if request.method == "POST":
Just as @SLDem said.
or else declare it in the function
def index(request, final_result=0)
This will also work. | unknown | |
d2426 | train | To add bulk hardware access, use the following rest api:
Method: POST
https://[username]:[apiKey]@api.softlayer.com/rest/v3.1/SoftLayer_User_Customer/[userCustomerId]/addBulkHardwareAccess
Body: Json
{
"parameters":[
[
111111,
222222,
333333,
444444
]
]
}
Reference:
https://softlayer.github.io/reference/services/SoftLayer_User_Customer/addBulkHardwareAccess/
Or if you want to add access to all hardware, use this rest api:
Method: POST
https://[username]:[apiKey]@api.softlayer.com/rest/v3.1/SoftLayer_User_Customer/[userCustomerId]/addPortalPermission
Body: Json
{
"parameters": [
{
"keyName": "ACCESS_ALL_HARDWARE"
}
]
}
Reference:
https://softlayer.github.io/reference/services/SoftLayer_User_Customer/addPortalPermission/
A: There is parameters() method to provide parameters.
slClient
.auth(slUserID, slApiKey)
.path('User_Customer', args.userID, 'addBulkHardwareAccess')
.parameters([[XXXXXX,XXXXXXXXXX]])
.post()
.then(res => {
resolve(res);
})
.catch(err => {
reject(err);
}); | unknown | |
d2427 | train | It was because of the margin you have added to the table.
<table class="sCost" style="width:650px; margin-left: 100px">
I removed margin-left from the tables which were causing the problem.
</head>
<style>
:root{
--clr-accent: #FEC3B3;
--clr-grey: rgb(207, 207, 207);
}
#confirmed{
background-color: var(--clr-accent);
display: table;
box-sizing: border-box;
text-indent: initial;
border-spacing: 2px;
border-top: 3px solid white;
}
#hours{
background-color: black;
color: white;
text-align: center;
border-color: black;
padding-bottom: 0px;
}
#congrats{
text-align: center;
}
#button1{
text-align: center;
}
#btn1{
background-color: black;
color: white;
}
@media screen and (max-width: 480px){
*{
max-width: 420px;
}
* table{
max-width: 410px;
}
element.style{
margin-right:0px;
}
html,body {
margin-right:0px;
padding: 0;
}
*img{
width: 80%;
}
.table01 {
width: 460px;
font-size: 12px;
}
#extra01{
width: 50%;
font-size: 12px;
}
#track img{
max-width: 380px;
}
#o_details{
font-size: 14px;
}
#track2 img{
width: 75%;
}
#details01, #details02{
font-size: 12px;
}
#o_items{
font-size: 14px;
}
#o_info{
font-size: 14px;
}
h1{
font-size: 20px;
}
.orders1 img, .orders2 img{
width: 80%;
}
.orders1, .orders2{
font-size: 12px;
}
#method{
font-size: 12px;
}
.o_conf img{
width: 70%;
}
#pers_sel p{
font-size: 12px;
}
.sTotal td,.sCost td,.tCost{
display:none;
}
#eButton{
padding: 5px 5px 5px 5px;
font-size: 12px;
}
}
</style>
<body>
<header>
<center>
<table class="table01" align="center" style="width:650px;border-collapse: collapse; ">
<tr>
<a href="#"><img src="./images/bracelate_03.jpg" alt="bracelate_03" /> </a>
</center>
</tr>
<tr id="extra01" style=" background-color: black;
color: white;
text-align: center;
border-color: black;
font-size: 12px;
font-weight:100;
">
<td id="oHours" style="padding-top: 5px; line-height: 0px;">
<p id="onlyh01" style="font-size: 16px; "> <b>48 HOURS ONLY</p></br>
<p id="onlyh02" style="font-weight: 500; font-size: 16px;">EXTRA 15% OFF YOUR NEXT ORDER | CODE : B15CK
</p>
</td>
</tr>
<tr id="confirmed" style="width:650px">
<th rowspan="2" style="padding-left:50px ;"><img src="./images/bracelate_07.jpg" alt="bracelate_07" /></th>
<td style="padding-left:10px ;">
<h1> YOUR ORDER IS CONFIRMED!</h1>
</td>
</tr>
<tr id="congrats">
<td style=" padding-top: 20px;
padding-bottom: 20px;">Congratulations %%firstname%%, you made a great choice </br>
We're excited to start working on your personalized jewelry. </br>
You will recieve a shipping notice as soon as it leaves our hand.
</td>
</tr>
<tr id="button1">
<td> <button id="btn1" style="padding:5px 40px 5px 40px; font-weight: bold; ">GET 15% OFF</button> </td>
</tr>
<tr id="track1" style="text-align: center;">
<td style="padding-top: 15px; padding-bottom:25px; font-size: 14px;"> <b><u>TRACK YOUR ORDER ></u></b> </td>
</tr>
<tr id="track2">
<td>
<center><img src="./images/bracelate_11.jpg" alt="bracelate_11" /> </center>
</td>
</tr>
</table>
<table class="oDetails" style="width:650px">
<tr id="o_details">
<td style="font-weight: bold; padding :5px; padding-left: 50px ; background-color: #f3f3f3;">Order
Details
</td>
</tr>
<tr id="details01">
<td style="padding-left:50px; padding-top:20px"> <u>Order Number:</u> 65224865 </td>
<tr id="details02">
<td style="padding-left:50px; padding-bottom:20px"> <u>Order Date:</u> 02/09/2018</td>
</tr>
<tr id="o_items">
<td style="font-weight: bold; padding :5px; padding-left: 50px ; background-color: #f3f3f3;">Ordered
Items
</td>
</tr>
<tr id="items01">
<td></td>
</tr>
</table>
<table class="orders1">
<tbody>
<tr>
<td rowspan="7" width="200"><b>
<img src="./images/bracelate_22.jpg" alt="bracelate_22" style="margin-bottom:40px" />
</b></td>
<td colspan="2" width="367" style="padding-top: 5px; padding-bottom: 15px;">Personalized Engraved
Mum Birthstone Neklace</td>
</tr>
<tr>
<td width="184" style="padding-top: 5px; padding-bottom: 5px;">Material :</td>
<td width="183" style="padding-top: 5px; padding-bottom: 5px;">Sterling Silver</td>
</tr>
<tr>
<td width="184" style="padding-top: 5px; padding-bottom: 5px;">1st Inscription</td>
<td width="183" style="padding-top: 5px; padding-bottom: 5px;">Name#1</td>
</tr>
<tr>
<td width="184" style="padding-top: 5px; padding-bottom: 5px;">2nd Inscription</td>
<td width="183" style="padding-top: 5px; padding-bottom: 5px;">Name#2</td>
</tr>
<tr>
<td width="184" style="padding-top: 5px; padding-bottom: 5px;">Chain Length</td>
<td width="183" style="padding-top: 5px; padding-bottom: 5px;">45 cm chain - adult</td>
</tr>
<tr>
<td width="184" style="padding-top: 5px; padding-bottom: 5px;">Price</td>
<td width="183" style="padding-top: 5px; padding-bottom: 5px;"></td>
</tr>
<tr>
<td width="184" style="padding-top: 10px; padding-bottom: 10px; color:#ee9d86">Make Changes</td>
<td width="183" style="padding-top: 10px; padding-bottom: 10px;"></td>
</tr>
</tbody>
</table>
<table>
<tr id="divider2">
<td rowspan="2"><img src="./images/divider2.jpg" alt="divider2" /></td>
</tr>
</table>
<table class="orders2">
<tbody>
<tr>
<td rowspan="7" width="200"><b>
<img src="./images/Order_Confirmation_23.jpg" alt="Order_Confirmation_23" style="margin-bottom:40px"/>
</b></td>
<td colspan="2" width="367" style="padding-top: 5px; padding-bottom: 15px;">Personalized Engraved
Mum Birthstone Neklace</td>
</tr>
<tr>
<td width="184" style="padding-top: 5px; padding-bottom: 5px;">Material :</td>
<td width="183" style="padding-top: 5px; padding-bottom: 5px;">Sterling Silver</td>
</tr>
<tr>
<td width="184" style="padding-top: 5px; padding-bottom: 5px;">1st Inscription</td>
<td width="183" style="padding-top: 5px; padding-bottom: 5px;">Name#1</td>
</tr>
<tr>
<td width="184" style="padding-top: 5px; padding-bottom: 5px;">2nd Inscription</td>
<td width="183" style="padding-top: 5px; padding-bottom: 5px;">Name#2</td>
</tr>
<tr>
<td width="184" style="padding-top: 5px; padding-bottom: 5px;">Chain Length</td>
<td width="183" style="padding-top: 5px; padding-bottom: 5px;">45 cm chain - adult</td>
</tr>
<tr>
<td width="184" style="padding-top: 5px; padding-bottom: 5px;">Price</td>
<td width="183" style="padding-top: 5px; padding-bottom: 5px;"></td>
</tr>
<tr>
<td width="184" style="padding-top: 10px; padding-bottom: 10px; color:#ee9d86">Make Changes</td>
<td width="183" style="padding-top: 10px; padding-bottom: 10px;"></td>
</tr>
</tbody>
</table>
<table style="width:650px">
<tbody>
<tr id="o_info">
<td style="font-weight: bold; padding :5px; padding-left: 50px ; background-color: #f3f3f3;">
Shipping Info</td>
</tr>
<tr>
<td style=" padding-left: 50px ; padding-top: 10px; padding-bottom: 20px; text-align: center; ">
<center> <button id="eButton"
style="padding: 5px 20px 5px 20px; background-color: white; display: flex; align-items: center;"><img
src="./images/bracelate_15.jpg" alt="bracelate_15" /> Estimated Delivery Date
<b>Thursday November 7</b> </button></center>
</td>
</tr>
<tr>
<td style=" padding-left: 50px ; "><u>Shipping Method:</u> </br>
</u>standard shipping – 10 business days – FREE
</td>
<tr>
<td id="method" style=" padding-left: 50px ; "><a href="#">Change Shopping Method</a></td>
</tr>
</tr>
<tr>
<td style=" padding-left: 50px ; padding-top: 20px;"><u>Shipping Address </br>
</u>Idania pérez </br>
3001 nw 15 st </br>
Miami, florida 33125 </br>
united states </br>
<a href="#"> Change Shopping Method</a></td>
</tr>
</tbody>
</table>
<table>
<tr id="divider">
<th rowspan="2"><img src="./images/divider.jpg" alt="divider" /></th>
</tr>
</table>
<table class="sTotal" style="width:650px;">
<tr>
<td id="stotal_1" style = "width:500px">Subtotal</td>
<td id="stotal_2" >89.80</td>
</tr>
</table>
<table class="sCost" style="width:650px;">
<tr>
<td id="scost_1"style = "width:500px">Shipping cost</td>
<td id="scost_2">Free of Charge</td>
</tr>
</table>
<table>
<tr id="divider2">
<td rowspan="2"><img src="./images/divider2.jpg" alt="divider2" /></td>
</tr>
</table>
<table class="tCost" style="width:650px;">
<tr>
<td id="tcost_1" style = "width:500px"><strong>Total Cost</strong></td>
<td id="tcost_2"><strong>89.80</strong></td>
</tr>
</table>
<table>
<tr id="bracelate_18">
<th rowspan="2"><img src="./images/bracelate_18.jpg" alt="bracelate_18" /></th>
<td>
</table>
<table >
<tr id="selected">
<td id="pers_sel" style="width: 650px; text-align: center;padding: 10px 0px 10px 0px; font-size: 18px;"> <p>Personally
Selected for %%firstname%%</p> </td>
</tr>
</table>
<table class="o_conf"style="width: 650px;">
<tbody>
<tr>
<td width="190" style="text-align: center;"><img src="./images/Order_Confirmation_21.jpg" alt="Order_Confirmation_21" /> <p style="text-align: center; font-weight: bold; text-decoration: underline; "> SHOP NOW ></p></td>
<td width="190"style="text-align: center;"><img src="./images/bracelate_22.jpg" alt="bracelate_22" /> <p style="text-align: center;font-weight: bold; text-decoration: underline; ">SHOP NOW ></p></td>
<td width="190" style="text-align: center;"><img src="./images/Order_Confirmation_23.jpg" alt="Order_Confirmation_23" /><p style="text-align: center;font-weight: bold; text-decoration: underline; ">SHOP NOW ></p></td>
</tr>
</tbody>
</table>
<tr>
<td id="btm_menu" width="650" style="padding-top: 30px;">
<table id="new_menue_2020" valign="middle" cellpadding="0" cellspacing="0" border="0" width="650"
align="center" bgcolor="#ffffff" style="padding: 0px 0px 0px; vertical-align: middle;">
<tbody>
<tr>
<td id="btm_menu_men_icon" bgcolor="#f3f3f3" width="222" align="right"
style="border-bottom: 3px solid #ffffff; padding: 0px;">
<a href="https://www.mynamenecklace.com/"
target="_blank" style="text-decoration: none; color: #3a4249;">
<img id="btm_menu_men_icon_img" width="38"
src="./images/bracelate_27.jpg"></a>
</td>
<td id="btm_menu_men_text" bgcolor="#f3f3f3" width="372" align="left"
style="border-bottom: 3px solid #ffffff; text-transform: uppercase; letter-spacing: 2px; font-family: Verdana, sans-serif; font-size: 18px; padding-left: 13px;">
<a href="https://www.mynamenecklace.com/"
target="_blank" style="text-decoration: none; color: #3a4249;">
Jewelry for Him</a>
</td>
<td id="btm_menu_men_arrow" bgcolor="#f3f3f3" width="70" align="right"
style="border-bottom: 3px solid #ffffff; padding: 0px;">
<a href="https://www.mynamenecklace.com/"
target="_blank" style="text-decoration: none; color: #3a4249;">
<img id="btm_menu_men_arrow_img" width="70"
src="./images/bracelate_29.jpg"> </a>
</td>
</tr>
<tr>
<td id="btm_menu_mom_icon" width="222" bgcolor="#f3f3f3" align="right"
style="border-bottom: 3px solid #ffffff; padding: 0px;">
<a href="https://www.mynamenecklace.com/"
target="_blank" style="text-decoration: none; color: #3a4249;">
<img id="btm_menu_mom_icon_img" width="38"
src="./images/bracelate_36.jpg" ></a>
</td>
<td id="btm_menu_mom_text" width="372" bgcolor="#f3f3f3" align="left"
style="border-bottom: 3px solid #ffffff; text-transform: uppercase; letter-spacing: 2px; font-family: Verdana, sans-serif; font-size: 18px; padding-left: 13px;">
<a href="https://www.mynamenecklace.com/"
target="_blank" style="text-decoration: none; color: #3a4249;">
Jewelry for Her</a>
</td>
<td id="btm_menu_mom_arrow" width="70" bgcolor="#f3f3f3" align="right"
style="border-bottom: 3px solid #ffffff; padding: 0px;">
<a href="https://www.mynamenecklace.com/"
target="_blank" style="text-decoration: none; color: #3a4249;">
<img id="btm_menu_mom_arrow_img" width="70"
src="./images/bracelate_29.jpg"></a>
</td>
</tr>
<tr>
<td id="btm_menu_kid_icon" bgcolor="#f3f3f3" width="222" align="right"
style="border-bottom: 3px solid #ffffff; padding: 0px;">
<a href="https://www.mynamenecklace.com/"
target="_blank" style="text-decoration: none; color: #3a4249;">
<img id="btm_menu_kid_icon_img" width="38"
src="./images/bracelate_32.jpg"></a>
</td>
<td id="btm_menu_kid_text" bgcolor="#f3f3f3" width="358"
style="border-bottom: 3px solid #ffffff; vertical-align: middle; text-transform: uppercase; letter-spacing: 2px; font-family: Verdana, sans-serif; font-size: 18px; padding-left: 13px;">
<a href="https://www.mynamenecklace.com/"
target="_blank" style="text-decoration: none; color: #3a4249;">
Best Sellers </a>
</td>
<td id="btm_menu_kid_arrow" bgcolor="#f3f3f3" width="70" align="right"
style="border-bottom: 3px solid #ffffff;">
<a href="https://www.mynamenecklace.com/"
target="_blank" style="text-decoration: none; color: #3a4249;">
<img id="btm_menu_kid_arrow_img" width="70"
src="./images/bracelate_29.jpg"></a>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<table style="margin-top: 20px;">
</table>
<table
style="width:650px; margin: 30px, 0px, 30px, 0px; text-align: center; background-color:#f3f3f3; padding: 5px; line-height: 0px;">
<tbody>
<tr>
<tr>
<td style="border: 1px solid rgb(189, 188, 188)">
<p style="font-size: 18px;"> <i> Got a Question ?</i></p>
<p style="font-size: 14px;">Visit Our Help Center</p>
</td>
</tr>
</tr>
</tbody>
</table>
<table style="margin-top: 20px;">
</table>
<table>
<tr>
<td style="text-align:center; line-height: 5px;">
<h1 style="padding-bottom: 5px;">SUBSCRIBERS SAVE THE MOST!</h1>
<p> Sign up now for VIP access to exclusive offers, </p>
<p>giveaways and new jewellery launches</p>
</td>
</tr>
<tr id="button1">
<td> <button id="btn1" style="padding:5px 40px 5px 40px; font-weight: bold; ">SUBSCRIBE NOW</button>
</td>
</tr>
</table>
<table>
<tr id="divider">
<th rowspan="2"><img src="./images/divider.jpg" alt="divider" /></th>
<tr>
</table>
<table style="margin-top: 20px; line-height: 25px;">
<tr>
<td>This e-mail was sent from an automated system that is unable to accept incoming e-mails. <br> Please
do not reply to this e-mail.
<p style="line-height: 0rem; color: gray;">Copyright <a href="https://www.mynamenecklace.com/"
target="_blank" style="text-decoration: none; color: #3a4249;"> <u>MyNameNecklace. </u> </a> All rights reserved.</p>
</td>
</tr>
</table>
</center>
</header>
</body>
</html> | unknown | |
d2428 | train | I keep these local changes in a branch that never gets pushed. My workflow looks like this (assuming master tracks a public branch origin/master):
git checkout -b private
// make local changes, such as plugging in license keys, passwords, etc.
git commit -am "DO NOT PUSH: local changes"
// tag here because later my cherry-pick starts here
git tag -f LOCAL
// now work on what you need to work on... and whenever I am ready, commit away
git commit -am "feature 1"
// keep hacking...
git commit -am "feature 2"
// When I get to a point where I want to push the series of commits I've got to the remote repo:
git checkout master
git cherry-pick LOCAL..private
git push origin master
git rebase master private
git tag -f LOCAL
// resume working... | unknown | |
d2429 | train | This code solved my question request.env["HTTP_MY_HEADER"]. The trick was that I had to prefix my header's name with HTTP
A: I've noticed in Rails 5 they now expect headers to be spelled like this in the request:
Access-Token
Before they are transformed into:
HTTP_ACCESS_TOKEN
In Rails. Doing ACCESS_TOKEN will no longer work.
A: request.headers does not return a hash, but an instance of ActionDispatch::Http::Headers, which is a wrapper around rack env.
ActionDispatch::Http::Headers implements many methods like [] and []= which make it behave like a hash, but it doesn't override the default inspect, hence you can't see the key-value pairs by just p or pp it.
You can, however, see the request headers in the rack env:
pp request.headers.env.select{|k, _| k =~ /^HTTP_/}
Remember that the request headers in rack env are the upcased, underscored and HTTP_ prefixed version of the original http request headers.
UPDATE
Actually there are a finite set of request headers that are not prefixed HTTP_. These (capitalized and underscored) header names are stored in ActionDispatch::Http::Headers::CGI_VARIABLES. I list them below:
AUTH_TYPE
CONTENT_LENGTH
CONTENT_TYPE
GATEWAY_INTERFACE
HTTPS
PATH_INFO
PATH_TRANSLATED
QUERY_STRING
REMOTE_ADDR
REMOTE_HOST
REMOTE_IDENT
REMOTE_USER
REQUEST_METHOD
SCRIPT_NAME
SERVER_NAME
SERVER_PORT
SERVER_PROTOCOL
SERVER_SOFTWARE
So the full version of listing request headers would be
pp request.headers.env.select{|k, _| k.in?(ActionDispatch::Http::Headers::CGI_VARIABLES) || k =~ /^HTTP_/}
A: You can see hash of actual http headers using @_headers in controller. | unknown | |
d2430 | train | Problem
The decode method you want belongs to Bytes and BytesArray objects. So you need to convert your hex string to Bytes (or BytesArray I guess).
Solution
For this, you can use the fromhex method to convert the hex string. But it may require some formatting beforehand to exclude the '0x' part of the string. You may be better off therefore using Python's format, or f-strings, instead of hex.
Here is an example.
integer = 207
hexstring = f'{integer:x}'
hexbytes = bytes.fromhex(hexstring)
decoded = hexbytes.decode('cp1251',errors='strict')
Of course, you can combine the above into your original one-liner if you wish. | unknown | |
d2431 | train | If your input is reasonably small, then you can try using recursion (however if the input is big, you might fail with a stack overflow).
You first call find_on_row giving it the whole list of way elements, the whole array, and also indices of the current way element we find (in the beginning it's 0) and the index of a row you want to search over (in the beginning it's 0, as you said).
find_on_row goes over all elements in the specified row, and for each elements that is equal to the needed way element it calls find_on_col function (since you have BD only once on the first row, the function find_on_col is called once with this column.
find_on_col does the similar thing - it goes over all elements in the specified column, looks for the next way elements and calls find_on_row for each match (2 times in this case, since 1C can be found twice on the first column.
These two calls now search the answer separately, one from the 3rd row, the other from the 4th row. They go until either the whole way is found (i.e. way_index is the maximum possible), or if there's no match for the current way elements (so no answer from this search path).
def find_on_row(way, array, way_index, row_index):
if way_index == len(way): # found answer
return []
for col_index in range(len(array[0])):
if array[row_index][col_index]== way[way_index]:
candidate_answer = find_on_col(way, array, way_index + 1, col_index)
if not candidate_answer is None: # unwind answer
return [col_index] + candidate_answer
return None
def find_on_col(way, array, way_index, col_index):
if way_index == len(way): # found answer
return []
for row_index in range(len(array)):
if array[row_index][col_index] == way[way_index]:
candidate_answer = find_on_row(way, array, way_index + 1, row_index)
if not candidate_answer is None: # unwind answer
return [row_index] + candidate_answer
return None
way = ['BD', '1C', 'BD', '55']
array = [['1C', 'BD', '1C', '55', '55'], ['55', '55', '55', '1C', '1C'], ['E9', '1C', '55', '55', 'E9'], ['BD', '1C', '1C', '1C', 'BD'], ['55', 'BD', 'E9', '55', '1C']]
print(f'Starting from first row the answer is {find_on_row(way, array, 0, 0)}')
# Starting from first row the answer is [1, 3, 0, 1]
It prints indices starting from 0, so to get your desired output you can increment each value by 1 (I don't do that, because it's more convenient to work with indices starting from 0) | unknown | |
d2432 | train | Just snap the header and footer at the bottom of the page using fixed positioning.
header, footer{ position:fixed; left:0; right:0; z-index:1; }
header{ top:0; }
footer{ bottom:0; }
Then you can give your body the background your div#body had before. The div gets no background and will expand as much as needed.
div#body{ background:none; }
body{ background:#eee; }
This will look like the div would fill the remaining space of the page. Finally give your header and footer a background so that you can't see the background of the body under it.
header, footer{ background:#fff; }
By the way I would suggest removing body margins. body{ margin:0; }
A: I believe it's a bit impossible to do that with just CSS. You can make a webpage with 100% height like this:
html{
height: 100%;
}
body{
height: 100%;
}
#body{
height: 100%;
}
And then for header, body and footer you can do like this:
header{
height: 100px;
left: 0;
position: absolute;
top: 0;
width: 100%;
background-color: #f00;
}
#body{
bottom: 100px;
left: 0;
position: absolute;
right: 0;
top: 100px;
background-color: #fff;
}
footer{
bottom: 0;
height: 100px;
left: 0;
position: absolute;
width: 100%;
background-color: #ff0;
}
It might work for a bit, but it'll break at some point. When you resize your browser, it'll be running out of room for your #body. If you want a better solution, you should use javascript. In your javascript, calculate how much space you have for your #body, then either adjust the height of header and footer. Or adjust the #body instead. | unknown | |
d2433 | train | Here is the unit test solution:
index.tsx:
import React, { useReducer, useEffect } from 'react';
import { listReducer, fetchList } from './reducer';
export const Posts = () => {
const [list, dispatch] = useReducer(listReducer, []);
useEffect(() => {
fetchList(dispatch);
}, []);
return (
<ul>
{list.map((el) => (
<li key={el.id}>{el.title}</li>
))}
</ul>
);
};
reducer.ts:
import axios from 'axios';
const LIST_SUCCES = 'LIST_SUCCES';
const LIST_FAILURE = 'LIST_FAILURE';
export const fetchList = async (dispatch) => {
try {
const result = await axios.get('/list/'); /* AXIOS */
dispatch({ type: LIST_SUCCES, payload: result.data.list });
} catch (error) {
dispatch({ type: LIST_FAILURE });
}
};
export const listReducer = (state, action) => {
switch (action.type) {
case LIST_SUCCES:
return action.payload;
case LIST_FAILURE:
return [];
default:
throw new Error();
}
};
index.spec.tsx:
import React from 'react';
import { Posts } from './';
import { mount } from 'enzyme';
import axios from 'axios';
import { act } from 'react-dom/test-utils';
describe('Posts', () => {
afterAll(() => {
jest.restoreAllMocks();
});
it('should render list correctly', async () => {
const mResponse = { data: { list: [{ id: 1, title: 'jest' }] } };
jest.spyOn(axios, 'get').mockResolvedValueOnce(mResponse);
const wrapper = mount(<Posts></Posts>);
expect(wrapper.find('ul').children()).toHaveLength(0);
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 0));
});
wrapper.update();
expect(wrapper.find('ul').children()).toHaveLength(1);
expect(wrapper).toMatchInlineSnapshot(`
<Component>
<ul>
<li
key="1"
>
jest
</li>
</ul>
</Component>
`);
});
it('should render empty list when request list data failed', async () => {
const mError = new Error('Internal server error');
jest.spyOn(axios, 'get').mockRejectedValueOnce(mError);
const wrapper = mount(<Posts></Posts>);
expect(wrapper.find('ul').children()).toHaveLength(0);
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 0));
});
wrapper.update();
expect(wrapper.find('ul').children()).toHaveLength(0);
expect(wrapper).toMatchInlineSnapshot(`
<Component>
<ul />
</Component>
`);
});
});
Unit test result with coverage report:
PASS src/stackoverflow/59197574/index.spec.tsx (12.494s)
Posts
✓ should render list correctly (105ms)
✓ should render empty list when request list data failed (37ms)
› 1 snapshot written.
------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
------------|----------|----------|----------|----------|-------------------|
All files | 95.83 | 66.67 | 100 | 95 | |
index.tsx | 100 | 100 | 100 | 100 | |
reducer.ts | 92.86 | 66.67 | 100 | 91.67 | 21 |
------------|----------|----------|----------|----------|-------------------|
Snapshot Summary
› 1 snapshot written from 1 test suite.
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 1 written, 1 passed, 2 total
Time: 14.409s
Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59197574 | unknown | |
d2434 | train | If you are worried about size of request an response, you can add GZip support.
public class CompressAttribute : System.Web.Mvc.ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpRequestBase request = filterContext.HttpContext.Request;
string acceptEncoding = request.Headers["Accept-Encoding"];
if (string.IsNullOrEmpty(acceptEncoding)) return;
acceptEncoding = acceptEncoding.ToUpperInvariant();
HttpResponseBase response = filterContext.HttpContext.Response;
if (acceptEncoding.Contains("GZIP") && response.Filter != null)
{
response.AppendHeader("Content-encoding", "gzip");
response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
}
else if (acceptEncoding.Contains("DEFLATE") && response.Filter != null)
{
response.AppendHeader("Content-encoding", "deflate");
response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
}
}
}
then in your controller add attribute to the action or the controller itself:
[Compress]
public class AccountController : Controller | unknown | |
d2435 | train | The information is available through the catalog views in the SYSIBM schema.
Schema (library) information is available in SQLSCHEMAS.
Table (file) information is available in SQLTABLES.
Column (field) information is available in SQLCOLUMNS.
*
*V7R1: IBM i catalog tables and views
*V5R4: ODBC and JDBC catalog views | unknown | |
d2436 | train | Solved it:
go build -ldflags '-linkmode external -s -w -extldflags "--static-pie"' -buildmode=pie -tags 'osusergo,netgo,static_build' -o /hello hello.go | unknown | |
d2437 | train | $ cat f1
"desc_test":[
"id",
"name",
],
$ cat ip.txt
1
2
3
I would suggest to avoid i command and use r command which will be robust regardless of file content
$ # to insert before first line
$ cat f1 ip.txt
"desc_test":[
"id",
"name",
],
1
2
3
$ # to insert any other line number, use line_num-1
$ # for example, to insert before 2nd line, use 1r
$ # r command will read entire contents from a file
$ sed '1r f1' ip.txt
1
"desc_test":[
"id",
"name",
],
2
3 | unknown | |
d2438 | train | You don't need to run parallel tasks in order to measure the elapsed time. An example in C++11:
#include <chrono>
#include <string>
#include <iostream>
int main()
{
auto t1 = std::chrono::system_clock::now();
std::string s;
std::cin >> s;
// Or whatever you want to do...
auto t2 = std::chrono::system_clock::now();
auto elapsedMS =
(std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1)).count()
std::cout << elapsedMS;
}
EDIT:
Since it seems you are interested in a way to launch several tasks in parallel, here is a hint (again, using C++11):
#include <ctime>
#include <future>
#include <thread>
#include <iostream>
int long_computation(int x, int y)
{
std::this_thread::sleep_for(std::chrono::seconds(5));
return (x + y);
}
int main()
{
auto f = std::async(std::launch::async, long_computation, 42, 1729);
// Do things in the meanwhile...
std::string s;
std::cin >> s;
// And we could continue...
std::cout << f.get(); // Here we join with the asynchronous operation
}
The example above starts a long computation that will take at least 5 seconds, and in the meanwhile does other stuff. Then, eventually, it calls get() on the future object to join with the asynchronous computation and retrieve its result (waiting until it is finished if it hasn't finished yet).
A: If you really want to use threads, not just counting time you can use boost.
Example:
include <boost/thread.hpp>
void task1() {
// do something
}
void task2() {
// do something
}
void main () {
using namespace boost;
thread thread1 = thread(task1);
thread thread2 = thread(task2);
thread2.join();
thread1.join();
}
A:
I'm not trying to do this timing thing in particular, it's just the easiest example I could come up with to ask about running functions independently..
Then you may want to look into multithreading. In C++11, you can do this:
#include <thread>
#include <iostream>
void func1() {
std::cout << "func1" << std::endl;
}
void func2() {
std::cout << "func2" << std::endl;
}
int main() {
std::thread td1(func1);
std::thread td2(func2);
std::cout << "Started 2 threads. Waiting for them to finish..." << std::endl;
td1.join();
td2.join();
std::cout << "Threads finished." << std::endl;
return 0;
}
If you're not using C++11, you still have options. You can look into:
*
*Boost Threads (Requires Boost of course)
*POSIX threads
A: Firstly you don't need to increment your own time variable. Just record the time when the program starts and the time command will return the difference between time now and start time.
More generally -
*
*It's possible to kick off a long-running task in another thread. You'll need to research this on your own; try googling that phrase.
*Event-driven programming might be more appropriate for this use case. Try "C++ event driven IO" for google, or something. | unknown | |
d2439 | train | RxJava is unopinionated about concurrency. It will produce values on the subscribing thread if you do not use any other mechanisem like observeOn/ subscribeOn. Please don't use low-level constructs like Thread in operators, you could break the contract.
Due to the use of Thread, the onNext will be called from the calling Thread ('background-thread-1'). The subscription happens on the calling (UI-Thread). Every operator down the chain will be called from 'background-thread-1'-calling-Thread. The subscription onNext will also be called from 'background-thread-1'.
If you want to produce values not on the calling thread use: subscribeOn. If you want to switch the thread back to main use observeOn somewhere in the chain. Most likely before subscribing to it.
Example:
Observable.just(1,2,3) // creation of observable happens on Computational-Threads
.subscribeOn(Schedulers.computation()) // subscribeOn happens only once in chain. Nearest to source wins
.map(integer -> integer) // map happens on Computational-Threads
.observeOn(AndroidSchedulers.mainThread()) // Will switch every onNext to Main-Thread
.subscribe(integer -> {
// called from mainThread
});
Here is a good explanitation.
http://tomstechnicalblog.blogspot.de/2016/02/rxjava-understanding-observeon-and.html | unknown | |
d2440 | train | Try with change this line while($record = mysqli_fetch_array($mydata)){ to this while($record = mysqli_fetch_array($mydata,MYSQLI_ASSOC)){
or show us your $record variable data | unknown | |
d2441 | train | I think instead of:
$this->beforeFilter('canViewThisMessage', array('only', 'show'));
you should use:
$this->beforeFilter('canViewThisMessage', array('only' => ['show']));
or
$this->beforeFilter('canViewThisMessage', array('only' => 'show'));
looking at documentation | unknown | |
d2442 | train | The output which you're seeing is the standart Node output when printing and Object. It shows that it has an Object, but does not print it out in detail.
JSON.stringify will allow you to format your object as required. It takes three arguments - the object to format, an optional replacer function, and an optional indent level. Note that the order of properties is not guaranteed.
In your case, you do not need to use the replacer function, so pass null as the second argument. The required indent level is 4 spaces, so you can pass the number 4 as the third argument.
var field=[]
var obj1={"title":"a"}
var obj2={"title":"b"}
field.push(obj1)
field.push(obj2)
var outerfiled={}
outerfiled.field=field
outerfiled.name="xyz"
var list=[outerfiled]
var result = {attechent: list}
// Extra args for JSON.stringify:
// no replacer function required - pass null, indent level of 4 spaces required
console.log(JSON.stringify(result, null, 4))
A: You need the right variable for the name.
outerfiled.name = "xyz";
// ^^^^^^^
and later an assignment to the result, like
var result = { attechent: list };
var field = [];
var obj1 = { title: "a" };
var obj2 = { title: "b" };
field.push(obj1);
field.push(obj2);
var outerfiled = {};
outerfiled.field = field;
outerfiled.name = "xyz";
var list = [outerfiled];
var result = { attechent: list };
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
A: console.log doesn't print the whole object. You can use util.inspect() if you want to print the whole object. Here is the code
var utl = require("util");
var field=[]
var obj1={"title":"a"}
var obj2={"title":"b"}
field.push(obj1)
field.push(obj2)
console.log(field)
var outerfiled={}
outerfiled.field=field
outerfiled.name="xyz"
console.log(outerfiled)
var list=[outerfiled]
console.log(utl.inspect(list, false, null)) | unknown | |
d2443 | train | Seems there is no CCSpriteFrame named mypong%04d.png in CCSpriteFrameCache. You might have ran CCSpriteFrameCache::sharedSpriteFrameCache()->removeUnusedSpriteFrames() or something simillar before.
Or you are missing .png files in your project folder so they failed to add into CCSpriteFrameCache
A: okay the problem was that my spritesheet got corrupted or something weird happened with it..it does not contain images from frame 10 to 15 ...dont know what happened to it...there are five black images in the spritesheet !! | unknown | |
d2444 | train | The 1st level cache is maintained by the Session or EntityManager, and it's only used during the life of that object. That ensures that if you get/find/retrieve a specific entity more than once during the lifetime of a Session, you'll get the same instance back (or at least a proxy to the same instance).
The 2nd level cache is maintained outside the Session/EntityManager and usually there's a copy of the object, but that is not directly linked (as with objects in the Session).
A word of caution. If you use hibernate in an application that has several instances, the 2nd level cache is not shared amongst instances. For that you need to use a distributed cache (such as terracotta)... if you want consistency amongst the instances of the app. This is not a problem if you are caching static data. | unknown | |
d2445 | train | I'm having a difficult time replicating your problem but I suspect you can solve it by added one of the following after your geometry.setCoordinates(coordinates); line:
map.updateSize();
or
map.render(); | unknown | |
d2446 | train | Because those two view controllers are in separate navigation controllers, allowing different colours for each.
A: Since all you want to do is change the colour, here is what you can do:
Simply animate the colour change:
-(void)viewWillDisappear:(BOOL)animated
{
[UIView animateWithDuration: 0.8 animations:^{
[self.navigationController.navigationBar setBarTintColor: [[UIColor orangeColor] colorWithAlphaComponent: 0.1]];
}];
}
-(void)viewWillAppear:(BOOL)animated
{
[UIView animateWithDuration: 0.8 animations:^{
[self.navigationController.navigationBar setBarTintColor: [[UIColor whiteColor] colorWithAlphaComponent: 0.1]];
}];
}
Click the GIF below for illustration: | unknown | |
d2447 | train | If you're running your script under Google Chrome, you can disable the hang monitor with the flag: --disable-hang-monitor at the command line.
Under Mozilla based browsers (e.g., Firefox, Camino, SeaMonkey, Iceweasel), go to about:config and change the value of dom.max_script_run_time key.
A: If you're asking about programmatically changing it, you can't since it is an unsecured action and no browser will allow you to do it.
PS. As suggested above, try to understand the problem and refactor your code to reduce the execution time.
A: Under Internet Explorer the maximum instruction allowed to run in a script before seeing timeout dialog is controlled by a registry key :
HKEY_CURRENT_USER\Software\Microsoft\InternetExplorer\Styles\MaxScriptStatements
This is a maximum statements so it shouldn't be related to how fast the computer run. There might be others values that I'm not aware of.
The default value is 5 000 000. Are you doing too much ?
See http://support.microsoft.com/kb/175500.
A: jQuery has its own timeout property. See: http://www.mail-archive.com/[email protected]/msg15274.html
However the message you're getting is not a jQuery issue but a server or architecture issue.
Try to see if you're loading too many Ajax calls at the same time. See if you can change it to handle less calls at a time.
Also, check the server to see how long it takes to get a response. In long running XHR requests the server may take too long to respond. In this case the server-side application or service needs modification.
Hope that helps. | unknown | |
d2448 | train | You should convert CGPoint(x: 0.0, y: 0.0) to a point relative to the collection view's frame of reference (textField.convertPoint(point: yourZeroPoint, toView: yourCollectionView)), then use yourCollectionView.indexPathForItemAtPoint to get the indexPath at that point.
A: func textFieldDidBeginEditing(textField: UITextField) {
let point: CGPoint = textField.convertPoint(CGPointZero, toView: collview1);
let indexPath:NSIndexPath? = collview1.indexPathForItemAtPoint(point)
print(point)
print(indexPath)
}
collview1 is a collection view outlet | unknown | |
d2449 | train | You are not saving your JSON file back, based on the edited amounts dict. | unknown | |
d2450 | train | It all depends. It depends on the speed, type & quality of network (e.g. is it micro-segmented or shared, how good are your switches), it depends on the size & frequency of the packets, the number of broadcasting clients, etc. If you're running a routed network i.e. multiple subnets, how (if at all) are you intending to handle broadcasts to the non-native subnets? How will the routers handle this? It depends on the capability of your end devices too, they'll need to process every UDP broadcast frame - at high rates this can slow down low-end machines quite considerably. Don't let this put you off though, if you've ever done a network trace then, unless you're on a microsegmented LAN, you'll probably see quite a bit of background broadcast traffic anyway and it all ticks along happily.
It might be worth reading up on multicast groups and seeing if that might be an option for your application as there are ways, with various types of network equipment, that you can configure your network to handle multicast more efficiently that straight UDP broadcasts.
A: I imagine it would depend on:
*
*your network configuration (do you use switches? Hubs?)
*the amount of data you're sending
*The frequency you're sending the data
*The capacity of your network.
I'd suggest writing a simple test program which attempts to send different amounts of data and the running something like netlimiter to see how much bandwidth you're using. With that information in hand you can judge how close to the limit of your network you're getting and get a firm answer to your question.. | unknown | |
d2451 | train | From http://code.google.com/p/red5/wiki/ServerWontStart
ClassNotFoundException Launcher
When the Launcher cannot be located, it usually means the server jar
is missing or misnamed. The Red5 server jar must be named like so
until we fix the bootstrap bug: red5-server-1.0.jar | unknown | |
d2452 | train | It seems that the keyword you need are "neural network interpretability" and "feature attribution". One of the best known methods in this area is called Integrated Gradients; it shows how model prediction depend on each input feature (each word embedding, in your case).
This tutorial shows how to implement IG in pure tensorflow for images, and this one uses the alibi library to highlight the words in the input text with the highest impact on a classification model. | unknown | |
d2453 | train | Update: I was mistaken, and due to simulators and iPhones having different architectures, you have to compile the framework for each one respectively. However, I was able to create a "fat framework" by following this Medium article: https://medium.com/@hassanahmedkhan/a-noobs-guide-to-creating-a-fat-library-for-ios-bafe8452b84b
This fat framework can be used for both "Generic iOS Device" and the simulator. | unknown | |
d2454 | train | Simulate your observable like this:
import { of } from 'rxjs';
statuses$ = of([new NameValue('Open', 'OPEN'), new NameValue('Closed', 'CLOSED')]);
which gives an array that *ngFor can interpret, rather than the object you are returning currently. | unknown | |
d2455 | train | it turns out I was mistaken.
Solution is: in anaconda (as well as in other implementations), set the path environment variable to the directory where 'python.exe' is installed.
As a default, the python.exe file in anaconda is in:
c:\.....\anaconda
after you do that, obviously, the python command works, in my case, yielding the following.
python
Python 3.4.3 |Anaconda 2.2.0. (64|bit)|(default, Nov 7 2015), etc, etc
A: C:\Users\\Anaconda3
I just added above path , to my path environment variables and it worked.
Now, all we have to do is to move to the .py script location directory, open the cmd with that location and run to see the output.
A: C:\Users\<Username>\AppData\Local\Continuum\anaconda2
For me this was the default installation directory on Windows 7. Found it via Rusy's answer
A: In windows 10 you can find it here:
C:\Users\[USER]\AppData\Local\conda\conda\envs\[ENVIRONMENT]\python.exe
A: Instead of giving the path following way:
C:\Users\User_name\AppData\Local\Continuum\anaconda3\python.exe
Do this:
C:\Users\User_name\AppData\Local\Continuum\anaconda3\
A: To export the exact set of paths used by Anaconda, use the command echo %PATH% in Anaconda Prompt. This is needed to avoid problems with certain libraries such as SSL.
Reference: https://stackoverflow.com/a/54240362/663028
A: You can also run conda init as below,
C:\ProgramData\Anaconda3\Scripts\conda init cmd.exe
or
C:\ProgramData\Anaconda3\Scripts\conda init powershell
Note that the execution policy of powershell must be set, e.g. using Set-ExecutionPolicy Unrestricted.
A: Try path env var for system (on windows)
C:\ ...\Anaconda3\
C:\ ...\Anaconda3\scripts
C:\ ...\Anaconda3\Library\bin
Must solve! It worked for me.
A: The default location for python.exe should be here: c:\users\xxx\anaconda3
One solution to find where it is, is to open the Anaconda Prompt then execute:
> where python
This will return the absolute path of locations of python eg:
(base) C:\>where python
C:\Users\Chad\Anaconda3\python.exe
C:\ProgramData\Miniconda2\python.exe
C:\dev\Python27\python.exe
C:\dev\Python34\python.exe
A: I want to mention that in some win 10 systems, Microsoft pre-installed a python. Thus, in order to invoke the python installed in the anaconda, you should adjust the order of the environment variable to ensure that the anaconda has a higher priority.
A: You could also just re-install Anaconda, and tick the option add variable to Path.. This will prevent you from making mistakes when editing environment variables. If you make mistakes here, your operating system could start malfunctioning.
A: Provide the Directory/Folder path where python.exe is available in Anaconda folder like
C:\Users\user_name\Anaconda3\
This should must work. | unknown | |
d2456 | train | The equality of keys is done using isEqual on the keys in question. Thus, the comparison of {1,3,5} and {3,5,1} (assuming that the numbers are represented by NSNUmber instances) will be YES.
A: Yep it seems to work nicely (not sure if there are any gotchas).
NSMutableDictionary * dict = [NSMutableDictionary dictionary];
NSSet * set;
set = [NSSet setWithObjects:@"a", @"b", @"c", @"d", nil];
[dict setObject:@"1" forKey:set];
set = [NSSet setWithObjects:@"b", @"c", @"d", @"e", nil];
[dict setObject:@"2" forKey:set];
id key;
NSEnumerator * enumerator = [dict keyEnumerator];
while ((key = [enumerator nextObject]))
NSLog(@"%@ : %@", key, [dict objectForKey:key]);
set = [NSSet setWithObjects:@"c", @"b", @"e", @"d", nil];
NSString * value = [dict objectForKey:set];
NSLog(@"set: %@ : key: %@", set, value);
Outputs:
2009-12-08 15:42:17.885 x[4989] (d, e, b, c) : 2
2009-12-08 15:42:17.887 x[4989] (d, a, b, c) : 1
2009-12-08 15:42:17.887 x[4989] set: (d, e, b, c) : key: 2
A: Yes (since a set conforms to NSCopying and implements isEqual:), with one catch: Do not use a mutable set, or any other mutable object, as a key. You will mutate it, whereupon you will break your ability to look up its value in the dictionary.
A: Yes.
Try this in irb:
require 'osx/cocoa'
abc=OSX::NSSet.setWithArray([1,2,3])
cba=OSX::NSSet.setWithArray([3,2,1])
dict=OSX::NSMutableDictionary.dictionary
dict[abc] = 'hello'
puts dict[cba]
(it works, because isEqual: for NSSet is true when you'd expect it to be and NSDictionary bases its actions on that) | unknown | |
d2457 | train | Link to documentation: https://firebase.google.com/docs/firestore/query-data/queries#simple_queries
You can where this query, which is beneficial to you in multiple ways:
1: Fewer docs pulled back = fewer reads = lower cost to you.
2: Less work on the client side = better performance.
So how do we where it? Easy.
db.collection("Users")
.where("username", "==", this.username)
.get()
.then(querySnapshot => {
//Change suggested by Frank van Puffelen (https://stackoverflow.com/users/209103/frank-van-puffelen)
//querySnapshot.forEach(doc => {
// if (this.username === doc.data().username) {
// usernameExist = true;
// }
//});
usernameExists = !querySnapshot.empty
}); | unknown | |
d2458 | train | with according to Rails conventions the logic should be separated,
*
*controllers handle permissions, auth/authorization, assign instance/class variables
*helpers handle html logic what to show/hide to user
*views should not provide any logic, permissions check. think about it from designer's point of view
*models handle data collection/manipulation over ORM
I'd like to ask you to try:
#helper
def self.best(limit)
all(:limit => limit, :order => "acception_rate desc")
end
#controller
@best_posts = Post.best
#view
<%= render :partial => "post", :collection => @best_posts %>
A: You should not bypass the controller and include much logic in your view.
You could keep a single route and filter the Post model depending on one of the params.
You don't tell enough here to answer more clearly but you have the big picture.
A: You can leave just the view file and it should work. | unknown | |
d2459 | train | This will solve the myLine access problem.
However, it doesn't solve your crossover() problem, because that function expects 2 series as arguments.
You're providing a series (rsi) and a line object (myLine), which will result in an error.
I've commented out that line.
//@version=4
study("Test", shorttitle="TST")
var line myLine = line.new(na, na, na, na, color=color.lime, extend=extend.right)
var int SHI = 30
var int FHI = 20
rsi = rsi(close, 14)
if (barstate.islast)
line.set_xy1(myLine, bar_index[SHI], rsi[SHI])
line.set_xy2(myLine, bar_index[FHI], rsi[FHI])
plot(rsi)
// alertcondition(condition=crossover(rsi, myLine), title="RSI breakout", message="RSI crossed The Line") | unknown | |
d2460 | train | Basically the FKey Constraint works in such a way that if you try to insert a value in child table with FKey value not present in your parent table, it will fail. This is not specific to JPA. It is how relational DB is designed. | unknown | |
d2461 | train | I've actually figured out what went wrong. The emulator instances now show up when I run the application but then upon launching the app in the emulator I get the following error messages:
Emulator: emulator: ERROR: Windows 7 or newer is required to run the Android Emulator.
Emulator: Process finished with exit code 1
So no, it's not possible to run the emulator on Windows Vista.
A: Try GenyMotion Android Emulator , it has a lot of features. | unknown | |
d2462 | train | You must separate your code into two different functions.
If you have this:
var txt;
var r = confirm("Press a button!");
if (r == true) {
// Put this in a function ...
txt = "You pressed OK!";
} else {
// ... and this in another function
txt = "You pressed Cancel!";
}
Would like this:
var onOkClick = function(){
txt = "You pressed OK!";
};
var onCancelClick = function(){
txt = "You pressed Cancel!";
};
And in the buttons of your modal:
<button type='button' class='btn btn-success' onclick="onOkClick()">OK</button>
<button type='button' class='btn btn-default' onclick="onCancelClick()">Cancel</button> | unknown | |
d2463 | train | As has been pointed out, there are better ways to do this, however:
$string = "<!DOCTYPE html>\n<html>\n\t<head>\n\t\t<!--[if IE 9]>\n\t\t\t<script src=\"\/js\/PIE\/PIE_IE9.js\"><\/script>\n\t\t\t<link rel=\"stylesheet\"";
echo preg_replace('/\r|\n|\t|\\\/', '', $string);
this will replace the special chars \n, \t, \r and \ | unknown | |
d2464 | train | You're describing Hungarian Notation: Do people use the Hungarian Naming Conventions in the real world?
There's lots of discussion on Stack Overflow about people's feelings on the topic.
A: It nearly is Hungarian Notation, but when you use Hungarian Notation it is more common to use a prefix instead of a suffix. | unknown | |
d2465 | train | Your problem is here:
<option value={{ top }}>
add quotes outside of {{top}}
<option value="{{ top }}" /> | unknown | |
d2466 | train | The position of the popup of a PopupView is always relative to the PopupView component. So the only way to center the popup to the middle of the Window is to but the PopupView component itself to the middle of the Window. | unknown | |
d2467 | train | You could restructure df1 to have 2 columns, location and person. That would simplify the subsequent operations.
df1_new = df1.melt(id_vars='location',
value_vars=df1.columns[1:],
value_name='person')
df1_new = df1_new.drop('variable', axis=1)
Now you can join df2 and df1_new
combined = df2.join(df1_new.set_index('person'), on='person', how='left')
Then create a pivot table
combined.pivot_table(index=['location', 'year'], columns='action', aggfunc='count')
After the pivot table is created, you can rename the columns however you'd like. | unknown | |
d2468 | train | Try below css. You have to change top: 20px; with height of .first_head.
.fix-table-paren thead .first_head th{ position: sticky; top: 0; }
.fix-table-paren thead .second_head th{ position: sticky; top: 20px; } | unknown | |
d2469 | train | Could it be you are using more or less random ids for your resources? It seems that by default resources are being sorted by id. Just stumbled across the same issue.
Also you can change the ordering: https://fullcalendar.io/docs/resourceOrder | unknown | |
d2470 | train | Your question covers a lot of ground. I will pick some quotes and answer them directly.
My project is to be a native-like HTML5 application with desktop level
complexity in need of a complete application framework
Ember.js specifically bills itself as a "web-style" framework, not a an RIA framework. That said, you can build anything you want, but you would be trailblazing.
Sproutcore bills itself as an RIA framework. You have complete control over the DOM, so if you can do it in the browser, you can do it in Sproutcore.
Ext-Js is also a good application framework for desktops (Sencha Touch is for Mobile). If you like the way its examples look, then its a good choice. You can of course customize the dom and write your own widgets.
Blossom is basically Sproutcore with a canvas based view layer. It just went into beta, so you would definitely be trailblazing if you went with it.
So, you can basically use any of the frameworks you mentioned for the RIA part of your enterprise. I would eliminate Ember.js simply because the framework itself purposes itself for web-style (e.g. twitter) as opposed to RIA (e.g. iCloud) apps, which is not what you want.
The widgets should be native-like (not web-like), but customizable so
to be unique to the application.
All three of your remaining options can do this. If you like Senchas widgets, its a good choice. I don't know if they are native enough for you. That said, with any of the remaining frameworks you can customize the DOM to your heart's content.
Mobile Appropreatness. Framework should be appropreate for mobile devices
This is a tough one. Sencha Touch (which is separate but similar to Ext-Js) is very popular and gets the job done. It is performant too; a non-trivial app ran fine on my original Droid (which surprised me).
Sproutcore is very heavy weight. It has mobile support (i.e. for touch events) but you need to very careful about the dom you create, so as not to overwhelm the browser. I wouldn't choose Sproutcore for mobile, although you could if you are very careful.
and blossom compile to native is not acceptable
That does not seem reasonable to me. To be clear, NONE of these frameworks run natively on mobile devices; they ALL run in the browser. Blossom comes closes as the canvas API is mapped directly to the native API, giving you a truly native app. The only way you could get closer would be to use objective-c/java for iOs and Android.
So basically, at this point your left with Sencha(Ext-Js) and Blossom. Blossom is still in Beta, you would be trailblazing if you tried it. Sencha is established, has great support (Blossom support is good on irc), and a large developer base.
So Sencha is the choice, unless you really want to be cutting edge, and take a little risk.
A: Troy. Indeed, ember can run with another view layer framework such as jQuery Mobile which can provide a "app-like" look and feel.There is a github project: https://github.com/LuisSala/emberjs-jqm. In my view, if you need very cool animation you can use blossom.If you want to build a app, SC or ember should be OK. I'll choose ember because it 's loosely coupled. | unknown | |
d2471 | train | With pip you can create a requirements file:
$ pip freeze > requirements.txt
Then in the server to install all of these you do:
$ pip install -r requirements.txt
And with this (if the server has everything necessary to build the binary packages that you might have included) all is ready. | unknown | |
d2472 | train | sw_sanitize does this already.
{{ '<b> hello' | sw_sanitize }}
Produces:
<b> hello</b
Internally \HTMLPurifier::purify is used, which
Filters an HTML snippet/document to be XSS-free and standards-compliant. | unknown | |
d2473 | train | for all those who have had this problem here is the solution:
override func awakeFromNib() {
super.awakeFromNib()
draw(self.frame)
}
override func draw(_ rect: CGRect) {
UIColor.gray.set()
let path = UIBezierPath(roundedRect: rect, cornerRadius: 20)
path.lineWidth = 2
path.stroke()
} | unknown | |
d2474 | train | As per the given HTML text heizil is within <strong> tag which is the immediate descendant of the <a> tag.
<a id="id_109996" class="activity">
<strong>heizil</strong>
:
<label id="sample_label">
...
...
</label>
</a>
Solution
To print the text heizil you can use either of the following locator strategies:
*
*Using cssSelector and getAttribute("innerHTML"):
System.out.println(driver.findElement(By.cssSelector("a.activity > strong")).getAttribute("innerHTML"));
*Using xpath and getText():
System.out.println(driver.findElement(By.xpath("//a[@class='activity']/strong")).getText());
Ideally, to extract the text value, you have to induce WebDriverWait for the visibilityOfElementLocated() and you can use either of the following locator strategies:
*
*Using cssSelector and getText():
System.out.println(new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("a.activity > strong"))).getText());
*Using xpath and getAttribute("innerHTML"):
System.out.println(new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[@class='a-link-normal' and @id='vvp-product-details-modal--product-title']"))).getAttribute("innerHTML")); | unknown | |
d2475 | train | I never get a chance to work on Postgres. But I have a workaround solution for this. Try as follows:
table_name = '"Table"'
table_name.find(:first)
I haven't try this in my machine since I do not have the required setup. I hope it should work. | unknown | |
d2476 | train | There is an official branch for caffe on Windows. BVLC/caffe
Follow the steps in that repository, like the below
C:\Projects> git clone https://github.com/BVLC/caffe.git
C:\Projects> cd caffe
C:\Projects\caffe> git checkout windows
:: Edit any of the options inside build_win.cmd to suit your needs
C:\Projects\caffe> scripts\build_win.cmd
If you got all the tools successfully installed, you will be able to build it successfully. Then you could find a .mex64 file under the caffe/matlab folder.
Simply add that directory into matlab, you can use matcaffe then. | unknown | |
d2477 | train | You can use lambdas and still use variables. For example, if you had:
class B {
private PropertyChangeListener listener1 = this::doSomething;
private PropertyChangeListener listener2 = e -> doSomethingElse();
void listenToA(A a) {
// using method reference
a.addPropertyChangeListener("Property1", listener1);
// using lambda expression
a.addPropertyChangeListener("Property2", listener2);
}
Then it would be easy to remove listener1 or listener2 when and where needed.
Also there are other ways, since the PropertyChangeSupport object has a getPropertyChangeListeners() that would allow removal of all listeners in a for loop if need be.
class A {
final PropertyChangeSupport pcs = new PropertyChangeSupport(this);
void addPropertyChangeListener(String name, PropertyChangeListener listener) {
pcs.addPropertyChangeListener(name, listener);
}
void removePropertyChangeListener(String name, PropertyChangeListener listener) {
pcs.removePropertyChangeListener(name, listener);
}
public void removeAllListeners() {
for (PropertyChangeListener l : pcs.getPropertyChangeListeners()) {
pcs.removePropertyChangeListener(l);
}
}
}
A: You can declare your listeners as follows:
private final PropertyChangeListener myProperty1Listener = this::doSomething;
private final PropertyChangeListener myProperty2Listener = e -> doSomethingElse());
then, you can add your listeners:
// using method reference
a.addPropertyChangeListener( "Property1", myProperty1Listener );
// using lambda expression
a.addPropertyChangeListener( "Property2", myProperty2Listener );
and you can remove them:
a.removePropertyChangeListener( "Property1", myProperty1Listener );
a.removePropertyChangeListener( "Property2", myProperty2Listener ); | unknown | |
d2478 | train | Your code works without any error but I think what you were trying to do was :
library(dplyr)
var = 'col1'
x <- df %>% summarize(mu = mean(.data[[var]], na.rm=TRUE))
x | unknown | |
d2479 | train | You should do a GET operation on your instance and fetch the current settings, those settings will contain the current version number, you should use that value.
This is done to avoid unintentional settings overwrites.
For example, if two people get the current instance status which has version 1, and they both try to change something different (for example, one wants to change the tier and the other wants to change the pricingPlan) by doing an Update operation, the second one to send the request would undo the change of the first one if the operation was permitted. However, since the version number is increased every time an update operation is performed, once the first person updates the instance, the second person's request will fail because the version number does not match anymore. | unknown | |
d2480 | train | It must be your variable be getting overwritten somewhere in the code which you have not mentioned.
Also please dd($sorted) your result after executing the eloquent query to see whether you are getting data from db in right format as per your need. | unknown | |
d2481 | train | Try this:
const token = this.authService.decodedAccessToken?.token || null; | unknown | |
d2482 | train | The easiest thing to do is probably to use webpack-target-electron-renderer, you can find examples of using it in electron-react-boilerplate.
A: First of all: Don't lost time with webpack with react and electron, react already have everything it need itself to pack themself when building.
As Hossein say in his answer:
const fs = window.require('fs');
that works for me.
Additionally on webpreferences on the main.js of electron i set this settings:
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: true,
enableRemoteModule: true,
contextIsolation: false,
nodeIntegrationInWorker: true,
nodeIntegrationInSubFrames: true
}
following the electron website that webpreferences are a security problem so we need to found a better a more safer ways as described here
A: use window.require() instead of require().
const fs = window.require('fs');
A: Since Electron 12 contextIsolation is true by default and it is recommended.
So with nodeIntegration: true and contextIsolation: true
First see https://www.electronjs.org/docs/latest/tutorial/context-isolation/
FIRST in preload.js expose the require function to renderer:
require: (callback) => window.require(callback)
THEN in renderer you can import it by:
const { myAPI } = window
const fs = myAPI.require('fs') | unknown | |
d2483 | train | you want this modification..........
if ($row1 = $value->fetch(PDO::FETCH_OBJ)){
$main = array('data'=>array($row1));
echo json_encode($main);
}else{
echo '{"data":["catagory":"' . $row['category'] . '"]}';
}
A: You problem stems from the fact that you have a 'soup' category but you don't have any items belonging to the soup category. You should add a condition for empty result and change the echoing array accordingly.
if (empty($row1))
{
$main = array('data'=>array('category'=>$cat));
}
else
{
$main = array('data'=>array($row1));
} | unknown | |
d2484 | train | Your str is adding the two chars first, so it's basically this:
String str = (char)(255 + 255) + "1"; // 5101
What you want is (something like) this:
String str = (char) 255 + "" + (char) 255 + "1";
Or, using String.format:
String str = String.format("%c%c%d", 255, 255, 1); | unknown | |
d2485 | train | I have seen that error before, when porting from VS 2005 to 2008. Never seen in 2010.
For some reason, the build settings for app.xaml were lost. So you can check the the properties of app.xaml. The correct settings are shown in the image attached.
On the other hand, if you are working with MVVC, it can be a different cause, like explained here: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/39d7a4dd-9034-4ae8-843c-ccd4940ba51c/
A: I have the same situation as specified in question (VS2010).
Yesterday, project worked without problems. Today, with no changes to the code, project reported error.
In my case after Menu -> Build -> Clean Solution project run without error.
A: Changing Windows 10 display language from English to German (the app was originally developed on a German system) fixed it for me. | unknown | |
d2486 | train | You are right, there is no way to do that.
You can however, define different themes (color and icon) for each workspace (Preferences: Open Workspace Settings). It's not exactly what you are looking for, but it may be useful if your different languages are located/related in different workspaces.
A: It's now possible to do using an extension called "Theme by language" from Julien Saulou. It can be downloaded from Visual Studio Code Marketplace. | unknown | |
d2487 | train | I don't think you can add ticks to minor breaks, but you can have unlabeled major ticks, as you were thinking, by labeling them explicitly in scale_x_continuous. You can set the "minor" tick labels to blank using boolean indexing with mod (%%).
Similarly, you can set the tick sizes explicitly in theme if you want the "minor" ticks to be a different size.
set.seed(5)
df <- data.frame(x = rnorm(500, mean = 12.5, sd = 3))
breaks <- seq(2.5, 25, .1)
labels <- as.character(breaks)
labels[!(breaks %% 2.5 == 0)] <- ''
tick.sizes <- rep(.5, length(breaks))
tick.sizes[(breaks %% 2.5 == 0)] <- 1
df %>%
ggplot(aes(x)) +
geom_histogram(binwidth = .1, color = 'black', fill = 'gray35') +
scale_x_continuous(breaks = breaks, labels = labels, limits = c(2.5,25)) +
theme_bw() +
theme(panel.grid = element_blank(),
axis.ticks.x = element_line(size = tick.sizes))
Also as you might notice from my code, you can just call theme() once and put all the theme modifications into that one call. | unknown | |
d2488 | train | You can use the WScript.Shell function CreateShortcut
var objShell = new ActiveXObject("WScript.Shell")
var lnk = objShell.CreateShortcut("C:\\my_shortcut.lnk")
lnk.TargetPath = "C:\\Windows\\System32\\Calc.exe";
lnk.Arguments = "/mode:QWE /role:Admin";
lnk.Description = "Your description here...";
lnk.IconLocation = "C:\\Windows\\System32\\Calc.exe, 0";
lnk.WorkingDirectory = "C:\\Windows\\System32";
lnk.Save(); | unknown | |
d2489 | train | I found my own answer.
I had to set 'schema'
ifc_file = ifcopenshell.file(schema=other_ifc_file.schema)
ifc_file.add({IfcBuildingElementProxy}) | unknown | |
d2490 | train | :Copy(unsigned int, void const*, unsigned long)+0x54 (my_server:arm64+0x100109f08)
#2 0x10010ce14 in google_breakpad::MinidumpGenerator::WriteStackFromStartAddress(unsigned long long, MDMemoryDescriptor*)+0xf8 (my_server:arm64+0x10010ce14)
#3 0x10010d244 in google_breakpad::MinidumpGenerator::WriteThreadStream(unsigned int, MDRawThread*)+0x100 (my_server:arm64+0x10010d244)
#4 0x10010c04c in google_breakpad::MinidumpGenerator::WriteThreadListStream(MDRawDirectory*)+0xfc (my_server:arm64+0x10010c04c)
#5 0x10010bd20 in google_breakpad::MinidumpGenerator::Write(char const*)+0xc8 (my_server:arm64+0x10010bd20)
#6 0x10010adc0 in google_breakpad::ExceptionHandler::WriteMinidumpWithException(int, int, int, __darwin_ucontext64*, unsigned int, bool, bool)+0x160 (my_server:arm64+0x10010adc0)
#7 0x10010af1c in google_breakpad::ExceptionHandler::WaitForMessage(void*)+0x104 (my_server:arm64+0x10010af1c)
#8 0x1a330a068 in _pthread_start+0x90 (libsystem_pthread.dylib:arm64e+0x7068)
#9 0x1a3304e28 in thread_start+0x4 (libsystem_pthread.dylib:arm64e+0x1e28)
Address 0x00016fdfee00 is located in stack of thread T0 at offset 0 in frame
#0 0x1000034cc in main main.cpp:36
This frame has 10 object(s):
[32, 56) 'reportPath' (line 39) <== Memory access at offset 0 partially underflows this variable
[96, 120) 'ref.tmp' (line 40) <== Memory access at offset 0 partially underflows this variable
[160, 208) 'parser' (line 43) <== Memory access at offset 0 partially underflows this variable
[240, 264) 'configPath' (line 45) <== Memory access at offset 0 partially underflows this variable
[304, 320) 'ref.tmp12' (line 46) <== Memory access at offset 0 partially underflows this variable
[336, 360) 'agg.tmp' <== Memory access at offset 0 partially underflows this variable
[400, 416) 'ref.tmp30' (line 57) <== Memory access at offset 0 partially underflows this variable
[432, 456) 'agg.tmp42' <== Memory access at offset 0 partially underflows this variable
[496, 520) 'agg.tmp80' <== Memory access at offset 0 partially underflows this variable
[560, 568) 'ref.tmp86' (line 74) <== Memory access at offset 0 partially underflows this variable
HINT: this may be a false positive if your program uses some custom stack unwind mechanism, swapcontext or vfork
(longjmp and C++ exceptions *are* supported)
SUMMARY: AddressSanitizer: stack-buffer-underflow (libclang_rt.asan_osx_dynamic.dylib:arm64e+0x1902c) in wrap_write+0x15c
Shadow bytes around the buggy address:
0x00702dfdfd70: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x00702dfdfd80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x00702dfdfd90: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x00702dfdfda0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x00702dfdfdb0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
=>0x00702dfdfdc0:[f1]f1 f1 f1 00 00 00 f2 f2 f2 f2 f2 f8 f8 f8 f2
0x00702dfdfdd0: f2 f2 f2 f2 f8 f8 f8 f8 f8 f8 f2 f2 f2 f2 f8 f8
0x00702dfdfde0: f8 f2 f2 f2 f2 f2 f8 f8 f2 f2 00 00 00 f2 f2 f2
0x00702dfdfdf0: f2 f2 f8 f8 f2 f2 00 00 00 f2 f2 f2 f2 f2 00 00
0x00702dfdfe00: 00 f2 f2 f2 f2 f2 f8 f3 f3 f3 f3 f3 00 00 00 00
0x00702dfdfe10: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
Shadow byte legend (one shadow byte represents 8 application bytes):
Addressable: 00
Partially addressable: 01 02 03 04 05 06 07
Heap left redzone: fa
Freed heap region: fd
Stack left redzone: f1
Stack mid redzone: f2
Stack right redzone: f3
Stack after return: f5
Stack use after scope: f8
Global redzone: f9
Global init order: f6
Poisoned by user: f7
Container overflow: fc
Array cookie: ac
Intra object redzone: bb
ASan internal: fe
Left alloca redzone: ca
Right alloca redzone: cb
Thread T2 created by T0 here:
#0 0x100ae8c5c in wrap_pthread_create+0x54 (libclang_rt.asan_osx_dynamic.dylib:arm64e+0x38c5c)
#1 0x10010a360 in google_breakpad::ExceptionHandler::Setup(bool)+0xd0 (my_server:arm64+0x10010a360)
#2 0x10010a1c4 in google_breakpad::ExceptionHandler::ExceptionHandler(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, bool (*)(void*), bool (*)(char const*, char const*, void*, bool), void*, bool, char const*)+0x110 (my_server:arm64+0x10010a1c4)
#3 0x1001132b4 in crashhandler::init(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)+0x58 (my_server:arm64+0x1001132b4)
#4 0x10000367c in main main.cpp:41
#5 0x1a2fdfe4c (<unknown module>)
==5060==ABORTING
To reiterate, if I run the program outside of the debugger, it proceeds normally.
What can cause this?
A: Breakpad is inserting a right into the process's "task exception port" - which is where you listen for crashes and the like either from within the process or externally - i.e. when you are a debugger. But in Mach the exception ports only have a single owner. So when you run under the debugger, Breakpad and the debugger fight for control of the exception port. For example, if you got your port right set up before the debugger attached, you will end up with a bad port right after the attach, because lldb now owns the port.
Debugging programs that use task exception port handlers is not well supported, because (a) it would be tricky to get that right and (b) there aren't enough programs that need to do this to motivate the effort (at least on the debugger side). Most people turn off their exception handling for their debug builds since their exception catcher and the debugger are pretty much doing the same job, and it's more convenient to trap in the debugger than the internal exception handler. And the core part of the exception handler is usually simple enough that you can do printf debugging if you really need to debug that part. | unknown | |
d2491 | train | Try this..
<?php
$errors=array();
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$username=$_POST['username'];
$password=$_POST['password'];
$email=$_POST['email'];
//not empty
//at least 3 characters long
//start the validation
//check the username
if(empty($_POST['username'])){
$errors['username1'] = "Required fields";
}
if (strlen($username) <3 ) {
$errors['username2'] ="Username must at least 3 characrters long.";
}
//check the password
if (empty($_POST['password'])){
$errors['password1'] ="Required fields";
}
if (strlen($password) < 8) {
$errors['password2'] = "Password must be 8 characrters long";
}
//check the email
if (empty($_POST['email'])){
$errors['email1'] = "Required fields";
}
if (strlen($email) < 12){
$errors['email2'] ="Email must at least 12 characrters long";
}
//check the errors
if(count($errors) == 0){
$query="INSERT INTO user(Username,Password,Email) VALUES ('".$_POST['username']."','".$_POST['password']."','".$_POST['email']."')";
mysqli_query($con,$query);
}
}
?>
<div id="content">
<form action="" method="POST">
<fieldset>
<legend>Sign up your Watevershit account to unlock more shit!</legend>
<p>
<label>
<span>Username :</span>
<input type="text"name="username">
</label>
</p>
<p><?php if(!empty($errors['username1'])) { echo $errors['username1']; } ?></p>
<p>
<label>
<span>Password</span>
<input type="password" name="password">
</label>
</p>
<p><?php if(!empty($errors['password1'])) { echo $errors['password1']; }?></p>
<p>
<label>
<span>Confirm Password :</span><input type="password"name="password">
</label>
</p>
<p>
<label>
<span>Email:</span>
<input type="email"name="email">
</label>
</p>
<p><?php if(!empty($errors['email1'])) { echo $errors['email1']; }?></p>
<p>
<label>
<input type="submit"id="submit"value="Sign Up Now!">
</label>
</p>
<p>
<label>
<span><a href="login.html">Already member?Log in here</a></span>
</label>
</p>
</fieldset>
</form>
</div>
A: Replace this block:
//check the errors
if(count($errors) == 0){
//redirect to sucess page
header('Location:login.html');
}
With this:
//check the errors
if(count($errors) > 0){
//redirect to sucess page
header('Location:login.html');
}
And also replace following line:
if ($_SERVER["REQUEST_METHOD"] == "POST"){
With:
if ($_POST){ | unknown | |
d2492 | train | I'm not sure how you want the Readings rendered, but here is an example:
http://jsfiddle.net/jearles/aZnzg/
You can simply use another foreach to start a new binding context, and then render the properties as you wish. | unknown | |
d2493 | train | Hadley's answer:
Just set the attributes— Hadley Wickham (@hadleywickham) October 27, 2017
So there you have it: the canonical haven answer is just to set the attributes. | unknown | |
d2494 | train | Place this line gridView=(GridView) getActivity().findViewById(R.id.homeGridView); in onCreate and do it like this gridView=(GridView) view.findViewById(R.id.homeGridView); because your gridview is part of your View. Or pass the View view to init();
like this:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
init(view);
return view;
}
private void init(View rootView) {
// TODO Auto-generated method stub
gridView=(GridView) rootView.findViewById(R.id.homeGridView);
categoryHomeGridView=getActivity().getResources().getStringArray(R.array.category_array);
homeGridViewItems=new ArrayList();
homeGridViewItems.add(new HomeGridViewItem(categoryHomeGridView[0],
icon[0]));
homeGridViewItems.add(new HomeGridViewItem(categoryHomeGridView[1],
icon[1]));
homeGridViewItems.add(new HomeGridViewItem(categoryHomeGridView[2],
icon[2]));
homeGridViewItems.add(new HomeGridViewItem(categoryHomeGridView[3],
icon[3]));
// iconHomeGridView.recycle();
adapter=new HomeGridViewListAdapter(getActivity().getApplicationContext()
,homeGridViewItems);
gridView.setAdapter(adapter);
}
A: The gridView probably belongs to the fragment layout
So you need to change this
gridView=(GridView) getActivity().findViewById(R.id.homeGridView);
to
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false)
gridView=(GridView) view.findViewById(R.id.homeGridView);
A: Change this:
gridView=(GridView) getActivity().findViewById(R.id.homeGridView);
to this:
View view = inflater.inflate(R.layout.fragment_home, container, false);
gridView=(GridView) view .findViewById(R.id.homeGridView); | unknown | |
d2495 | train | Simply quote the 1 with double quotes:
SELECT mydata."1" FROM my_table
A: This can be queried using unnest operator.You can use below query to fetch the items from array :
select t1.* from test cross join UNNEST("mydata"."1") as t1(record); | unknown | |
d2496 | train | As of now, the strategy I am undertaking is to instantiate a singleton object early in the boot process and then use it to maintain threads. Threadsafe practices are obviously needed for this.
The file application.rb defines MyApp::Application. At this point I declare an accessor my_thing_manager, require my_thing_manager and set self.my_thing_manager = MyThingManager.instance.
class MyThingManager
def instance
return Thread.main[:thing_manager] unless Thread.main[:thing_manager].nil?
Thread.main[:thing_manager] = self.new
end
private
def initialize
end
end
This approach works in a single multithreaded process but does not work in a clustered production environment. For my requirements that is completely acceptable. For a multi-process app, one could utilize hooks in e.g. Puma after_worker_fork or Unicorn's after_fork to manage a subscription to something like Redis pubsub. This will be a requirement for an upcoming project so I expect to develop this strategy further. | unknown | |
d2497 | train | You set found to true the moment you find any character that is equal to the 'mirror' character. For a word with an odd number of characters, that is always going to be true (the middle character is equal to the middle character), for example, but other words are going to generate a false match too. Take the word winner for example, the two ns in there are in mirror positions and your function will proclaim it a palindrome while clearly it is not.
Instead of setting found to true, exit early if you find a mismatch:
found = True
for i in range(len(string)):
if string[i] != string[len(string) - 1 - i]:
found = False
break
So you start out assuming it is a palindrome, and you exit when you find evidence to the contrary.
Note that you could stop checking when you have checked half the string:
for i in range((len(string) + 1) // 2):
if string[i] != string[len(string) - 1 - i]:
found = False
break
or you could just test if the string is equal to its reverse; the [::-1] gives you the string reversed:
string == string[::-1] | unknown | |
d2498 | train | Without using a crawler, which is most likely against the TOS, this is not possible.
You could use the first depth to make only a first degree connection graph based on mutual friends within your friend network.
/userid1/friends/userid2
It would be easier to center your project around Twitter's data. | unknown | |
d2499 | train | Got there in the end:
yaml config:
/read/products_many/{drug_product_ids}:
get:
operationId: products.read_products_many
tags:
- Product
summary: Read multiple drug products for the provided drug_product_ids
description: Read multiple drug products for the provided drug_product_ids
parameters:
- name: drug_product_ids
in: path
required: true
schema:
type: array
items:
type: integer
minItems: 1
style: simple
explode: false
description: drug_product_ids primary keys of the required products
responses:
'200':
description: Successfully retrieved product
content:
application/json:
schema:
$ref: '#/components/schemas/product'
Based on:https://swagger.io/docs/specification/serialization/#uri-templates
Then in my method, I see a list coming in as a parameter, so I am converting to string and then creating the SQL using string formatting.
def read_products_many(drug_product_ids):
conn_ariel = get_connection()
cursor_ariel = conn_ariel.cursor()
print(drug_product_ids) # --> [4670, 4671]
print(type(drug_product_ids)) # --> List
# convert to string for use in IN clause in SQL
drug_product_ids = [str(x) for x in drug_product_ids]
print("read_many product, id", drug_product_ids)
# Create the list of products from our data
sql = """
SELECT DRUG_PRODUCT_ID, PREFERRED_TRADE_NAME, PRODUCT_LINE, PRODUCT_TYPE, FLAG_PASSIVE , PRODUCT_NUMBER
FROM DIM_DRUG_PRODUCT
WHERE DRUG_PRODUCT_ID in ({0})
AND PREFERRED_TRADE_NAME NOT LIKE '%DO NOT USE%'
AND UPPER(PREFERRED_TRADE_NAME) NOT LIKE '%DELETE%'
AND UPPER(PREFERRED_TRADE_NAME) NOT LIKE '%TEST%'
""".format(",".join(drug_product_ids))
print("SQL")
print(sql)
cursor_ariel.execute(sql)
product = None
products = []
for row in cursor_ariel.fetchall():
r = reg(cursor_ariel, row, False)
product = {
"drug_product_id" : r.DRUG_PRODUCT_ID,
"preferred_trade_name" : r.PREFERRED_TRADE_NAME,
"product_line" : r.PRODUCT_LINE,
"product_type" : r.PRODUCT_TYPE,
"flag_passive" : r.FLAG_PASSIVE,
"product_number" : r.PRODUCT_NUMBER
}
products.append(product)
pool.release(conn_ariel)
return products
SQL being returned when I enter this URL:
localhost:5000/api/read/products_many/4671,4670
is correct as:
SELECT DRUG_PRODUCT_ID, PREFERRED_TRADE_NAME, PRODUCT_LINE, PRODUCT_TYPE, FLAG_PASSIVE , PRODUCT_NUMBER
FROM DIM_DRUG_PRODUCT
WHERE DRUG_PRODUCT_ID in (4671,4670)
AND PREFERRED_TRADE_NAME NOT LIKE '%DO NOT USE%'
AND UPPER(PREFERRED_TRADE_NAME) NOT LIKE '%DELETE%'
AND UPPER(PREFERRED_TRADE_NAME) NOT LIKE '%TEST%' | unknown | |
d2500 | train | In plain Scala you can use type class Integral:
scala> def doubleit[A : Integral](a: A): A = implicitly[Integral[A]].plus(a, a)
doubleit: [A](a: A)(implicit evidence$1: Integral[A])A
scala> doubleit(2)
res0: Int = 4
scala> doubleit(BigInt(4))
res1: scala.math.BigInt = 8
Another possible syntax:
def doubleit[A](a: A)(implicit ev: Integral[A]): A = ev.plus(a, a)
ev is a commonly used name for those implicit parameters.
It is also possible to use normal operations like +, -, etc. instead of plus and minus:
def doubleit[A](a: A)(implicit ev: Integral[A]): A = {
import ev._
a + a
}
Or as per suggestion by @KChaloux, import from Integral.Implicits beforehand:
import Integral.Implicits._
def doubleit[A : Integral](a: A): A = a + a
If you want the function to support not only integers, but also Doubles, BigDecimals, etc. you can use Numeric instead of Integral:
import Numeric.Implcits._
def doubleit[A : Numeric](a: A): A = a + a
Explanation:
Writing [A : Integral] makes the function receive an implicit parameter of type Integral[A]. The implicits for all basic integral types are already defined in Scala, so you can use it with Int or BigInt straightaway. It is also possible to define new Integral types by defining a new implicit variable of type Integral[NewIntegralType] and implementing all the necessary methods.
The call to implicitly[Integral[A]] returns this implicit instance of Integral[A] which has method plus for addition, and other methods for performing other operations on integrals. | unknown |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.