I have modified and extended Malcolm Swaine's code to modify a specific node by it's name attribute, and to also modify an external config file. Hope it helps.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Reflection;
namespace LobbyGuard.UI.Registration
{
public class ConfigSettings
{
private static string NodePath = "//system.serviceModel//client//endpoint";
private ConfigSettings() { }
public static string GetEndpointAddress()
{
return ConfigSettings.loadConfigDocument().SelectSingleNode(NodePath).Attributes["address"].Value;
}
public static void SaveEndpointAddress(string endpointAddress)
{
// load config document for current assembly
XmlDocument doc = loadConfigDocument();
// retrieve appSettings node
XmlNodeList nodes = doc.SelectNodes(NodePath);
foreach (XmlNode node in nodes)
{
if (node == null)
throw new InvalidOperationException("Error. Could not find endpoint node in config file.");
//If this isnt the node I want to change, look at the next one
//Change this string to the name attribute of the node you want to change
if (node.Attributes["name"].Value != "DataLocal_Endpoint1")
{
continue;
}
try
{
// select the 'add' element that contains the key
//XmlElement elem = (XmlElement)node.SelectSingleNode(string.Format("//add[@key='{0}']", key));
node.Attributes["address"].Value = endpointAddress;
doc.Save(getConfigFilePath());
break;
}
catch (Exception e)
{
throw e;
}
}
}
public static void SaveEndpointAddress(string endpointAddress, string ConfigPath, string endpointName)
{
// load config document for current assembly
XmlDocument doc = loadConfigDocument(ConfigPath);
// retrieve appSettings node
XmlNodeList nodes = doc.SelectNodes(NodePath);
foreach (XmlNode node in nodes)
{
if (node == null)
throw new InvalidOperationException("Error. Could not find endpoint node in config file.");
//If this isnt the node I want to change, look at the next one
if (node.Attributes["name"].Value != endpointName)
{
continue;
}
try
{
// select the 'add' element that contains the key
//XmlElement elem = (XmlElement)node.SelectSingleNode(string.Format("//add[@key='{0}']", key));
node.Attributes["address"].Value = endpointAddress;
doc.Save(ConfigPath);
break;
}
catch (Exception e)
{
throw e;
}
}
}
public static XmlDocument loadConfigDocument()
{
XmlDocument doc = null;
try
{
doc = new XmlDocument();
doc.Load(getConfigFilePath());
return doc;
}
catch (System.IO.FileNotFoundException e)
{
throw new Exception("No configuration file found.", e);
}
}
public static XmlDocument loadConfigDocument(string Path)
{
XmlDocument doc = null;
try
{
doc = new XmlDocument();
doc.Load(Path);
return doc;
}
catch (System.IO.FileNotFoundException e)
{
throw new Exception("No configuration file found.", e);
}
}
private static string getConfigFilePath()
{
return Assembly.GetExecutingAssembly().Location + ".config";
}
}
}
I agree with nemo and I wrote a little tool to make it all real easy.
bitbucket.org/gotamer/cfg is a json configuration package
See doc.go for an example
.project
When a project is created in the workspace, a project description file is automatically generated that describes the project. The sole purpose of this file is to make the project self-describing, so that a project that is zipped up or released to a server can be correctly recreated in another workspace.
.classpath
Classpath specifies which Java source files and resource files in a project are considered by the Java builder and specifies how to find types outside of the project. The Java builder compiles the Java source files into the output folder and also copies the resources into it.
Add an Application Configuration File
item to your project (Right -Click Project > Add item). This will create a file called app.config
in your project.
Edit the file by adding entries like <add key="keyname" value="someValue" />
within the <appSettings>
tag.
Add a reference to the System.Configuration
dll, and reference the items in the config using code like ConfigurationManager.AppSettings["keyname"]
.
The nature and even existence of file extensions is platform-dependent (some obscure platforms don't even have them, remember) -- in other systems they're only conventional (UNIX and its ilk), while in still others they have definite semantics and in some cases specific limits on length or character content (Windows, etc.).
Since the maintainers have asked that you use ".yaml", that's as close to an "official" ruling as you can get, but the habit of 8.3 is hard to get out of (and, appallingly, still occasionally relevant in 2013).
A double quote to the left of the text you want to comment.
Example:
" this is how a comment looks like in ~/.vimrc
I use a package.json
for my packages and a config.js
for my configuration, which looks like:
var config = {};
config.twitter = {};
config.redis = {};
config.web = {};
config.default_stuff = ['red','green','blue','apple','yellow','orange','politics'];
config.twitter.user_name = process.env.TWITTER_USER || 'username';
config.twitter.password= process.env.TWITTER_PASSWORD || 'password';
config.redis.uri = process.env.DUOSTACK_DB_REDIS;
config.redis.host = 'hostname';
config.redis.port = 6379;
config.web.port = process.env.WEB_PORT || 9980;
module.exports = config;
I load the config from my project:
var config = require('./config');
and then I can access my things from config.db_host
, config.db_port
, etc... This lets me either use hardcoded parameters, or parameters stored in environmental variables if I don't want to store passwords in source control.
I also generate a package.json
and insert a dependencies section:
"dependencies": {
"cradle": "0.5.5",
"jade": "0.10.4",
"redis": "0.5.11",
"socket.io": "0.6.16",
"twitter-node": "0.0.2",
"express": "2.2.0"
}
When I clone the project to my local machine, I run npm install
to install the packages. More info on that here.
The project is stored in GitHub, with remotes added for my production server.
in Bash, to source some command's output, instead of a file:
source <(echo vara=3) # variable vara, which is 3
source <(grep yourfilter /path/to/yourfile) # source specific variables
Other options, instead of using a custom XML file, we can use a more user friendly file format: JSON or YAML file.
You can store your settings file in multiple special folders (for all users and per user) as listed here Environment.SpecialFolder Enumeration and multiple files (default read only, per role, per user, etc.)
If you choose to use multiple settings, you can merge those settings: For example, merging settings for default + BasicUser + AdminUser. You can use your own rules: the last one overrides the value, etc.
Well - it would be sort of difficult to store your database configuration data in a database - don't ya think?
But really, this is a pretty heavily opinionated question because any style works really and it's all a matter of preference. Personally, I'd go for a configuration variable rather than constants - generally because I don't like things in the global space unless necessary. None of the functions in my codebase should be able to easily access my database password (except my database connection logic) - so I'd use it there and then likely destroy it.
Edit: to answer your comment - none of the parsing mechanisms would be the fastest (ini, json, etc) - but they're also not the parts of your application that you'd really need to focus on optimizing since the speed difference would be negligible on such small files.
Goto Package properties->Configurations->Enable Package Configurations->Add->xml configuration file->Specify dtsconfig file->click next->In OLEDB Properties tick the connection string->connection string value will be displayed->click next and finish package is hence configured.
You can add Environment variable also in this process
Use the Maven debug option, ie mvn -X
:
Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100)
Maven home: /usr/java/apache-maven-3.0.3
Java version: 1.6.0_12, vendor: Sun Microsystems Inc.
Java home: /usr/java/jdk1.6.0_12/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.32-32-generic", arch: "i386", family: "unix"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from /usr/java/apache-maven-3.0.3/conf/settings.xml
[DEBUG] Reading user settings from /home/myhome/.m2/settings.xml
...
In this output, you can see that the settings.xml is loaded from /home/myhome/.m2/settings.xml
.
An easier alternative for those who would prefer not to write all that configuration boilerplate manually...
1) Install Nerdle.AutoConfig from NuGet
2) Define your ServiceConfig type (either a concrete class or just an interface, either will do)
public interface IServiceConfiguration
{
int Port { get; }
ReportType ReportType { get; }
}
3) You'll need a type to hold the collection, e.g.
public interface IServiceCollectionConfiguration
{
IEnumerable<IServiceConfiguration> Services { get; }
}
4) Add the config section like so (note camelCase naming)
<configSections>
<section name="serviceCollection" type="Nerdle.AutoConfig.Section, Nerdle.AutoConfig"/>
</configSections>
<serviceCollection>
<services>
<service port="6996" reportType="File" />
<service port="7001" reportType="Other" />
</services>
</serviceCollection>
5) Map with AutoConfig
var services = AutoConfig.Map<IServiceCollectionConfiguration>();
Not sure about Win but n *nix (OS X, Linux, etc.) its in ~/.subversion
app.config
app.name=Properties Sample Code
app.version=1.09
Source code:
Properties prop = new Properties();
String fileName = "app.config";
InputStream is = null;
try {
is = new FileInputStream(fileName);
} catch (FileNotFoundException ex) {
...
}
try {
prop.load(is);
} catch (IOException ex) {
...
}
System.out.println(prop.getProperty("app.name"));
System.out.println(prop.getProperty("app.version"));
Output:
Properties Sample Code
1.09
One of the things that you might want to try out is starting eclipse with the -clean
option. If you have chosen to have eclipse use the same workspace every time then there is nothing else you need to do after that. With that option in place the workspace should be cleaned out.
However, if you don't have a default workspace chosen, when opening up eclipse you will be prompted to choose the workspace. At this point, choose the workspace you want cleaned up.
See "How to run eclipse in clean mode" and "Keeping Eclipse running clean" for more details.
This is quick Bash command, that you're probably searching for, will print only a basename of the remote repository:
Where you fetch from:
basename $(git remote show -n origin | grep Fetch | cut -d: -f2-)
Alternatively where you push to:
basename $(git remote show -n origin | grep Push | cut -d: -f2-)
Especially the -n
option makes the command much quicker.
----FirstActivity.java-----
package com.mindscripts.eid;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class FirstActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button orderButton = (Button) findViewById(R.id.order);
orderButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(FirstActivity.this,OrderScreen.class);
startActivity(intent);
}
});
}
}
---OrderScreen.java---
package com.mindscripts.eid;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class OrderScreen extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.second_class);
Button orderButton = (Button) findViewById(R.id.end);
orderButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
---AndroidManifest.xml----
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mindscripts.eid"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".FirstActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".OrderScreen"></activity>
</application>
Use .prop
instead (and clean up your selector string):
function disable(i){
$("#rbutton_"+i).prop("disabled",true);
}
generated HTML:
<button id="rbutton_1" onclick="disable(1)">Click me</button>
<!-- wrap your onclick in quotes -->
But the "best practices" approach is to use JavaScript event binding and this
instead:
$('.rbutton').on('click',function() {_x000D_
$(this).prop("disabled",true);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<button class="rbutton">Click me</button>
_x000D_
Could be simplified to this:
SELECT article FROM table1 ORDER BY publish_date DESC FETCH FIRST 20 ROWS ONLY;
You could also add many argument in the ORDER BY
that is just comma separated like: ORDER BY publish_date, tab2, tab3 DESC
etc...
I agree with the current answers, but in my case it does not work, I hope this code help someone in the future:
// check
$('#checkbox_id').click()
Here are the rules for how these functions work:
stringValue.CompareTo(otherStringValue)
null
comes before a stringCultureInfo.CurrentCulture.CompareInfo.Compare
, which means it will use a culture-dependent comparison. This might mean that ß
will compare equal to SS
in Germany, or similarstringValue.Equals(otherStringValue)
null
is not considered equal to anythingStringComparison
option, it will use what looks like a direct ordinal equality check, i.e. ß
is not the same as SS
, in any language or culturestringValue == otherStringValue
stringValue.Equals()
.==
operator calls the static Equals(string a, string b)
method (which in turn goes to an internal EqualsHelper
to do the comparison..Equals()
on a null
string gets null
reference exception, while on ==
does not.Object.ReferenceEquals(stringValue, otherStringValue)
Just checks that references are the same, i.e. it isn't just two strings with the same contents, you're comparing a string object with itself.
Note that with the options above that use method calls, there are overloads with more options to specify how to compare.
My advice if you just want to check for equality is to make up your mind whether you want to use a culture-dependent comparison or not, and then use .CompareTo
or .Equals
, depending on the choice.
if (listA.Except(listB).Any())
Be sure that android:debuggable="true"
is set in the application
tag of your manifest file, and then:
If you're using jQuery-UI, you must include the jQuery UI CSS package, otherwise the UI components don't know how to be styled.
If you don't like the jQuery UI styles, then you'll have to recreate all the styles it would have otherwise applied.
Here's an example and some possible fixes.
Here's a demo in Stack Snippets without jquery-ui.css (doesn't work)
$(function() {_x000D_
var availableTags = [_x000D_
"ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++",_x000D_
"Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran",_x000D_
"Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl",_x000D_
"PHP", "Python", "Ruby", "Scala", "Scheme"_x000D_
];_x000D_
_x000D_
$(".autocomplete").autocomplete({_x000D_
source: availableTags_x000D_
});_x000D_
});
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
_x000D_
<div class="form-group">_x000D_
<label>Languages</label>_x000D_
<input class="form-control autocomplete" placeholder="Enter A" />_x000D_
</div>_x000D_
_x000D_
<div class="form-group">_x000D_
<label >Another Field</label>_x000D_
<input class="form-control">_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
Just include jquery-ui.css and everything should work just fine with the latest supported versions of jquery.
$(function() {_x000D_
var availableTags = [_x000D_
"ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++",_x000D_
"Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran",_x000D_
"Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl",_x000D_
"PHP", "Python", "Ruby", "Scala", "Scheme"_x000D_
];_x000D_
_x000D_
$(".autocomplete").autocomplete({_x000D_
source: availableTags_x000D_
});_x000D_
});
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.css" rel="stylesheet"/>_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
<div class="form-group">_x000D_
<label>Languages</label>_x000D_
<input class="form-control autocomplete" placeholder="Enter A" />_x000D_
</div>_x000D_
_x000D_
<div class="form-group">_x000D_
<label >Another Field</label>_x000D_
<input class="form-control">_x000D_
</div>_x000D_
</div>
_x000D_
There is a project that created a Bootstrap-esque theme for jQuery-UI components called jquery-ui-bootstrap. Just grab the stylesheet from there and you should be all set.
$(function() {_x000D_
var availableTags = [_x000D_
"ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++",_x000D_
"Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran",_x000D_
"Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl",_x000D_
"PHP", "Python", "Ruby", "Scala", "Scheme"_x000D_
];_x000D_
_x000D_
$(".autocomplete").autocomplete({_x000D_
source: availableTags_x000D_
});_x000D_
});
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-ui-bootstrap/0.5pre/css/custom-theme/jquery-ui-1.10.0.custom.css" rel="stylesheet"/>_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
<div class="form-group">_x000D_
<label>Languages</label>_x000D_
<input class="form-control autocomplete" placeholder="Enter A" />_x000D_
</div>_x000D_
_x000D_
<div class="form-group">_x000D_
<label >Another Field</label>_x000D_
<input class="form-control">_x000D_
</div>_x000D_
</div>
_x000D_
If you only need the AutoComplete widget from jQuery-UI's library, you should start by doing a custom build so you don't pull in resources you're not using.
After that, you'll need to style it yourself. Just look at some of the other styles that are applied to jquery's autocomplete.css and theme.css to figure out what styles you'll need to manually replace.
You can use bootstrap's dropdowns.less for inspiration.
Here's a sample CSS that fits pretty well with Bootstrap's default theme:
.ui-autocomplete {
position: absolute;
z-index: 1000;
cursor: default;
padding: 0;
margin-top: 2px;
list-style: none;
background-color: #ffffff;
border: 1px solid #ccc;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
-moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
}
.ui-autocomplete > li {
padding: 3px 20px;
}
.ui-autocomplete > li.ui-state-focus {
background-color: #DDD;
}
.ui-helper-hidden-accessible {
display: none;
}
$(function() {_x000D_
var availableTags = [_x000D_
"ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++",_x000D_
"Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran",_x000D_
"Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl",_x000D_
"PHP", "Python", "Ruby", "Scala", "Scheme"_x000D_
];_x000D_
_x000D_
$(".autocomplete").autocomplete({_x000D_
source: availableTags_x000D_
});_x000D_
});
_x000D_
.ui-autocomplete {_x000D_
position: absolute;_x000D_
z-index: 1000;_x000D_
cursor: default;_x000D_
padding: 0;_x000D_
margin-top: 2px;_x000D_
list-style: none;_x000D_
background-color: #ffffff;_x000D_
border: 1px solid #ccc_x000D_
-webkit-border-radius: 5px;_x000D_
-moz-border-radius: 5px;_x000D_
border-radius: 5px;_x000D_
-webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);_x000D_
-moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);_x000D_
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);_x000D_
}_x000D_
.ui-autocomplete > li {_x000D_
padding: 3px 20px;_x000D_
}_x000D_
.ui-autocomplete > li.ui-state-focus {_x000D_
background-color: #DDD;_x000D_
}_x000D_
.ui-helper-hidden-accessible {_x000D_
display: none;_x000D_
}
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
<div class="form-group ui-widget">_x000D_
<label>Languages</label>_x000D_
<input class="form-control autocomplete" placeholder="Enter A" />_x000D_
</div>_x000D_
_x000D_
<div class="form-group ui-widget">_x000D_
<label >Another Field</label>_x000D_
<input class="form-control" />_x000D_
</div>_x000D_
</div>
_x000D_
Tip: Since the dropdown menu hides every time you go to inspect the element (i.e. whenever the input loses focus), for easier debugging of the style, find the control with
.ui-autocomplete
and removedisplay: none;
.
It's worth figuring out CSS and divs so the central content column loads and renders before the sidebar in a page layout. But if you are struggling to use floating divs to vertically align a logo with some sponsorship text, just use the table and move on with life. The Zen garden religion just doesn't give much bang for the buck.
The idea of separating content from presentation is to partition the application so different kinds of work affect different blocks of code. This is actually about change management. But coding standards can only examine the present state of code in a superficial manner.
The change log for an application that depends on coding standards to "separate content from presentation" will show a pattern of parallel changes across vertical silos. If a change to "content" is always accompanied by a change to "presentation", how successful is the partitioning?
If you really want to partition your code productively, use Subversion and review your change logs. Then use the simplest coding techniques -- divs, tables, JavaScript, includes, functions, objects, continuations, whatever -- to structure the application so that the changes fit in a simple and comfortable manner.
My solution:
var temp = "This is a string.";_x000D_
_x000D_
function countOcurrences(str, value) {_x000D_
var regExp = new RegExp(value, "gi");_x000D_
return (str.match(regExp) || []).length;_x000D_
}_x000D_
_x000D_
console.log(countOcurrences(temp, 'is'));
_x000D_
There are so many Answers. My solution for this was:
globalNamespace.globalArray = new Array();
if (typeof console === "undefined" || typeof console.log === "undefined") {
console = {};
console.log = function(message) {globalNamespace.globalArray.push(message)};
}
In short, if console.log doesn't exists (or in this case, isn't opened) then store the log in a global namespace Array. This way, you're not pestered with millions of alerts and you can still view your logs with the developer console opened or closed.
In addition to @Bergi’s answer, I’d like to offer a third alternative. It's very similar to @Bergi’s 2nd example, but instead of awaiting each readFile
individually, you create an array of promises, each which you await at the end.
import fs from 'fs-promise';
async function printFiles () {
const files = await getFilePaths();
const promises = files.map((file) => fs.readFile(file, 'utf8'))
const contents = await Promise.all(promises)
contents.forEach(console.log);
}
Note that the function passed to .map()
does not need to be async
, since fs.readFile
returns a Promise object anyway. Therefore promises
is an array of Promise objects, which can be sent to Promise.all()
.
In @Bergi’s answer, the console may log file contents in the order they’re read. For example if a really small file finishes reading before a really large file, it will be logged first, even if the small file comes after the large file in the files
array. However, in my method above, you are guaranteed the console will log the files in the same order as the provided array.
Its in the standard float.h include file. You want DBL_MAX
It is always ideal to use the json.dumps()
method.
To get rid of this error, I used the following code
json.dumps(YOUR_DICT_STRING).replace("'", '"')
You have to use UPDATE instead of INSERT:
For Example:
UPDATE table1 SET col_a='k1', col_b='foo' WHERE key_col='1';
UPDATE table1 SET col_a='k2', col_b='bar' WHERE key_col='2';
outgoing url in mvc generated based on the current routing schema.
because your Information action method require id parameter, and your route collection has id of your current requested url(/Admin/Information/5), id parameter automatically gotten from existing route collection values.
to solve this problem you should use UrlParameter.Optional:
<a href="@Url.Action("Information", "Admin", new { id = UrlParameter.Optional })">Add an Admin</a>
One of the cause could be your "project => Build Settings => Signing => Development Team" is different from your "target => Build Settings => Signing => Development Team", just make them same
Here is a dplyr
based option:
newV = df %>% slice(1) %>% unlist(use.names = FALSE)
# or slightly different:
newV = df %>% slice(1) %>% unlist() %>% unname()
For the 24-hour time, you need to use HH24
instead of HH
.
For the 12-hour time, the AM/PM indicator is written as A.M.
(if you want periods in the result) or AM
(if you don't). For example:
SELECT invoice_date,
TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
FROM invoices
;
For more information on the format models you can use with TO_CHAR
on a date, see http://docs.oracle.com/cd/E16655_01/server.121/e17750/ch4datetime.htm#NLSPG004.
I use a lot the "Send To" functionality.
I create my own batch (.bat) files in the shell:sendto
folder and send files/folders to them using the context menu (to get there just write 'shell:sendto' in location bar).
I have scripts to perform all sort of things: send files by ftp, launch a php server in the current folder, create folders named with the current date, copy sent path to clipboard, etc.
Sorry, a bit offtopic but useful anyway.
I had the same error and just wanted to share my solution. In turned out that the minified version of popper had the code in the same line as the comment and so the entire code was commented out. I just pressed enter after the actual comment so the code was on a new line and then it worked fine.
Ok this is the solution I would have liked to find, instead here I write it:
First create the directory structure corresponding to the package defined for the .java file, if it is my.super.application create the directory "my" and inside it "super" and inside it the .java file "App.java"
then from command line:
javac -cp /path/to/lib1.jar:/path/to/lib2.jar path/to/my/super/App.java
Notice the above will include multiple libraries, if under windows use "," to separate multiple files otherwise under GNU/Linux use ":" To create a jar file
jar -cvfe App.jar App my/app/
the above will create the application with its corresponding Manifest indicating the App as the main class.
Including the required libraries inside the jar file is not possible using java or jar command line parameters.
You can instead:
<target name="-post-jar"> <!-- Empty placeholder for easier customization. --> <!-- You can override this target in the ../build.xml file. --> <jar jarfile="${dist.jar}" update="true"> <zipfileset src="${dist.jar}" includes="**/*.class" /> <zipfileset src="${file.reference.iText-1.0.8.jar}" includes="**/*"/> <zipfileset src="${file.reference.itextpdf-3.2.1.jar}" includes="**/*"/> </jar> </target>
the file.reference names are found inside project.properties file after you added the libraries to the Netbeans IDE.
You can access keys in the App.Config using:
ConfigurationSettings.AppSettings["KeyName"]
Take alook at this Thread
you need to add it like
insert into table1(date1) values('12-mar-2013');
I had this same issue, and solved it with a solution similar to what Cheeso provided, above.
"doesn't work, says password is srequire, tried it a couple different ways "
Yep, that's because FTP sessions via a command file don't require the username to be prefaced with the string "user". Drop that, and try it.
Or, you could be seeing this because your FTP command file is not properly encoded (that bit me, too). That's the crappy part about generating a FTP command file at runtime. Powershell's out-file cmdlet does not have an encoding option that Windows FTP will accept (at least not one that I could find).
Regardless, as doing a WebClient.DownloadFile is the way to go.
A BLOB is a binary string to hold a variable amount of data. For the most part BLOB's are used to hold the actual image binary instead of the path and file info. Text is for large amounts of string characters. Normally a blog or news article would constitute to a TEXT field
L in this case is used stating the storage requirement. (Length|Size + 3) as long as it is less than 224.
The beta version of Sencha Touch has drag and drop support.
You can refer to their DnD Example. This only works on webkit browsers by the way.
Retrofitting that logic into a web page is probably going to be difficult. As I understand it they disable all browser panning and implement panning events entirely in javascript, allowing correct interpretation of drag and drop.
Update: the original example link is dead, but I found this alternative:
https://github.com/kostysh/Drag-Drop-example-for-Sencha-Touch
Here are various optimisations and applications of proper Python style to make your code a lot neater. I've put in some optional code using the csv
module, which is more desirable than parsing it manually. I've also put in a bit of namedtuple
goodness, but I don't use the attributes that then provides. Names of the parts of the namedtuple are inaccurate, you'll need to correct them.
import csv
from collections import namedtuple
from time import localtime, strftime
# Method one, reading the file into lists manually (less desirable)
with open('grades.dat') as files:
grades = [[e.strip() for e in s.split(',')] for s in files]
# Method two, using csv and namedtuple
StudentRecord = namedtuple('StudentRecord', 'id, lastname, firstname, something, homework1, homework2, homework3, homework4, homework5, homework6, homework7, exam1, exam2, exam3')
grades = map(StudentRecord._make, csv.reader(open('grades.dat')))
# Now you could have student.id, student.lastname, etc.
# Skipping the namedtuple, you could do grades = map(tuple, csv.reader(open('grades.dat')))
request = open('requests.dat', 'w')
cont = 'y'
while cont.lower() == 'y':
answer = raw_input('Please enter the Student I.D. of whom you are looking: ')
for student in grades:
if answer == student[0]:
print '%s, %s %s %s' % (student[1], student[2], student[0], student[3])
time = strftime('%a, %b %d %Y %H:%M:%S', localtime())
print time
print 'Exams - %s, %s, %s' % student[11:14]
print 'Homework - %s, %s, %s, %s, %s, %s, %s' % student[4:11]
total = sum(int(x) for x in student[4:14])
print 'Total points earned - %d' % total
grade = total / 5.5
if grade >= 90:
letter = 'an A'
elif grade >= 80:
letter = 'a B'
elif grade >= 70:
letter = 'a C'
elif grade >= 60:
letter = 'a D'
else:
letter = 'an F'
if letter = 'an A':
print 'Grade: %s, that is equal to %s.' % (grade, letter)
else:
print 'Grade: %.2f, that is equal to %s.' % (grade, letter)
request.write('%s %s, %s %s\n' % (student[0], student[1], student[2], time))
print
cont = raw_input('Would you like to search again? ')
print 'Goodbye.'
Let's use this example. Maybe you want the user of your website to know a field is valid or it needs attention by changing the background color of the field. If the user hits reset then your code should only reset the fields that have data and not bother to loop through every other field on your page.
This jQuery filter will remove the class "highlightCriteria" only for the input or select fields that have this class.
$form.find('input,select').filter(function () {
if((!!this.value) && (!!this.name)) {
$("#"+this.id).removeClass("highlightCriteria");
}
});
Your test requires a ServletContext: add @WebIntegrationTest
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
@WebIntegrationTest
public class UserServiceImplIT
...or look here for other options: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html
UPDATE
In Spring Boot 1.4.x and above @WebIntegrationTest
is no longer preferred. @SpringBootTest
or @WebMvcTest
You have created a table with ID
as PRIMARY KEY
, which satisfies UNIQUE
and NOT NULL
constraints, so you can't make the ID
as NULL
by inserting name field, so ID
should also be inserted.
The error message indicates this.
seeing how the rules are fairly complicated, I'd suggest the following:
/^[a-z](\w*)[a-z0-9]$/i
match the whole string and capture intermediate characters. Then either with the string functions or the following regex:
/__/
check if the captured part has two underscores in a row. For example in Python it would look like this:
>>> import re
>>> def valid(s):
match = re.match(r'^[a-z](\w*)[a-z0-9]$', s, re.I)
if match is not None:
return match.group(1).count('__') == 0
return False
Release build did not work for me, however, I looked through my event viewer and Application log and saw that the Windows Service was throwing a security exception when it was trying to create an event log. I fixed this by adding the event source manually with administration access.
I followed this guide from Microsoft:
As matt burns says in his answer, you may need to enable CORS on the server where the problem images are hosted.
If the server is Apache, this can be done by adding the following snippet (from here) to either your VirtualHost config or an .htaccess
file:
<IfModule mod_setenvif.c>
<IfModule mod_headers.c>
<FilesMatch "\.(cur|gif|ico|jpe?g|png|svgz?|webp)$">
SetEnvIf Origin ":" IS_CORS
Header set Access-Control-Allow-Origin "*" env=IS_CORS
</FilesMatch>
</IfModule>
</IfModule>
...if adding it to a VirtualHost, you'll probably need to reload Apache's config too (eg. sudo service apache2 reload
if Apache's running on a Linux server)
If you are using Swift, the Just library does this for you. Example from it's readme file:
// talk to registration end point
Just.post(
"http://justiceleauge.org/member/register",
data: ["username": "barryallen", "password":"ReverseF1ashSucks"],
files: ["profile_photo": .URL(fileURLWithPath:"flash.jpeg", nil)]
) { (r)
if (r.ok) { /* success! */ }
}
You could use DATE_ADD : (or ADDDATE with INTERVAL
)
UPDATE table SET date = DATE_ADD(date, INTERVAL 1 YEAR)
you can try to export as "Runnable jar" in eclipse. I have also problems, when i export as "jar", but i have never problems when i export as "Runnable jar".
Firstly, you should check if your image column is BLOB type!
I don't know anything about your SQL table, but if I'll try to make my own as an example.
We got fields id
(int), image
(blob) and image_name
(varchar(64)).
So the code should look like this (assume ID is always '1' and let's use this mysql_query):
$image = addslashes(file_get_contents($_FILES['image']['tmp_name'])); //SQL Injection defence!
$image_name = addslashes($_FILES['image']['name']);
$sql = "INSERT INTO `product_images` (`id`, `image`, `image_name`) VALUES ('1', '{$image}', '{$image_name}')";
if (!mysql_query($sql)) { // Error handling
echo "Something went wrong! :(";
}
You are doing it wrong in many ways. Don't use mysql functions - they are deprecated! Use PDO or MySQLi. You should also think about storing files locations on disk. Using MySQL for storing images is thought to be Bad Idea™. Handling SQL table with big data like images can be problematic.
Also your HTML form is out of standards. It should look like this:
<form action="insert_product.php" method="POST" enctype="multipart/form-data">
<label>File: </label><input type="file" name="image" />
<input type="submit" />
</form>
Sidenote:
When dealing with files and storing them as a BLOB, the data must be escaped using mysql_real_escape_string()
, otherwise it will result in a syntax error.
In a bash terminal I like to use the double dash. Using VS Code, you can right click on the spec file in the explorer, or on the open tab. Then select 'Copy Relative Path'. Run the command below pasting the relative path in from the clipboard.
npm t -- --include relative/path/to/file.spec.ts
The double dash signals the end of your command options for npm t
and passes anything after that to the next command which is pointing to ng t
. It's doesn't require any modification and quickly gives desired results.
Creating and destroying the connections in each query maybe complicated, i had some headaches with a server migration when i decided to install MariaDB instead MySQL. For some reason in the file etc/my.cnf the parameter wait_timeout had a default value of 10 sec (it causes that the persistence can't be implemented). Then, the solution was set it in 28800, that's 8 hours. Well, i hope help somebody with this "güevonada"... excuse me for my bad english.
setDatabasePath() method was deprecated in API level 19. I advise you to use storage locale like this:
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setDatabaseEnabled(true);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
webView.getSettings().setDatabasePath("/data/data/" + webView.getContext().getPackageName() + "/databases/");
}
For one liner lovers Array.from()
// creates 8x8 array filed with "0"
const arr2d = Array.from({ length: 8 }, () => Array.from({ length: 8 }, () => "0"))
Another one (from comment by dmitry_romanov) use Array().fill()
// creates 8x8 array filed with "0"
const arr2d = Array(8).fill(0).map(() => Array(8).fill("0"))
Using ES6+ spread operator ("inspired" by InspiredJW answer :) )
// same as above just a little shorter
const arr2d = [...Array(8)].map(() => Array(8).fill("0"))
You cannot create a primary key on a view. In SQL Server you can create an index on a view but that is different to creating a primary key.
If you give us more information as to why you want a key on your view, perhaps we can help with that.
Perhaps a function along these lines is what you're after:
def add_unique_to_dict_list(dict_list, key, value):
for d in dict_list:
if key in d:
return d[key]
dict_list.append({ key: value })
return value
The translation is correct, the typing of the expression isn't. TypeScript is incorrectly typing the expression new Thing[100]
as an array. It should be an error to index Thing
, a constructor function, using the index operator. In C# this would allocate an array of 100 elements. In JavaScript this calls the value at index 100 of Thing
as if was a constructor. Since that values is undefined
it raises the error you mentioned. In JavaScript and TypeScript you want new Array(100)
instead.
You should report this as a bug on CodePlex.
Instance variable is the variable declared inside a class, but outside a method: something like:
class IronMan {
/** These are all instance variables **/
public String realName;
public String[] superPowers;
public int age;
/** Getters and setters here **/
}
Now this IronMan Class can be instantiated in another class to use these variables. Something like:
class Avengers {
public static void main(String[] a) {
IronMan ironman = new IronMan();
ironman.realName = "Tony Stark";
// or
ironman.setAge(30);
}
}
This is how we use the instance variables. Shameless plug: This example was pulled from this free e-book here here.
Server side:
if (mysql_query($query)) {
// ...
}
else {
ajaxError();
}
Client side:
error: function() {
alert("There was an error. Try again please!");
},
success: function(){
alert("Thank you for subscribing!");
}
ALTER TABLE table_name ALTER COLUMN id SET DEFAULT uuid_in((md5((random())::text))::cstring);
After reading @ZuzEL's answer, i used the above code as the default value of the column id and it's working fine.
Consider Matt Price's solution.
What you want is, expressed in C++ semantics, to put your function (for it is a function) in a namespace.
There is no "static class" in C++. The nearest concept would be a class with only static methods. For example:
// header
class MyClass
{
public :
static void myMethod() ;
} ;
// source
void MyClass::myMethod()
{
// etc.
}
But you must remember that "static classes" are hacks in the Java-like kind of languages (e.g. C#) that are unable to have non-member functions, so they have instead to move them inside classes as static methods.
In C++, what you really want is a non-member function that you'll declare in a namespace:
// header
namespace MyNamespace
{
void myMethod() ;
}
// source
namespace MyNamespace
{
void myMethod()
{
// etc.
}
}
In C++, the namespace is more powerful than classes for the "Java static method" pattern, because:
Conclusion: Do not copy/paste that Java/C#'s pattern in C++. In Java/C#, the pattern is mandatory. But in C++, it is bad style.
There was an argument in favor to the static method because sometimes, one needs to use a static private member variable.
I disagree somewhat, as show below:
// HPP
class Foo
{
public :
void barA() ;
private :
void barB() ;
static std::string myGlobal ;
} ;
First, myGlobal is called myGlobal because it is still a global private variable. A look at the CPP source will clarify that:
// CPP
std::string Foo::myGlobal ; // You MUST declare it in a CPP
void Foo::barA()
{
// I can access Foo::myGlobal
}
void Foo::barB()
{
// I can access Foo::myGlobal, too
}
void barC()
{
// I CAN'T access Foo::myGlobal !!!
}
At first sight, the fact the free function barC can't access Foo::myGlobal seems a good thing from an encapsulation viewpoint... It's cool because someone looking at the HPP won't be able (unless resorting to sabotage) to access Foo::myGlobal.
But if you look at it closely, you'll find that it is a colossal mistake: Not only your private variable must still be declared in the HPP (and so, visible to all the world, despite being private), but you must declare in the same HPP all (as in ALL) functions that will be authorized to access it !!!
So using a private static member is like walking outside in the nude with the list of your lovers tattooed on your skin : No one is authorized to touch, but everyone is able to peek at. And the bonus: Everyone can have the names of those authorized to play with your privies.
private
indeed...
:-D
Anonymous namespaces will have the advantage of making things private really private.
First, the HPP header
// HPP
namespace Foo
{
void barA() ;
}
Just to be sure you remarked: There is no useless declaration of barB nor myGlobal. Which means that no one reading the header knows what's hidden behind barA.
Then, the CPP:
// CPP
namespace Foo
{
namespace
{
std::string myGlobal ;
void Foo::barB()
{
// I can access Foo::myGlobal
}
}
void barA()
{
// I can access myGlobal, too
}
}
void barC()
{
// I STILL CAN'T access myGlobal !!!
}
As you can see, like the so-called "static class" declaration, fooA and fooB are still able to access myGlobal. But no one else can. And no one else outside this CPP knows fooB and myGlobal even exist!
Unlike the "static class" walking on the nude with her address book tattooed on her skin the "anonymous" namespace is fully clothed, which seems quite better encapsulated AFAIK.
Unless the users of your code are saboteurs (I'll let you, as an exercise, find how one can access to the private part of a public class using a dirty behaviour-undefined hack...), what's private
is private
, even if it is visible in the private
section of a class declared in a header.
Still, if you need to add another "private function" with access to the private member, you still must declare it to all the world by modifying the header, which is a paradox as far as I am concerned: If I change the implementation of my code (the CPP part), then the interface (the HPP part) should NOT change. Quoting Leonidas : "This is ENCAPSULATION!"
When are classes static methods are actually better than namespaces with non-member functions?
When you need to group together functions and feed that group to a template:
namespace alpha
{
void foo() ;
void bar() ;
}
struct Beta
{
static void foo() ;
static void bar() ;
};
template <typename T>
struct Gamma
{
void foobar()
{
T::foo() ;
T::bar() ;
}
};
Gamma<alpha> ga ; // compilation error
Gamma<Beta> gb ; // ok
gb.foobar() ; // ok !!!
Because, if a class can be a template parameter, a namespaces cannot.
REPLACE INTO table(column_list) VALUES(value_list);
is a shorter form of
INSERT OR REPLACE INTO table(column_list) VALUES(value_list);
For REPLACE to execute correctly your table structure must have unique rows, whether a simple primary key or a unique index.
REPLACE deletes, then INSERTs the record and will cause an INSERT Trigger to execute if you have them setup. If you have a trigger on INSERT, you may encounter issues.
This is a work around.. not checked the speed..
INSERT OR IGNORE INTO table (column_list) VALUES(value_list);
followed by
UPDATE table SET field=value,field2=value WHERE uniqueid='uniquevalue'
This method allows a replace to occur without causing a trigger.
I'd suggest:
document.querySelector('.rateRecipe.btns-one-small').click();
The above code assumes that the given element has both of those classes; otherwise, if the space is meant to imply an ancestor-descendant relationship:
document.querySelector('.rateRecipe .btns-one-small').click();
The method getElementsByClassName()
takes a single class-name (rather than document.querySelector()
/document.querySelectorAll()
, which take a CSS selector), and you passed two (presumably class-names) to the method.
References:
This will make the div fixed at the bottom of the page but in case the page is long it will only be visible when you scroll down.
<style type="text/css">
#footer {
position : absolute;
bottom : 0;
height : 40px;
margin-top : 40px;
}
</style>
<div id="footer">I am footer</div>
The height and margin-top should be the same so that the footer doesnt show over the content.
On my Mac, I wrote this code in my Terminal:
xxx-MacBook-Pro:~ xxx$ cd /Users/xxx/Documents/0_Software/adt20140702/sdk/platform-tools/
xxx-MacBook-Pro:platform-tools xxx$ ./adb kill-server
xxx-MacBook-Pro:platform-tools xxx$ ./adb start-server
- daemon not running. starting it now on port 5037 *
- daemon started successfully *
xxx-MacBook-Pro:platform-tools tuananh$
Hope this help.
#!/bin/sh
WID=$(xprop -root | grep "_NET_ACTIVE_WINDOW(WINDOW)"| awk '{print $5}')
xdotool windowfocus $WID
xdotool key ctrl+shift+t
wmctrl -i -a $WID
This will auto determine the corresponding terminal and opens the tab accordingly.
With jQuery, you can do a single-line operation like this:
Example: http://jsfiddle.net/HWKQY/
y.splice( $.inArray(removeItem, y), 1 );
Uses the native .splice()
and jQuery's $.inArray()
.
This is common issue only. Even I have faced this issue. On the development machine, configured with Windows authentication, it is worked perfectly:
<add name="ShoppingCartAdminEntities" connectionString="metadata=res://*/ShoppingCartAPIModel.csdl|res://*/ShoppingCartAPIModel.ssdl|res://*/ShoppingCartAPIModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.\SQlExpress;initial catalog=ShoppingCartAdmin;Integrated Security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
Once hosted in IIS with the same configuration, I got this error:
The underlying provider failed on Open
It was solved changing connectionString
in the configuration file:
<add name="MyEntities" connectionString="metadata=res://*/ShoppingCartAPIModel.csdl|res://*/ShoppingCartAPIModel.ssdl|res://*/ShoppingCartAPIModel.msl;provider=System.Data.SqlClient;provider connection string="data source=MACHINE_Name\SQlExpress;initial catalog=ShoppingCartAdmin;persist security info=True;user id=sa;password=notmyrealpassword;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
Other common mistakes could be:
Something to be aware of, the $_SESSION
variables are still set in the same page after calling session_destroy()
where as this is not the case when using unset($_SESSION)
or $_SESSION = array()
. Also, unset($_SESSION)
blows away the $_SESSION
superglobal so only do this when you're destroying a session.
With all that said, it's best to do like the PHP docs has it in the first example for session_destroy()
.
When working with Docker Compose, you can use command: postgres -c option=value
in your docker-compose.yml
to configure Postgres.
For example, this makes Postgres log to a file:
command: postgres -c logging_collector=on -c log_destination=stderr -c log_directory=/logs
Adapting Vojtech Vitek's answer, you can use
command: postgres -c config_file=/etc/postgresql.conf
to change the config file Postgres will use. You'd mount your custom config file with a volume:
volumes:
- ./customPostgresql.conf:/etc/postgresql.conf
Here's the docker-compose.yml
of my application, showing how to configure Postgres:
# Start the app using docker-compose pull && docker-compose up to make sure you have the latest image
version: '2.1'
services:
myApp:
image: registry.gitlab.com/bullbytes/myApp:latest
networks:
- myApp-network
db:
image: postgres:9.6.1
# Make Postgres log to a file.
# More on logging with Postgres: https://www.postgresql.org/docs/current/static/runtime-config-logging.html
command: postgres -c logging_collector=on -c log_destination=stderr -c log_directory=/logs
environment:
# Provide the password via an environment variable. If the variable is unset or empty, use a default password
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD:-4WXUms893U6j4GE&Hvk3S*hqcqebFgo!vZi}
# If on a non-Linux OS, make sure you share the drive used here. Go to Docker's settings -> Shared Drives
volumes:
# Persist the data between container invocations
- postgresVolume:/var/lib/postgresql/data
- ./logs:/logs
networks:
myApp-network:
# Our application can communicate with the database using this hostname
aliases:
- postgresForMyApp
networks:
myApp-network:
driver: bridge
# Creates a named volume to persist our data. When on a non-Linux OS, the volume's data will be in the Docker VM
# (e.g., MobyLinuxVM) in /var/lib/docker/volumes/
volumes:
postgresVolume:
Note that when on Linux, the log directory on the host must have the right permissions. Otherwise you'll get the slightly misleading error
FATAL: could not open log file "/logs/postgresql-2017-02-04_115222.log": Permission denied
I say misleading, since the error message suggests that the directory in the container has the wrong permission, when in reality the directory on the host doesn't permit writing.
To fix this, I set the correct permissions on the host using
chgroup ./logs docker && chmod 770 ./logs
Rabin-Miller is a standard probabilistic primality test. (you run it K times and the input number is either definitely composite, or it is probably prime with probability of error 4-K. (a few hundred iterations and it's almost certainly telling you the truth)
There is a non-probabilistic (deterministic) variant of Rabin Miller.
The Great Internet Mersenne Prime Search (GIMPS) which has found the world's record for largest proven prime (274,207,281 - 1 as of June 2017), uses several algorithms, but these are primes in special forms. However the GIMPS page above does include some general deterministic primality tests. They appear to indicate that which algorithm is "fastest" depends upon the size of the number to be tested. If your number fits in 64 bits then you probably shouldn't use a method intended to work on primes of several million digits.
I find this to be concise and self-documenting:
[true, false].include? foo
If using Rails or ActiveSupport, you can even do a direct query using in?
foo.in? [true, false]
Checking against all possible values isn't something I'd recommend for floats, but feasible when there are only two possible values!
I would have added this as a comment, but my reputation is not yet high enough.
Under version 4.5.4.1deb2ubuntu2, and I am guessing any other versions 4.5.x or newer. There is no need to modify the config.inc.php file at all. Instead go one more directory down conf.d.
Create a new file with the '.php' extension and add the lines. This is a better modularized approach and isolates each remote database server access information.
Jquery Select Box Validation.You can Alert Message via alert or Put message in Div as per your requirements.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="message"></div>_x000D_
<form method="post">_x000D_
<select name="year" id="year">_x000D_
<option value="0">Year</option>_x000D_
<option value="1">1919</option>_x000D_
<option value="2">1920</option>_x000D_
<option value="3">1921</option>_x000D_
<option value="4">1922</option>_x000D_
</select>_x000D_
<button id="clickme">Click</button>_x000D_
</form>_x000D_
<script>_x000D_
$("#clickme").click(function(){_x000D_
_x000D_
if( $("#year option:selected").val()=='0'){_x000D_
_x000D_
alert("Please select one option at least");_x000D_
_x000D_
$("#message").html("Select At least one option");_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
});_x000D_
_x000D_
</script>
_x000D_
First, go to c:\mongodb\bin>
to turn on mongoDB, if you see in console that mongo is listening in port 27017, it is OK
If not, close console and create folder c:\data\db
and start mongod again
This problem mainly happens when you are using connection pooling because when you close connection that connection go back to the connection pool and all cursor associated with that connection never get closed as the connection to database is still open. So one alternative is to decrease the idle connection time of connections in pool, so may whenever connection sits idle in connection for say 10 sec , connection to database will get closed and new connection created to put in pool.
Remember that in Swift, extension are definitely your friends!
public extension UINavigationController {
/**
Pop current view controller to previous view controller.
- parameter type: transition animation type.
- parameter duration: transition animation duration.
*/
func pop(transitionType type: String = kCATransitionFade, duration: CFTimeInterval = 0.3) {
self.addTransition(transitionType: type, duration: duration)
self.popViewControllerAnimated(false)
}
/**
Push a new view controller on the view controllers's stack.
- parameter vc: view controller to push.
- parameter type: transition animation type.
- parameter duration: transition animation duration.
*/
func push(viewController vc: UIViewController, transitionType type: String = kCATransitionFade, duration: CFTimeInterval = 0.3) {
self.addTransition(transitionType: type, duration: duration)
self.pushViewController(vc, animated: false)
}
private func addTransition(transitionType type: String = kCATransitionFade, duration: CFTimeInterval = 0.3) {
let transition = CATransition()
transition.duration = duration
transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
transition.type = type
self.view.layer.addAnimation(transition, forKey: nil)
}
}
Absolute positioning positions an element relative to its nearest positioned ancestor. So put position: relative
on the container, then for child elements, top
and left
will be relative to the top-left of the container so long as the child elements have position: absolute
. More information is available in the CSS 2.1 specification.
Here's a simpler (but not so short) version which doesn't require try-catch:
Map<String, String> data = new HashMap<>();
data.put("user", "[email protected]");
data.put("pass", "123");
JSONObject jsonData = new JSONObject(data);
If you want to add a jsonObject into a field, you can do this way:
data.put("socialMedia", (new JSONObject()).put("facebookId", "1174989895893400"));
data.put("socialMedia", (new JSONObject()).put("googleId", "106585039098745627377"));
Unfortunately it needs a try-catch because of the put() method.
IF you want to avoid try-catch again (not very recommended, but it's ok if you can guarantee well formated json strings), you might do this way:
data.put("socialMedia", "{ 'facebookId': '1174989895893400' }");
You can do the same about JsonArrays and so on.
Cheers.
You could address the problem with an X-Macro
You would change your struct definition into:
#define LIST_OF_foo_MEMBERS \
X(int,id) \
X(int,route) \
X(int,backup_route) \
X(int,current_route)
#define X(type,name) type name;
struct foo {
LIST_OF_foo_MEMBERS
};
#undef X
And then you would be able to easily define a flexible function that sets all fields to dont_care
.
#define X(type,name) in->name = dont_care;
void setFooToDontCare(struct foo* in) {
LIST_OF_foo_MEMBERS
}
#undef X
Following the discussion here, one could also define a default value in this way:
#define X(name) dont_care,
const struct foo foo_DONT_CARE = { LIST_OF_STRUCT_MEMBERS_foo };
#undef X
Which translates into:
const struct foo foo_DONT_CARE = {dont_care, dont_care, dont_care, dont_care,};
And use it as in hlovdal answer, with the advantage that here maintenance is easier, i.e. changing the number of struct members will automatically update foo_DONT_CARE
. Note that the last "spurious" comma is acceptable.
I first learned the concept of X-Macros when I had to address this problem.
It is extremely flexible to new fields being added to the struct. If you have different data types, you could define different dont_care
values depending on the data type: from here, you could take inspiration from the function used to print the values in the second example.
If you are ok with an all int
struct, then you could omit the data type from LIST_OF_foo_MEMBERS
and simply change the X function of the struct definition into #define X(name) int name;
$("input").datepicker({ dateFormat: 'dd, mm, yy' });
later in your code when the date is set you could get it by
dateVariable = $("input").val();
dateString = $.datepicker.formatDate('dd, MM, yy', new Date("20 April 2012"));
I've updated the jsfiddle for experimenting with this
Assuming that you are using Windows, run the application as Admin.
For that, you have at least two options:
• Open the file location, right click and select "Run as Administrator".
• Using Windows Start menu, search for "Git Bash", and you will find the following:
Then, just press "Run as Administrator".
As others have said this can be caused when you've not installed an app that is listed in INSTALLED_APPS
.
In my case, manage.py
was attempting to log the exception, which led to an attempt to render it which failed due to the app not being initialized yet. By
commenting out the except
clause in manage.py
the exception was displayed without special rendering, avoiding the confusing error.
# Temporarily commenting out the log statement.
#try:
execute_from_command_line(sys.argv)
#except Exception as e:
# log.error('Admin Command Error: %s', ' '.join(sys.argv), exc_info=sys.exc_info())
# raise e
This will solve your problem
interface
TArrayStr = Array Of string;
implementation
function SplitString(Text: String): TArrayStr;
var
intIdx: Integer;
intIdxOutput: Integer;
const
Delimiter = ';';
begin
intIdxOutput := 0;
SetLength(Result, 1);
Result[0] := '';
for intIdx := 1 to Length(Text) do
begin
if Text[intIdx] = Delimiter then
begin
intIdxOutput := intIdxOutput + 1;
SetLength(Result, Length(Result) + 1);
end
else
Result[intIdxOutput] := Result[intIdxOutput] + Text[intIdx];
end;
end;
When you execute a program the child program inherits its environment variables from the parent. For instance if $HOME
is set to /root
in the parent then the child's $HOME
variable is also set to /root
.
This only applies to environment variable that are marked for export. If you set a variable at the command-line like
$ FOO="bar"
That variable will not be visible in child processes. Not unless you export it:
$ export FOO
You can combine these two statements into a single one in bash (but not in old-school sh):
$ export FOO="bar"
Here's a quick example showing the difference between exported and non-exported variables. To understand what's happening know that sh -c
creates a child shell process which inherits the parent shell's environment.
$ FOO=bar
$ sh -c 'echo $FOO'
$ export FOO
$ sh -c 'echo $FOO'
bar
Note: To get help on shell built-in commands use help export
. Shell built-ins are commands that are part of your shell rather than independent executables like /bin/ls
.
import os
path = chap_name
if not os.path.exists(path):
os.makedirs(path)
filename = img_alt + '.jpg'
with open(os.path.join(path, filename), 'wb') as temp_file:
temp_file.write(buff)
Key point is to use os.makedirs
in place of os.mkdir
. It is recursive, i.e. it generates all intermediate directories. See http://docs.python.org/library/os.html
Open the file in binary mode as you are storing binary (jpeg) data.
In response to Edit 2, if img_alt sometimes has '/' in it:
img_alt = os.path.basename(img_alt)
You can't serialize a class that implements IDictionary. Check out this link.
Q: Why can't I serialize hashtables?
A: The XmlSerializer cannot process classes implementing the IDictionary interface. This was partly due to schedule constraints and partly due to the fact that a hashtable does not have a counterpart in the XSD type system. The only solution is to implement a custom hashtable that does not implement the IDictionary interface.
So I think you need to create your own version of the Dictionary for this. Check this other question.
Vue just warns you: you change the prop in the component, but when parent component re-renders, "list" will be overwritten and you lose all your changes. So it is dangerous to do so.
Use computed property instead like this:
Vue.component('task', {
template: '#task-template',
props: ['list'],
computed: {
listJson: function(){
return JSON.parse(this.list);
}
}
});
A complementary note about CREATE TABLE .. TYPE=""
syntax in SQL dump files
TLDR: If you still get CREATE TABLE ... TYPE="..."
statements in SQL dump files generated by third party tools, it most certainly indicates that your server is configured to use a default sqlmode
of MYSQL40
or MYSQL323
.
Long story
As it was said by others, the TYPE
argument to CREATE TABLE
has been deprecated for a long time in MySQL. mysqldump
correctly uses the ENGINE
argument, unless you specifically ask it to generate a backward compatible dump (for example using --compatible=mysql40
in versions of mysqldump
up to 5.7).
However, many external SQL dump tools (for example, those integrated in MySQL clients such as phpmyadmin, Navicat and DBVisualizer, as well as those used by external automated backup services such as iControlWP) are not specifically aware of this change, and instead rely on the SHOW CREATE TABLE ...
command to provide table creation statements for each tables (and just to it make it clear: this is actually a good thing). However, the SHOW CREATE TABLE
will actually produce outdated syntax, including the TYPE
argument, if the sqlmode
variable is set to MYSQL40
or MYSQL323
.
Therefore, if you still get CREATE TABLE ... TYPE="..."
statements in SQL dump files generated by third party tools, it most certainly indicates that your server is configured to use a default sqlmode
of MYSQL40
or MYSQL323
.
These sqlmode
s basically configure MySQL to retain some backward compatible behaviours, and using them by default was largely recommended a few years ago. It is however highly improbable that you still have any code that wouldn't work correctly without these modes. Anyway, MYSQL40
, MYSQL323
and several other similar sqlmode
s have themselves been deprecated and are not supported in MySQL 8.0 and higher.
If your server is still configured with these sqlmode
s and you are worried that some legacy program might fail if you change these, then one possibility is to set the sqlmode
locally for that program, by executing SET SESSION sql_mode = 'MYSQL40';
immediately after connection. Note that this should only be considered as a temporary patch, and will not work in MySQL 8.0 and higher.
A more future-proof solution that do not involve rewriting your SQL queries would be to determine exactly which compatibility features need to be enable, and to enable only those, on a per-program basis (as described previously). The default sqlmode
(that is, in server's configuration) should ideally be left unset (which will use official MySQL defaults for your current version). The full list of sqlmode
(as of MySQL 5.7) is described here: https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html.
I think you can try this Bash debugger: http://bashdb.sourceforge.net/.
Use the Ctrl+Space
shortcut for getting all possible autocomplete options available in a particular context in the editor.
Auto Complete will also allow you to insert custom code templates into the editor, with placeholders for various inputs. For instance, attempting to auto complete the word "test" in a Java editor, in the context of a class body, will allow you to create a unit test that uses JUnit; you'll have to code the body of the method though. Some code templates like the former, come out of the box.
Configuration options of interest
.
character by default. When you have just keyed in typeA.
and you expect to see relevant members that can be accessed, the auto completion list will automatically popup with the appropriate members, on this trigger.Places is a list and not a dictionary. This line below should therefore not work:
print data['places']['latitude']
You need to select one of the items in places and then you can list the place's properties. So to get the first post code you'd do:
print data['places'][0]['post code']
try this: //*[contains(@class, 'atag')]
OK, answering to my own question.
Steps to connect LocalDB to Visual Studio Server Explorer
SqlLocalDB.exe start v11.0
SqlLocalDB.exe info v11.0
(localdb)\v11.0
. If it didn't work, use the Instance pipe name that you copied earlier. You can also use this to connect with SQL Management Studio.In my case this was being issued by wp cli
, and the problem was that I didn't have php7.3-curl
installed. Fixed with: apt-get install -y --quiet php7.3-curl
I am using Spring Boot version 2.1.2 and the errorAttributes.getErrorAttributes()
signature didn't work for me (in acohen's response). I wanted a JSON type response so I did a little digging and found this method did exactly what I needed.
I got most of my information from this thread as well as this blog post.
First, I created a CustomErrorController
that Spring will look for to map any errors to.
package com.example.error;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
@RestController
public class CustomErrorController implements ErrorController {
private static final String PATH = "error";
@Value("${debug}")
private boolean debug;
@Autowired
private ErrorAttributes errorAttributes;
@RequestMapping(PATH)
@ResponseBody
public CustomHttpErrorResponse error(WebRequest request, HttpServletResponse response) {
return new CustomHttpErrorResponse(response.getStatus(), getErrorAttributes(request));
}
public void setErrorAttributes(ErrorAttributes errorAttributes) {
this.errorAttributes = errorAttributes;
}
@Override
public String getErrorPath() {
return PATH;
}
private Map<String, Object> getErrorAttributes(WebRequest request) {
Map<String, Object> map = new HashMap<>();
map.putAll(this.errorAttributes.getErrorAttributes(request, this.debug));
return map;
}
}
Second, I created a CustomHttpErrorResponse
class to return the error as JSON.
package com.example.error;
import java.util.Map;
public class CustomHttpErrorResponse {
private Integer status;
private String path;
private String errorMessage;
private String timeStamp;
private String trace;
public CustomHttpErrorResponse(int status, Map<String, Object> errorAttributes) {
this.setStatus(status);
this.setPath((String) errorAttributes.get("path"));
this.setErrorMessage((String) errorAttributes.get("message"));
this.setTimeStamp(errorAttributes.get("timestamp").toString());
this.setTrace((String) errorAttributes.get("trace"));
}
// getters and setters
}
Finally, I had to turn off the Whitelabel in the application.properties
file.
server.error.whitelabel.enabled=false
This should even work for xml
requests/responses. But I haven't tested that. It did exactly what I was looking for since I was creating a RESTful API and only wanted to return JSON.
The obligatory
#define FOR for
and
#define ONE 1
#define TWO 2
...
Who knew?
When I tried cloning from the remote, got the same issue repeatedly:
remote: Counting objects: 182, done.
remote: Compressing objects: 100% (149/149), done.
error: RPC failed; curl 18 transfer closed with outstanding read data remaining
fatal: The remote end hung up unexpectedly
fatal: early EOF
fatal: index-pack failed
Finally this worked for me:
git clone https://[email protected]/repositoryName.git --depth 1
If you're allowed to use the ch measurement (monospaced) it completely solved what I was trying to do.
onChange(e => {
e.target.style.width = `${e.target.length}ch`;
})
This was exactly what I needed but I'm not sure if it works for dynamic width font-families.
using System.IO;
...
Directory.CreateDirectory(@"C:\MP_Upload");
Directory.CreateDirectory does exactly what you want: It creates the directory if it does not exist yet. There's no need to do an explicit check first.
Any and all directories specified in path are created, unless they already exist or unless some part of path is invalid. The path parameter specifies a directory path, not a file path. If the directory already exists, this method does nothing.
(This also means that all directories along the path are created if needed: CreateDirectory(@"C:\a\b\c\d")
suffices, even if C:\a
does not exist yet.)
Let me add a word of caution about your choice of directory, though: Creating a folder directly below the system partition root C:\
is frowned upon. Consider letting the user choose a folder or creating a folder in %APPDATA%
or %LOCALAPPDATA%
instead (use Environment.GetFolderPath for that). The MSDN page of the Environment.SpecialFolder enumeration contains a list of special operating system folders and their purposes.
You say
I mean that it is not in use by any other application. If an application is using a port others can't use it until it becomes free.
But you can always connect to a port while others are using it if something's listening there. Otherwise, http port 80 would be a mess.
If your
c = new TcpClient(ip, port);
fails, then nothing's listening there. Otherwise, it will connect, even if some other machine/application has a socket open to that ip and port.
From the manpage of ld
(this does not work with gcc), referring to the --static
option:
You may use this option multiple times on the command line: it affects library searching for -l options which follow it.
One solution is to put your dynamic dependencies before the --static
option on the command line.
Another possibility is to not use --static
, but instead provide the full filename/path of the static object file (i.e. not using -l option) for statically linking in of a specific library. Example:
# echo "int main() {}" > test.cpp
# c++ test.cpp /usr/lib/libX11.a
# ldd a.out
linux-vdso.so.1 => (0x00007fff385cc000)
libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0x00007f9a5b233000)
libm.so.6 => /lib/libm.so.6 (0x00007f9a5afb0000)
libgcc_s.so.1 => /lib/libgcc_s.so.1 (0x00007f9a5ad99000)
libc.so.6 => /lib/libc.so.6 (0x00007f9a5aa46000)
/lib64/ld-linux-x86-64.so.2 (0x00007f9a5b53f000)
As you can see in the example, libX11
is not in the list of dynamically-linked libraries, as it was linked statically.
Beware: An .so
file is always linked dynamically, even when specified with a full filename/path.
You can even give multiple columns with null values and get multiple quantile values (I use 95 percentile for outlier treatment)
my_df[['field_A','field_B']].dropna().quantile([0.0, .5, .90, .95])
Try using the Dictionary Object or the Collection Object.
http://visualbasic.ittoolbox.com/documents/dictionary-object-vs-collection-object-12196
In my case the route in my router was:
Route::post('/new-order', 'Api\OrderController@initiateOrder')->name('newOrder');
and from the client app I was posting the request to:
https://my-domain/api/new-order/
So, because of the trailing slash I got a 405. Hope it helps someone
I was recently having trouble with this same thing and I found a really simple solution.
All you have to do is set the first option to disabled and selected. Like this:
<select id="select">_x000D_
<option disabled="disabled" selected="selected">select one option</option>_x000D_
<option>one</option>_x000D_
<option>two</option>_x000D_
<option>three</option>_x000D_
<option>four</option>_x000D_
<option>five</option>_x000D_
</select>
_x000D_
This will display the first option (grayed out) when the page is loaded. It also prevents the user from being able to select it once they click on the list.
Look into the theme attributes buttonBarStyle
, buttonBarButtonStyle
, and borderlessButtonStyle
.
If you want to use NodeJS, you can use a package called chokidar (or chokidar-cli actually) for the watching and then use rsync
(included with Mac):
Rsync command:
$ rsync -avz --exclude 'some-file' --exclude 'some-dir' './' '/my/destination'
Chokidar cli (installed globally via npm):
chokidar \"**/*\" -c \"your-rsync-command-above\"
This is an old post, but I thought I should provide an illustrated answer anyway.
Use javascript's object notation. Like so:
states_dictionary={
"CT":["alex","harry"],
"AK":["liza","alex"],
"TX":["fred", "harry"]
};
And to access the values:
states_dictionary.AK[0] //which is liza
or you can use javascript literal object notation, whereby the keys not require to be in quotes:
states_dictionary={
CT:["alex","harry"],
AK:["liza","alex"],
TX:["fred", "harry"]
};
Try this,
window.location.href="sample.html";
Here sample.html
is a next page. It will go to the next page.
There is no built-in auto_increment in Oracle.
You need to use sequences
and triggers
.
Read here how to do it right. (Step-by-step how-to for "Creating auto-increment columns in Oracle")
Custom String Values for Enum
from http://javahowto.blogspot.com/2006/10/custom-string-values-for-enum.html
The default string value for java enum is its face value, or the element name. However, you can customize the string value by overriding toString() method. For example,
public enum MyType {
ONE {
public String toString() {
return "this is one";
}
},
TWO {
public String toString() {
return "this is two";
}
}
}
Running the following test code will produce this:
public class EnumTest {
public static void main(String[] args) {
System.out.println(MyType.ONE);
System.out.println(MyType.TWO);
}
}
this is one
this is two
First take a label. set its visibility to false, then on the DataGridView_CellClick event write this
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
label.Text=dataGridView1.Rows[e.RowIndex].Cells["Your Coloumn name"].Value.ToString();
// then perform your select statement according to that label.
}
//try it it might work for you
I used read_csv
from the readr
package
In my experience, the parameter row.names=NULL
in the read.csv
function will lead to a wrong reading of the
file if a column name is missing, i.e. every column will be shifted.
read_csv
solves this.
You may try this:
Page::where('id', $id)->update(array('image' => 'asdasd'));
There are other ways too but no need to use Page::find($id);
in this case. But if you use find()
then you may try it like this:
$page = Page::find($id);
// Make sure you've got the Page model
if($page) {
$page->image = 'imagepath';
$page->save();
}
Also you may use:
$page = Page::findOrFail($id);
So, it'll throw an exception if the model with that id was not found.
Windows and Linux:
Ctrl + Shift + I keys to open Developer Tools
Ctrl + Shift + J to open Developer Tools and bring focus to the Console.
Ctrl + Shift + C to toggle Inspect Element mode.
Mac:
? + ? + I keys to open Developer Tools
? + ? + J to open Developer Tools and bring focus to the Console.
? + ? + C to toggle Inspect Element mode.
Just wanted to add on to what @aioobe mentioned above...
In that approach you use HTML to color code your text. Though this is one of the most frequently used ways to color code the label text, but is not the most efficient way to do it.... considering that fact that each label will lead to HTML being parsed, rendering, etc. If you have large UI forms to be displayed, every millisecond counts to give a good user experience.
You may want to go through the below and give it a try....
Jide OSS (located at https://jide-oss.dev.java.net/) is a professional open source library with a really good amount of Swing components ready to use. They have a much improved version of JLabel named StyledLabel. That component solves your problem perfectly... See if their open source licensing applies to your product or not.
This component is very easy to use. If you want to see a demo of their Swing Components you can run their WebStart demo located at www.jidesoft.com (http://www.jidesoft.com/products/1.4/jide_demo.jnlp). All of their offerings are demo'd... and best part is that the StyledLabel is compared with JLabel (HTML and without) in terms of speed! :-)
A screenshot of the perf test can be seen at (http://img267.imageshack.us/img267/9113/styledlabelperformance.png)
If you need to pass the asterisk symbol, you have to wrap it with quotes.
In my case, I need to configure cors for websockets. So, I decided to put cors urls into application.yml. For prod env I'll use specific urls, but for dev it's ok to use just *.
In yml file I have:
websocket:
cors: "*"
In Config class I have:
@Value("${websocket.cors}")
private String[] cors;
This answer is a much cleaner way to do it using new syntax.
Based on Glenn Howes' excellent answer, I created an extension to calculate the width of a string. If you're doing something like setting the width of a UISegmentedControl
, this can set the width based on the segment's title string.
extension String {
func widthOfString(usingFont font: UIFont) -> CGFloat {
let fontAttributes = [NSAttributedString.Key.font: font]
let size = self.size(withAttributes: fontAttributes)
return size.width
}
func heightOfString(usingFont font: UIFont) -> CGFloat {
let fontAttributes = [NSAttributedString.Key.font: font]
let size = self.size(withAttributes: fontAttributes)
return size.height
}
func sizeOfString(usingFont font: UIFont) -> CGSize {
let fontAttributes = [NSAttributedString.Key.font: font]
return self.size(withAttributes: fontAttributes)
}
}
usage:
// Set width of segmentedControl
let starString = "??"
let starWidth = starString.widthOfString(usingFont: UIFont.systemFont(ofSize: 14)) + 16
segmentedController.setWidth(starWidth, forSegmentAt: 3)
If you are using jQuery already, your best bet is .outerHeight()
or .height()
, as has been stated.
Without jQuery, you can check the box-sizing in use and add up various paddings + borders + clientHeight, or you can use getComputedStyle:
var h = getComputedStyle(document.getElementById('someDiv')).height;
h
will now be a string like a "53.825px".
And I can't find the reference, but I think I heard getComputedStyle()
can be expensive, so it's probably not something you want to call on each window.onscroll
event (but then, neither is jQuery's height()
).
I do the same task like this.
//in MessageHeader
private void SetValuesDefault()
{
MessageHeader header = this;
Framework.ObjectPropertyHelper.SetPropertiesToDefault<MessageHeader>(this);
}
//in ObjectPropertyHelper
public static void SetPropertiesToDefault<T>(T obj)
{
Type objectType = typeof(T);
System.Reflection.PropertyInfo [] props = objectType.GetProperties();
foreach (System.Reflection.PropertyInfo property in props)
{
if (property.CanWrite)
{
string propertyName = property.Name;
Type propertyType = property.PropertyType;
object value = TypeHelper.DefaultForType(propertyType);
property.SetValue(obj, value, null);
}
}
}
//in TypeHelper
public static object DefaultForType(Type targetType)
{
return targetType.IsValueType ? Activator.CreateInstance(targetType) : null;
}
The correct approach is to use preprocessing
For example
th:field="*{__${myVar}__}"
shutil.copy
and shutil.copy2
are copying files.
shutil.copytree
copies a folder with all the files and all subfolders. shutil.copytree
is using shutil.copy2
to copy the files.
So the analog to cp -r
you are saying is the shutil.copytree
because cp -r
targets and copies a folder and its files/subfolders like shutil.copytree
. Without the -r
cp
copies files like shutil.copy
and shutil.copy2
do.
use "\p{Pd}" without quotes to match any type of hyphen. The '-' character is just one type of hyphen which also happens to be a special character in Regex.
From Wikipedia http://en.wikipedia.org/wiki/Berkeley_sockets#bind.28.29
connect():
The connect() system call connects a socket, identified by its file descriptor, to a remote host specified by that host's address in the argument list.
Certain types of sockets are connectionless, most commonly user datagram protocol sockets. For these sockets, connect takes on a special meaning: the default target for sending and receiving data gets set to the given address, allowing the use of functions such as send() and recv() on connectionless sockets.
connect() returns an integer representing the error code: 0 represents success, while -1 represents an error.
bind():
bind() assigns a socket to an address. When a socket is created using socket(), it is only given a protocol family, but not assigned an address. This association with an address must be performed with the bind() system call before the socket can accept connections to other hosts. bind() takes three arguments:
sockfd, a descriptor representing the socket to perform the bind on. my_addr, a pointer to a sockaddr structure representing the address to bind to. addrlen, a socklen_t field specifying the size of the sockaddr structure. Bind() returns 0 on success and -1 if an error occurs.
Examples: 1.)Using Connect
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
int main(){
int clientSocket;
char buffer[1024];
struct sockaddr_in serverAddr;
socklen_t addr_size;
/*---- Create the socket. The three arguments are: ----*/
/* 1) Internet domain 2) Stream socket 3) Default protocol (TCP in this case) */
clientSocket = socket(PF_INET, SOCK_STREAM, 0);
/*---- Configure settings of the server address struct ----*/
/* Address family = Internet */
serverAddr.sin_family = AF_INET;
/* Set port number, using htons function to use proper byte order */
serverAddr.sin_port = htons(7891);
/* Set the IP address to desired host to connect to */
serverAddr.sin_addr.s_addr = inet_addr("192.168.1.17");
/* Set all bits of the padding field to 0 */
memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);
/*---- Connect the socket to the server using the address struct ----*/
addr_size = sizeof serverAddr;
connect(clientSocket, (struct sockaddr *) &serverAddr, addr_size);
/*---- Read the message from the server into the buffer ----*/
recv(clientSocket, buffer, 1024, 0);
/*---- Print the received message ----*/
printf("Data received: %s",buffer);
return 0;
}
2.)Bind Example:
int main()
{
struct sockaddr_in source, destination = {}; //two sockets declared as previously
int sock = 0;
int datalen = 0;
int pkt = 0;
uint8_t *send_buffer, *recv_buffer;
struct sockaddr_storage fromAddr; // same as the previous entity struct sockaddr_storage serverStorage;
unsigned int addrlen; //in the previous example socklen_t addr_size;
struct timeval tv;
tv.tv_sec = 3; /* 3 Seconds Time-out */
tv.tv_usec = 0;
/* creating the socket */
if ((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
printf("Failed to create socket\n");
/*set the socket options*/
setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct timeval));
/*Inititalize source to zero*/
memset(&source, 0, sizeof(source)); //source is an instance of sockaddr_in. Initialization to zero
/*Inititalize destinaton to zero*/
memset(&destination, 0, sizeof(destination));
/*---- Configure settings of the source address struct, WHERE THE PACKET IS COMING FROM ----*/
/* Address family = Internet */
source.sin_family = AF_INET;
/* Set IP address to localhost */
source.sin_addr.s_addr = INADDR_ANY; //INADDR_ANY = 0.0.0.0
/* Set port number, using htons function to use proper byte order */
source.sin_port = htons(7005);
/* Set all bits of the padding field to 0 */
memset(source.sin_zero, '\0', sizeof source.sin_zero); //optional
/*bind socket to the source WHERE THE PACKET IS COMING FROM*/
if (bind(sock, (struct sockaddr *) &source, sizeof(source)) < 0)
printf("Failed to bind socket");
/* setting the destination, i.e our OWN IP ADDRESS AND PORT */
destination.sin_family = AF_INET;
destination.sin_addr.s_addr = inet_addr("127.0.0.1");
destination.sin_port = htons(7005);
//Creating a Buffer;
send_buffer=(uint8_t *) malloc(350);
recv_buffer=(uint8_t *) malloc(250);
addrlen=sizeof(fromAddr);
memset((void *) recv_buffer, 0, 250);
memset((void *) send_buffer, 0, 350);
sendto(sock, send_buffer, 20, 0,(struct sockaddr *) &destination, sizeof(destination));
pkt=recvfrom(sock, recv_buffer, 98,0,(struct sockaddr *)&destination, &addrlen);
if(pkt > 0)
printf("%u bytes received\n", pkt);
}
I hope that clarifies the difference
Please note that the socket type that you declare will depend on what you require, this is extremely important
The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:
ffmpeg -i input.mov -qscale 0 output.mp4
Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0
):
ffmpeg -i input.mov -q:v 0 output.mp4
Another advantage: Quick compilation
If you include a header file, any change in it causes the current file also to compile but this is not the case if the class name is included as @class name
. Of course you will need to include the header in source file
This will work for both file and folder:
absPath(){
if [[ -d "$1" ]]; then
cd "$1"
echo "$(pwd -P)"
else
cd "$(dirname "$1")"
echo "$(pwd -P)/$(basename "$1")"
fi
}
This code segment for your Model
function getCount($tblName){
$query = $this->db->get($tblName);
$rowCount = $query->num_rows();
return $rowCount;
}
This is for controlr
public function index() {
$data['employeeCount']= $this->CMS_model->getCount("employee");
$this->load->view("hrdept/main",$data);
}
This is for view
<div class="count">
<?php echo $employeeCount; ?>
</div>
This code is used in my project and is working properly.
I had the same issue and for me it had nothing to do with namespace or project naming.
But as several users hinted at it had to do with an old assembly still being referenced.
I recommend to delete all "bin"/binary folders of all projects and to re-build the whole solution. This washed out any potentially outdated assemblies and after that MEF exported all my plugins without issue.
java.lang.ClassNotFoundException means CLASSPATH issues. Not having a clue implies that you're assuming that the CLASSPATH is set properly, but it's not.
If you're building with Eclipse, make sure that the directory where your compiled .class files exists, is in the CLASSPATH, and has the necessary .class files in it.
If you're building with Ant, make sure you see something like this in your build.xml:
<path id="production.class.path">
<pathelement location="${production.classes}"/>
<pathelement location="${production.resources}"/>
<fileset dir="${production.lib}">
<include name="**/*.jar"/>
<exclude name="**/junit*.jar"/>
<exclude name="**/*test*.jar"/>
</fileset>
</path>
UPDATE: Either you don't have JAVA_HOME/bin in your PATH or you downloaded the JRE instead of the JDK. Check the directory where you installed Java and see if your /bin directory has javac.exe in it. If you don't have a /bin, download the JDK and install it.
If you do have a /bin with javac.exe in it, check your PATH to see that the Java /bin directory is in the PATH. Once you've set it, open a command shell and type "javac -version" to ensure that all is well.
What JDK did you tell Eclipse to use?
XSD defines a schema which is a definition of how an XML document can be structured. You can use it to check that a given XML document is valid and follows the rules you've laid out in the schema.
WSDL is a XML document that describes a web service. It shows which operations are available and how data should be structured to send to those operations.
WSDL documents have an associated XSD that show what is valid to put in a WSDL document.
You can have a mix of PHP and HTML in your PHP files... just do something like this...
<?php
$string = htmlentities("Résumé");
?>
<html>
<head></head>
<body>
<p><?= $string ?></p>
</body>
</html>
That should output Résumé
just how you want it to.
If you don't have short tags enabled, replace the <?= $string ?>
with <?php echo $string; ?>
In Kotlin we can do in one line
TEXT_VIEW_ID.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
Although not quite the same as disabling views within a layout, it is worth mentioning that you can prevent all children from receiving touches (without having to recurse the layout hierarchy) by overriding the ViewGroup#onInterceptTouchEvent(MotionEvent) method:
public class InterceptTouchEventFrameLayout extends FrameLayout {
private boolean interceptTouchEvents;
// ...
public void setInterceptTouchEvents(boolean interceptTouchEvents) {
this.interceptTouchEvents = interceptTouchEvents;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return interceptTouchEvents || super.onInterceptTouchEvent(ev);
}
}
Then you can prevent children from receiving touch events:
InterceptTouchEventFrameLayout layout = (InterceptTouchEventFrameLayout) findViewById(R.id.layout);
layout.setInterceptTouchEvents(true);
If you have a click listener set on layout
, it will still be triggered.
I found a way to do it (dont know if it is the best but it works)
string oldFile = "oldFile.pdf";
string newFile = "newFile.pdf";
// open the reader
PdfReader reader = new PdfReader(oldFile);
Rectangle size = reader.GetPageSizeWithRotation(1);
Document document = new Document(size);
// open the writer
FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();
// the pdf content
PdfContentByte cb = writer.DirectContent;
// select the font properties
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252,BaseFont.NOT_EMBEDDED);
cb.SetColorFill(BaseColor.DARK_GRAY);
cb.SetFontAndSize(bf, 8);
// write the text in the pdf content
cb.BeginText();
string text = "Some random blablablabla...";
// put the alignment and coordinates here
cb.ShowTextAligned(1, text, 520, 640, 0);
cb.EndText();
cb.BeginText();
text = "Other random blabla...";
// put the alignment and coordinates here
cb.ShowTextAligned(2, text, 100, 200, 0);
cb.EndText();
// create the new page and add it to the pdf
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);
// close the streams and voilá the file should be changed :)
document.Close();
fs.Close();
writer.Close();
reader.Close();
I hope this can be usefull for someone =) (and post here any errors)
None of the above code is working smoothly.i tried this
<HorizontalScrollView
android:id="@+id/horizontalScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</HorizontalScrollView>
On upgrading to Xcode 8, I got a message to upgrade to recommended settings. I accepted and everything was updated. I started getting compile time issue :
Duplicate symbol for XXXX Duplicate symbol for XXXX Duplicate symbol for XXXX
A total of 143 errors. Went to Target->Build settings -> No Common Blocks -> Set it to NO. This resolved the issue. The issue was that the integrated projects had code blocks in common and hence was not able to compile it. Explanation can be found here.
Things are pretty much simpler unless they are made confusing.
To Install GD library in Ubuntu
sudo apt-get install php5-gd
To Install Freetype in Ubuntu
sudo apt-get install libfreetype6-dev:i386
After using slf4s and logula for a while, I wrote loglady
, a simple logging trait wrapping slf4j.
It offers an API similar to that of Python's logging library, which makes the common cases (basic string, simple formatting) trivial and avoids formatting boilerplate.
by the way, the zoo package, if it is loaded, overrides the base as.Date() with its own which, by default, provides origin="1970-01-01".
(i mention this in case you find that sometimes you need to add the origin, and sometimes you don't.)
Shelving has many uses. The main ones are:
Any other uses?
It is possible to make noncase sensitive URLs
RewriteEngine on
rewritemap lowercase int:tolower
RewriteCond $1 [A-Z]
RewriteRule ^/(.*)$ /${lowercase:$1} [R=301,L]
Making Google.com..GOOGLE.com etc direct to google.com
Here is usage of Math.PI
to find circumference of circle and Area
First we take Radius as a string in Message Box and convert it into integer
public class circle {
public static void main(String[] args) {
// TODO code application logic here
String rad;
float radius,area,circum;
rad = JOptionPane.showInputDialog("Enter the Radius of circle:");
radius = Integer.parseInt(rad);
area = (float) (Math.PI*radius*radius);
circum = (float) (2*Math.PI*radius);
JOptionPane.showMessageDialog(null, "Area: " + area,"AREA",JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(null, "circumference: " + circum, "Circumfernce",JOptionPane.INFORMATION_MESSAGE);
}
}
I use:
IF OBJECT_ID('[dbo].[myView]') IS NOT NULL
DROP VIEW [dbo].[myView]
GO
CREATE VIEW [dbo].[myView]
AS
...
Recently I added some utility procedures for this kind of stuff:
CREATE PROCEDURE dbo.DropView
@ASchema VARCHAR(100),
@AView VARCHAR(100)
AS
BEGIN
DECLARE @sql VARCHAR(1000);
IF OBJECT_ID('[' + @ASchema + '].[' + @AView + ']') IS NOT NULL
BEGIN
SET @sql = 'DROP VIEW ' + '[' + @ASchema + '].[' + @AView + '] ';
EXEC(@sql);
END
END
So now I write
EXEC dbo.DropView 'mySchema', 'myView'
GO
CREATE View myView
...
GO
I think it makes my changescripts a bit more readable
String multiple commands together using the && command:
./run.sh && tail -f log.txt
or
kill -9 1111 && ./start.sh
SELECT
sysobjects.name AS trigger_name ,OBJECT_NAME(parent_obj) AS table_name ,s.name AS table_schema
,USER_NAME(sysobjects.uid) AS trigger_owner
,OBJECTPROPERTY( id, 'ExecIsUpdateTrigger') AS isupdate
,OBJECTPROPERTY( id, 'ExecIsDeleteTrigger') AS isdelete
,OBJECTPROPERTY( id, 'ExecIsInsertTrigger') AS isinsert
,OBJECTPROPERTY( id, 'ExecIsAfterTrigger') AS isafter
,OBJECTPROPERTY( id, 'ExecIsInsteadOfTrigger') AS isinsteadof
,OBJECTPROPERTY(id, 'ExecIsTriggerDisabled') AS [disabled]
FROM sysobjects
INNER JOIN sysusers
ON sysobjects.uid = sysusers.uid
INNER JOIN sys.tables t
ON sysobjects.parent_obj = t.object_id
INNER JOIN sys.schemas s
ON t.schema_id = s.schema_id
WHERE sysobjects.type = 'TR'
this working for me
Let's say I have a dictionary D
with the elements below. To sort, just use the key argument in sorted
to pass a custom function as below:
D = {'eggs': 3, 'ham': 1, 'spam': 2}
def get_count(tuple):
return tuple[1]
sorted(D.items(), key = get_count, reverse=True)
# Or
sorted(D.items(), key = lambda x: x[1], reverse=True) # Avoiding get_count function call
Check this out.
You may also use defer. The main difference is that the promise is not going to resolve or reject eagerly.
set define off <- This is the best solution I found
I also tried...
set define }
I was able to insert several records containing ampersand characters '&' but I cannot use the '}' character into the text So I decided to use "set define off" and everything works as it should.
public static String getCurrentMonthFirstDate(){
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_MONTH, 1);
DateFormat df = new SimpleDateFormat("MM-dd-yyyy");
//System.out.println(df.format(c.getTime()));
return df.format(c.getTime());
}
Change Your Web.Config file as below. It will act like charm.
In node <system.webServer>
add below portion of code
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule"/>
</modules>
After adding, your Web.Config will look like below
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule"/>
</modules>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
On a Windows 64 bit machine, echo %programfiles(x86)% does print C:\Program Files (x86)
You can also use:
button.setStyleSheet("qproperty-icon: url(:/path/to/images.png);");
Note: This is a little hacky. You should use this only as last resort. Icons should be set from C++
code or Qt Designer
.
I routinely use INSERT IGNORE
, and it sounds like exactly the kind of behavior you're looking for as well. As long as you know that rows which would cause index conflicts will not be inserted and you plan your program accordingly, it shouldn't cause any trouble.
There is no full-proof method to prevent your images being downloaded/stolen.
But, some solutions like: watermarking your images(from client side or server side), implement a background image, disable/prevent right clicks, slice images into small pieces and then present as a complete image to browser, you can also use flash to show images.
Personally, recommended methods are: Watermarking and flash. But it is a difficult and almost impossible mission to accomplish. As long as user is able to "see" that image, means they take "screenshot" to steal the image.
int numberOfSpaces = 3;
String space = String.format("%"+ numberOfSpaces +"s", " ");
I think no one has given the correct answer to the question. My working solution is : 1. Just declare another class along with container-fluid class example(.maxx):
<div class="container-fluid maxx">_x000D_
<div class="row">_x000D_
<div class="col-sm-12">_x000D_
<p>Hello</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
.container-fluid.maxx {_x000D_
padding-left: 0px;_x000D_
padding-right: 0px; }
_x000D_
This will work 100% and will remove the padding from left and right. I hope this helps.
As far as I can tell, whether you throw an exception, or you return Request.CreateErrorResponse, the result is the same. If you look at the source code for System.Web.Http.dll, you will see as much. Take a look at this general summary, and a very similar solution that I have made: Web Api, HttpError, and the behavior of exceptions
For Displaying digit upto two decimal places there are two possibilities - 1) Firstly, you only want to display decimal digits if it's there. For example - i) 12.10 to be displayed as 12.1, ii) 12.00 to be displayed as 12. Then use-
DecimalFormat formater = new DecimalFormat("#.##");
2) Secondly, you want to display decimal digits irrespective of decimal present For example -i) 12.10 to be displayed as 12.10. ii) 12 to be displayed as 12.00.Then use-
DecimalFormat formater = new DecimalFormat("0.00");
//arraylist/Pojo you can Pass using bundle like this
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
Bundle args = new Bundle();
args.putSerializable("imageSliders",(Serializable)allStoriesPojo.getImageSliderPojos());
intent.putExtra("BUNDLE",args);
startActivity(intent);
Get SecondActivity like this
Intent intent = getIntent();
Bundle args = intent.getBundleExtra("BUNDLE");
String filter = bundle.getString("imageSliders");
//Happy coding
Search up "Edit the system environment variables" on windows search
Click environmental variable on the bottom right corner
Find path under system variables and click edit on it
Click new to add a new path
add this path: C:\Users\yourUserName\AppData\Local\GitHubDesktop\bin\github.exe
To make sure everything is working fine, open cmd, and type github.exe
this.PowerButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
mysql> set global sql_slave_skip_counter=1; start slave; show slave status\G
Then got error exists :
Error 'Table './openx/f_scraper_banner_details' is marked as crashed and should be repaired' on query. Default database: 'openx'. Query: 'INSERT INTO f_scraper_banner_details(job_details_id, ad_id, client_id, zone_id, affiliateid, comments, pct_to_report, publisher_currency, sanity_check_enabled, status, error_code, report_date) VALUES (10274859, 321264, 0, 31926, 0, '', -1, 'USD', 1, 'FAILURE', 'INACTIVE_BANNER', '2016-06-28 04:00:00')'
mysql> repair table f_scraper_banner_details;
This worked for me
There are 2 types of Firebase push-notifications:
1- Notification message(Display message) ->
-- 1.1 If you choose this variant, the OS will create it self a notification if app is in Background and will pass the data in the intent
. Then it's up to the client to handle this data.
-- 1.2 If the app is in Foreground then the notification it will be received via callback-function
in the FirebaseMessagingService
and it's up to the client to handle it.
2- Data messages(up to 4k data) -> These messages are used to send only data to the client(silently) and it's up to the client to handle it for both cases background/foreground via callback-function in FirebaseMessagingService
This is according official docs:https://firebase.google.com/docs/cloud-messaging/concept-options
For anyone having the problem of the API being called more than once while downloading a fairly large file using the method in the accepted answer, please set response buffering to true System.Web.HttpContext.Current.Response.Buffer = true;
This makes sure that the entire binary content is buffered on the server side before it is sent to the client. Otherwise you will see multiple request being sent to the controller and if you do not handle it properly, the file will become corrupt.
Tag ids must be unique. You are updating the span with ID 'ItemCostSpan' of which there are two. Give the span a class and get it using find.
$("legend").each(function() {
var SoftwareItem = $(this).text();
itemCost = GetItemCost(SoftwareItem);
$("input:checked").each(function() {
var Component = $(this).next("label").text();
itemCost += GetItemCost(Component);
});
$(this).find(".ItemCostSpan").text("Item Cost = $ " + itemCost);
});
Like this
<?php
$prop = 'Name';
echo $obj->$prop;
Or, if you have control over the class, implement the ArrayAccess interface and just do this
echo $obj['Name'];
This may be a sketchy solution, and I'd appreciate anybody pointing out whether this is a bad idea, since it's not a standard use of functions. I've had some success getting HTML out of a PHP function without building the return value as a string with the following:
function noStrings() {
echo ''?>
<div>[Whatever HTML you want]</div>
<?php;
}
The just 'call' the function:
noStrings();
And it will output:
<div>[Whatever HTML you want]</div>
Using this method, you can also define PHP variables within the function and echo them out inside the HTML.
One Google search later we've learned that you can set the entire plotting device background color as Owen indicates. If you just want the plotting region altered, you have to do something like what is outlined in that R-Help thread:
plot(df)
rect(par("usr")[1],par("usr")[3],par("usr")[2],par("usr")[4],col = "gray")
points(df)
The barplot
function has an add
parameter that you'll likely need to use.
In addition to the existing answers, Overridden functions are in different scopes; whereas overloaded functions are in same scope.
One can implement a Builder pattern with nested class. Especially in C++, personally I find it semantically cleaner. For example:
class Product{
public:
class Builder;
}
class Product::Builder {
// Builder Implementation
}
Rather than:
class Product {}
class ProductBuilder {}
You need enctype="multipart/form-data"
otherwise you will load only the file name and not the data.
{{ $post->created_at }}
will return '2014-06-26 04:07:31'
The solution is
{{ $post->created_at->format('Y-m-d') }}
you could add an sed script to your commandline:
ls /home/user/new/*.txt | sed -r 's/^.+\///'
You need to join
the two tables and then filter the result in where
clause:
SELECT country.name as country, country.headofstate
from country
inner join city on city.id = country.capital
where city.population > 100000
and country.headofstate like 'A%'
HTTP and redirects
Let's first recap how ASP.NET MVC works:
Let's also remind ourselves what a redirect is:
An HTTP redirect is a response that the webserver can send to the client, telling the client to look for the requested content under a different URL. The new URL is contained in a Location
header that the webserver returns to the client. In ASP.NET MVC, you do an HTTP redirect by returning a RedirectResult
from an action.
Passing data
If you were just passing simple values like strings and/or integers, you could pass them as query parameters in the URL in the Location
header. This is what would happen if you used something like
return RedirectToAction("ActionName", "Controller", new { arg = updatedResultsDocument });
as others have suggested
The reason that this will not work is that the XDocument
is a potentially very complex object. There is no straightforward way for the ASP.NET MVC framework to serialize the document into something that will fit in a URL and then model bind from the URL value back to your XDocument
action parameter.
In general, passing the document to the client in order for the client to pass it back to the server on the next request, is a very brittle procedure: it would require all sorts of serialisation and deserialisation and all sorts of things could go wrong. If the document is large, it might also be a substantial waste of bandwidth and might severely impact the performance of your application.
Instead, what you want to do is keep the document around on the server and pass an identifier back to the client. The client then passes the identifier along with the next request and the server retrieves the document using this identifier.
Storing data for retrieval on the next request
So, the question now becomes, where does the server store the document in the meantime? Well, that is for you to decide and the best choice will depend upon your particular scenario. If this document needs to be available in the long run, you may want to store it on disk or in a database. If it contains only transient information, keeping it in the webserver's memory, in the ASP.NET cache or the Session
(or TempData
, which is more or less the same as the Session
in the end) may be the right solution. Either way, you store the document under a key that will allow you to retrieve the document later:
int documentId = _myDocumentRepository.Save(updatedResultsDocument);
and then you return that key to the client:
return RedirectToAction("UpdateConfirmation", "ApplicationPoolController ", new { id = documentId });
When you want to retrieve the document, you simply fetch it based on the key:
public ActionResult UpdateConfirmation(int id)
{
XDocument doc = _myDocumentRepository.GetById(id);
ConfirmationModel model = new ConfirmationModel(doc);
return View(model);
}
It looks like placing the click event directly on the button is causing the problem. For some reason it can't find the function. Not sure why...
If you attach the event handler in the javascript, it does work however.
See it here: http://jsfiddle.net/WfBRr/7/
<button id="display-text" type="button">Display text of all options</button>
document.getElementById('display-text').onclick = function () {
var x = document.getElementById("mySelect");
var txt = "All options: ";
var i;
for (i = 0; i < x.length; i++) {
txt = txt + "\n" + x.options[i].value;
}
alert(txt);
}
$("input").attr("disabled", true);
as of... I don't know any more.
It's December 2013 and I really have no idea what to tell you.
First it was always .attr()
, then it was always .prop()
, so I came back here updated the answer and made it more accurate.
Then a year later jQuery changed their minds again and I don't even want to keep track of this.
Long story short, as of right now, this is the best answer: "you can use both... but it depends."
You should read this answer instead: https://stackoverflow.com/a/5876747/257493
And their release notes for that change are included here:
Neither .attr() nor .prop() should be used for getting/setting value. Use the .val() method instead (although using .attr("value", "somevalue") will continue to work, as it did before 1.6).
Summary of Preferred Usage
The .prop() method should be used for boolean attributes/properties and for properties which do not exist in html (such as window.location). All other attributes (ones you can see in the html) can and should continue to be manipulated with the .attr() method.
Or in other words:
".prop = non-document stuff"
".attr" = document stuff
... ...
May we all learn a lesson here about API stability...
As you know the answer is to use the ObjectFactory(). Here is a sample of the code that worked for me :)
ObjectFactory myRootFactory = new ObjectFactory();
MyRootType myRootType = myRootFactory.createMyRootType();
try {
File file = new File("./file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(MyRoot.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
//output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
JABXElement<MyRootType> myRootElement = myRootFactory.createMyRoot(myRootType);
jaxbMarshaller.marshal(myRootElement, file);
jaxbMarshaller.marshal(myRootElement, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
Maybe you should better use a case
for such lists:
case "$cms" in
wordpress|meganto|typo3)
do_your_else_case
;;
*)
do_your_then_case
;;
esac
I think for long such lists this is better readable.
If you still prefer the if
you can do it with single brackets in two ways:
if [ "$cms" != wordpress -a "$cms" != meganto -a "$cms" != typo3 ]; then
or
if [ "$cms" != wordpress ] && [ "$cms" != meganto ] && [ "$cms" != typo3 ]; then
I got this error when I did a git merge BRANCH_NAME "some commit message"
- I'd forgotten to add the -m flag for the commit message, so it thought that the branch name included the comment.
i had a similar problem - firefox returned the correct value of obj.clientHeight but ie did not- it returned 0. I changed it to obj.offsetHeight and it worked. Seems there is some state that ie has for clientheight - that makes it iffy...
As ping
works, but telnet
to port 80
does not, the HTTP port 80
is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?).
You need to add some code to your python program, that handles the proxy, like described here:
One more alternative options
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 1,
center: new google.maps.LatLng(35.137879, -82.836914),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var myMarker = new google.maps.Marker({
position: new google.maps.LatLng(47.651968, 9.478485),
draggable: true
});
google.maps.event.addListener(myMarker, 'dragend', function (evt) {
document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + evt.latLng.lat().toFixed(3) + ' Current Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
});
google.maps.event.addListener(myMarker, 'dragstart', function (evt) {
document.getElementById('current').innerHTML = '<p>Currently dragging marker...</p>';
});
map.setCenter(myMarker.position);
myMarker.setMap(map);
and html file
<body>
<section>
<div id='map_canvas'></div>
<div id="current">Nothing yet...</div>
</section>
</body>
The calculation of the zoom level for the longitudes of Giles Gardam works fine for me. If you want to calculate the zoom factor for latitude, this is an easy solution that works fine:
double minLat = ...;
double maxLat = ...;
double midAngle = (maxLat+minLat)/2;
//alpha is the non-negative angle distance of alpha and beta to midangle
double alpha = maxLat-midAngle;
//Projection screen is orthogonal to vector with angle midAngle
//portion of horizontal scale:
double yPortion = Math.sin(alpha*Math.pi/180) / 2;
double latZoom = Math.log(mapSize.height / GLOBE_WIDTH / yPortion) / Math.ln2;
//return min (max zoom) of both zoom levels
double zoom = Math.min(lngZoom, latZoom);
You can use :
var MSIE = jQuery.support.leadingWhitespace; // This property is not supported by ie 6-8
$(document).ready(function(){
if (MSIE){
if (navigator.vendor == 'Apple Computer, Inc.'){
// some code for this navigator
} else {
// some code for others browsers
}
} else {
// default code
}});
copy *.csv new.csv
No need for /b as csv isn't a binary file type.
Make sure to run mvn install
before you compile your war.
Adding this for completeness. If you (like me) use a script in your package.json
file, just add the --timeout
option to mocha:
"scripts": {
"test": "mocha 'test/**/*.js' --timeout 10000",
"test-debug": "mocha --debug 'test/**/*.js' --timeout 10000"
},
Then you can run npm run test
to run your test suite with the timeout set to 10,000 milliseconds.
try ORDER BY MONTH(Date),DAY(DATE)
Try this:
ORDER BY YEAR(Date) DESC, MONTH(Date) DESC, DAY(DATE) DESC
Worked perfectly on a JET DB.
Another option (if you need/want to ping instead of send an HTTP request) is the Ping class for PHP. I wrote it for just this purpose, and it lets you use one of three supported methods to ping a server (some servers/environments only support one of the three methods).
Example usage:
require_once('Ping/Ping.php');
$host = 'www.example.com';
$ping = new Ping($host);
$latency = $ping->ping();
if ($latency) {
print 'Latency is ' . $latency . ' ms';
}
else {
print 'Host could not be reached.';
}
public static T isNull<T>(this T v1, T defaultValue)
{
return v1 == null ? defaultValue : v1;
}
myValue.isNull(new MyValue())
If the Subversion server version is not printed in the HTML listing, it is available in the HTTP RESPONSE header returned by the server. You can get it using this shell command
wget -S --no-check-certificate \
--spider 'http://svn.server.net/svn/repository' 2>&1 \
| sed -n '/SVN/s/.*\(SVN[0-9\/\.]*\).*/\1/p';
If the SVN server requires you provide a user name and password, then add the wget
parameters --user
and --password
to the command like this
wget -S --no-check-certificate \
--user='username' --password='password' \
--spider 'http://svn.server.net/svn/repository' 2>&1 \
| sed -n '/SVN/s/.*\(SVN[0-9\/\.]*\).*/\1/p';
This works for me:
Before installing nvm
, run this in terminal: touch ~/.bash_profile
After, run this in terminal:
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.1/install.sh | bash
Important... - DO NOT forget to Restart your terminal OR use command source ~/.nvm/nvm.sh
(this will refresh the available commands in your system path).
In the terminal, use command nvm --version
and you should see the version
import org.springframework.core.io.ClassPathResource;
...
File folder = new ClassPathResource("sql").getFile();
File[] listOfFiles = folder.listFiles();
It is worth noting that this will limit your deployment options, ClassPathResource.getFile()
only works if the container has exploded (unzipped) your war file.
I totally agree with the answers before. I just like to mention that the difference between expose and ports is part of the security concept in docker. It goes hand in hand with the networking of docker. For example:
Imagine an application with a web front-end and a database back-end. The outside world needs access to the web front-end (perhaps on port 80), but only the back-end itself needs access to the database host and port. Using a user-defined bridge, only the web port needs to be opened, and the database application doesn’t need any ports open, since the web front-end can reach it over the user-defined bridge.
This is a common use case when setting up a network architecture in docker. So for example in a default bridge network, not ports are accessible from the outer world. Therefor you can open an ingresspoint with "ports". With using "expose" you define communication within the network. If you want to expose the default ports you don't need to define "expose" in your docker-compose file.
You can check /etc/ld.so.preload file content
I fix it by:
echo "" > /etc/ld.so.preload
Example:
Process process = Process.Start(@"Data\myApp.exe");
int id = process.Id;
Process tempProc = Process.GetProcessById(id);
this.Visible = false;
tempProc.WaitForExit();
this.Visible = true;
Constant Value Description
----------------------------------------------------------------
vbCr Chr(13) Carriage return
vbCrLf Chr(13) & Chr(10) Carriage return–linefeed combination
vbLf Chr(10) Line feed
vbCr : - return to line beginning
Represents a carriage-return character for print and display functions.
vbCrLf : - similar to pressing Enter
Represents a carriage-return character combined with a linefeed character for print and display
functions.
vbLf : - go to next line
Represents a linefeed character for print and display functions.
Read More from Constants Class
The particular format for strptime
:
datetime.datetime.strptime(string_date, "%Y-%m-%d %H:%M:%S.%f")
#>>> datetime.datetime(2013, 9, 28, 20, 30, 55, 782000)
I am not sure I got you but this might be what you are looking for:
SELECT i.invoiceid, sum(case when i.amount is not null then i.amount else 0 end), sum(case when i.amount is not null then i.amount else 0 end) - sum(case when p.amount is not null then p.amount else 0 end) AS amountdue
FROM invoices i
LEFT JOIN invoicepayments ip ON i.invoiceid = ip.invoiceid
LEFT JOIN payments p ON ip.paymentid = p.paymentid
LEFT JOIN customers c ON p.customerid = c.customerid
WHERE c.customernumber = '100'
GROUP BY i.invoiceid
This would get you the amounts sums in case there are multiple payment rows for each invoice
Another dplyr
possibility could be:
df %>%
group_by(cat) %>%
mutate(num = 1:n())
cat val num
<fct> <dbl> <int>
1 aaa 0.0564 1
2 aaa 0.258 2
3 aaa 0.308 3
4 aaa 0.469 4
5 aaa 0.552 5
6 bbb 0.170 1
7 bbb 0.370 2
8 bbb 0.484 3
9 bbb 0.547 4
10 bbb 0.812 5
11 ccc 0.280 1
12 ccc 0.398 2
13 ccc 0.625 3
14 ccc 0.763 4
15 ccc 0.882 5
I can think of doing it in two ways:
Storing the file in file system in any directory (say dir1
) and renaming it which ensures that the name is unique for every file (may be a timestamp) (say xyz123.jpg
), and then storing this name in some DataBase. Then while generating the JSON you pull this filename and generate a complete URL (which will be http://example.com/dir1/xyz123.png
)and insert it in the JSON.
Base 64 Encoding, It's basically a way of encoding arbitrary binary data in ASCII text. It takes 4 characters per 3 bytes of data, plus potentially a bit of padding at the end. Essentially each 6 bits of the input is encoded in a 64-character alphabet. The "standard" alphabet uses A-Z, a-z, 0-9 and + and /, with = as a padding character. There are URL-safe variants. So this approach will allow you to put your image directly in the MongoDB, while storing it Encode the image and decode while fetching it, it has some of its own drawbacks:
A.) Canvas
Load the image into an Image-Object, paint it to a canvas and convert the canvas back to a dataURL.
function convertToDataURLviaCanvas(url, callback, outputFormat){
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function(){
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.height;
canvas.width = this.width;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
canvas = null;
};
img.src = url;
}
Usage
convertToDataURLviaCanvas('http://bit.ly/18g0VNp', function(base64Img){
// Base64DataURL
});
Supported input formats
image/png
, image/jpeg
, image/jpg
, image/gif
, image/bmp
, image/tiff
, image/x-icon
, image/svg+xml
, image/webp
, image/xxx
B.) FileReader
Load the image as blob via XMLHttpRequest and use the FileReader API to convert it to a data URL.
function convertFileToBase64viaFileReader(url, callback){
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function () {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.send();
}
This approach
Usage
convertFileToBase64viaFileReader('http://bit.ly/18g0VNp', function(base64Img){
// Base64DataURL
});
The MDN documentation shows how the getItem
method is implementated:
Object.defineProperty(oStorage, "getItem", {
value: function (sKey) { return sKey ? this[sKey] : null; },
writable: false,
configurable: false,
enumerable: false
});
If the value isn't set, it returns null
. You are testing to see if it is undefined
. Check to see if it is null
instead.
if(localStorage.getItem("username") === null){
You can use %p in C
In C:
printf("%p",p)
In C++:
cout<<"Address of pointer p is: "<<p
We use blat to do this all the time in our environment. I use it as well to connect to Gmail with Stunnel. Here's the params to send a file
blat -to [email protected] -server smtp.example.com -f [email protected] -subject "subject" -body "body" -attach c:\temp\file.txt
Or you can put that file in as the body
blat c:\temp\file.txt -to [email protected] -server smtp.example.com -f [email protected] -subject "subject"
Your "listen" directives are wrong. See this page: http://nginx.org/en/docs/http/server_names.html.
They should be
server {
listen 80;
server_name www.domain1.com;
root /var/www/domain1;
}
server {
listen 80;
server_name www.domain2.com;
root /var/www/domain2;
}
Note, I have only included the relevant lines. Everything else looked okay but I just deleted it for clarity. To test it you might want to try serving a text file from each server first before actually serving php. That's why I left the 'root' directive in there.
Walkthrough Steps
Running the following command will update the repo to use HTTP rather than HTTPS:
sudo sed -i "s/mirrorlist=https/mirrorlist=http/" /etc/yum.repos.d/epel.repo
You should then be able to update with this command:
yum -y update