INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How to install a certificate for a website in IIS 7+ and make https optional?
How do you install a certificate for a website in IIS 7+ and make the use of https optional?
Ideally, we would like http to be the default and then for specific pages use an https URL.
|
Easy, just point to url without https://
And here's a tutorial. <
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "iis, ssl, ssl certificate"
}
|
Unable to cast object of type 'System.DBNull' to type 'System.String'
I have a datable code to generate a string, which is sb.ToString().
DataTable dt = dbaccess.GetDataTable("TEST"); // get datatable
List<DataRow> drlist = dt.AsEnumerable().ToList(); // each row only has one element.
StringBuilder sb = new StringBuilder();
foreach (DataRow row in drlist)
{
foreach (string str in row.ItemArray)
{
sb.Append(str);
}
}
The datatable is
NULL
0
138
337
1666
1680
2511
8113
You see that there is "NULL" to cause the error "Unable to cast object of type 'System.DBNull' to type 'System.String'. How to fix it?
|
Try this:
foreach (object str in row.ItemArray)
{
if (DbNull.Value.Equals(str))
sb.Append("NULL");
else
sb.Append(str.ToString());
}
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "c#, string, datatable, datarow"
}
|
What is the meaning of this result from running 'lsof -i:8080'?
When I run the following command:
lsof -i:8080
This is the result:
node 32419 root 6u IPv4 122865 TCP localhost.localdomain:webcache (LISTEN)
That result is different from that of the following command:
lsof -i:80
Result:
nginx 32029 root 6u IPv4 121546 TCP *:http (LISTEN)
nginx 32030 nginx 6u IPv4 121546 TCP *:http (LISTEN)
Nginx is : "TCP *", but node's process "localhost.localdomain". What does it mean, `localhost.localdomain`? Does it means the process can access from `localhost` only?
I have trouble accessing the node process from another server via 8080 port.
|
in the first case nginx listens only on the loopback interface; 127.0.0.1 is resolved to localhost.localdomain thru /etc/hosts in the second case nginx listens on all the available interfaces (notice *:http)
so the answer is yes, it can be accessed from the local host only;
you can add "-n" flag to lsof to see ip addresses instead of the names those may be resolved to.
|
stackexchange-serverfault
|
{
"answer_score": 2,
"question_score": 0,
"tags": "lsof, ps"
}
|
How to weakly reference a single object in Squeak
Squeak Smalltalk has support for collections of weak references, but appears to lack a direct equivalent to Java's WeakReference class which supports a weak reference to a single object instance. If I'm defining a class of object with several instance variables, one of which I want to be a weak reference, what is the most idiomatic way to do this? Does it make sense to instantiate a WeakArray to hold that single reference, or is there a simpler way that I'm not aware of?
|
Use a WeakArray.
The Squeak VM implements weak references only as indexed variables, whereas instance variables are always strongly referenced. That's why using a one-element WeakArray is the right thing to do.
You could implement your own one-element WeakReference class, but it would not be any more efficient than a WeakArray.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "smalltalk, squeak"
}
|
What is the best way to format a large has_many through line?
This question is about code style.
I have this line in one of my models:
has_many :owning_artists, :through => :artist_tracks, :source => :artist, :conditions => { :artist_tracks => { :artistic_role_id => 1, :another_memeber => 42 } }
What is the best way to break this up on multiple lines, and indented of course, and what would it would look like?
I'd love to hear a more general recommendation/guideline for how to break up and indent nested hashes too.
|
This is what I would do:
has_many :owning_artists, {
:through => :artist_tracks,
:source => :artist,
:conditions => {
:artist_tracks => {
:artistic_role_id => 1,
:another_memeber => 42
}
}
}
|
stackexchange-codereview
|
{
"answer_score": 4,
"question_score": 1,
"tags": "ruby on rails, ruby"
}
|
Extracting characters from a string in vb.net
I am busy working on past exam papers in preparation for my vb.net exam next week. The question I am struggling with is as follows.
Take in a long string of alphabetical characters and special characters extract the alphabetical characters to string1 and extract special characters to string2
so the string hello://thisismystring!? must be displayed as follows
string1 = hellothisismystring
string2 = ://!?
My question is this **how do I extract characters from a string and store them in a variable?**
|
One way that is Unicode-friendly, clean and easy.
Imports System.Text
Module Module1
Sub Main()
Dim sValue As String = "hello://thisismystring!?"
Dim a As New StringBuilder
Dim b As New StringBuilder
For Each c As Char In sValue
If Char.IsLetter(c) Then
a.Append(c)
Else
b.Append(c)
End If
Next
Dim s1 As String = a.ToString()
Dim s2 As String = b.ToString()
End Sub
End Module
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "vb.net, string, character, extract"
}
|
Android : Create Service as Independent Project
I am working on an Android app that has two main projects:
* The main activity
* A service
These two projects are independent and I can't link them together.
I've tried Broadcast Receiver, Remote Service, Manifest permissions.. but it doesn't work. I know how to do it when they are in different packages and in the same project.
Has someone ever done something like this?
|
You must bind with your service with a Binder
<
and
how do i start (and bind) a remote service in android that is implemented in another app (different package)?
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "java, android, multithreading, service, project"
}
|
converting text file data to excel using powershell
I want to convert a text file data to excel, below is the content of the text file:
ModuleName FailedCount SucceededCount TotalCount
BESS 0 80 80
IG 0 14 14
the spaces between the words in the the text file are not fixed, so i how do i convert this data to excel? I tried the solution given in below URL, but it is not working.
<
|
The easiest way is to convert that file into a CSV file:
$rawData = Get-Content -Path 'D:\Test\theFile.txt' | Where-Object {$_ -match '\S'}
# this gets the list separator character your local Excel expects when double-clicking a CSV file
$delimiter = [cultureinfo]::CurrentCulture.TextInfo.ListSeparator
($rawData -replace '\s+', $delimiter) | Set-Content -Path 'D:\Test\theNewFile.csv'
Now you have a CSV file you can double-click to open in Excel
, is this a good way to do this?
|
Well.
On the server side, specifying "proto" twice doesn't actually do anything - "proto udp6" will make it bind a dual-stack socket to handle v4+v6, overwriting the "proto udp" in the previous line.
On a 2.3 client, having two remotes, with "udp6" and "udp" is the way to go, as the old socket code cannot failover itself properly.
On a git master (2.4-to-be) or 3.0 (OpenVPN Connect) client, you can just use "udp" as it will properly call getaddrinfo() and use whatever IP protocol the server and network supports, trying one family first and falling over to the other one, using the preference the OS signals (via getaddrinfo() result ordering).
gert
|
stackexchange-serverfault
|
{
"answer_score": 13,
"question_score": 12,
"tags": "openvpn, ipv6, ipv4"
}
|
How to create rowspan like below in HTML
Can someone help me to create a table similar to than i tried all examples here they are not helping. In Html part of that date in cells of datatable. I tried to change the culture information of current thread, but it didnt worked. Is there any other way to achieve this?
I am using MySQLas my database and there I have set datatype of this column as DATE, but I am still getting this time information. Can anyone explain this behavior of MySQL as well?
|
Set the Format property on your column to the Month/Year format specifier.aspx#YearMonth):
// Set the Format property on the "Last Prepared" column to cause
// the DateTime to be formatted as "Month, Year".
dataGridView1.Columns["Last Prepared"].DefaultCellStyle.Format = "y";
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "c#, mysql, c# 2.0"
}
|
Is "prevent getting sick" a shorthand of "prevent yourself from getting sick"?
> Eat vegetables in order to prevent getting sick.
I am not sure if the above sentence is grammatical. I have seen the phrase "prevent getting sick", but I am not sure if you can just use like that anywhere, or there is a particular way to use it to make sure it's grammatical.
|
Yes, it does.
In this case "getting sick" does not describe an action, it describes the end result. For example replace it with a more precise disease
> Eat vegetables in order to prevent scurvy.
Now the sentence makes sense again. This way is somewhat odd and probably depends on the dialect of Engish you are speaking in.
|
stackexchange-ell
|
{
"answer_score": 1,
"question_score": 0,
"tags": "grammar"
}
|
How to install Maven 2 plugin for Eclipse on 64-bit linux?
I have Fedora 11 (x86 64) installed with Eclipse. I need a Maven plugin, preferrably m2eclipse, but I cannot find out how to install it. I've tried going through yum, but to no avail (I can't even find any maven plugins).
On my other laptop, I've tried installing the plugin using yum on a 32 bit install of Fedora 11, and while the package shows as being installed, I still don't see it in Eclipse. I've even tried starting eclipse with the clean flag.
Could anyone provide me with help? I've got maven 2.0.4 installed. Thanks in advance!
|
I was able to install the core components of the m2eclipse plugin after I first installed the ganymede packages from their update site: <
Apparently "Fedora Eclipse" is not a flavor of the ganymede build.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "linux, eclipse, maven 2, 64 bit, fedora11"
}
|
How can I get size of prototype cell in descendant of UICollectionView?
I have a class that is descendant of UICollectionView. I'm using storyboards.
How can I get size of prototype cell in it ?
I tried calling `dequeueReusableCellWithReuseIdentifier` in `awakeFromNib` but I get `Exception: EXC_BAD_ACCESS (code=2, address=0xbf7fffdc))` in console.
I need cell size because I want to change layout in
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
|
**You can get it like this:**
CGFloat height = [[tableView dequeueReusableCellWithIdentifier:reusableIdentifier] bounds].size.height;
But if you get bad access in `awakeFromNib` probably you should paste some code from that custom cell.
|
stackexchange-stackoverflow
|
{
"answer_score": -1,
"question_score": 3,
"tags": "ios, uicollectionview, uicollectionviewlayout"
}
|
Where to find ready to use CLR dlls for SQL Server
There are a lot of standard tasks, which are not part of T-SQL, e.g.
* string concatenate aggregate function
* regex string compare
are there location where I can download recompiled dlls and get with installation instructions.
I'm not interested in compiling those dlls myself.
**Edit:**
The answers motivated me to change my attitude concerning compiling the CLR dlls myself.
|
Sorry, you'd generally have to compile yourself because of .net versions, or 32/64 bit etc.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "sql, sql server 2008"
}
|
Android Debugger - Firebase objects are obfuscated
I currently have an Android App that is using Firebase Auth. After google login, I get a `FirebaseUser` object. If I set a breakpoint and look at the object. I see obfuscated objects and values. See image:
, 'proguard-rules.pro'
}
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
Anyone know what I might be doing wrong? Any help is much appreciated!
|
Firebase library files are obsuscated themselves. You cannot really do anything about it. I guess Google does not want to make everything from their libraries public due to security reasons or using the library incorrectly.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 8,
"tags": "android, firebase, firebase authentication, android proguard, android debug"
}
|
Optimize shim configuration
Is there any way to do something like following
shim: {
bsAlert || bsTooltip || dbDropdown: {
deps: ['jquery']
}
}
instead of following
shim: {
bsAlert: {
deps: ['jquery']
},
bsTooltip: {
deps: ['jquery']
},
bsDropdown: {
deps: ['jquery']
}
}
My shim list is getting too long; Is there any way, where i can use logical operator or regular expressions to optimize my shim configuration?
|
Adding to @Louis-Dominique Dubeau answer. Definition for convert config can be given as follows.
define("convert_config", function(){
function convert_config(config){
for(var index in config.shim){
if(index.indexOf("||")!=-1){
var keys = index.split("||");
for(var i=0; i<keys.length; i++){
config.shim[keys[i]] = config.shim[index];
}
delete config.shim[index]
}
}
return config;
}
return convert_config;
})
var convert_config = require("convert_config");
var config = {
baseURL: "lib",
paths: {},
shim: {
moduleA: {},
"bsAlert || bsTooltip || bsDropdown": { deps: ['jquery'] },
}
};
config = convert_config(config);
require.config(config);
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "javascript, requirejs"
}
|
PHP check if IPAddress is local
Can i check if an ip is in a private network?
<?php
function isLocalIPAddress($IPAddress)
{
return ( !filter_var($IPAddress, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ) );
}
var_dump( isLocalIPAddress('127.0.0.1') ); // false
var_dump( isLocalIPAddress('192.168.1.20') ); // true
var_dump( isLocalIPAddress('64.233.160.0') ); // false
Why is `isLocalIPAddress('127.0.0.1')` giving `false` instead of `true`?
Isn't 127.0.0.1 a private ip?
* * *
**UPDATE**
Solution I used:
<?php
function isLocalIPAddress($IPAddress)
{
if( strpos($IPAddress, '127.0.') === 0 )
return true;
return ( !filter_var($IPAddress, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ) );
}
|
According to a test run, we can see that output for PHP 5.2.0 -> 5.3.5 is `false`, while output for PHP 5.3.6 -> 7.0.0beta1 and hhvm-3.3.1 -> 3.8.0 is `true`.
To solve your problem you can check for php version and if it is in the first range add:
function isLocalIPAddress($IPAddress)
{
if($IPAddress == '127.0.0.1'){return true;} <-- add this
return ( !filter_var($IPAddress, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ) );
}
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 3,
"tags": "php, networking, ip"
}
|
How to save Images in WPF
I am working on a wpf application. I am having one image, i have put some more images on it, with lowered transparency(sort of watermarking you can say). Is their any way to save the present look of the two or three images(watermarked images) into one new image??
|
You can use `RenderTargetBitmap` to render Visuals, to render your stack of images you should place them in some wrapping control (if only temporarily). This article might be helpful.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, wpf, image"
}
|
Bug in top users per tag (?)
Steps to reproduce:
1. Open <
2. Go to top answerers
3. Mouse over number of answers provided (i.e. number just left from the picture)
4. **Mouseover hint says "143 questions asked" (Should be something like "143 answers provided")**
5. Now, go to top askers and do the same
6. It says "x questions asked" - here it's ok.
Tested on Chrome
|
Fixed in latest, will be deployed with the next deploy.
Thanks for reporting this
|
stackexchange-meta
|
{
"answer_score": 4,
"question_score": 9,
"tags": "bug, status completed, top users"
}
|
How to match a folder name and use it in an if condition using grep in bash?
for d in */ ; do
cd $d
NUM = $(echo ${PWD##*/} | grep -q "*abc*");
if [[ "$NUM" -ne "0" ]]; then
pwd
fi
cd ..
done
Here I'm trying to match a folder name to some substring 'abc' in the name of the folder and check if the output of the grep is not 0. But it gives me an error which reads that `NUM: command not found`
* * *
An error was addressed in comments. `NUM = $(echo ${PWD##*/} | grep -q "*abc*");` should be `NUM=$(echo ${PWD##*/} | grep -q "*abc*");`.
* * *
To clarify, the core problem would be **to be able to match current directory name to a pattern.**
|
You can probably simply the code to just
if grep -q "*abc*" <<< "${PWD##*/}" 2>/dev/null; then
echo "$PWD"
# Your rest of the code goes here
fi
You can use the exit code of the `grep` directly in a if-conditional without using a temporary variable here (`$NUM` here). The condition will pass if `grep` was able to find a match. The here-string `<<<`, will pass the input to `grep` similar to `echo` with a pipeline. The part `2>/dev/null` is to just suppress any errors (`stderr - file descriptor 2`) _if_ `grep` throws!
* * *
As an additional requirement asked by OP, to negate the conditional check just do
if ! grep -q "*abc*" <<< "${PWD##*/}" 2>/dev/null; then
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "bash, grep"
}
|
How to generate random numbers with GoogleRefine or OpenRefine in GREL?
I'd like to generate random numbers in GREL. Is there any way to do this? I'd like to use a GREL phrase like:
"< + random + ".html"
|
GREL has not `random` function, but you can use Python/Jython instead :
import random
# return a random integer between 0 and 1000
return value + str(random.randint(0, 1000)) + ".html"
**Example :**
 rectangle (\textwidth,2);
\end{tikzpicture}
\end{figure}
\end{document}
With the output : ;
\end{tikzpicture}
\end{figure}
\end{document}
|
stackexchange-tex
|
{
"answer_score": 4,
"question_score": 1,
"tags": "tikz pgf"
}
|
How to find all inputs with values
The goal is to list ALL the values for all the inputs on the page, but not list inputs that do not have values, two question:
$(":input").not("[id*=a_prefix_]").map(function()
{
var value = this.val();
if( value ) console.log(this.id + ":=" + value );
}
);
1. There is an issue with the this.val(), I get an error "Object doesn't support property or method 'val'", what is the solution?
2. How do I move the check to see if there is a value into the actual selection so that the map only gets inputs with values?
|
var valueArray = $(":input")
// filter these things out, whatever they are
.not("[id*=a_prefix_]")
// filter only the elements that have a value
.filter(function(){ return this.value.trim(); })
// map the values
.map(function(){ return {[this.id]: this.value}; })
// turn the results into a real array, not a jQuery object of the values
.get();
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, jquery, jquery selectors"
}
|
Can Dired query replace use regular expression to rename a group of files?
So I have long list of files that I'm trying to use regex to rename but, it looks like it does not take standard regular expressions. I’m sure I’m just doing this incorrectly.
After entering dired and `C-x C-q` to make the files writable. I do `M-%` or `query-replace-regexp` to start the regex file rename but it does not work.
I tried doing a query replace for `.eps\d.*` to match everything then a replace with `.mkv` with no luck. What is the proper way to complete this task?
Starting File list example:
Show.S03E01.eps3.0.modifer322344.mkv
Show.S03E02.eps3.1.someihtng.else.mkv
Show.S03E03.eps3.2.lega.matters.mkv
Show.S03E04.eps3.3.data.par2.mkv
Finished File list example:
Show.S03E01.mkv
Show.S03E02.mkv
Show.S03E03.mkv
Show.S03E04.mkv
|
> I do `M-%` to start the regex file rename but it does not work.
`M-%` runs the command `query-replace`
`C-M-%` runs the command `query-replace-regexp`
* * *
> I see that it does not like backslash as an escape like `\d` for digits.
Indeed; a digit is matched with `[0-9]` or `[[:digit:]]`
You can read about the regular expression syntax supported by Emacs with:
* `C-h``i``g` `(emacs)Search`
* `C-h``i``g` `(elisp)Regular Expressions`
* * *
> I tried doing a query replace for `.eps\d.*` to match everything then a replace with `.mkv`
Search for `\.eps[0-9].*`
or perhaps `\.eps[0-9].*\.mkv`
|
stackexchange-emacs
|
{
"answer_score": 3,
"question_score": 3,
"tags": "dired, regular expressions, query replace"
}
|
What does "function() { get: function(...) { ... } }" in JavaScript mean?
I found the following code snippet here:
App.factory('myHttp',['$http',function($http) {
return function() {
get: function(url, success, fail) {
$http.get(url).success(function(response) {
return response.data;
}).error(fail);
}
};
}]);
I wonder what does this syntax mean:
function() {
get: function(...) { ... }
}
|
It looks like it's a typo. It's definitely a syntax error. It resembles the ES5 getter notation, but even so, you can only use that with a property name, like `get response() { ... }`.
Perhaps what the author intended was:
App.factory('myHttp',['$http',function($http) {
return {
get: function(url, success, fail) {
$http.get(url).success(function(response) {
return response.data;
}).error(fail);
}
};
}]);
which is _not_ the ES5 getter notation, but a simple object with one property called `get`, referring to HTTP GET (as opposed to POST).
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "javascript"
}
|
How to Handle Pause Event in SAPI Engine
I currently have a SAPI voice implemented which works fine. I would like to know how do I handle Pause event in the engine when the application calls ISpVoice->Pause.
|
As near as I can tell, `ISpVoice::Pause` is implemented entirely in the SAPI layer and doesn't make any engine calls.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "sapi"
}
|
File handling in TypeScript
I am new to TypeScript and was wondering what command to use to remove the file path and extension. for example if my file is ./data/input/myfile.js how can i strip it out to only have myfile (without path and extension)
|
In node.js, you would use the `path` module and use `path.basename()` in that module:
const path = require('path');
let basename = path.basename('./data/input/myfile.js');
console.log(basename); // "myfile.js"
FYI, this has nothing to do with TypeScript, this is just a plain node.js question.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "node.js, typescript"
}
|
sometimes when adding new fields in index, they don't get indexed in elasticsearch
Let's say I have an index `test` and which already exists. I want to add a new field `newfield1` with some data for all documents in the database. Currently I am simply deleting all everything and then reinserting the data with the `newfield1` data added in. I understand this isn't the most efficient way, but that's not my question right now.
Sometimes the data in `newfield1` does not get indexed and I can't visualize it in Kibana. It's pretty annoying. Is there something wrong with what I'm doing?
NOTE: I CAN query this field in ElasticSearch which makes me think there's a problem with Kibana
|
Kibana caches the field mapping. Go to Settings -> Indices, select your index, and click the orange "Refresh" button.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "elasticsearch, kibana, nosql"
}
|
node js get object array object
Hi everyone good day,
how can I get the value of this object that is returning from this
Post.find().lean()
.exec((err, post) => {
console.log(post);
req.post = JSON.stringify(post);
console.log(req.post);
});
the first console log returns this
[ { photo: [ [Object] ] } ]
the second console log returns this
[{"photo":[{"_id":"5d7dd20185251921882e2ba1","data":"...","contentType":"image/jpeg"}]}]
now what i want to get is the contentType and data.
thank you.
|
After stringify do `post = JSON.parse(post)` ,then you can access `post.data` and `post.contentType`
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "node.js, mongodb"
}
|
Is this password hashing function safe?
Would this be secure enough to hash passwords?
/**
* Creates a SHA-256 hash
* @param string $salt Salt for hashing algorithm
* @param string $string What is getting hashed
* @return string Returns a hashed string
*/
public function hash ($string, $salt) {
$crypt = crypt($string, '$5$rounds=5000$' . $salt . '$');
$hash = str_replace('$5$rounds=5000$' . $salt . '$', '', $crypt);
return $hash;
}
|
Using SHA-256 with a salt is not that bad. But PHP has built in functions like password_hash and password_verify to hash passwords. It uses bcrypt, which is currently one of the best methods to hash passwords these days. I would recommend this approach and it is just as easy to use like the function you've written.
|
stackexchange-codereview
|
{
"answer_score": 4,
"question_score": 2,
"tags": "php"
}
|
Does reassigning partitions of __consumer_offsets topic cause problems?
We are runnning 25 brokers. But partitions of the __consumer_offsets topic spreads on only 3 brokers and it's not fully available as we intended. This may not a problem because kafka supports reassigning partition across brokers. But we hesitate to reassign them because topic is __consumer_offsets.
Cluster information :
* Broker version: 0.11.0.2
* number of brokers : 25
__consumer_offsets topic status :
* number of partitions : 50
* number of replica : 3
* Broker spread : 3 (50 partitions are placed on 3 partitions)
My questions is : Does reassigning partitions of __consumer_offsets topic leads problem or not?
|
You can reassign partitions of __consumer_offset , there wouldn't be any issue as it's reassignment is treated the same way as other topics
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "apache kafka"
}
|
How to iterate over a List<string> in jquery
Hi I have a function in my MVC controller returning a `IList<string>`.
I call it in jquery via:
$.post('Invoice/Validate/' + invoiceId, function(data) {
$.each(data, function(key, value) {
alert(value);
});
The problem is instead of getting the strings in the List I'm getting the letters out of System.String[] individually displayed by the alert.
Could somebody please point me in the right direction?
|
You need to fix your controller method to return the JSON array of string rather than .ToString() of the List
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "jquery"
}
|
Metro StAX implementation - how to configure?
Is there any way to tell metro what StAX implementation it should use?
|
Finally I found the solution. We need to set system properties:
javax.xml.stream.XMLEventFactory
javax.xml.stream.XMLInputFactory
javax.xml.stream.XMLOutputFactory
for example:
System.setProperty("javax.xml.stream.XMLEventFactory" ,"com.sun.xml.stream.events.ZephyrEventFactory");
System.setProperty("javax.xml.stream.XMLInputFactory" ,"com.sun.xml.stream.ZephyrParserFactory");
System.setProperty("javax.xml.stream.XMLOutputFactory" ,"com.sun.xml.stream.ZephyrWriterFactory");
for more information look at this
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "web services, java metro framework, stax"
}
|
Rails console is not showing attribute when called
>> Reply.first
=> #< Reply id: 1, body: "line1\r\n\r\nline2\r\n" >
But when I do
>> Reply.first.body
=> "line1"
Its breaking a few of my tests where they are looking for :
assert_difference 'Reply.where(:body => "line1\r\n\r\nline2").count' do
How can my tests be reassured there are line breaks?
|
Seems like you have a custom getter, something like:
class Reply < ActiveRecord::Base
def body
"foo"
end
end
reply = Reply.new(body: "bar")
#=> #<Reply id:nil, body: "bar" created_at: nil, updated_at: nil>
reply.body
#=> "foo"
In that case, you can fetch the raw attribute using `Model[:attribute_name]`:
reply[:body]
#=> "bar"
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "ruby on rails, ruby"
}
|
Knockout submit binding on click of a button
I am trying to get text entered in an input box to apply to the page on click of a button. I am using the submit binding, but can not figure out what I am doing wrong.
**HTML:**
<form data-bind="submit: doSomething">
<label>
<input data-bind='value: showText' />
</label>
<button type="submit">button</button>
</form>
<h1><span data-bind='text: fullText'> </span></h1>
**JS:**
var ViewModel = function(text) {
this.showText = ko.observable(text);
this.doSomething : function(formElement) {
this.fullText = ko.computed(function(){
return this.showText();
}, this);
}
};
ko.applyBindings(new ViewModel());
|
First error:
this.doSomething : function(formElement) {
should be
this.doSomething = function(formElement) {
Second error:
this.fullText
is defined inside the function, but you use it in binding to viewModel.
I've prepared jsfiddle with fixed code.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, html, knockout.js"
}
|
Can't figure it out: Have eclipse use single window
I haven't used eclipse in a while, and in opening it today somehow something is set so that all windows float separately. I want them all docked in the same instance/whatever. I haven't used the magic word to google or eclipse help figure out how to get things all back under the same roof, and assume it is something ditzy I am just missing - this is version 23.0.2.1259578 - adtproduct.
|
Have you tried going to the Menu Bar : Window -> Reset Perspective ?
Mac : !Reset Perspective Location
Windows : <
Hope this helps!
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "eclipse"
}
|
How can I ensure users have the latest version of my PHP JavaScript?
To be clear, this has nothing to do with script tags. I am not using them. This is JS placed on the page using PHP include.
Most of my JavaScript files mix in PHP and use PHP's include instead of script tags. Usually the solution would be adding a query string to the end of src attribute for a script tag. As far as I know, I can't really do this when I use include. For the most part, I'm having issues on mobile for users to get the latest JS source instead of an old stored cached version on their device.
|
Ok so you if you use include() function to refers to a .php file. You might aswell inside that .php file add a variable of the address of your latest .js
//file to include
...
<script src="<php? echo $latest_JS_reference ?>" ></script>
...
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -3,
"tags": "javascript, php, caching, include"
}
|
ZXing to verify a text form barcode reader
The question is simple. Is it possible to use ZXing C# library to veryify a barcode entered manually form a user ? We need this because sometimes happens that the barcodes are corrupt and the operator must insert the underlying numbers by hand. The barcode format is unknown.
|
Yes, it is.
On my code I use the following to generate an image from the code entered by a user:
var writer = new BarcodeWriter();
writer.Format = BarcodeFormat.CODE_128;
var options = new EncodingOptions();
options.Height = 140;
options.Width = 300;
writer.Options = options;
try
{
Bitmap image = writer.Write(textBoxCodigoDeBarras.Text);
BitmapImage bi = ImageManager.BitmapToImagesource(image);
ImageCodigoDeBarras.Source = bi;
}
catch
{
//Could not generate image.
//Therefone Barcode is invalid.
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c#, zxing"
}
|
Only link is visible while integrating twitter feed in a website?
Here is the code i used given by the Twitter developer widget
<a class="twitter-timeline" href=" data-widget-
id="274533936351289345">Tweets by @PineappleTimes</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)
[0];if(!d.getElementById(id))
{js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
|
Found my answer atlast. While previewing the code in dreamweaver the tweets won't be visible, only a link will be visible, but after uploding the code into server, it worked.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "twitter, web, integration"
}
|
Add current date and PC username when a class is created in Visual Studio
Is it possible to add creation date and username when a *.cs file is created in Visual Studio like IntelliJ IDEA do?
For example:
//Created by Tamerlan, 9.28.2016 11:00 <- add this line automatically
public class MyNewClass
{
}
|
Yes, you can create an item template for C# classes and use parameter substitution. Username, date, and time are available as pre-defined substitutions.
<
Although possible, source control makes this redundant. In my opinion.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "visual studio, class, date, author, credits"
}
|
Learning Ruby on Rails in terms of Flask
I'm very experienced with Flask and have built a couple things in it. I'm just learning Rails, and since I know Flask the best, I keep on trying to tie everything I learn back to it. Would anyone mind explaining ROR in terms of Flask? Obviously Flask isn't an MVC, but I have used it with SQLAlchemy, so I've been thinking of my Model as that.
|
Learning Rails in terms of Flask is like trying to fit a large truck inside a small sports car. Rails is a large framework full of powerful features and Flask is a micro framework with limited features designed to build simple sites fast. You are best off learning Rails on its own and then comparing the few features Flask has from Rails.
If you are finding Rails to be too much to learn at once, perhaps try Sinatra first. It's a Ruby micro-framework from which Flask was cloned. Those two will have a lot in common. After mastering Sinatra, Rails is a relatively easy step.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 0,
"tags": "ruby on rails, ruby"
}
|
difference between TreeSets based on their interface
Is there any difference between the two TreeSets ?:
Set<String> s = new TreeSet<String>();
SortedSet<String> s = new TreeSet<String>();
|
Difference is s have acccess to method shared by s type (if you don't cast it). But the object real type is the same.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "java, collections"
}
|
How open youtube video manually with fancybox
I am building an angularJS webapp and I want to open a youtube video by calling a method of my constructor. To achieve that; I want to reproduce the same behavior as
$(document).ready(function() {
$('.fancybox-media')
.attr('rel', 'media-gallery')
.fancybox({
openEffect : 'fade',
closeEffect : 'fade',
padding: 0,
helpers : {
media : {},
buttons : {}
}
});
});
But using the manual way, `$.fancybox.open([ ... ])`. Can someone guide me on how to do it?
|
$.fancybox.open({
content: '<iframe width="xxx" height="xxx" src="//www.youtube.com/embed/xxxxxxxx" frameborder="0" allowfullscreen></iframe>'
});
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, fancybox"
}
|
Does anyone have any idea about BEAM - Blackberry Enterprise Application Middleware?
I am trying to make an application which uses the features in the upcoming BEAM ? Does anyone have any idea how to get started with this ?
Thanks in advance
|
Despite it was announced in 2010 I am not able to find any documentation/API on this. As well as no BEAM SDK publicly available at RIM site for download (despite I am logged in as a developer). I am under impression the SDK/API is still under progress.
BTW, have you tried to regiter here: Register to be notified about BlackBerry Enterprise Application Middleware features, functionality and SDK availability ? Just a guess - maybe upon registration you'll be provided with some useful info on this.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "blackberry, blackberry simulator"
}
|
How to get price from bitcoin to USD with api
Please help me how to get the price from bitcoin to USD with bitpay API. I wrote the following code, but I got USD to bitcoin price. I want bitcoin to USD price. Thanks!
<?php
$url = "
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
$rate = $data[1]["rate"];
$usd_price = 10; # Let cost of elephant be 10$
$bitcoin_price = round( $usd_price / $rate , 8 );
?>
|
Is this what you mean?
$url='
$json=json_decode( file_get_contents( $url ) );
$dollar=$btc=0;
foreach( $json as $obj ){
if( $obj->code=='USD' )$btc=$obj->rate;
}
echo "1 bitcoin=\$" . $btc . "USD<br />";
$dollar=1 / $btc;
echo "10 dollars = " . round( $dollar * 10,8 )."BTC";
returns
1 bitcoin=$11485USD
10 dollars = 0.0008707BTC
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 3,
"tags": "php, json"
}
|
Adding an icon beside a button in CSS
I am trying to do something as "trivial" as this in CSS with bootstrap but I am having no luck. Can anyone help me out with how to add an icon with a background right beside my form button?
!enter image description here
<form>
<button type="submit" class="btn btn-primary">COOL BUTTON
</button>
</form>
<
Thanks!
|
You can use any image or icon for that, but if you use bootstrap icons for example, you can do it like that:
<form>
<button type="submit" class="btn btn-primary">
COOL BUTTON
<span class="glyphicon glyphicon-search"></span>
</button>
</form>
`**Demo**`
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": -3,
"tags": "html, css, twitter bootstrap"
}
|
Is there any good desktop/application or command line tool to show two different timezone concurrently?
I want to find a desktop application or command line tool to show two different timezone concurrently under **LINUX.**
Anyone knows there are such application?
Say i want to know the time at london and USA at the same time. (different time zone)
|
Assuming you are using Ubuntu 10.10 or previous version .
The GNOME clock applet can show two times in the drop down.
!enter image description here
Right click on the clock and select "Preferences." Goto the "Locations" tab and press "add."
Then, select "whatever" from the "Timezone" list.
!enter image description here
|
stackexchange-superuser
|
{
"answer_score": 2,
"question_score": 1,
"tags": "linux, time zone, command line tool"
}
|
Name error: Image to text error in python
I am working on developing code to convert image to text using the below code. I see the below error while executing the code. I dont really understand what is causing the issue. Can any one help me to identify the issue.
from PIL import Image
import PIL.Image
from pytesseract import image_to_string
import pytesseract
img = Image.open('C:\\Users\\Documents\\convert_image_to_text\\Sample.png')
pytesseract.pytesseract.tesseract_cmd = 'C:\AppData\Local\Tesseract-OCR\tesseract.exe'
text = pytesseract.image_to_string('C:\\Users\\Documents\\convert_image_to_text\\Sample.png')
print(text)
Below is the error:
File "C:/Users/Documents/convert_image_to_text/program_to_convert_image_to_text.py", line 21, in <module>
text=image_to_string(img)
NameError: name 'img' is not defined
|
You should be passing the `img` object and not the path
text = pytesseract.image_to_string(img)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "python, pandas, spyder, python tesseract"
}
|
Cannot replace £ with £ from string
I have a HTML string containing £ signs, for some reason i'm not able to replace them. I'm assuming this is an encoding issue although i can't work out how. The site is using ISO-8859-1 for its encoding
$str = '<span class="price">£89.99</span>';
var_dump(mb_detect_encoding($str, 'ISO-8859-1', true)); // outputs ISO-8859-1
echo str_replace(array("£","£"),"",$str); // nothing is removed
echo htmlentities($str); // the entire string is converted, including £ to £
Any ideas?
**EDIT**
should have pointed out i want to replace the £ with `£`; - i had temporarily added `£` to the array of items to replace in case it had already been converted
|
Just a guess but could it be that even thou your website outputs in ISO-8859-1 encoding, your actual *.php files are saved as utf-8? i don't think that str_replace works correctly with utf-8 strings. To test it try:
str_replace(utf8_decode("£"),"£",utf8_decode($str));
Yeah, if this works then your *.php files are saved in utf-8 encoding. This means all the string constants are in utf-8. It's probably worth switching default encoding in your IDE to ISO-8859-1
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 7,
"tags": "php, encoding, character encoding, str replace"
}
|
Unable to remove the start menu and desktop shortcuts in NSIS uninstaller
ExecWait '"$INSTDIR\uninstall.exe" _?=$INSTDIR'
I am using this code to invoke the uninstaller but it could not remove start menu item and desktop link while a normal uninstallation by double clicking is able to remove all these things.
|
Do you have RequestExecutionLevel in your script? Without it Windows might do some compatibility hacks with your shortcuts.
Code like `Delete "$SMPROGRAMS\myapp\myapp.lnk"` should not change behavior just because you launched with `_?=`, is there something special about the shortcuts paths or the way you delete them?
You should try Process Monitor, it might be able to shed some light on the issue...
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "nsis"
}
|
How to reflect changes in view without refreshing a page?
I am using MySQL database and hibernate and jsp,using hibernate i am reading database and prepare a view using jsp.it done but i want to make sure that any changes on database is also reflected on my prepared view without refreshing a page.please provide some clear idea to do that.
thanks
|
make ajax call to your servlet
start with this tutorial
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "ajax"
}
|
Бесконечный цикл в c++
#include <iostream>
int main()
{
int count(0);
while (count < 10)
{
if (count == 5)
continue;
std::cout << count << " ";
++count;
}
return 0;
}
Я ожидаю, что программа прежде чем войти в бесконечный цикл выведет `1 2 3 4 `, но она этого не делает. У меня сразу начинается цикл. Но если я изменю строчку `std::cout << count << " ";` на `std::cout << count << " " << std::endl;`, то тогда будет происходить вывод `1 2 3 4 `(но в столбик). Вопрос: почему в первом случае числа не выводятся ?
|
Потому что `cout` буферизует вывод - писать числа в терминал "дорого" по времени, они попадают во временный буфер. А так как программа зацикливается, они в этом буфере остаются навечно.
`endl` же не только переводит строку, но и заставляет буфер сброситься.
Чтобы сбросить буфер без перевода строки, используйте `cout << flush;`
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "c++"
}
|
Every parallelizable even dimensional manifold is symplectic?
I am just thinking about this. So, we have the symplectic form on $\mathbb{R}^{2n}:\omega_o=\sum_{i=1}^{2n}dx_i\wedge dy_i,$ where $x_1,\dots,x_n,y_1,\dots,y_n$ are linear coordinates on $\mathbb{R}^{2n}.$ We can just use this form to get a symplectic form on the manifold. Is this correct or am I making some mistake here?
**Edit:** In details what I mean is suppose we have $\phi:TM\rightarrow M\times\mathbb{R}^{2n}$ which gives us an diffeomorphism such that it gives us linear isomorphism on each tangent space level. Now my proposed symplectic form is the following: for $x\in M,v,w\in T_mM,\omega_x(v,w)=\omega_0(\pi_2\circ \phi(x,v),\pi_2\circ \phi(x,w))$ where $\pi_2$ is the projection onto $\mathbb{R}^{2n}$ from $M\times\mathbb{R}^{2n}$.
|
A counterexample is $S^{1}\times S^{3}$. It does not have a symplectic structure because $H^{2}(S^{1}\times S^{3})=0$.
But $S^{1}\times S^{3}$ is parallelizable: both $S^{1}$ and $S^{3}$ are parallelizable since they are Lie groups, and the product of parallelizable manifolds is again parallelizable.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 2,
"tags": "solution verification, symplectic geometry"
}
|
How do I get to know value of this unusual character? square matrix having digits inside
!enter image description here
The uploaded image shows unusual characters **(square matrix having digits written inside).** This is happening when I try to write
write(fd, buf,len)'s `buf` variable using fprintf function.
Is there any way to interpret these characters ?
Additional info:- `write()` is having a socket fd to write on. Please tell me , If I am missing anything here. Also, please retag this post , because I don't know which tag is suitable for this post. [edit] : please zoom the web page (using ctrl++), if these characters are not clearly visible.
|
They are all unprintable control characters, the box is just a way to print them. Another option is to not show them at all but then you wouldn't know about them as easily.
There's
* `0x1F` Unit separator
* `0x7F` Delete
* `0x01` Start of Heading
* `0x1C` File Separator
(You can read all of the above from the boxes already)
Since these are almost never used in text, you should probably not treat them as text. If you look at the meaning of them as control characters, they don't make sense even as control characters.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c, sockets, character encoding, special characters"
}
|
Flickr: Same photo multiple permissions
* Lets say I upload 10 images on Flickr
* I put all the 10 images in set1 with private permissions(visible only to me and my friends and family)
Now, lets say out of these 10 photos, I want to share 4 photos to everyone (public). So, can I do it by creating another set, set2, and by putting set2 permissions as public? I tried doing it however it does not work?
How can I achieve my goal? Are the permissions tied to a photo or to a set?
|
Permissions are tied to a photo. Unless I'm misunderstanding things, you should be able to accomplish what you want simply by marking the four photos you want other people to be able to see as public. For example, this set of mine actually has 17 photos in it - but you can see only 5 of them; the other 12 are private.
|
stackexchange-photo
|
{
"answer_score": 4,
"question_score": 0,
"tags": "flickr"
}
|
Attempting to print array elements recursively
#include <stdio.h>
int printArray(a[], unsigned int n){
if (n == 4){
printf("%d", a[4]);
}
else {
printf("%d", printArray(a,n+1)); // here is the error, I know. But why?
}
}
int main(){
int a[5] = {1,2,3,4,5};
printArray(a,0);
}
I am a begginer with C. I am trying to print each of the elements of the array, but it only prints the last one correctly, and not the former ones. I know there's something about recursive way wrong. It's the first time I use recursive way without return and using printf. Maybe is this that misleaded me?
Output:
$ ./a.out
5
0
1
1
0
|
You should print the array item, not the return value of the function, Use this code
int printArray(int *a, unsigned int n){
if (n == 4){
printf("%d", a[4]);
}
else {
printf("%d", a[n]);
printArray(a,n+1);
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c, arrays, printf"
}
|
Regex to capture episode number
What is wrong with the following regular expression I have:
s = "s4, ep2 -- The one"
>>> re.search(r'(Episode|Ep?\.?)?\s?(\d{0,})', s, re.IGNORECASE).group(2)
''
I am trying to capture the `2` from the `"S4, Ep2"`. I thought the `Ep?\.?\s?d{0,}` would capture it but it seems like I'm missing something.
Here are other example inputs that might be entered:
Episode 2
Ep. 2
E. 2
2
Season 4, E 2 -- Hello
All of the above should come out as "2"
|
This version is working. We can try matching on `Episode`, `Ep`, or just `E`, followed by an optional dot and/or space. Then, capture an episode number.
s = "s4, ep2 -- The one"
print(re.search(r'(?:Season \d+,\s+)?(?:Episode|Ep|E)?\.?\s?(\d{0,})',
s, re.IGNORECASE).group(1))
2
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "python, regex"
}
|
How to find the CDF and PDF
How to find the Cumulative Distribution Function (CDF) and Probability Distribution Function (PDF) for uniform variable inside circle given by $R^2 = (X-c_1)^2+(Y-c_2)^2$, where ($c_1, c_2$) is the center of circle.
I think that the PDF for problem is given by
\begin{equation} f(x,y) = \begin{cases} \frac{1}{\pi R^2}&, \quad (x-c_1)^2 + (y-c_2)^2 \leq R^2\\\ 0&, \quad otherwise \end{cases} \end{equation}
|
**HINT** $$ \begin{split} F_T(t) &= \mathbb{P}[T < t] \\\ &= \mathbb{P}\left[X^2 + Y^2 < t^2\right] \\\ &= \frac{1}{(b-a)^2} \int_a^b \int_a^b \mathbb{I}_{x^2 + y^2 < t^2}dxdy \end{split} $$ and you can transform the integral over the indicator by integrating over the correct region...
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "probability, probability distributions"
}
|
Git check if there is outstanding commits to push
Is there a command I can run to check if there is any commits to push to origin/master?
git [some command] origin master
Would output something like:
origin/master is behind by 7 commits
|
Here are two ways to list the "extra" commits you have which are not on origin/master:
git log --oneline origin/master..HEAD
git rev-list --oneline ^origin/master HEAD
The `--oneline` just lists them in a shorter format. Also, if your branch tracks origin/master, a simple `git status` will show you.
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 6,
"tags": "git, version control"
}
|
How to read analog pin data from the Blynk HTTP RESTful API?
I am making my own app for my project with Blynk so I need the Blynk API it works fine with Digital Pins I am getting the right value. But I tried with analog pin I used this syntax: <
When I give the analog pin it shows the value as 0 always but in Blynk app it shows correctly.
["0"]
This is what I get when I give
How can I get the analog pin value?
|
Type D17 instead of A0. It Works!!
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "esp8266, nodemcu, arduino esp8266, blynk"
}
|
Can I improve my SQL response times?
I am executing a query that gets some data from a remote server.
It is a simple select query say
select * from opendatasource(----).[Database].[dbo].[Table1]
Now Table1 (has 4 columns) contains 15 hundred-thousand records and is growing in size.
On my server where I get the result set of the query it takes around 6 seconds to get the data. It looks slow to me.
**The Table1 has a primary key field of datatype char(28)** and no other index of any kind is defined.
This seems to be the problem.
What might be a possible workaround to make the database do work faster?
Help is appreciated
Thanks
|
You are pulling whole table. I don't think you can make it faster.
Unless:
* you filter the number of pulled rows (`where` condition)
* add index covering you `where` condition
* limit the number of returned field (`select field1, field2` vs `select *`)
* get faster connection between the client (wherever you run the script) and server
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "sql server 2008"
}
|
Inserting a new managed object in Core Data
I am new to Core Data and I feel that I don't get a hang of it. When you are going to create a new managed object you have to use the method that I pasted in at the bottom from the NSEntityDescription class.
Now is this object registered in the context, it is right? Why do you have the `insertObject:` in NSManagedContext then? It works without invoking that method after using the one in `NSEntityDescription`. Could somebody explain?
**NSManagedContext**
insertObject:
**NSEntityDescription**
+ (id)insertNewObjectForEntityForName:(NSString *)entityName inManagedObjectContext:(NSManagedObjectContext *)context
|
You can create NSManagedObject with `nil` context and then decide whether you want to add it to context or not. You may also like this: Is there a way to instantiate a NSManagedObject without inserting it?
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "iphone, objective c, ios, core data"
}
|
How do ISVs login to customer orgs after they have been granted access?
For a while now you have been able to grant administrator access to apps you have installed for support purposes.
A customer has granted me access but as an ISV I cannot see how to get into a customers org from either the org where the managed package is developed for the LMO org. I haven't found any useful documentation around this on DeveloperForce.
Any help from ISVs appreciated.
|
Providing the customer has gone into Grant Login Access and selected access to your app and not Salesforce.com Support (as that is for Salesforce only).
!enter image description here
Then in your LMO, you should see a Subscribers tab.
!enter image description here
Which looks like this...
!enter image description here
Just enter your customers name, click the entry and it should bring up a summary page with some licensing details on it etc. There should be a related list with users from that organisation that have granted login. Click Login next to the desired user.
Here are some useful links...
* Supporting Your Subscribers
* Logging in to Subscriber Organizations
|
stackexchange-salesforce
|
{
"answer_score": 16,
"question_score": 13,
"tags": "app development"
}
|
Best practice for text in html
What html tag is used for text that is neither a heading `<h1>` nor a paragraph `<p>` ? The `<pre>` tag is not appropriate because I need to style the text with CSS. (So, the text is basically a non-important phrase.)
Example 1: Price per product: $5
Example 2: Add to Cart
What would be the best practice (or standard way) of dealing with this situation ? Can text be placed inside an `<aside>` tag without first surrounding it with `<h1>` or `<p>` ?
|
**Example 1:** If you're feeling semantic, you can write it like this:
<dl>
<dt>Price per product:</dt>
<dd>$5</dd>
<dt>Products in stock:</dt>
<dd>12</dd>
</dl>
Otherwise, a span tag would be fine.
* * *
**Example 2:** Use an `<a />` or `<button />`
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "html, seo"
}
|
multiple c# windows form application
I have two forms, the main form and a form named FrmSteg. I added a button on the main form and entered the code below in the click event of the button.But i got an error "Only assignment, call, increment, decrement, and new object expressions can be used as a statement"
private void btnsteg_Click(object sender, EventArgs e)
{
FrmSteg newForm = new FrmSteg();
newForm.Show;
this.Hide;
}
|
Try this:
newForm.Show();
this.Hide();
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 0,
"tags": "c#"
}
|
Serializing Related Entities
I'm using the Entity Framework 4 to serialize an object via an XML web service. The scalar properties on the object serialize fine, and I have a 0 or 1 property which also serializes.
I have one property however which is omitted from the output. It's a one to many (My object has a List), but the Sections navigation property isn't even included in the output. I'm including the property in my linq query, and debugging shows that the items in the `Sections` property are indeed loading, just not serializing. Here's my code:
dim item = Db.Surveys.Include("SurveySections").FirstOrDefault(Function(u) u.SurveyID = surveyId)
|
I got around this by creating an additional property which acted like an extra getter/setter for the EF property.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": ".net, web services, entity framework, asmx"
}
|
Add a newline character in a string of the title of a colorbar
I want to newline character in a string. \n doesn't work.
Problem: I wish the title of a colorbar to be displayed in two lines.
Code:
h = colorbar;
set(get(h,'title'),'string','Total distance moved by staying individuals away from their initial position (m)');
Please help.
|
To have multiple lines in a title, you have to pass a cell to the `title` function:
title({'Line 1', 'Line 2'});
For colorbar titles, it's the same idea:
set(get(h, 'Title'), 'String', {'Line 1', 'Line 2'})
and the result (with a random image):
!enter image description here
Best,
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "matlab"
}
|
Find the values of $a$ for which these matrices commute, in $\mathbb{Z}_{23}$
Find the values of $a$ for which these matrices commute, in $\mathbb{Z}_{23}$
$A = \left( \begin{array}{cc} 9 & 22 \\\ 18 & a + 3 \end{array} \right) % \ \ \ \ \ B = \left( \begin{array}{cc} 6 & 22 \\\ 18 & a \end{array} \right)$
My attempt:
If we calculate $AB$ and $BA$
$AB = \left( \begin{array}{cc} 9\cdot6 + 22\cdot18 & 22\cdot9 + 22\cdot a \\\ 18\cdot6 + 18\cdot (a + 3) & 22\cdot18 + a\cdot(a + 3) \end{array} \right)$
$BA = \left( \begin{array}{cc} 9\cdot6 + 22\cdot18 & 22\cdot6 + 22\cdot (a + 3) \\\ 18\cdot9 + 18\cdot a & 22\cdot18 + a\cdot(a + 3) \end{array} \right)$
If we compare the two matrices element by element we can see that $AB=BA$ for any value of $a$ in $\mathbb{Z}_{23}$.
Is there something wrong with this? Do I need to reduce something modulo $23$?
|
You don't really need to do any reduction. Note that $B = A + 3I$. Therefore $$AB = A(A + 3I) = A^2 + 3A = (A + 3I)A = BA.$$
|
stackexchange-math
|
{
"answer_score": 5,
"question_score": 2,
"tags": "matrices, modular arithmetic"
}
|
Java to JSP. How to?
i have written a java program which currently runs as a desktop app,
it is returning all results accurately as required in the console. I am now faced by a challenge to convert this application to a web application (JSP).
Currently, the code for my projects is in user/workspace (as i am using eclipse)
and my tomcat has been installed at c:/server/tomcat..
I am basically a .net developer and know peanuts about java web development. Can someone please guide me as to how i can convert my current project into a web application?
how do i include the project in user/workspace in the jsp file? havent done it before so its as confusing as hell.
it will be most helpful if you can point me in the right directon, or even provide some links so that I can use thm as a pointer
Many Thanks in Advance.
|
I suggest not to use the JSP technology anymore unless you have to (-> customer demands it).
Instead, get GWT or Grails. Both come with tools to setup a project in Eclipse from scratch that compiles and can be run with the press of a button. Also, both technologies are much more advanced than JSP and you'll find them much more simple to understand as a .Net developer.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "java, jsp"
}
|
How to update row and return id?
I use this function ORM to update row in table:
$client = Client::where("unique_code", $this->unique_code)->whereHas('types', function ($query) {
$query->where("type", $this->type);
})->update(["status" => 1]);
How to return `id` of updated row?
|
First what your using is not the ORM but the QueryBuilder.
You should assign the query result in a variable, process the update and then access the id.
$client = Client::where("unique_code", $this->unique_code)
->whereHas('types', function ($query) {
$query->where("type", $this->type);
})->first();
$client->update(["status" => 1]);
$client->id; // to get the id
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "laravel, laravel 5.3, laravel 5.4"
}
|
How to show and hide common header in ng-view which is out of scope
I need to have a common header outside `ng-view` and I also need to show and hide it from the controller. I am trying to do the following task but unable to achieve
html:
<body ng-app="myApp">
<div id="titleHead" ng-show="{{th}}">
<h1>{{title}}</h1>
</div>
<div ng-view></div>
</body>
js:
controller1($rootScope){
$rootScope.th = 'true';
}
controller2($rootScope){
$rootScope.th = 'false';
}
Please see my code.Is there any other way to do this?
|
HTML should be:
<body ng-app="myApp">
<div id="titleHead" ng-show="th">
<h1>{{title}}</h1>
</div>
<div ng-view></div>
</body>
Controller:
controller1($rootScope){
$rootScope.th = true;
}
controller2($rootScope){
$rootScope.th = false;
}
If you use `$rootScope.th = 'false';`, it has string value is `false`. When you check with `ng-show="'false'"` it will show.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, angularjs"
}
|
assign value of type 'JSON' to type '[JSON]'
I have a tableview and data saved in JSON on var data = JSON and I tried to save the same data to another view with same type but it gives error **" Cannot assign value of type 'JSON' to type '[JSON]'"**
var data = [JSON]()
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let vc = storyboard?.instantiateViewController(withIdentifier: "SecAdsViewController") as? SecAdsViewController else { return }
vc.data = self.data[indexPath.row]
self.navigationController?.pushViewController(vc, animated: true)
}
on the second view
var data = [JSON]()
|
in your first view you are used the array of dictionary using swiftyJSON, once user tapped the cell you want to move the one dictionary to second view, so in your second view you need to create the dictionary not a array,
var data: JSON = [:]
|
stackexchange-stackoverflow
|
{
"answer_score": -1,
"question_score": 0,
"tags": "ios, json, swift, uitableview"
}
|
Affirmations with question marks
Today I was reviewing some code on GitHub, and end up with the following sentence/question:
So, are you using a context to update a record? That makes no sense.
I know that verbs and subjects are "swapped" when used in questions. What about affirmations with a question tone? Should it be written like this?
So, you are using a context to update a record? That makes no sense.
|
Yes, the way you have it written is correct.
I do not know the word for this form, but as @sxpmaths said, it carries an implication of rebuke, or incredulity. You could make it more explicit with a tag, for example:
> So, you are using a context to update a record, are you?
|
stackexchange-english
|
{
"answer_score": 0,
"question_score": 0,
"tags": "grammar, question mark"
}
|
Show that the set of functions under composition is isomorphic to $S_3$
Show that the set $\\{f_1, f_2, f_3, f_4, f_5, f_6\\}$ of functions $\mathbb{R}-\\{0, 1\\}\rightarrow \mathbb{R}-\\{0,1\\}$ under composition is isomorphic to $S_3$, where $$f_1(x)= x\\\ f_2(x) = 1-x\\\f_3(x)=1/x\\\f_4(x)=1-1/x\\\f_5(x)=1/(1-x)\\\f_6(x)=x/(x-1)$$
I am unsure how to start with this. I want to understand how to go about doing this and not just the answer. Any pointers would be a appreciated.
|
**Hint:** You need to construct a bijection between your $6$ functions and the $3!=6$ elements of $S_3$. Try writing them down in separate columns and matching them together. Can you spot the identity element? Compose each function with itself until you get the identity function; this will help you figure out its order.
Once you've done that, you should find that $3$ functions have order $2$. Arbitrarily assign these $3$ functions to the three $2$-cycles in $S_3$. To figure out how to assign the remaining $2$ functions of order $3$, pick any two distinct $2$-cycles in $S_3$ and multiply them to obtain a $3$-cycle. Match this $3$-cycle to the function of order $3$ obtained by composing the corresponding functions of order $2$.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 2,
"tags": "abstract algebra, group theory, function and relation composition"
}
|
Build multiple branches at once in a YAML pipeline
I have the following need: I want to produce/publish an artifact that is the result of multiple branches build.
Example: I have release/Update2, release/Update3, release/Update4, I want to build each of them to obtain Update2/Task.exe, Update3/Task.exe, Update4/Task.exe. And then zip them to release.zip.
I'd like to do it in YAML, but I can't find documentation saying how to build different branches at once. My other solution is to create a release pipeline on Azure DevOps, but I can't do it in YAML.
Is there a way to do this?
|
You can use your yaml to build one default branch (like release/Update2). Additionally, add to yaml Command Line task with `git checkout --force "your_branch"` and build steps. Consider using build templates to simplify your yaml file: Template types & usage
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "azure devops, yaml"
}
|
How to include static information in logging with Log4j or similar?
We have an application where a log message without the context in which it was run (i.e. the database) does nearly never make sense. The information is always available, but it is quite cumbersome to include it everywhere by hand. Is there a more elegant way of doing it?
I was thinking along the lines of implementing a wrapper around logging that always includes the information. I have tried it, but I'd like the LogFactory (either slf4j or Log4j) to pick this class by default, and I don't know how to do that...
Any suggestions?
|
You could take a look at the `NDC` or `MDC` classes. You can push context information on the stack and include this automatically in your log messages.
You can find a small example here.
In your `PatternLayout`, use `'%x'` to log `NDC` information and `'%X'` for `MDC`.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "java, logging, log4j, slf4j"
}
|
Convert JSON file in <ul><li> using plain Javascript
I have JSON file that contains :
{
"age": 0,
"id": "motorola-xoom-with-wi-fi",
"imageUrl": "img/phones/motorola-xoom-with-wi-fi.0.jpg",
"name": "Motorola XOOM\u2122 with Wi-Fi",
"snippet": "The Next, Next Generation\r\n\r\nExperience the future with Motorola XOOM with Wi-Fi, the world's first tablet powered by Android 3.0 (Honeycomb)."
},
Im need to somehow display it as "ul" "li" list by using plain javascript I wrote this code but it doesn't work:
function createList(){
var arr = JSON.parse(phones);
var out = "<ul>";
for(var i = 0; i < arr.length;i++){
out+="<li>" + arr[i].age + arr.id[i]+
arr[i].imageUrl + arr[i].name + arr[i].snippet + "</li>";
}
out+= "</ul>";
document.getElementById("div1").innerHTML = out;
}
|
try this
var phones = {"age" : "0", "id" : "motorola-xoom-with-wi-fi", "imageUrl" : "img/phones/motorola-xoom-with-wi-fi.0.jpg", "name" : "Motorola XOOM\u2122 with Wi-Fi", "snippet" : "The Next Next Generation Experience the future with Motorola XOOM with Wi-Fi, the worlds first tablet powered by Android 3.0 (Honeycomb)."};
var arr = phones;
console.log(arr);
var out = "<ul><li> age : " + arr.age + "</li><br><li> id : " + arr.id + "</li><br><img src='" + arr.imageUrl + "'/></li><br><li> name : " + arr.name + "</li><br><li> snippet : " + arr.snippet + "</li>"
document.getElementById("div1").innerHTML = out;
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, html, json"
}
|
Powershell replace only numbers in beginning of string
I have a lot of strings that I am going to loop through and be changing various characters in. One thing I need to do is convert numbers at the beginning of the string to their string representation. Example: `'10_hello_1'` to `'ten_hello_1'`. There will always be a '_' after a number. I have tried various things such as: `$a.replace('\d{2}_','')` (just to at least delete the beginning numbers) but that does not work.
I have even thought of breaking this down further and using a '$a.startswith()` clause but can not get powershell to ask "does this start with any arbitrary number".
I have found a lot about string manipulation on the web I just can't piece it altogether. Thanks!
|
The string .Replace method does not use regular expressions. Instead use the -Replace operator:
$a = '10_hello_1'
$a -replace '^\d+', ''
As for getting a word conversion of a number, I'm not aware of any built in method. Here is a question that proposes a .Net way to do it that you could easily convert to Powershell:
.NET convert number to string representation (1 to one, 2 to two, etc...)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "string, powershell, replace"
}
|
Laravel cookies with redirect
I've got Laravel cookies working on my localhost but not on Laravel Forge. On Forge, I get a Nginx `502` bad gateway error that I can't analyze because Forge doesn't give access to error logs. Might someone help?
Here's my code:
\Cookie::queue('linkedin_user', $li_user); //commenting out this line allows for the proper redirect on Forge
return redirect('/signup');
|
I couldn't get cookies to work so I ended up using `Session` instead. An easy swap with no hassles.
\Session::put('linkedin_user', $li_user);
return redirect('/signup');
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php, laravel, cookies, nginx, laravel forge"
}
|
Does the type of sheet rock behind a glue up tub surround matter?
Since the drywall, green board, or cement board is covered completely why does it matter. The exposed area would be exposed regardless.
|
You can read the manufacturers guidelines. Most tub surrounds offer the choice of using basic drywall. I have a little experience with this and I would go drywall if you can - especially if it for a "cheaper" vinyl surround that has any kind of curves or shelves.
What happens with concrete board is that the vinyl feels more hollow with the harder board and it kind of feels cheap(er).
I almost always drywall now. Now if I feel there might be the potential for any kind of water issue I will paint the drywall with a waterproofing membrane like redgard.
|
stackexchange-diy
|
{
"answer_score": 1,
"question_score": 3,
"tags": "bathroom, drywall, waterproofing"
}
|
How to convert JSONArray to ListView?
I have a code which does following -
1. Connect to a web service via HttpClient to PHP file
2. Returns a result from an SQL query
3. Returns format is a jArray (a JSONArray)
****
for(int i=0; i < jArray.length() ; i++) {
json_data = jArray.getJSONObject(i);
int id=json_data.getInt("id");
String name=json_data.getString("name");
Log.d(name,"Output");
}
When I look at the LogCat, I see all the "names" of the query, Each record is printed. I just need to plug these results into a ListView. How can I accomplish this ?
PS - I do not have a separate class for an ArrayAdapter. Could this be the reason ?
|
If you just want to display a list of textViews you don't need to override anything, you can just add all of the items into an arrayList and use an arrayAdapter.
Put a list view in your xml that is named android:list and then create your arrayAdapter with the textView you want to use.
After that all you have to do is call setListAdapter(mArrayAdapter) and it should populate your list.
ArrayList<String> items = new ArrayList<String>();
for(int i=0; i < jArray.length() ; i++) {
json_data = jArray.getJSONObject(i);
int id=json_data.getInt("id");
String name=json_data.getString("name");
items.add(name);
Log.d(name,"Output");
}
ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_expandable_list_item_1, items));
setListAdapter(mArrayAdapter)
hope this helps!
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 5,
"tags": "java, android, json, android arrayadapter"
}
|
Is $\mathbb{Q}(\sqrt3 i) = \mathbb{Q}(\sqrt3, i)$?
Hi I am a little bit confused by extension fields and splitting fields.
I have an exercise that asks me to find the degree of the extension $E/\mathbb{Q}$, where $E$ is the splitting field of the polynomial $x^4 -2x^2 - 3$.
I found $E = \mathbb{Q}(\sqrt3,i)$ because the polynomial has roots $\pm\sqrt3, \pm i$
Now $\mathbb{Q}(\sqrt3)/\mathbb{Q}$ is a degree $2$ extension, since $x^2 - 3$ is irreducible over $\mathbb{Q}$, and since $i \notin \mathbb{Q}(\sqrt3)$ it follows that $\mathbb{Q}(\sqrt3, i)/\mathbb{Q}(\sqrt3)$ is also a degree $2$ extension, since $x^2 + 1$ is irreducible over $\mathbb{Q}(\sqrt3)$.
So by the tower law, we have $[E : \mathbb{Q}] = [ E :\mathbb{Q}(\sqrt3)][\mathbb{Q}(\sqrt3):\mathbb{Q}] = 2 * 2 = 4$
But why can't I say, that $\mathbb{Q}(\sqrt3,i) = \mathbb{Q}(\sqrt3 i)$?
|
You probably meant $x^4 - 2x^2 - 3$.
As to whether $\mathbb{Q}(\sqrt{3}i) = \mathbb{Q}(\sqrt{3},i)$, they aren't the same. One way to look at this is that $\mathbb{Q}(\sqrt{3},i)$ has a subextension $K = \mathbb{Q}(\sqrt{3})$ which satisfies $\mathbb{Q} \subsetneq K \subsetneq \mathbb{R}$, while $\mathbb{Q}(\sqrt{3}i)$ is an extension of $\mathbb{Q}$ of degree two (it is the splitting field of $x^2 + 3$) and therefore has no subfields containing $\mathbb{Q}$ other than $\mathbb{Q}$ itself.
|
stackexchange-math
|
{
"answer_score": 4,
"question_score": 0,
"tags": "abstract algebra, extension field, splitting field"
}
|
Node works globally but not in a specific directory after brew install yarn
MacOS Mojave here. When I installed `yarn` with `brew install`, I couldn't run `node` (and thus `npm`). I went through a fair amount of troubleshooting steps that essentially forced uninstalled node and removed symlinks to node files in `/usr/bin`. I then installed `nvm` and successfully installed `node`. But, when I run `node -v` in a specific directory that I'm developing in, I get `bash: node: command not found`, even though I can successfully run that command globally. Why can't I access the command in this directory?
Edit: Successfully running `node -v` globally was an isolated success that apparently happened because I had installed `nvm` on that terminal. Once I opened a new terminal window, `node` gave the same "command not found" issue.
|
After some more experimenting, I found a suboptimal solution. Installing `nvm` should place a folder called `.nvm` in the home directory, and this folder contains a script called `nvm.sh`. Running `source ~/.nvm/nvm.sh` makes the `nvm` installation of `node` available in the immediate terminal. You can then run this command every time you open an interactive bash terminal (different for other shells) by putting `source ~/.nvm/nvm.sh` at the end of `~/.bash_profile`. The reason this is suboptimal is that this (fairly long) script is run every time you open a terminal, which adds a half second delay on my machine. I'd love to see better answers. Long story short, don't use `brew` for `node` related tasks.
|
stackexchange-superuser
|
{
"answer_score": 0,
"question_score": 0,
"tags": "macos, homebrew, node.js"
}
|
iPhone iOS is there an expression parser for an algebraic calculator-like app?
I'm building an app that would analyze phone's motion through accelerometer and gyroscope output. It is likely that I will capture this motion as a set of variables that the app would keep track of internally.
I'm trying to include a way to graph these variables and equations involving these variables. I would like to offer the user an ability to adjust how the app displays equations of these variables by typing equations like a + b - c = d with the a,b,c variables being calculated by my app. The user can write equations and graph variables in the field. Since it has been ages since I wrote an algebraic parser in any language, **I'm wandering if there's an expression parser in objective-c that I can readily plug into my app** , where a user would type something like a + b - c = d into a text field and the app would tokenize and substitute variables that I provide in place of the user-entered placeholders.
|
A couple of open source options:
GCMathParser <
DDMathParser <
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "iphone, objective c, ios, parsing, expression"
}
|
How to clean cache after a new deployment?
I am developing an application using JSF2.0/Primefaces 4.0 and JBoss 7.
The problem is that every time i make a new deployment (using .war), all of the users have to clean their browser cache to see the changes(mainly with images positioning).
I know that browsers save the content of the page to make it run faster, but i also know that there is a way to control the HTTP param `cache-control` to make it re-validate the page.
**And the question is:** How to make the client browser recognize that there is a new deployment and clean the stored cache? Of course, using JBoss 7.
Also, i don't want to re-validate the cache in every access, only when there is a new deployment.
Is that possible?
|
I would suggest to use the build in _JSF resource library_ mechanism, which supports versioning of resources. Since the clients caches will load a given resource when its' path changes. This way you can change the version number of your resoures and urge the client to reload them, without having to deal with any cache ageing strategies.
There are several good write-ups about this topic here on SO
* What is the JSF resource library for and how should it be used?
* JSF resource versioning
* JSF2 Static resource caching
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "java, jsf, caching, jboss, browser"
}
|
Codeigniter Where generate wrong query
I try to get all cities of country but the codeigniter generate wrong sql, Why? Here is my Model
private $cities = "cities";
public function get_cities_by_country($country_id){
$this->db->select('id, city');
$this->db->where('country_id', $country_id);
$this->db->from($this->cities);
return $this->db->get()->result_array();
}
And I use a log_message for $country_id And $this->db->last_query()
INFO - 2017-01-16 18:30:25 --> '7'
INFO - 2017-01-16 18:30:25 --> 'SELECT `id`, `city`
FROM (`cities`)
WHERE `country_id` = \'7\'
AND `status` = 1'
I think this is a probliem `country_id` = \'7\' Thanks !
|
CI is attempting to escape the where value, you can avoid it by passing FALSE as an optional parameter to your where clause:
$this->db->where('country_id', $country_id, FALSE);
Read more here: <
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "php, sql, codeigniter, where clause"
}
|
Combine Angular 2 application server and REST server modules
I am creating a new Angular 4 application. I have followed it's official tutorial <
The application server is started using `ng serve` command.
I have created a separate node js (+express) server that provides the REST services to the main app on a different port.
Is there any way to serve the main angular application from the same nodejs/express server so that i don't have to use two servers for the application?
I have used typescript which needs to be somehow compiled into plain javascript before statically being served via nodejs, if i understand it right?
|
Absolutely, just use ng build and serve the dist folder of the built application, or even the src. Example:
const staticFor = rel => express.static(path.resolve(__dirname, rel));
const app = express();
if (!config.production) {
app.use('/node_modules', staticFor('../node_modules'));
// In development we do not copy the files over, so map used path
}
app.use('/', staticFor('../dist/app'));
const appPath = path.resolve(
__dirname,
config.production ? '../dist/app/index.html' : '../src/app/index.html'
);
app.get('/yourAppPath/*', (req, res) => {
const markup = fs.readFileSync(appPath, 'utf8');
res.send(markup);
});
Dont forget to require the right libraries.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, node.js, angular"
}
|
putting int/float from file into a dictionary
I like to put some values from a csv file into a dict. An example is:
TYPE, Weldline
Diam, 5.0
Num of Elems, 4
and I end up after reading into a dictionary (for later use in an API) in:
{'TYPE':'Weldline' , 'Diam':'5.0','Num of Elems':'4'}
Since the API expects a dictionary i provided all the necessary keywords like 'TYPE', 'Diam', ... according to the API doc.
The problem I have is, that the API expects a float for `Diam` and an integer for `Num of Elems`
Since I have a large number of entries: is there an simple automatic way for string conversion into float or int? Or do I have to write something on my own?
|
You can use `literal_eval`
> This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.
import ast
_dict = {}
with open('file.txt', 'r') as f:
for line in f.readlines():
if line.strip():
key, value = line.split(',')
value = value.strip()
try:
_dict[key] = ast.literal_eval(value)
except ValueError:
_dict[key] = value
print _dict
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, type conversion"
}
|
How can I safely uninstall Perkus Maximus?
I installed Perkus Maximus before I ever created any save games. Now that I've played with it for awhile, I'm considering uninstalling it. I know I'll have to start over with all of my characters, and I'm fine with that.
What I'm not sure about is how to uninstall Perkus. Do I just disable it in NMM? Or are there additional steps I need to do to make sure everything runs properly? I've done a few searches, and found plenty of info on installing Perma, but none on uninstalling it.
Could I perhaps get some pointers in the correct direction?
As a side question, will I be able to just re-activate Perkus and resume with my old saves if I decide I like it again?
|
Any save games made while using PerMa will not work (well) after uninstalling it; it modifies too much of the game. Uninstalling the mod to start a new game should be simple enough to do. You should also remove any other compatibility patches you might have for it and other mods that depend on it.
## Installed via NMM (or another mod manager)
Simply deactivate/uninstall the mod from the manager (the same way you installed it, but in reverse).
If you have mods that work differently with and without PerMa installed, you should check their documentation for what to do with them. The safest bet is probably to reinstall them.
## Installed manually
Deactivate the ESP's via Skyrim Launcher and remove all the files you extracted when installing the mod.
|
stackexchange-gaming
|
{
"answer_score": 3,
"question_score": 2,
"tags": "the elder scrolls v skyrim"
}
|
Summing outputs from a case statement
I have a query like this:
SELECT
case [Group]
when 1 then 'in'
when 0 then 'out'
end as traffic
FROM [GW_Test_Back_Up].[dbo].[ARC_Calls_ReportView]
Which creates a new column with many rows containing in/out for traffic, but what I really want is only two rows, one for the sum of the in's and the other for the sum of the out's. I am stuck on how I would do this.
|
I do believe you are after:
SELECT
SUM(CASE WHEN [Group] = 1 then 1 ELSE 0 END ) AS InCount,
SUM(CASE WHEN [Group] = 0 then 1 ELSE 0 END ) AS OutCount
FROM [GW_Test_Back_Up].[dbo].[ARC_Calls_ReportView]
Or maybe this:
SELECT 'InCount' AS Type,
SUM(CASE WHEN [Group] = 1 then 1 ELSE 0 END ) AS InCount
FROM [GW_Test_Back_Up].[dbo].[ARC_Calls_ReportView]
UNION ALL
SELECT 'OutCount' AS Type,
SUM(CASE WHEN [Group] = 0 then 1 ELSE 0 END ) AS OutCount
FROM [GW_Test_Back_Up].[dbo].[ARC_Calls_ReportView]
**EDIT:**
SELECT
CASE WHEN m.InCount > 10 THEN 'High' ELSE 'Low' END AS InCountStatus
CASE WHEN m.OutCount > 10 THEN 'High' ELSE 'Low' END AS OutCountStatus
FROM
(
SELECT
SUM(CASE WHEN [Group] = 1 then 1 ELSE 0 END ) AS InCount,
SUM(CASE WHEN [Group] = 0 then 1 ELSE 0 END ) AS OutCount
FROM [GW_Test_Back_Up].[dbo].[ARC_Calls_ReportView]
) m
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "sql, sql server, case"
}
|
Eine Alternative zum Ausdruck "Eine tolle Sache"
> Eine tolle Sache, dass ich 15 Jahre Deutsch gelernt habe, also habe ich keine Probleme zu verstehen, was sie sagen.
Good thing that I studied German for 15 years, so i have no problems comprehending what they're saying
Was ist die Alternative zum Ausdruck "Eine tolle Sache" ?
|
A good replacement for "eine gute Sache" could be
> (Es war) eine gute Entscheidung, dass ich 15 Jahre Deutsch gelernt habe. _(It's been a good decision to study German for 15 years)._
Further replacements could be:
> Ein wichtiger Schritt, dass ich 15 Jahre Deutsch gelernt habe.
> Eine wichtige Erfahrung...
|
stackexchange-german
|
{
"answer_score": 3,
"question_score": 0,
"tags": "grammar, expression"
}
|
Trim long number in JavaScript
For example, I got that long nubmer 1517778188788. How can i get first 6 digits from that number, like 151777 and trim another digits?
|
Just convert a number to string and then slice it and convert it back to Number.
const a = 1517778188788;
const str_a = a.toString();
const result = Number(str_a.slice(0, 6));
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 0,
"tags": "javascript, numbers, trim, digits"
}
|
Google API supports .NET but not Unity?
I was working on Google API and in that link, it says that it supports .NET Framework 4.0 but not Unity.
To my knowledge, Unity runs on .NET 4.x equivalent.
How can the API support .NET Framework 4.0 but not support Unity?
Is this related to Android support in Unity, which is used when apps are built for Android?
It's very confusing for me.
|
From these FAQ:
## Why aren't Unity, Xamarin or UWP supported?
> At a team discussion in October 2018 we made the decision to not proceed with support for these platforms. We don't see evidence that there would be enough usage to justify the technical work and infrastructure required for us to **fully support** these extra platforms.
>
> We will revisit this decision on a regular basis, in case the situation changes.
In a nutshell this means they won't be testing or improving support.
But despite the above, I have successfully managed to integrate YouTube API from that repository.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "c#, .net, unity3d, google api dotnet client"
}
|
Ruby: what is an easy way to check of all values in a 2D array are the same in a particular column or row?
[[0, 1, 2],
[2, 1, 0],
[0, 1, 2]]
What is an easy way to check of this matrix has all values down a column the same?
[[0, 1, 0],
[2, 2, 2],
[0, 1, 2]]
And then horizontally?
|
1.
a.map{|row|row[x]}.uniq.size == 1
or
a.transpose[x].uniq.size == 1
2.
a[x].uniq.size == 1
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "ruby"
}
|
Is this aggregation possible in the Mule ESB DataMapper
Is this aggregation possible in the Mule ESB DataMapper
I have the following structures:
Strcuture A:
<item>
<id>123</id>
<price>1</price>
</item>
<item>
<id>124</id>
<price>2</price>
</item>
<item>
<id>125</id>
<price>3</price>
</item>
Structure B:
<total>
<totalPrice>6</totalPrice>
</total>
If I want a sumation of all the fields in structure A to be placed into the totalprice of structure B, would taht be possible in the DataMapper.
If it is possible, how would you do it?
Thanks
|
The source XML you show is invalid, you can only have one root element to have a valid XML. So I guess you have a `<items>` root element.
You could say, from prices generate total, and then create an xpath rule with `sum(//price)` and then map it to total.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "dictionary, mule, esb"
}
|
Docker mount volume to reflect container files in host
The use case is that I want to download and image that contains python code files. Assume the image does not have any text editor installed. So i want to mount a drive on host, so that files in the container show up in this host mount and i can use different editors installed on my host to update the code. Saving the changes are to be reflected in the image.
if i run the following >
docker run -v /host/empty/dir:/container/folder/with/code/files -it myimage
the _/host/empty/dir_ is still empty, and browsing the container dir also shows it as empty. What I want is the file contents of _/container/folder/with/code/files_ to show up in _/host/empty/dir_
|
Sébastien Helbert answer is correct. But there is still a way to do this in 2 steps.
First run the container to extract the files:
docker run --rm -it myimage
In another terminal, type this command to copy what you want from the container.
docker cp <container_id>:/container/folder/with/code/files /host/empty/dir
Now stop the container. It will be deleted (--rm) when stopped. Now if you run your original command, it will work as expected.
docker run -v /host/empty/dir:/container/folder/with/code/files -it myimage
There is another way to access the files from within the container without copying it but it's very cumbersome.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "docker"
}
|
objeto session mvc 4 en razor
Buenas,
Tengo un AccountControler en mi aplicación, el AccountControler tiene los ActionResult para poder loguearse y desconectarse.
Una vez conectado el usuario (usuario que esta dentro de una tabla en sqlserver), necesito saber como puede obtener los datos de diferentes campos de ese usuario.
Ejemplo(tonto)
Pepito pone su nombre y su password y entra correctamente, pero al entrar tengo que filtrar por el código postal de donde vive, para poder ver un listado de sus calles.
Creo que funciona con el objeto session pero no consigo entender como funciona o como hacerlo.
|
Para utilizar las variables de sesión es tan fácil como en tu método Login guardar lo que te sea necesario:
string codigoPostal = "XXXXX"; //Obtén la información que necesites
Session["CodigoPostal"]=codigoPostal;
Y para luego acceder en cualquier función a lo que has guardado:
var codigoPostal=Session["CodigoPostal"] as string; //Fíjate que se tiene que hacer un cast con el as para poder acceder.
|
stackexchange-es_stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "c#"
}
|
convergence of series and sum and series
Say $\sum a_n+b_n$ converges then will it automatically mean $\sum a_n$ converges as well as $\sum b_n$, too?
If $\sum a_n$ and $\sum b_n$ both converge will it be the case that $\sum a_n-b_n$ converge?
|
The answer to your second question is "yes". You should be able to prove it from the definition.
For the first, what if all $a_n = 1$ and all $b_n = -1$?
**Edit** in response to comment.
If the terms are all nonnegative then each series converges since the increasing sequence of partial sums of each is bounded by the sum of the sums.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "real analysis, sequences and series"
}
|
How can I set the custom path of an AutoroutePart programmatically in a migration in Orchard?
In my `Migrations.cs` file I'm attaching an AutoroutePart to a Content Item.
ContentDefinitionManager.AlterTypeDefinition("Faq", type => type
.WithPart("AutoroutePart")
);
How can I tell the AutoroutePart to use some arbitrary string + the Content Item's slug as the custom path? I know I can change the settings of fields using `.WithSetting("FieldSettings.Setting","Value")` but this doesn't seem to be an option for Parts. I also wouldn't know how to refer to the SlugToken in code.
|
Should be possible
ContentDefinitionManager.AlterTypeDefinition("Faq", type => type
.WithPart("AutoroutePart", part => part
.WithSetting("AutorouteSettings.AllowCustomPattern", "True")
.WithSetting("AutorouteSettings.AutomaticAdjustmentOnEdit", "False")
.WithSetting("AutorouteSettings.PatternDefinitions", "[{\"Name\":\"Title\",\"Pattern\":\"{Content.Slug}\",\"Description\":\"my-faq\"}]")
.WithSetting("AutorouteSettings.DefaultPatternIndex", "0"))));
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "orchardcms, orchardcms 1.7"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.