You probably want something like this overload of String.Join:
String.Join<T> Method (String, IEnumerable<T>)
Docs:
http://msdn.microsoft.com/en-us/library/dd992421.aspx
In your example, you'd use
String.Join("", Client);
use this Reload page
success: function(data){
if(data.success == true){ // if true (1)
setTimeout(function(){// wait for 5 secs(2)
location.reload(); // then reload the page.(3)
}, 5000);
}
}
Thanks, but that was not the solution. I found it out why it wasn't working for me.
Since I'd done a declaration:
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
I thought I would refer to root directory of the project when beans.xml file was there. Then I put the configuration file to src/main/resources and changed initialization to:
ApplicationContext context = new ClassPathXmlApplicationContext("src/main/resources/beans.xml");
it still was an IO Exception.
Then the file was left in src/main/resources/ but I changed declaration to:
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
and it solved the problem - maybe it will be helpful for someone.
thanks and cheers!
Edit:
Since I get many people thumbs up for the solution and had had first experience with Spring as student few years ago, I feel desire to explain shortly why it works.
When the project is being compiled and packaged, all the files and subdirs from 'src/main/java' in the project goes to the root directory of the packaged jar (the artifact we want to create). The same rule applies to 'src/main/resources'.
This is a convention respected by many tools like maven or sbt in process of building project (note: as a default configuration!). When code (from the post) was in running mode, it couldn't find nothing like "src/main/resources/beans.xml" due to the fact, that beans.xml was in the root of jar (copied to /beans.xml in created jar/ear/war).
When using ClassPathXmlApplicationContext, the proper location declaration for beans xml definitions, in this case, was "/beans.xml", since this is path where it belongs in jar and later on in classpath.
It can be verified by unpacking a jar with an archiver (i.e. rar) and see its content with the directories structure.
I would recommend reading articles about classpath as supplementary.
We can directly specify the destination file with the dest
option now. In the below example, the output json is stored into the /tmp/repo_version_file
- name: Get repository file repo_version model to set ambari_managed_repositories=false
uri:
url: 'http://<server IP>:8080/api/v1/stacks/HDP/versions/3.1/repository_versions/1?fields=operating_systems/*'
method: GET
force_basic_auth: yes
user: xxxxx
password: xxxxx
headers:
"X-Requested-By": "ambari"
"Content-type": "Application/json"
status_code: 200
dest: /tmp/repo_version_file
You get undefined for the various scenarios:
You declare a variable with var but never set it.
var foo;
alert(foo); //undefined.
You attempt to access a property on an object you've never set.
var foo = {};
alert(foo.bar); //undefined
You attempt to access an argument that was never provided.
function myFunction (foo) {
alert(foo); //undefined.
}
As cwolves pointed out in a comment on another answer, functions that don't return a value.
function myFunction () {
}
alert(myFunction());//undefined
A null usually has to be intentionally set on a variable or property (see comments for a case in which it can appear without having been set). In addition a null is of type object
and undefined is of type undefined
.
I should also note that null is valid in JSON but undefined is not:
JSON.parse(undefined); //syntax error
JSON.parse(null); //null
Here is the simple method which I used to test the service, without any additional "Debug" methods and with integrated VS Unit Tests.
[TestMethod]
public void TestMyService()
{
MyService fs = new MyService();
var OnStart = fs.GetType().BaseType.GetMethod("OnStart", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
OnStart.Invoke(fs, new object[] { null });
}
// As an extension method
public static void Start(this ServiceBase service, List<string> parameters)
{
string[] par = parameters == null ? null : parameters.ToArray();
var OnStart = service.GetType().GetMethod("OnStart", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
OnStart.Invoke(service, new object[] { par });
}
I like the approach of using a table with a column for each global variable. This way you get autocomplete to aid in coding the retrieval of the variable. The table can be restricted to a single row as outlined here: SQL Server: how to constrain a table to contain a single row?
If you are not using maven, then you will need **
The difference is primarily in deployment. Web forward and reverse proxies all have the same underlying features. They accept requests for HTTP requests in various formats and provide a response, usually by accessing the origin or contact server.
Fully featured servers usually have access control, caching, and some link-mapping features.
A forward proxy is a proxy that is accessed by configuring the client machine. The client needs protocol support for proxy features (redirection, proxy authentication, etc.). The proxy is transparent to the user experience, but not to the application.
A reverse proxy is a proxy that is deployed as a web server and behaves like a web server, with the exception that instead of locally composing the content from programs and disk, it forwards the request to an origin server. From the client perspective it is a web server, so the user experience is completely transparent.
In fact, a single proxy instance can run as a forward and reverse proxy at the same time for different client populations.
If a PEM contains only one RSA private key without encryption, it must be an ASN.1 sequence structure including 9 numbers to present a Chinese Remainder Theorem (CRT) key:
We can implement an RSAPrivateCrtKey
:
class RSAPrivateCrtKeyImpl implements RSAPrivateCrtKey {
private static final long serialVersionUID = 1L;
BigInteger n, e, d, p, q, dp, dq, qinv;
@Override
public BigInteger getModulus() {
return n;
}
@Override
public BigInteger getPublicExponent() {
return e;
}
@Override
public BigInteger getPrivateExponent() {
return d;
}
@Override
public BigInteger getPrimeP() {
return p;
}
@Override
public BigInteger getPrimeQ() {
return q;
}
@Override
public BigInteger getPrimeExponentP() {
return dp;
}
@Override
public BigInteger getPrimeExponentQ() {
return dq;
}
@Override
public BigInteger getCrtCoefficient() {
return qinv;
}
@Override
public String getAlgorithm() {
return "RSA";
}
@Override
public String getFormat() {
throw new UnsupportedOperationException();
}
@Override
public byte[] getEncoded() {
throw new UnsupportedOperationException();
}
}
Then read the private key from a PEM file:
import sun.security.util.DerInputStream;
import sun.security.util.DerValue;
static RSAPrivateCrtKey getRSAPrivateKey(String keyFile) {
RSAPrivateCrtKeyImpl prvKey = new RSAPrivateCrtKeyImpl();
try (BufferedReader in = new BufferedReader(new FileReader(keyFile))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
// skip "-----BEGIN/END RSA PRIVATE KEY-----"
if (!line.startsWith("--") || !line.endsWith("--")) {
sb.append(line);
}
}
DerInputStream der = new DerValue(Base64.
getDecoder().decode(sb.toString())).getData();
der.getBigInteger(); // 0
prvKey.n = der.getBigInteger();
prvKey.e = der.getBigInteger(); // 65537
prvKey.d = der.getBigInteger();
prvKey.p = der.getBigInteger();
prvKey.q = der.getBigInteger();
prvKey.dp = der.getBigInteger();
prvKey.dq = der.getBigInteger();
prvKey.qinv = der.getBigInteger();
} catch (IllegalArgumentException | IOException e) {
logger.warn(keyFile + ": " + e.getMessage());
return null;
}
}
Slightly hacky, but it works:
const input = '\text';_x000D_
const output = JSON.stringify(input).replace(/((^")|("$))/g, "").trim();_x000D_
_x000D_
console.log({ input, output });_x000D_
// { input: '\text', output: '\\text' }
_x000D_
You can use something like this scopeValue[field]
, but if your field is in another object you will need another solution.
To solve all kind of situations, you can use this directive:
this.app.directive('dynamicModel', ['$compile', '$parse', function ($compile, $parse) {
return {
restrict: 'A',
terminal: true,
priority: 100000,
link: function (scope, elem) {
var name = $parse(elem.attr('dynamic-model'))(scope);
elem.removeAttr('dynamic-model');
elem.attr('ng-model', name);
$compile(elem)(scope);
}
};
}]);
Html example:
<input dynamic-model="'scopeValue.' + field" type="text">
x_train = x_train.reshape(-1,28, 28, 1) #Reshape for CNN - should work!!
x_test = x_test.reshape(-1,28, 28, 1)
history_cnn = cnn.fit(x_train, y_train, epochs=5, validation_data=(x_test, y_test))
Output:
Train on 60000 samples, validate on 10000 samples Epoch 1/5 60000/60000 [==============================] - 157s 3ms/step - loss: 0.0981 - acc: 0.9692 - val_loss: 0.0468 - val_acc: 0.9861 Epoch 2/5 60000/60000 [==============================] - 157s 3ms/step - loss: 0.0352 - acc: 0.9892 - val_loss: 0.0408 - val_acc: 0.9879 Epoch 3/5 60000/60000 [==============================] - 159s 3ms/step - loss: 0.0242 - acc: 0.9924 - val_loss: 0.0291 - val_acc: 0.9913 Epoch 4/5 60000/60000 [==============================] - 165s 3ms/step - loss: 0.0181 - acc: 0.9945 - val_loss: 0.0361 - val_acc: 0.9888 Epoch 5/5 60000/60000 [==============================] - 168s 3ms/step - loss: 0.0142 - acc: 0.9958 - val_loss: 0.0354 - val_acc: 0.9906
Another one, using git log:
git log -1 --format="%H"
It's very similar to the of @outofculture though a bit shorter.
var lbltext = document.getElementById('*spaM4').innerHTML
This is what worked for me:
.pdf::before {
content: url('path/to/image.png');
display: flex;
align-items: center;
justify-content: center;
height: inherit;
}
ALTER SCHEMA NewSchema TRANSFER [OldSchema].[TableName]
I always have to use the brackets when I use the ALTER SCHEMA
query in SQL, or I get an error message.
It is possible. But you have to hack it a little, there is a code What you have to do is to run stand alone server and "patch" RemoteWebDriver
public class CustomRemoteWebDriver : RemoteWebDriver
{
public static bool newSession;
public static string capPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles", "tmp", "sessionCap");
public static string sessiodIdPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles", "tmp", "sessionid");
public CustomRemoteWebDriver(Uri remoteAddress)
: base(remoteAddress, new DesiredCapabilities())
{
}
protected override Response Execute(DriverCommand driverCommandToExecute, Dictionary<string, object> parameters)
{
if (driverCommandToExecute == DriverCommand.NewSession)
{
if (!newSession)
{
var capText = File.ReadAllText(capPath);
var sidText = File.ReadAllText(sessiodIdPath);
var cap = JsonConvert.DeserializeObject<Dictionary<string, object>>(capText);
return new Response
{
SessionId = sidText,
Value = cap
};
}
else
{
var response = base.Execute(driverCommandToExecute, parameters);
var dictionary = (Dictionary<string, object>) response.Value;
File.WriteAllText(capPath, JsonConvert.SerializeObject(dictionary));
File.WriteAllText(sessiodIdPath, response.SessionId);
return response;
}
}
else
{
var response = base.Execute(driverCommandToExecute, parameters);
return response;
}
}
}
Just use DROP TABLE IF EXISTS
:
DROP TABLE IF EXISTS `foo`;
CREATE TABLE `foo` ( ... );
Try searching the MySQL documentation first if you have any other problems.
$.ajax({
url: 'http://url.of.my.server/submit',
dataType: "jsonp",
jsonp: 'callback',
jsonpCallback: 'jsonp_callback'
});
jsonp is the querystring parameter name that is defined to be acceptable by the server while the jsonpCallback is the javascript function name to be executed at the client.
When you use such url:
url: 'http://url.of.my.server/submit?callback=?'
the question mark ? at the end instructs jQuery to generate a random function while the predfined behavior of the autogenerated function will just invoke the callback -the sucess function in this case- passing the json data as a parameter.
$.ajax({
url: 'http://url.of.my.server/submit?callback=?',
success: function (data, status) {
mySurvey.closePopup();
},
error: function (xOptions, textStatus) {
mySurvey.closePopup();
}
});
The same goes here if you are using $.getJSON with ? placeholder it will generate a random function while the predfined behavior of the autogenerated function will just invoke the callback:
$.getJSON('http://url.of.my.server/submit?callback=?',function(data){
//process data here
});
df.set_index('Mid').reset_index()
seems to be a pretty easy way about this.
First of all, the easiest way to run things at startup is to add them to the file /etc/rc.local
.
Another simple way is to use @reboot
in your crontab. Read the cron manpage for details.
However, if you want to do things properly, in addition to adding a script to /etc/init.d
you need to tell ubuntu when the script should be run and with what parameters. This is done with the command update-rc.d
which creates a symlink from some of the /etc/rc*
directories to your script. So, you'd need to do something like:
update-rc.d yourscriptname start 2
However, real init scripts should be able to handle a variety of command line options and otherwise integrate to the startup process. The file /etc/init.d/README
has some details and further pointers.
I know this is old, but here is a one liner solution:
const hourDiff = start.diff(end, "hours");
Where start and end are moment objects.
Enjoy!
I would use a decimal with the proper precision for your data.
I got around this by upgrading both the version of Angular that I was using (from v8 -> v9) and the version of TypeScript (from 3.5.3 -> latest).
Are you using the Team Synchronise view? If so that's the problem. Conflict resolution in the Team Synchronise view doesn't work with EGit. Instead you need to use the Git Repository view.
Open the Git perspective. In the Git Repository view, go to on Branches ? Local ? master and right click ? Merge...
It should auto select Remote Tracking ? origin/master
. Press Merge.
It should show result:conflict
.
Open the conflicting files. They should have an old sk000l >>>> ===== <<<< style merge conflict in the files. Edit the file to resolve the conflict, and save.
Now in the 'Git Staging' view, it should show the changed file in 'Unstaged Changes'. Right click and 'Add to Index'
Repeat for any remaining files.
Now from the 'git staging' view, commit and push. As Git/Eclipse now knows that you have merged the remote origin changes into your master, you should avoid the non-fast-forward error.
Here's a possible solution.
HTML
<img id="source" src="http://www.byui.edu/images/agriculture-life-sciences/flower.jpg" />
<div id="crop">
<img id="overlay" src="http://www.byui.edu/images/agriculture-life-sciences/flower.jpg" />
</div>
CSS
#crop {
overflow: hidden;
position: absolute;
left: 100px;
top: 100px;
width: 450px;
height: 150px;
}
#overlay {
-webkit-filter:blur(4px);
filter:blur(4px);
width: 450px;
}
#source {
height: 300px;
width: auto;
position: absolute;
left: 100px;
top: 100px;
}
I know the CSS can be simplified and you probably should get rid of the ids. The idea here is to use a div as a cropping container and then apply blur on duplicate of the image. Fiddle
To make this work in Firefox, you would have to use SVG hack.
So in order to achieve a desired output, we should first know how the function works.
The syntax for join()
method as described in the python documentation is as follows:
string_name.join(iterable)
Things to be noted:
string
concatenated with the elements of iterable
. The separator between the elements being the string_name
. iterable
will raise a TypeError
Now, to add white spaces, we just need to replace the string_name
with a " "
or a ' '
both of them will work and place the iterable
that we want to concatenate.
So, our function will look something like this:
' '.join(my_list)
But, what if we want to add a particular number of white spaces
in between our elements in the iterable
?
We need to add this:
str(number*" ").join(iterable)
here, the number
will be a user input.
So, for example if number=4
.
Then, the output of str(4*" ").join(my_list)
will be how are you
, so in between every word there are 4 white spaces.
PATTERN FORMAT
A blank line matches no files, so it can serve as a separator for readability.
A line starting with #
serves as a comment.
An optional prefix !
which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.
If the pattern ends with a slash, it is removed for the purpose of the following description, but it would only find a match with a directory. In other words, foo/
will match a directory foo
and paths underneath it, but will not match a regular file or a symbolic link foo
(this is consistent with the way how pathspec works in general in git).
If the pattern does not contain a slash /
, git treats it as a shell glob pattern and checks for a match against the pathname relative to the location of the .gitignore
file (relative to the toplevel of the work tree if not from a .gitignore
file).
Otherwise, git treats the pattern as a shell glob suitable for consumption by fnmatch(3)
with the FNM_PATHNAME
flag: wildcards in the pattern will not match a /
in the pathname. For example, Documentation/*.html
matches Documentation/git.html
but not Documentation/ppc/ppc.html
or tools/perf/Documentation/perf.html
.
A leading slash matches the beginning of the pathname. For example, /*.c
matches cat-file.c
but not mozilla-sha1/sha1.c
.
git help gitignore
or
man gitignore
I wanna Disable an Input Field on a form and when i submit the form the values from the disabled form is not submitted.
Use Case: i am trying to get Lat Lng from Google Map and wanna Display it.. but dont want the user to edit it.
You can use the readonly
property in your input field
<input type="text" readonly="readonly" />
I had the same issue while adding firebase to my Ionic App. To fix the issue I followed these steps:
npm install @angular/fire firebase --save
In my app/app.module.ts:
...
import { AngularFireModule } from '@angular/fire';
import { environment } from '../environments/environment';
import { AngularFirestoreModule, SETTINGS } from '@angular/fire/firestore';
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [
BrowserModule,
AppRoutingModule,
AngularFireModule.initializeApp(environment.firebase),
AngularFirestoreModule
],
providers: [
{ provide: SETTINGS, useValue: {} }
],
bootstrap: [AppComponent]
})
Previously we used FirestoreSettingsToken instead of SETTINGS. But that bug got resolved, now we use SETTINGS. (link)
In my app/services/myService.ts I imported as:
import { AngularFirestore } from "@angular/fire/firestore";
For some reason vscode was importing it as "@angular/fire/firestore/firestore";I After changing it for "@angular/fire/firestore"; the issue got resolved!
There isn't a 'correct way'. They're all syntactically correct, though there are some conventions. You could follow the Google style guide, although there are others out there.
From said guide:
Regular functions have mixed case; accessors and mutators match the name of the variable: MyExcitingFunction(), MyExcitingMethod(), my_exciting_member_variable(), set_my_exciting_member_variable().
It's an old question but it worth to mention that in Angular 1.4 $httpParamSerializer is added and when using $http.post, if we use $httpParamSerializer(params) to pass the parameters, everything works like a regular post request and no JSON deserializing is needed on server side.
https://docs.angularjs.org/api/ng/service/$httpParamSerializer
Boolean("true") will do the work too
#footer ul li {
position: relative;
opacity: 0.99;
}
#footer ul li::before {
content: "";
position: absolute;
width: 100%;
height: 100%;
z-index: -1;
background: url(/images/arrow.png) no-repeat 0 50%;
opacity: 0.5;
}
Hack with opacity .99 (less than 1) creates z-index context so you can not worry about global z-index values. (Try to remove it and see what happens in the next demo where parent wrapper has positive z-index.)
If your element already has z-index, then you don't need this hack.
In my case failure was caused by com.android.providers.media
app. I faced this on x86 android emulator. What did I do:
$ adb shell df
Filesystem Size Used Free Blksize
...
/data 224M 209M 14M 4096
....
Too low free space on /data
$ adb shell du /data
...
409870 /data/data/com.android.providers.media
...
Almost all was consumed by single app! It's system app so I consider better not to delete it. Instead I cleaned up app data.
$ adb shell pm clear com.android.providers.media
Success
$ adb shell df
Filesystem Size Used Free Blksize
...
/data 224M 8M 215M 4096
...
Disk was cleared and app installed successfully.
If you use pandas, you can append your dataframes to an existing CSV file this way:
df.to_csv('log.csv', mode='a', index=False, header=False)
With mode='a' we ensure that we append, rather than overwrite, and with header=False we ensure that we append only the values of df rows, rather than header + values.
You can create one with:-
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
var date = new Date();
console.log(date.addDays(5));
_x000D_
This takes care of automatically incrementing the month if necessary. For example:
8/31 + 1 day will become 9/1.
The problem with using setDate
directly is that it's a mutator and that sort of thing is best avoided. ECMA saw fit to treat Date
as a mutable class rather than an immutable structure.
I would suggest reading this for a specific answer. The conclusion of the article is that using for loop is generally better and faster than the foreach loop.
This is great for creating sample data. Example: put all testing data in a directory called "test-create-volume-123", then after your test is done, zap the entire directory. By generating exactly three digits, you don't have weird sorting issues.
printf '%02d\n' $((1 + RANDOM % 100))
This scales down, e.g. to one digit:
printf '%01d\n' $((1 + RANDOM % 10))
It scales up, but only to four digits. See above as to why :)
Use the following code it worked for me:
# Create the figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Generate the values
x_vals = X_iso[:, 0:1]
y_vals = X_iso[:, 1:2]
z_vals = X_iso[:, 2:3]
# Plot the values
ax.scatter(x_vals, y_vals, z_vals, c = 'b', marker='o')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
plt.show()
while X_iso is my 3-D array and for X_vals, Y_vals, Z_vals I copied/used 1 column/axis from that array and assigned to those variables/arrays respectively.
Better
if ! wget -q --spider --tries=10 --timeout=20 google.com
then
echo 'Sorry you are Offline'
exit 1
fi
You might use flush
to force validation constraints to be realised and detected in a known place rather than when the transaction is committed. It may be that commit
gets called implicitly by some framework logic, through declarative logic, the container, or by a template. In this case, any exception thrown may be difficult to catch and handle (it could be too high in the code).
For example, if you save()
a new EmailAddress object, which has a unique constraint on the address, you won't get an error until you commit.
Calling flush()
forces the row to be inserted, throwing an Exception if there is a duplicate.
However, you will have to roll back the session after the exception.
Either use instanceof
or method Class.isAssignableFrom(Class<?> cls)
.
When reading sp_lock information, use the OBJECT_NAME( ) function to get the name of a table from its ID number, for example:
SELECT object_name(16003073)
EDIT :
There is another proc provided by microsoft which reports objects without the ID translation : http://support.microsoft.com/kb/q255596/
Your only option is to somehow clone the object.
See this stackoverflow question on how you can achieve this.
For simple JSON objects, the simplest way would be:
var newObject = JSON.parse(JSON.stringify(oldObject));
if you use jQuery, you can use:
// Shallow copy
var newObject = jQuery.extend({}, oldObject);
// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);
UPDATE 2017: I should mention, since this is a popular answer, that there are now better ways to achieve this using newer versions of javascript:
In ES6 or TypeScript (2.1+):
var shallowCopy = { ...oldObject };
var shallowCopyWithExtraProp = { ...oldObject, extraProp: "abc" };
Note that if extraProp
is also a property on oldObject, its value will not be used because the extraProp : "abc"
is specified later in the expression, which essentially overrides it. Of course, oldObject will not be modified.
There some kind of old school 'Marxismic' way to the cast int -> bool without C4800 warnings of Microsoft's cl compiler - is to use negation of negation.
int i = 0;
bool bi = !!i;
int j = 1;
bool bj = !!j;
I had let this go for a good while but revisited it later. Since this question is viewed regularly. This is eventually what I ended up using that worked for me.
define("DOC_ROOT","/path/to/html");
//username and password of account
$username = trim($values["email"]);
$password = trim($values["password"]);
//set the directory for the cookie using defined document root var
$path = DOC_ROOT."/ctemp";
//build a unique path with every request to store. the info per user with custom func. I used this function to build unique paths based on member ID, that was for my use case. It can be a regular dir.
//$path = build_unique_path($path); // this was for my use case
//login form action url
$url="https://www.example.com/login/action";
$postinfo = "email=".$username."&password=".$password;
$cookie_file_path = $path."/cookie.txt";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_NOBODY, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
//set the cookie the site has for certain features, this is optional
curl_setopt($ch, CURLOPT_COOKIE, "cookiename=0");
curl_setopt($ch, CURLOPT_USERAGENT,
"Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.7.12) Gecko/20050915 Firefox/1.0.7");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $_SERVER['REQUEST_URI']);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postinfo);
curl_exec($ch);
//page with the content I want to grab
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/page/");
//do stuff with the info with DomDocument() etc
$html = curl_exec($ch);
curl_close($ch);
Update: This code was never meant to be a copy and paste. It was to show how I used it for my specific use case. You should adapt it to your code as needed. Such as directories, vars etc
If you have standart output redirect to "nohup.out" just see who use this file
lsof | grep nohup.out
You can write your query like this.
var query = from t1 in myTABLE1List // List<TABLE_1>
join t2 in myTABLE1List
on t1.ColumnA equals t2.ColumnA
and t1.ColumnB equals t2.ColumnA
If you want to compare your column with multiple columns.
SQL Management Studio => Tools => SQL Server profiler
File => New Trace...
Use the Template => Blank
Event selection => T-SQL
Lefthandside check for: SP.StmtComplete
Column filters can be used to select a specific ApplicationName or DatabaseName
Start that profile running then trigger the query.
Click here for Source information
sure,
just have to create a ".gitignore" on the home directory of your project and have to contain
*.swp
that's it
in one command
project-home-directory$ echo '*.swp' >> .gitignore
LINQ is very effective and easy to use on Lists rather than DataTable. I can see the above answers have a loop(for, foreach), which I will not prefer.
So the best thing to select a perticular column from a DataTable is just use a DataView to filter the column and use it as you want.
Find it here how to do this.
DataView dtView = new DataView(dtYourDataTable);
DataTable dtTableWithOneColumn= dtView .ToTable(true, "ColumnA");
Now the DataTable dtTableWithOneColumn contains only one column(ColumnA).
I am using ui-router and my code looks like this:
$rootScope.$on('$stateChangeSuccess', function(event, toState, toParams){
/* Google analytics */
var path = toState.url;
for(var i in toParams){
path = path.replace(':' + i, toParams[i]);
}
/* global ga */
ga('send', 'pageview', path);
});
This way I can track different states. Maybe someone will find it usefull.
SELECT
table1.*
, table2.*
INNER JOIN table2 ON table2.SomeFkId = table1.SomeId
That gets you a result set where child rows in table2 cause duplication by returning the table1 results for each child row in table2. O/R mappers should differentiate table1 instances based on a unique key field, then use all the table2 columns to populate child instances.
SELECT table1.*
SELECT table2.* WHERE SomeFkId = #
The N+1 is where the first query populates the primary object and the second query populates all the child objects for each of the unique primary objects returned.
Consider:
class House
{
int Id { get; set; }
string Address { get; set; }
Person[] Inhabitants { get; set; }
}
class Person
{
string Name { get; set; }
int HouseId { get; set; }
}
and tables with a similar structure. A single query for the address "22 Valley St" may return:
Id Address Name HouseId
1 22 Valley St Dave 1
1 22 Valley St John 1
1 22 Valley St Mike 1
The O/RM should fill an instance of Home with ID=1, Address="22 Valley St" and then populate the Inhabitants array with People instances for Dave, John, and Mike with just one query.
A N+1 query for the same address used above would result in:
Id Address
1 22 Valley St
with a separate query like
SELECT * FROM Person WHERE HouseId = 1
and resulting in a separate data set like
Name HouseId
Dave 1
John 1
Mike 1
and the final result being the same as above with the single query.
The advantages to single select is that you get all the data up front which may be what you ultimately desire. The advantages to N+1 is query complexity is reduced and you can use lazy loading where the child result sets are only loaded upon first request.
In the Rails console, the variable app holds a session object on which you can call path and URL helpers as instance methods.
app.users_path
No, it is better practice to leave them out.
Without strip(), you can have empty keys and values:
apples<tab>round, fruity things
oranges<tab>round, fruity things
bananas<tab>
Without strip(), bananas is present in the dictionary but with an empty string as value. With strip(), this code will throw an exception because it strips the tab of the banana line.
My windows solution:
Go here and download and unzip to an easy location:
http://developer.android.com/sdk/win-usb.html#top
Right click 'My Computer' or 'Computer'
Select properties
Select Device manager
Look for your device. It should have a yellow mark above it.
Click 'update driver software'.
select browse my computer for driver software.
select the usb_driver folder you saved earlier.
install it
and wala. magic.
I needed to kill processes on different ports so I created a bash script:
killPort() {
PID=$(echo $(lsof -n -i4TCP:$1) | awk 'NR==1{print $11}')
kill -9 $PID
}
Just add that to your .bashrc and run it like this:
killPort 8080
You can pass whatever port number you wish
Another possibility would be to use pidof
it usually comes with most distributions. It will return you the PID of a given process by using it's name.
pidof process_name
This way you could store that information in a variable and execute kill -9
on it.
#!/bin/bash
pid=`pidof process_name`
kill -9 $pid
I've just got this working. You can use the AWS SDK for PHP like this:
use Aws\S3\S3Client;
$sourceBucket = '*** Your Source Bucket Name ***';
$sourceKeyname = '*** Your Source Object Key ***';
$targetBucket = '*** Your Target Bucket Name ***';
$targetKeyname = '*** Your Target Key Name ***';
// Instantiate the client.
$s3 = S3Client::factory();
// Copy an object.
$s3->copyObject(array(
'Bucket' => $targetBucket,
'Key' => $targetKeyname,
'CopySource' => "{$sourceBucket}/{$sourceKeyname}",
));
http://docs.aws.amazon.com/AmazonS3/latest/dev/CopyingObjectUsingPHP.html
While AngularJS allows you to get a hand on a click event (and thus a target of it) with the following syntax (note the $event
argument to the setMaster
function; documentation here: http://docs.angularjs.org/api/ng.directive:ngClick):
function AdminController($scope) {
$scope.setMaster = function(obj, $event){
console.log($event.target);
}
}
this is not very angular-way of solving this problem. With AngularJS the focus is on the model manipulation. One would mutate a model and let AngularJS figure out rendering.
The AngularJS-way of solving this problem (without using jQuery and without the need to pass the $event
argument) would be:
<div ng-controller="AdminController">
<ul class="list-holder">
<li ng-repeat="section in sections" ng-class="{active : isSelected(section)}">
<a ng-click="setMaster(section)">{{section.name}}</a>
</li>
</ul>
<hr>
{{selected | json}}
</div>
where methods in the controller would look like this:
$scope.setMaster = function(section) {
$scope.selected = section;
}
$scope.isSelected = function(section) {
return $scope.selected === section;
}
Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/WXJ3p/15/
git commit
record your changes to the local repository.
git push
update the remote repository with your local changes.
How many thousands of users?
I've run some TCP/IP client/server connection tests in the past on Windows 2003 Server and managed more than 70,000 connections on a reasonably low spec VM. (see here for details: http://www.lenholgate.com/blog/2005/10/the-64000-connection-question.html). I would be extremely surprised if Windows 2008 Server is limited to less than 2003 Server and, IMHO, the posting that Cloud links to is too vague to be much use. This kind of question comes up a lot, I blogged about why I don't really think that it's something that you should actually worry about here: http://www.serverframework.com/asynchronousevents/2010/12/one-million-tcp-connections.html.
Personally I'd test it and see. Even if there is no inherent limit in the Windows 2008 Server version that you intend to use there will still be practical limits based on memory, processor speed and server design.
If you want to run some 'generic' tests you can use my multi-client connection test and the associated echo server. Detailed here: http://www.lenholgate.com/blog/2005/11/windows-tcpip-server-performance.html and here: http://www.lenholgate.com/blog/2005/11/simple-echo-servers.html. These are what I used to run my own tests for my server framework and these are what allowed me to create 70,000 active connections on a Windows 2003 Server VM with 760MB of memory.
Edited to add details from the comment below...
If you're already thinking of multiple servers I'd take the following approach.
Use the free tools that I link
to and prove to yourself that you
can create a reasonable number of
connections onto your target OS
(beware of the Windows limits on
dynamic ports which may cause your
client connections to fail, search
for MAX_USER_PORT
).
during development regularly test your actual server with test clients that can create connections and actually 'do something' on the server. This will help to prevent you building the server in ways that restrict its scalability. See here: http://www.serverframework.com/asynchronousevents/2010/10/how-to-support-10000-or-more-concurrent-tcp-connections-part-2-perf-tests-from-day-0.html
while (itr.hasNext()) {
Vehicle vc=(Vehicle) itr.next();
if(vc.getVehicleType().equalsIgnoreCase(s)) {
count++;
}
}
FYI for those that are trying to create a package installer for a bundle or plugin, it's easy:
pkgbuild --component "Color Lists.colorPicker" --install-location ~/Library/ColorPickers ColorLists.pkg
If you look closely at the second output you can see that the new location for the libraries is used. Maybe there are still missing libraries that are part of the glibc.
I also think that all the libraries used by your program should be compiled against that version of glibc. If you have access to the source code of the program, a fresh compilation appears to be the best solution.
You can't set the value
of a file
input in the markup, like you did with value="123"
.
This example shows that it really works: http://jsfiddle.net/marcosfromero/7bUba/
Generally, you can use the func(*tuple)
syntax. You can even pass a part of the tuple, which seems like what you're trying to do here:
t = (2010, 10, 2, 11, 4, 0, 2, 41, 0)
dt = datetime.datetime(*t[0:7])
This is called unpacking a tuple, and can be used for other iterables (such as lists) too. Here's another example (from the Python tutorial):
>>> range(3, 6) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args) # call with arguments unpacked from a list
[3, 4, 5]
Oracle has various combinations of b-tree, bitmap, partitioned and non-partitioned, reverse byte, bitmap join, and domain indexes.
Here's a link to the 11gR1 documentation on the subject: http://download.oracle.com/docs/cd/B28359_01/server.111/b28274/data_acc.htm#PFGRF004
The transforms you apply to data to make it safe for inclusion in an SQL statement are completely different from those you apply for inclusion in HTML are completely different from those you apply for inclusion in Javascript are completely different from those you apply for inclusion in LDIF are completely different from those you apply to inclusion in CSS are completely different from those you apply to inclusion in an Email....
By all means validate input - decide whether you should accept it for further processing or tell the user it is unacceptable. But don't apply any change to representation of the data until it is about to leave PHP land.
A long time ago someone tried to invent a one-size fits all mechanism for escaping data and we ended up with "magic_quotes" which didn't properly escape data for all output targets and resulted in different installation requiring different code to work.
Smells like more homework. My very very old graphing calculator had a is prime program like this. Technnically the inner devision checking loop only needs to run to i^(1/2). Do you need to find "all" prime numbers between 0 and L ? The other major problem is that your loop variables are "int" while your input data is "long", this will be causing an overflow making your loops fail to execute even once. Fix the loop variables.
Take away the spaces. So do:
matches <- unique(grep("A1|A9|A6", myfile$Letter, value=TRUE, fixed=TRUE))
If you want to use the same port number then type kill %
in the terminal, which kills the current background process and frees up the port for further usage.
There are errors here :
var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");
The code must change to:
var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");
By the way, there is another error at line 129 :
var createLi.appendChild(createSubList);
Replace it with:
createLi.appendChild(createSubList);
Tried a lot of things, it did not help.
It get access in a simple way:
eval $(ssh-agent) > /dev/null
killall ssh-agent
eval `ssh-agent`
ssh-add ~/.ssh/id_rsa
Note that at the end of the ssh-add -L
output must be not a path to the key, but your email.
in the latest version of android studio, you can just do:
./gradlew assembleRelease
or aR
for short. This will produce an unsigned release apk. Building a signed apk can be done similarly or you can use Build -> Generate Signed Apk in Android Studio.
Here is my build.gradle for reference:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.5.+'
}
}
apply plugin: 'android'
dependencies {
compile fileTree(dir: 'libs', include: '*.jar')
}
android {
compileSdkVersion 17
buildToolsVersion "17.0.0"
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
aidl.srcDirs = ['src']
renderscript.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
}
// Move the tests to tests/java, tests/res, etc...
instrumentTest.setRoot('tests')
// Move the build types to build-types/<type>
// For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
// This moves them out of them default location under src/<type>/... which would
// conflict with src/ being used by the main source set.
// Adding new build types or product flavors should be accompanied
// by a similar customization.
debug.setRoot('build-types/debug')
release.setRoot('build-types/release')
}
buildTypes {
release {
}
}
It will depend of your php version. Check it running:
php -version
Now, according to your current version, run:
sudo apt-get install php7.2-mysql
This is a later answer that works for me, if it may be of use to anyone in the future. I wanted a simple border around all four sides of the grid and I achieved it like so...
<DataGrid x:Name="dgDisplay" Margin="5" BorderBrush="#1266a7" BorderThickness="1"...
As mentioned in this tutorial, it's as simple as:
To install
brew install gradle
To upgrade
brew upgrade gradle
(using Homebrew of course)
Also see (finally) updated docs.
Cheers :)!
I've found FileFormat.info's Unicode Character Search to be most helpful in finding exact character codes.
Entering simply '
(the character to the left of the return key on my US Mac keyboard) into their search yields several results of various curls and languages.
I would presume the original question was asking for the typographically correct U+02BC '
, rather than the typewriter fascimile U+0027 '
.
The W3C recommends hex codes for HTML entities (see below). For U+02BC that would be ʼ
, rather than '
for U+0027.
http://www.w3.org/International/questions/qa-escapes
Using character escapes in markup and CSS
Hex vs. decimal. Typically when the Unicode Standard refers to or lists characters it does so using a hexadecimal value. … Given the prevalence of this convention, it is often useful, though not required, to use hexadecimal numeric values in escapes rather than decimal values…
http://www.w3.org/TR/html4/charset.html
5 HTML Document Representation … 5.4 Undisplayable characters
…If missing characters are presented using their numeric representation, use the hexadecimal (not decimal) form, since this is the form used in character set standards.
If you are trying to run some dynamically generated JavaScript, you would be slightly better off by using eval
. However, JavaScript is such a dynamic language that you really should not have a need for that.
If the script is static, then Rocket's getScript
-suggestion is the way to go.
Had the same problem on Windows 10. The user's %Path% environment already had the required "C:\Users\ user \AppData\Roaming\npm".
path command would not show it, but it did show tons of other paths added earlier by other installations.
Turned out I needed to delete some of them from the system's PATH environment variable.
As far as I understand this happens because there's a length limit on these variables: https://software.intel.com/en-us/articles/limitation-to-the-length-of-the-system-path-variable
Probably happens often on dev machines who install lots of stuff that needs to be in the PATH.
Overloading is the concept in which you have same signatures or methods with same name but different parameters and overriding, we have same name methods with different parameters also have inheritance is known as overriding.
I don't think you should use the data
option, because this does more than just setting a default value.
You're also overriding any data that's being passed to the form during creation. So basically, you're breaking
support for that feature. - Which might not matter when you're letting the user create data, but does matter when you
want to (someday) use the form for updating data.
See http://symfony.com/doc/current/reference/forms/types/choice.html#data
I believe it would be better to pass any default data during form creation. In the controller.
For example, you can pass in a class and define the default value in your class itself.
(when using the default Symfony\Bundle\FrameworkBundle\Controller\Controller
)
$form = $this->createForm(AnimalType::class, [
'species' => 174 // this id might be substituted by an entity
]);
Or when using objects:
$dog = new Dog();
$dog->setSpecies(174); // this id might be substituted by an entity
$form = $this->createForm(AnimalType::class, $dog);
Even better when using a factory: (where dog probably extends from animal)
$form = $this->createForm(AnimalType::class, DogFactory::create());
This will enable you to separate form structure and content from each other and make your form reusable in more situations.
Or, use the preferred_choices
option, but this has the side effect of moving the default option to the top of your form.
See: http://symfony.com/doc/current/reference/forms/types/choice.html#preferred-choices
$builder->add(
'species',
'entity',
[
'class' => 'BFPEduBundle:Item',
'property' => 'name',
'query_builder' => ...,
'preferred_choices' => [174] // this id might be substituted by an entity
]
);
I got a solution for you, Why dont you rather use Explode if your url is something like
Url-> website.com/test/blog.php
$StringExplo=explode("/",$_SERVER['REQUEST_URI']);
$HeadTo=$StringExplo[0]."/Index.php";
Header("Location: ".$HeadTo);
Sublime Text -> Preferences -> Setting:
Write your style in right screen:
Here the code to use your app.js
input specifies file name
res.download(__dirname+'/'+input);
Here's another one in case you don't want to use Collectors.toMap()
Map<String, Choice> result =
choices.stream().collect(HashMap<String, Choice>::new,
(m, c) -> m.put(c.getName(), c),
(m, u) -> {});
From the Bootstrap Docs:
<!--Activate a modal without writing JavaScript. Set data-toggle="modal" on a
controller element, like a button, along with a data-target="#foo" or href="#foo"
to target a specific modal to toggle.-->
<button type="button" data-toggle="modal" data-target="#myModal">Launch modal</button>
Have you tried rewording your query like this?
@Query("SELECT DISTINCT p.name FROM People p WHERE p.name NOT IN ?1")
List<String> findNonReferencedNames(List<String> names);
Note, I'm assuming your entity class is named People
, and not people
.
Corrected a few things and added an alternative select - delete as appropriate.
DELIMITER |
CREATE PROCEDURE getNearestCities
(
IN p_cityID INT -- should this be int unsigned ?
)
BEGIN
DECLARE cityLat FLOAT; -- should these be decimals ?
DECLARE cityLng FLOAT;
-- method 1
SELECT lat,lng into cityLat, cityLng FROM cities WHERE cities.cityID = p_cityID;
SELECT
b.*,
HAVERSINE(cityLat,cityLng, b.lat, b.lng) AS dist
FROM
cities b
ORDER BY
dist
LIMIT 10;
-- method 2
SELECT
b.*,
HAVERSINE(a.lat, a.lng, b.lat, b.lng) AS dist
FROM
cities AS a
JOIN cities AS b on a.cityID = p_cityID
ORDER BY
dist
LIMIT 10;
END |
delimiter ;
XOR is a binary operation, it stands for "exclusive or", that is to say the resulting bit evaluates to one if only exactly one of the bits is set.
This is its function table:
a | b | a ^ b
--|---|------
0 | 0 | 0
0 | 1 | 1
1 | 0 | 1
1 | 1 | 0
This operation is performed between every two corresponding bits of a number.
Example: 7 ^ 10
In binary: 0111 ^ 1010
0111
^ 1010
======
1101 = 13
Properties: The operation is commutative, associative and self-inverse.
It is also the same as addition modulo 2.
Use button.layer.cornerRadius
, button.layer.borderColor
and button.layer.borderWidth
.
Note that borderColor
requires a CGColor
, so you could say (Swift 3/4):
button.backgroundColor = .clear
button.layer.cornerRadius = 5
button.layer.borderWidth = 1
button.layer.borderColor = UIColor.black.cgColor
or programmaticaly
String s = String.class.getName();
s = s.substring(s.lastIndexOf('.') + 1);
<ul>
<li><strong>This text will be bold.</strong>This text will NOT be bold.
</li>
</ul>
There is not currently any way to style HTML5 <audio>
players using CSS. Instead, you can leave off the control
attribute, and implement your own controls using Javascript. If you don't want to implement them all on your own, I'd recommend using an existing themeable HTML5 audio player, such as jPlayer.
Simple way
@{
Model.CRN = ViewBag.CRN;
}
@Html.HiddenFor(x => x.CRN)
If anyone wants to use purely Java configuration instead of xml
configuration of hibernate, use this:
You can configure Hibernate without using persistence.xml at all in Spring like like this:
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean()
{
Map<String, Object> properties = new Hashtable<>();
properties.put("javax.persistence.schema-generation.database.action",
"none");
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setDatabasePlatform("org.hibernate.dialect.MySQL5InnoDBDialect"); //you can change this if you have a different DB
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(adapter);
factory.setDataSource(this.springJpaDataSource());
factory.setPackagesToScan("package name");
factory.setSharedCacheMode(SharedCacheMode.ENABLE_SELECTIVE);
factory.setValidationMode(ValidationMode.NONE);
factory.setJpaPropertyMap(properties);
return factory;
}
Since you are not using persistence.xml, you should create a bean that returns DataSource which you specify in the above method that sets the data source:
@Bean
public DataSource springJpaDataSource()
{
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl("jdbc:mysql://localhost/SpringJpa");
dataSource.setUsername("tomcatUser");
dataSource.setPassword("password1234");
return dataSource;
}
Then you use @EnableTransactionManagement
annotation over this configuration file. Now when you put that annotation, you have to create one last bean:
@Bean
public PlatformTransactionManager jpaTransactionManager()
{
return new JpaTransactionManager(
this.entityManagerFactoryBean().getObject());
}
Now, don't forget to use @Transactional
Annotation over those method that deal with DB.
Lastly, don't forget to inject EntityManager
in your repository (This repository class should have @Repository
annotation over it).
You don't need to change the compliance level here, or rather, you should but that's not the issue.
The code compliance ensures your code is compatible with a given Java version.
For instance, if you have a code compliance targeting Java 6, you can't use Java 7's or 8's new syntax features (e.g. the diamond, the lambdas, etc. etc.).
The actual issue here is that you are trying to compile something in a Java version that seems different from the project dependencies in the classpath.
Instead, you should check the JDK/JRE you're using to build.
In Eclipse, open the project properties and check the selected JRE in the Java build path.
If you're using custom Ant (etc.) scripts, you also want to take a look there, in case the above is not sufficient per se.
You need to include inttypes.h
if you want all those nifty new format specifiers for the intN_t
types and their brethren, and that is the correct (ie, portable) way to do it, provided your compiler complies with C99. You shouldn't use the standard ones like %d
or %u
in case the sizes are different to what you think.
It includes stdint.h
and extends it with quite a few other things, such as the macros that can be used for the printf/scanf
family of calls. This is covered in section 7.8 of the ISO C99 standard.
For example, the following program:
#include <stdio.h>
#include <inttypes.h>
int main (void) {
uint32_t a=1234;
uint16_t b=5678;
printf("%" PRIu32 "\n",a);
printf("%" PRIu16 "\n",b);
return 0;
}
outputs:
1234
5678
If I remember rightly, then adding an unload() event means that page cannot be cached (in forward/backward cache) - because it's state changes/may change when user navigates away. So - it is not safe to restore the last-second state of the page when returning to it by navigating through history object.
If its a mismatch of a dependencies dependencies, go to the NuGet package manager at the solution level and check the Update and Consolidate tabs, harmonise it all.
My solution is adding an UIView as a container for the cell subviews. Then set this UIView constraints (top,bottom,trailing,leading) to 0 points. And all the unnecessary mass go away.the image showing the logic
You have #include "fun.cpp"
in mainfile.cpp
so compiling with:
g++ -o hw1 mainfile.cpp
will work, however if you compile by linking these together like
g++ -g -std=c++11 -Wall -pedantic -c -o fun.o fun.cpp
g++ -g -std=c++11 -Wall -pedantic -c -o mainfile.o mainfile.cpp
As they mention above, adding #include "fun.hpp"
will need to be done or it won't work. However, your case with the funct()
function is slightly different than my problem.
I had this issue when doing a HW assignment and the autograder compiled by the lower bash recipe, yet locally it worked using the upper bash.
Thanks for the info, think I see the problem. This is a bug in hive-go
that only shows up when you add a host. The last lines of it are:
app.listen(3001);
console.log("... port %d in %s mode", app.address().port, app.settings.env);
When you add the host on the first line, it is crashing when it calls app.address().port
.
The problem is the potentially asynchronous nature of .listen()
. Really it should be doing that console.log
call inside a callback passed to listen. When you add the host, it tries to do a DNS lookup, which is async. So when that line tries to fetch the address, there isn't one yet because the DNS request is running, so it crashes.
Try this:
app.listen(3001, 'localhost', function() {
console.log("... port %d in %s mode", app.address().port, app.settings.env);
});
Works with VS 2017
I did installed Visual Studio Command Prompt (devCmd) extension tool.
You can download it here: https://marketplace.visualstudio.com/items?itemName=ShemeerNS.VisualStudioCommandPromptdevCmd#review-details
Double click on the file, make sure IDE is closed during installation.
Open visual studio and Run Developer Command Prompt from VS2017
Egypt (free software)
KcacheGrind (GPL)
Graphviz (CPL)
CodeViz (GPL)
Have a look at wxArt2d it is a complete framework for 2d editing and plotting. See the screenshots for more examples.
Some interesting features:
If, like me, you want to make a function pack or something that people can download then it's very simple. Just write your function in a python file and save it as the name you want IN YOUR PYTHON DIRECTORY. Now, in your script where you want to use this, you type:
from FILE NAME import FUNCTION NAME
Note - the parts in capital letters are where you type the file name and function name.
Now you just use your function however it was meant to be.
Example:
FUNCTION SCRIPT - saved at C:\Python27 as function_choose.py
def choose(a):
from random import randint
b = randint(0, len(a) - 1)
c = a[b]
return(c)
SCRIPT USING FUNCTION - saved wherever
from function_choose import choose
list_a = ["dog", "cat", "chicken"]
print(choose(list_a))
OUTPUT WILL BE DOG, CAT, OR CHICKEN
Hoped this helped, now you can create function packs for download!
--------------------------------This is for Python 2.7-------------------------------------
Most of the time,bootstrap project uses jQuery, so you can use jQuery.
Just get the width and height of parent with JQuery.offsetHeight()
and JQuery.offsetWidth()
, and set them to the child element with JQuery.width()
and JQuery.height()
.
If you want to make it responsive, repeat the above steps in the $(window).resize(func)
, as well.
I looked the pointed other thread and came up with this variation in my coding style, this returns the index of choice for purpose of tallying, but it is simple to return the string ( commented return alternative):
import random
import bisect
try:
range = xrange
except:
pass
def weighted_choice(choices):
total, cumulative = 0, []
for c,w in choices:
total += w
cumulative.append((total, c))
r = random.uniform(0, total)
# return index
return bisect.bisect(cumulative, (r,))
# return item string
#return choices[bisect.bisect(cumulative, (r,))][0]
# define choices and relative weights
choices = [("WHITE",90), ("RED",8), ("GREEN",2)]
tally = [0 for item in choices]
n = 100000
# tally up n weighted choices
for i in range(n):
tally[weighted_choice(choices)] += 1
print([t/sum(tally)*100 for t in tally])
This is what I've been using for development:
<?xml version="1.0" ?>
<cross-domain-policy>
<allow-access-from domain="*" />
</cross-domain-policy>
This is a very liberal approach, but is fine for my application.
As others have pointed out below, beware the risks of this.
You can use
import re
s = re.search(r"\[.*?]", string)
if s:
print(s.group(0))
If rm cannot remove a symlink, perhaps you need to look at the permissions on the directory that contains the symlink. To remove directory entries, you need write permission on the containing directory.
This works well:
{{ app('request')->input('a') }}
Where a
is the url parameter.
See more here: http://blog.netgloo.com/2015/07/17/lumen-getting-current-url-parameter-within-a-blade-view/
Congratulation ! ¨^^ I have an easy & efficient solution for you, yes!
<iframe width="100%" height="300" [attr.src]="video.url"></iframe
[attr.src] instead of src "video.url" and not {{video.url}}
Great ;)
Well you can achieve this using Color State Resource. If you notice inside your NavigationView
you're using
app:itemIconTint="@color/black"
app:itemTextColor="@color/primary_text"
Here instead of using @color/black
or @color/primary_test
, use a Color State List Resource
. For that, first create a new xml
(e.g drawer_item.xml) inside color
directory (which should be inside res
directory.) If you don't have a directory named color
already, create one.
Now inside drawer_item.xml
do something like this
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="checked state color" android:state_checked="true" />
<item android:color="your default color" />
</selector>
Final step would be to change your NavigationView
<android.support.design.widget.NavigationView
android:id="@+id/activity_main_navigationview"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/drawer_header"
app:itemIconTint="@color/drawer_item" // notice here
app:itemTextColor="@color/drawer_item" // and here
app:itemBackground="@android:color/transparent"// and here for setting the background color to tranparent
app:menu="@menu/menu_drawer">
Like this you can use separate Color State List Resources for IconTint
, ItemTextColor
, ItemBackground
.
Now when you set an item as checked (either in xml
or programmatically), the particular item will have different color than the unchecked ones.
You should not try to do this directly. Design your tasks to work with a CancellationToken, and cancel them this way.
In addition, I would recommend changing your main thread to function via a CancellationToken as well. Calling Thread.Abort()
is a bad idea - it can lead to various problems that are very difficult to diagnose. Instead, that thread can use the same Cancellation that your tasks use - and the same CancellationTokenSource
can be used to trigger the cancellation of all of your tasks and your main thread.
This will lead to a far simpler, and safer, design.
Although its very old, but I thought of sharing another idea to do this:
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
password = ("anything")
hash_obj = SHA256.new(password.encode('utf-8'))
hkey = hash_obj.digest()
def encrypt(info):
msg = info
BLOCK_SIZE = 16
PAD = "{"
padding = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PAD
cipher = AES.new(hkey, AES.MODE_ECB)
result = cipher.encrypt(padding(msg).encode('utf-8'))
return result
msg = "Hello stackoverflow!"
cipher_text = encrypt(msg)
print(cipher_text)
def decrypt(info):
msg = info
PAD = "{"
decipher = AES.new(hkey, AES.MODE_ECB)
pt = decipher.decrypt(msg).decode('utf-8')
pad_index = pt.find(PAD)
result = pt[: pad_index]
return result
plaintext = decrypt(cipher_text)
print(plaintext)
Outputs:
> b'\xcb\x0b\x8c\xdc#\n\xdd\x80\xa6|\xacu\x1dEg;\x8e\xa2\xaf\x80\xea\x95\x80\x02\x13\x1aem\xcb\xf40\xdb'
> Hello stackoverflow!
As I'm beginner for vba, I'm willing to get a deep knowledge of vba of how all excel in-built functions work form there back.
So as on the above question I have putted my basic efforts.
Function multi_add(a As Range, ParamArray b() As Variant) As Double
Dim ele As Variant
Dim i As Long
For Each ele In a
multi_add = a + ele.Value **- a**
Next ele
For i = LBound(b) To UBound(b)
For Each ele In b(i)
multi_add = multi_add + ele.Value
Next ele
Next i
End Function
- a: This is subtracted for above code cause a count doubles itself so what values you adds it will add first value twice.
Can you use:
[self.navigationController pushViewController:controller animated:YES];
Going back (I think):
[self.navigationController popToRootViewControllerAnimated:YES];
You could also wrap the transaction up into it's own stored procedure and handle it that way instead of doing transactions in C# itself.
Typically you want to mirror dict hierarchy into your object but not list or tuples which are typically at lowest level. So this is how I did this:
class defDictToObject(object):
def __init__(self, myDict):
for key, value in myDict.items():
if type(value) == dict:
setattr(self, key, defDictToObject(value))
else:
setattr(self, key, value)
So we do:
myDict = { 'a': 1,
'b': {
'b1': {'x': 1,
'y': 2} },
'c': ['hi', 'bar']
}
and get:
x.b.b1.x
1
x.c
['hi', 'bar']
If you need to support other languages, instead of the typical A-Z, you can use the following:
preg_replace('/[^\p{L}\p{N} ]+/', '', $string);
[^\p{L}\p{N} ]
defines a negated (It will match a character that is not defined) character class of:
\p{L}
: a letter from any language.\p{N}
: a numeric character in any script.
: a space character.+
greedily matches the character class between 1 and unlimited times.This will preserve letters and numbers from other languages and scripts as well as A-Z:
preg_replace('/[^\p{L}\p{N} ]+/', '', 'hello-world'); // helloworld
preg_replace('/[^\p{L}\p{N} ]+/', '', 'abc@~#123-+=öäå'); // abc123öäå
preg_replace('/[^\p{L}\p{N} ]+/', '', '????!@£$%^&*()'); // ????
Note: This is a very old, but still relevant question. I am answering purely to provide supplementary information that may be useful to future visitors.
It's already answered here -> Is my virtual environment (python) causing my PYTHONPATH to break?
Add "export PYTHONPATH=/usr/local/lib/python2.0" this to ~/.bashrc file and source it by typing "source ~/.bashrc" OR ". ~/.bashrc".
1) Go to the Control panel 2) Double click System 3) Go to the Advanced tab 4) Click on Environment Variables
In the System Variables window, check if you have a variable named PYTHONPATH. If you have one already, check that it points to the right directories. If you don't have one already, click the New button and create it.
Alternatively, you can also do below your code:-
import sys
sys.path.append("/home/me/mypy")
You could also use the .add()
function:
df.loc[:,'variance'] = df.loc[:,'budget'].add(df.loc[:,'actual'])
dir /ad /b /s
will give the required answer.
If you want to just label the data points above the bar, you could use plt.annotate()
My code:
import numpy as np
import matplotlib.pyplot as plt
n = [1,2,3,4,5,]
s = [i**2 for i in n]
line = plt.bar(n,s)
plt.xlabel('Number')
plt.ylabel("Square")
for i in range(len(s)):
plt.annotate(str(s[i]), xy=(n[i],s[i]), ha='center', va='bottom')
plt.show()
By specifying a horizontal and vertical alignment of 'center'
and 'bottom'
respectively one can get centered annotations.
Update image field to add full URL, ignoring null fields:
UPDATE test SET image = CONCAT('https://my-site.com/images/',image) WHERE image IS NOT NULL;
You should be able to adjust the width using the .modal-dialog
class selector (in conjunction with media queries or whatever strategy you're using for responsive design):
.modal-dialog {
width: 400px;
}
You can use the DateDiff class of the Time Period Library for .NET:
// ----------------------------------------------------------------------
public void DateDiffSample()
{
DateTime date1 = new DateTime( 2009, 11, 8, 7, 13, 59 );
DateTime date2 = new DateTime( 2011, 3, 20, 19, 55, 28 );
DateDiff dateDiff = new DateDiff( date1, date2 );
// differences
Console.WriteLine( "DateDiff.Months: {0}", dateDiff.Months );
// > DateDiff.Months: 16
// elapsed
Console.WriteLine( "DateDiff.ElapsedMonths: {0}", dateDiff.ElapsedMonths );
// > DateDiff.ElapsedMonths: 4
// description
Console.WriteLine( "DateDiff.GetDescription(6): {0}", dateDiff.GetDescription( 6 ) );
// > DateDiff.GetDescription(6): 1 Year 4 Months 12 Days 12 Hours 41 Mins 29 Secs
} // DateDiffSample
You need to leverage the @ViewChild
decorator to reference the child component from the parent one by injection:
import { Component, ViewChild } from 'angular2/core';
(...)
@Component({
selector: 'my-app',
template: `
<h1>My First Angular 2 App</h1>
<child></child>
<button (click)="submit()">Submit</button>
`,
directives:[App]
})
export class AppComponent {
@ViewChild(Child) child:Child;
(...)
someOtherMethod() {
this.searchBar.someMethod();
}
}
Here is the updated plunkr: http://plnkr.co/edit/mrVK2j3hJQ04n8vlXLXt?p=preview.
You can notice that the @Query
parameter decorator could also be used:
export class AppComponent {
constructor(@Query(Child) children:QueryList<Child>) {
this.childcmp = children.first();
}
(...)
}
Here is my solution. The code should be easy enough to follow but here is the idea:
The code:
function focusFirst(parent) {
$(parent).find('input, textarea, select')
.not('input[type=hidden],input[type=button],input[type=submit],input[type=reset],input[type=image],button')
.filter(':enabled:visible:first')
.focus();
}
Then simply call focusFirst with your parent element or selector.
Selector:
focusFirst('form#aspnetForm');
Element:
var el = $('form#aspnetForm');
focusFirst(el);
There are many ways...one is to use the std::find()
algorithm, e.g.
#include <algorithm>
int myArray[] = { 3, 2, 1, 0, 1, 2, 3 };
size_t myArraySize = sizeof(myArray) / sizeof(int);
int *end = myArray + myArraySize;
// find the value 0:
int *result = std::find(myArray, end, 0);
if (result != end) {
// found value at "result" pointer location...
}
I use the following with a MSSQL server:
if (DB_NAME() = 'YOUR_DATABASE')
begin
while(exists(select 1 from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where CONSTRAINT_TYPE='FOREIGN KEY'))
begin
declare @sql nvarchar(2000)
SELECT TOP 1 @sql=('ALTER TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME + '] DROP CONSTRAINT [' + CONSTRAINT_NAME + ']')
FROM information_schema.table_constraints
WHERE CONSTRAINT_TYPE = 'FOREIGN KEY'
exec (@sql)
PRINT @sql
end
while(exists(select 1 from INFORMATION_SCHEMA.TABLES))
begin
declare @sql2 nvarchar(2000)
SELECT TOP 1 @sql2=('DROP TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME + ']')
FROM INFORMATION_SCHEMA.TABLES
exec (@sql2)
PRINT @sql2
end
end
else
print('Only run this script on the development server!!!!')
Replace YOUR_DATABASE with the name of your database or remove the entire IF statement (I like the added safety).
On Servlet 3.0 or newer you could just specify
<web-app ...>
<error-page>
<location>/general-error.html</location>
</error-page>
</web-app>
But as you're still on Servlet 2.5, there's no other way than specifying every common HTTP error individually. You need to figure which HTTP errors the enduser could possibly face. On a barebones webapp with for example the usage of HTTP authentication, having a disabled directory listing, using custom servlets and code which can possibly throw unhandled exceptions or does not have all methods implemented, then you'd like to set it for HTTP errors 401, 403, 500 and 503 respectively.
<error-page>
<!-- Missing login -->
<error-code>401</error-code>
<location>/general-error.html</location>
</error-page>
<error-page>
<!-- Forbidden directory listing -->
<error-code>403</error-code>
<location>/general-error.html</location>
</error-page>
<error-page>
<!-- Missing resource -->
<error-code>404</error-code>
<location>/Error404.html</location>
</error-page>
<error-page>
<!-- Uncaught exception -->
<error-code>500</error-code>
<location>/general-error.html</location>
</error-page>
<error-page>
<!-- Unsupported servlet method -->
<error-code>503</error-code>
<location>/general-error.html</location>
</error-page>
That should cover the most common ones.
Since char
is a primitive type, you can just write c == ' '
.
You only need to call equals()
for reference types like String
or Character
.
if(!$('element').val()) {
// code
}
File > Settings > Editor > General >Auto Import (Mac: Android Studio > Preferences > Editor > General >Auto Import).
Select all check boxes and set Insert imports on paste to All. Unambiguous imports are now added automatically to your files.
You can try this way:
open('u.item', encoding='utf8', errors='ignore')
To get the current working directory, you can use:
process.cwd()
However, be aware that some scripts, notably gulp, will change the current working directory with process.chdir()
.
You can get the path of the current module with:
__filename
__dirname
If you are running a script from the command line, and you want the original directory from which the script was run, regardless of what directory the script is currently operating in, you can use:
process.env.INIT_CWD
It's sometimes desirable to run an NPM script in the current directory, rather than the root of the project.
This variable is available inside npm package scripts as:
$INIT_CWD.
You must be running a recent version of NPM. If this variable is not available, make sure NPM is up to date.
This will allow you access the current path in your package.json, e.g.:
scripts: {
"customScript": "gulp customScript --path $INIT_CWD"
}
first add two frameworks in your project
1: MapKit
2: Corelocation (no longer necessary as of XCode 7.2.1)
Define in your class
var manager:CLLocationManager!
var myLocations: [CLLocation] = []
then in viewDidLoad method code this
manager = CLLocationManager()
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestAlwaysAuthorization()
manager.startUpdatingLocation()
//Setup our Map View
mapobj.showsUserLocation = true
do not forget to add these two value in plist file
1: NSLocationWhenInUseUsageDescription
2: NSLocationAlwaysUsageDescription
I searched for many pages of the web through of the Google and here on the Stack Overflow, but nothing suggested resolved my problem.
After many attempts, I've changed my way of to test that controller. Then I have discovered that the problem occurs always which I reopened the page through of the Ctrl + Shift + T
shortcut in Chrome. So the page ran, but without a parent window reference, and because this can't be closed.
Since you want to pivot multiple columns of data, I would first suggest unpivoting the result
, score
and grade
columns so you don't have multiple columns but you will have multiple rows.
Depending on your version of SQL Server you can use the UNPIVOT function or CROSS APPLY. The syntax to unpivot the data will be similar to:
select ratio, col, value
from GRAND_TOTALS
cross apply
(
select 'result', cast(result as varchar(10)) union all
select 'score', cast(score as varchar(10)) union all
select 'grade', grade
) c(col, value)
See SQL Fiddle with Demo. Once the data has been unpivoted, then you can apply the PIVOT function:
select ratio = col,
[current ratio], [gearing ratio], [performance ratio], total
from
(
select ratio, col, value
from GRAND_TOTALS
cross apply
(
select 'result', cast(result as varchar(10)) union all
select 'score', cast(score as varchar(10)) union all
select 'grade', grade
) c(col, value)
) d
pivot
(
max(value)
for ratio in ([current ratio], [gearing ratio], [performance ratio], total)
) piv;
See SQL Fiddle with Demo. This will give you the result:
| RATIO | CURRENT RATIO | GEARING RATIO | PERFORMANCE RATIO | TOTAL |
|--------|---------------|---------------|-------------------|-----------|
| grade | Good | Good | Satisfactory | Good |
| result | 1.29400 | 0.33840 | 0.04270 | (null) |
| score | 60.00000 | 70.00000 | 50.00000 | 180.00000 |
UPDATED: January 19, 2016
As of moment 2.8.4 - use .add(5, 'd')
(or .add(5, 'days')
) instead of .add('d', 5)
var new_date = moment(startdate, "DD-MM-YYYY").add(5, 'days');
Thanks @Bala for the information.
UPDATED: March 21, 2014
This is what you'd have to do to get that format.
startdate = "20.03.2014";
var new_date = moment(startdate, "DD-MM-YYYY").add('days', 5);
var day = new_date.format('DD');
var month = new_date.format('MM');
var year = new_date.format('YYYY');
alert(day + '.' + month + '.' + year);
ORIGINAL: March 20, 2014
You're not telling it how/what unit to add. Use -
var new_date = moment(startdate, "DD-MM-YYYY").add('days', 5);
Start Android Studio and select Configure --> SDK Manager
Then, check the path of Android SDK
If you can't find the SDK location, you may want to download it. Just scroll down to near end of the download page and select the Android SDK with respect to your OS.
All given answers are wrong. It is impossible to globalise a variable inside a function in a separate file.
Moq version 4.8 (or later) has much improved support for by-ref parameters:
public interface IGobbler
{
bool Gobble(ref int amount);
}
delegate void GobbleCallback(ref int amount); // needed for Callback
delegate bool GobbleReturns(ref int amount); // needed for Returns
var mock = new Mock<IGobbler>();
mock.Setup(m => m.Gobble(ref It.Ref<int>.IsAny)) // match any value passed by-ref
.Callback(new GobbleCallback((ref int amount) =>
{
if (amount > 0)
{
Console.WriteLine("Gobbling...");
amount -= 1;
}
}))
.Returns(new GobbleReturns((ref int amount) => amount > 0));
int a = 5;
bool gobbleSomeMore = true;
while (gobbleSomeMore)
{
gobbleSomeMore = mock.Object.Gobble(ref a);
}
The same pattern works for out
parameters.
It.Ref<T>.IsAny
also works for C# 7 in
parameters (since they are also by-ref).
This seems like the easiest (but not most robust) way to me. Simply compute the sum from row 6 to the maximum allowed row number, as specified by Excel. According to this site, the maximum is currently 1048576, so the following should work for you:
=sum(c6:c1048576)
For more robust solutions, see the other answers.
I don't see any answers yet that mention performance. Passing Func<>
s into Where()
or Count()
is bad. Real bad. If you use a Func<>
then it calls the IEnumerable
LINQ stuff instead of IQueryable
, which means that whole tables get pulled in and then filtered. Expression<Func<>>
is significantly faster, especially if you are querying a database that lives another server.
Use the web browser control. This requires Adobe reader to be installed but most likely you have it anyway. Set the UrL of the control to the file location.
As an alternative, you might use a 9 patch image as the background for your layout, allowing for more "natural" shadows:
Result:
Put the image in your /res/drawable
folder.
Make sure the file extension is .9.png
, not .png
By the way, this is a modified (reduced to the minimum square size) of an existing resource found in the API 19 sdk resources folder.
I left the red markers, since they don't seem to be harmful, as shown in the draw9patch tool.
[EDIT]
About 9 patches, in case you never had anything to do with them.
Simply add it as the background of your View.
The black-marked areas (left and top) will stretch (vertically, horizontally).
The black-marked areas (right, bottom) define the "content area" (where it's possible to add text or Views - you can call the unmarked regions "padding", if you like to).
Tutorial: http://radleymarx.com/blog/simple-guide-to-9-patch/
This question is now a bit old... but I'll throw my hat into the ring.
I personally find an algorithm of the form find_paths[s, t, d, k]
useful, where:
Using your programming language's form of infinity for d
and k
will give you all paths§.
§ obviously if you are using a directed graph and you want all undirected paths between s
and t
you will have to run this both ways:
find_paths[s, t, d, k] <join> find_paths[t, s, d, k]
I personally like recursion, although it can difficult some times, anyway first lets define our helper function:
def find_paths_recursion(graph, current, goal, current_depth, max_depth, num_paths, current_path, paths_found)
current_path.append(current)
if current_depth > max_depth:
return
if current == goal:
if len(paths_found) <= number_of_paths_to_find:
paths_found.append(copy(current_path))
current_path.pop()
return
else:
for successor in graph[current]:
self.find_paths_recursion(graph, successor, goal, current_depth + 1, max_depth, num_paths, current_path, paths_found)
current_path.pop()
With that out of the way, the core function is trivial:
def find_paths[s, t, d, k]:
paths_found = [] # PASSING THIS BY REFERENCE
find_paths_recursion(s, t, 0, d, k, [], paths_found)
First, lets notice a few thing:
[]
is an uninitialized list, replace this with the equivalent for your programming language of choicepaths_found
is passed by reference. It is clear that the recursion function doesn't return anything. Handle this appropriately.graph
is assuming some form of hashed
structure. There are a plethora of ways to implement a graph. Either way, graph[vertex]
gets you a list of adjacent vertices in a directed graph - adjust accordingly.For straight HTML, with no JavaScript required:
<a href="#something">Add '#something' to URL</a>
Or, to take your question more literally, to just add '#' to the URL:
<a href="#">Add '#' to URL</a>
You have specified different colors for the li elements but it is being overridden by the specified color in the a within the li. Remove color: #C1C1C1; style from a element and it should work.
For
throw new Exception('test exception');
I got 500 (but didn't see anything in the browser), until I put
php_flag display_errors on
in my .htaccess (just for a subfolder). There are also more detailed settings, see Enabling error display in php via htaccess only
/
starts from the root only, to get the relative path we should use ./
or ../
hibernate3.HibernateQueryException: Books is not mapped [SELECT COUNT(*) FROM Books];
Hibernate is trying to say that it does not know an entity named "Books". Let's look at your entity:
@javax.persistence.Entity
@javax.persistence.Table(name = "Books")
public class Book {
Right. The table name for Book
has been renamed to "Books" but the entity name is still "Book" from the class name. If you want to set the entity name, you should use the @Entity
annotation's name instead:
// this allows you to use the entity Books in HQL queries
@javax.persistence.Entity(name = "Books")
public class Book {
That sets both the entity name and the table name.
The opposite problem happened to me when I was migrating from the Person.hbm.xml
file to using the Java annotations to describe the hibernate fields. My old XML file had:
<hibernate-mapping package="...">
<class name="Person" table="persons" lazy="true">
...
</hibernate-mapping>
And my new entity had a @Entity(name=...)
which I needed to set the name of the table.
// this renames the entity and sets the table name
@javax.persistence.Entity(name = "persons")
public class Person {
...
What I then was seeing was HQL errors like:
QuerySyntaxException: Person is not mapped
[SELECT id FROM Person WHERE id in (:ids)]
The problem with this was that the entity name was being renamed to persons
as well. I should have set the table name using:
// no name = here so the entity can be used as Person
@javax.persistence.Entity
// table name specified here
@javax.persistence.Table(name = "persons")
public class Person extends BaseGeneratedId {
Hope this helps others.
You can dirctly get last index by:
$numItems = count($arr);
echo $arr[$numItems-1];
in ur XCODE (4.3) next the play button :) (run)
select : edit scheme
the scheme management window will open
click on the Arguments tab
you should see : 1- Arguments passed on launch 2- environment variables
inside the the (2- environment variables) place
Name: NSZombieEnabled
Value: YES
And its done....
One thing no one has pointed out is that you can use LATERAL
queries to apply a user-defined function on every selected row.
For instance:
CREATE OR REPLACE FUNCTION delete_company(companyId varchar(255))
RETURNS void AS $$
BEGIN
DELETE FROM company_settings WHERE "company_id"=company_id;
DELETE FROM users WHERE "company_id"=companyId;
DELETE FROM companies WHERE id=companyId;
END;
$$ LANGUAGE plpgsql;
SELECT * FROM (
SELECT id, name, created_at FROM companies WHERE created_at < '2018-01-01'
) c, LATERAL delete_company(c.id);
That's the only way I know how to do this sort of thing in PostgreSQL.
<b>
and <i>
should be avoided because they describe the style of the text. Instead, use <strong>
and <em>
because that describes the semantics (the meaning) of the text.
As with all things in HTML, you should be thinking not about how you want it to look, but what you actually mean. Sure, it might just be bold and italics to you, but not to a screen reader.
If you backup a table in Oracle Database. You try the statement below.
CREATE TABLE name_table_bk
AS
SELECT *
FROM name_table;
I am using Oracle Database 12c.
cron
is clearly a great choice for many purposes. However it doesn't create a service or daemon as you requested in the OP. cron
just runs jobs periodically (meaning the job starts and stops), and no more often than once / minute. There are issues with cron
-- for example, if a prior instance of your script is still running the next time the cron
schedule comes around and launches a new instance, is that OK? cron
doesn't handle dependencies; it just tries to start a job when the schedule says to.
If you find a situation where you truly need a daemon (a process that never stops running), take a look at supervisord
. It provides a simple way to wrapper a normal, non-daemonized script or program and make it operate like a daemon. This is a much better way than creating a native Python daemon.
The problem is that this character is UTF8, but json_encode does not handle it correctly. To say more, there is a list of other characters (see Unicode characters list), that will trigger the same error, so stripping off this one (Å) will not correct an issue to the end.
What we have used is to convert these chars to html entities like this:
htmlentities( (string) $value, ENT_QUOTES, 'utf-8', FALSE);
@jstn's answer is good, but a bit verbose. Swift is known as a protocol-oriented language, so we can achieve the same result without having to implement boilerplate code for every class in the integer family, by adding a default implementation for the protocol extension.
public extension ExpressibleByIntegerLiteral {
public static func arc4random() -> Self {
var r: Self = 0
arc4random_buf(&r, MemoryLayout<Self>.size)
return r
}
}
Now we can do:
let i = Int.arc4random()
let j = UInt32.arc4random()
and all other integer classes are ok.
var stud = (from s1 in entities.Students
where s1.ID== student.ID
select s1).SingleOrDefault();
//Delete it from memory
entities.DeleteObject(stud);
//Save to database
entities.SaveChanges();
If you are lost with errors like module not found there is noway other the than following method if you have used react native CLI.I had faced similar issue as a result of openning xcode project from .xcodeproj file instead of .xcworkspace. Also please note that react-native eject only for Expo project.
The only workaround to regenarate ios and android folders within a react native project is the following.
Now your problem should be solved
The javax.servlet dependency is missing in your pom.xml. Add the following to the dependencies-Node:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
The best method I've ever come across to update the content size of a UIScrollView
based on its contained subviews:
Objective-C
CGRect contentRect = CGRectZero;
for (UIView *view in self.scrollView.subviews) {
contentRect = CGRectUnion(contentRect, view.frame);
}
self.scrollView.contentSize = contentRect.size;
Swift
let contentRect: CGRect = scrollView.subviews.reduce(into: .zero) { rect, view in
rect = rect.union(view.frame)
}
scrollView.contentSize = contentRect.size
Here is a great explaination on this!
Also implements loading delays and timeouts!
http://happyworm.com/blog/2010/01/28/a-simple-and-robust-cdn-failover-for-jquery-14-in-one-line/
In your XML layout:
<Button
android:id="@+id/cancelskill"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"
android:layout_weight="1"
android:background="@drawable/button_border"
android:padding="10dp"
android:text="Cancel"
android:textAllCaps="false"
android:textColor="#ffffff"
android:textSize="20dp" />
In the drawable folder, create a file for the button's border style:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<stroke
android:width="1dp"
android:color="#f43f10" />
</shape>
And in your Activity:
GradientDrawable gd1 = new GradientDrawable();
gd1.setColor(0xFFF43F10); // Changes this drawbale to use a single color instead of a gradient
gd1.setCornerRadius(5);
gd1.setStroke(1, 0xFFF43F10);
cancelskill.setBackgroundDrawable(gd1);
cancelskill.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cancelskill.setBackgroundColor(Color.parseColor("#ffffff"));
cancelskill.setTextColor(Color.parseColor("#f43f10"));
GradientDrawable gd = new GradientDrawable();
gd.setColor(0xFFFFFFFF); // Changes this drawbale to use a single color instead of a gradient
gd.setCornerRadius(5);
gd.setStroke(1, 0xFFF43F10);
cancelskill.setBackgroundDrawable(gd);
finish();
}
});
Perhaps you want something like:
<style name="CustomActivityTheme" parent="@android:style/Theme.Holo">
<item name="android:checkboxStyle">@style/customCheckBoxStyle</item>
</style>
<style name="customCheckBoxStyle" parent="@android:style/Widget.CompoundButton.CheckBox">
<item name="android:textColor">@android:color/black</item>
</style>
Note, the textColor item.
So it looks like there are a few things going wrong here. Based on your post it looks like you are attempting to support file uploads using the connect-multiparty
middleware. What this middleware does is take the uploaded file, write it to the local filesystem and then sets req.files
to the the uploaded file(s).
The configuration of your route looks fine, the problem looks to be with your items.upload()
function. In particular with this part:
var params = {
Key: file.name,
Body: file
};
As I mentioned at the beginning of my answer connect-multiparty
writes the file to the local filesystem, so you'll need to open the file and read it, then upload it, and then delete it on the local filesystem.
That said you could update your method to something like the following:
var fs = require('fs');
exports.upload = function (req, res) {
var file = req.files.file;
fs.readFile(file.path, function (err, data) {
if (err) throw err; // Something went wrong!
var s3bucket = new AWS.S3({params: {Bucket: 'mybucketname'}});
s3bucket.createBucket(function () {
var params = {
Key: file.originalFilename, //file.name doesn't exist as a property
Body: data
};
s3bucket.upload(params, function (err, data) {
// Whether there is an error or not, delete the temp file
fs.unlink(file.path, function (err) {
if (err) {
console.error(err);
}
console.log('Temp File Delete');
});
console.log("PRINT FILE:", file);
if (err) {
console.log('ERROR MSG: ', err);
res.status(500).send(err);
} else {
console.log('Successfully uploaded data');
res.status(200).end();
}
});
});
});
};
What this does is read the uploaded file from the local filesystem, then uploads it to S3, then it deletes the temporary file and sends a response.
There's a few problems with this approach. First off, it's not as efficient as it could be, as for large files you will be loading the entire file before you write it. Secondly, this process doesn't support multi-part uploads for large files (I think the cut-off is 5 Mb before you have to do a multi-part upload).
What I would suggest instead is that you use a module I've been working on called S3FS which provides a similar interface to the native FS in Node.JS but abstracts away some of the details such as the multi-part upload and the S3 api (as well as adds some additional functionality like recursive methods).
If you were to pull in the S3FS library your code would look something like this:
var fs = require('fs'),
S3FS = require('s3fs'),
s3fsImpl = new S3FS('mybucketname', {
accessKeyId: XXXXXXXXXXX,
secretAccessKey: XXXXXXXXXXXXXXXXX
});
// Create our bucket if it doesn't exist
s3fsImpl.create();
exports.upload = function (req, res) {
var file = req.files.file;
var stream = fs.createReadStream(file.path);
return s3fsImpl.writeFile(file.originalFilename, stream).then(function () {
fs.unlink(file.path, function (err) {
if (err) {
console.error(err);
}
});
res.status(200).end();
});
};
What this will do is instantiate the module for the provided bucket and AWS credentials and then create the bucket if it doesn't exist. Then when a request comes through to upload a file we'll open up a stream to the file and use it to write the file to S3 to the specified path. This will handle the multi-part upload piece behind the scenes (if needed) and has the benefit of being done through a stream, so you don't have to wait to read the whole file before you start uploading it.
If you prefer, you could change the code to callbacks from Promises. Or use the pipe() method with the event listener to determine the end/errors.
If you're looking for some additional methods, check out the documentation for s3fs and feel free to open up an issue if you are looking for some additional methods or having issues.
image=myCamera.getImage().crop(xx,xx,xx,xx).scale(xx,xx).greyscale()
You can use greyscale()
directly for the transformation.
This is now built in Laravel 5.5 https://laravel.com/docs/5.5/blade#switch-statements
You can't push into other people's repositories. This is because push permanently gets code into their repository, which is not cool.
What you should do, is to ask them to pull from your repository. This is done in GitHub by going to the other repository and sending a "pull request".
There is a very informative article on the GitHub's help itself: https://help.github.com/articles/using-pull-requests
To interact with your own repository, you have the following commands. I suggest you start reading on Git a bit more for these instructions (lots of materials online).
To add new files to the repository or add changed files to staged area:
$ git add <files>
To commit them:
$ git commit
To commit unstaged but changed files:
$ git commit -a
To push to a repository (say origin
):
$ git push origin
To push only one of your branches (say master
):
$ git push origin master
To fetch the contents of another repository (say origin
):
$ git fetch origin
To fetch only one of the branches (say master
):
$ git fetch origin master
To merge a branch with the current branch (say other_branch
):
$ git merge other_branch
Note that origin/master
is the name of the branch you fetched in the previous step from origin
. Therefore, updating your master branch from origin is done by:
$ git fetch origin master
$ git merge origin/master
You can read about all of these commands in their manual pages (either on your linux or online), or follow the GitHub helps:
this few lines are the simple answer for this question in sql server.
WITH mycte AS
(
SELECT CAST('2011-01-01' AS DATETIME) DateValue
UNION ALL
SELECT DateValue + 1
FROM mycte
WHERE DateValue + 1 < '2021-12-31'
)
SELECT DateValue
FROM mycte
OPTION (MAXRECURSION 0)
While the previous answers do scale the image and take care of the aspect ratio, the resampling itself should be done so that there is no aliasing. Taking care of scale is a matter of fixing arguments correctly. There are many comments about the quality of the output images from standard scaling call. to maintain quality of the image one should use the standard call:
Bitmap resizedBitmap = Bitmap.createScaledBitmap(originalBitmap, newWidth, newHeight, true);
with the last argument set to true
because it will do the bilinear filtering for resampling to prevent aliasing. Read more about aliasing here: https://en.wikipedia.org/wiki/Aliasing
From android documentation:
public static Bitmap createScaledBitmap (Bitmap src,
int dstWidth,
int dstHeight,
boolean filter)
filter : boolean, Whether or not bilinear filtering should be used when scaling the bitmap. If this is true then bilinear filtering will be used when scaling which has better image quality at the cost of worse performance. If this is false then nearest-neighbor scaling is used instead which will have worse image quality but is faster. Recommended default is to set filter to 'true' as the cost of bilinear filtering is typically minimal and the improved image quality is significant.
In my case I downloaded version 22 of Android M and Android 5.1.1 using Android Studio 1.2.1.1 but when I try to do a Hello World this same error showed me
So the solution for me was doing right click in app like the image below and choose "Open Module Settings"
then there you have 2 options. I've changed both with the last version I had.
Compile SDK version to API 21 Lollipop
and Build Tools Version to 21.1.2
Finally clean the project and Build
UPDATED
TO Get Android Studio 1.3 follow these steps
Then you'll have something like this to update your Androud Studio to 1.3 and with this you can test Android M
This bug happens when the versions of SDK, Build Tools and Gradle Plugins doesn't match (in terms of compatibility). The solution is to verify whether you are using the latest version of them or not. The gradle plugins are placed in the build.gradle of the project, and the other versions are on the build.gradle of the module. For example, for SDK 23, you must use the Build Tools 23.0.1 and gradle plugins version 1.3.1.
Another simple way without using import OS is,
outFileName="F:\\folder\\folder\\filename.txt"
outFile=open(outFileName, "w")
outFile.write("""Hello my name is ABCD""")
outFile.close()
It returns false
if the element is not visible.
function checkVisible(e) {
if (!(e instanceof Element)) throw Error('not an Element');
const elementStyle = getComputedStyle(e);
if (elementStyle.display === 'none' || elementStyle.visibility !== 'visible' || elementStyle.opacity < 0.1) return false;
if (e.offsetWidth + e.offsetHeight + e.getBoundingClientRect().height +
e.getBoundingClientRect().width === 0) {
return false;
}
const elemCenter = {
x: e.getBoundingClientRect().left + e.offsetWidth / 2,
y: e.getBoundingClientRect().top + e.offsetHeight / 2
};
if (elemCenter.x < 0 || elemCenter.y < 0) return false;
if (elemCenter.x > (document.documentElement.clientWidth || window.innerWidth)) return false;
if (elemCenter.y > (document.documentElement.clientHeight || window.innerHeight)) return false;
let pointContainer = document.elementFromPoint(elemCenter.x, elemCenter.y);
do {
if (pointContainer === e) return true;
} while (pointContainer = pointContainer.parentNode);
return false;
}
Not exactly answering your question, but if you could move away from your self-made wrapper then there is Simple Logging Facade for Java (SLF4J) which Hibernate has now switched to (instead of commons logging).
SLF4J suffers from none of the class loader problems or memory leaks observed with Jakarta Commons Logging (JCL).
SLF4J supports JDK logging, log4j and logback. So then it should be fairly easy to switch from log4j to logback when the time is right.
Edit: Aplogies that I hadn't made myself clear. I was suggesting using SLF4J to isolate yourself from having to make a hard choice between log4j or logback.
I have placed here complete bins for above query. you can check demo link too.
Demo: http://codebins.com/bin/4ldqp78/2/How%20to%20make%20a%20simple%20modal%20pop
HTML
<div id="panel">
<input type="button" class="button" value="1" id="btn1">
<input type="button" class="button" value="2" id="btn2">
<input type="button" class="button" value="3" id="btn3">
<br>
<input type="text" id="valueFromMyModal">
<!-- Dialog Box-->
<div class="dialog" id="myform">
<form>
<label id="valueFromMyButton">
</label>
<input type="text" id="name">
<div align="center">
<input type="button" value="Ok" id="btnOK">
</div>
</form>
</div>
</div>
JQuery
$(function() {
$(".button").click(function() {
$("#myform #valueFromMyButton").text($(this).val().trim());
$("#myform input[type=text]").val('');
$("#myform").show(500);
});
$("#btnOK").click(function() {
$("#valueFromMyModal").val($("#myform input[type=text]").val().trim());
$("#myform").hide(400);
});
});
CSS
.button{
border:1px solid #333;
background:#6479fd;
}
.button:hover{
background:#a4a9fd;
}
.dialog{
border:5px solid #666;
padding:10px;
background:#3A3A3A;
position:absolute;
display:none;
}
.dialog label{
display:inline-block;
color:#cecece;
}
input[type=text]{
border:1px solid #333;
display:inline-block;
margin:5px;
}
#btnOK{
border:1px solid #000;
background:#ff9999;
margin:5px;
}
#btnOK:hover{
border:1px solid #000;
background:#ffacac;
}
Demo: http://codebins.com/bin/4ldqp78/2/How%20to%20make%20a%20simple%20modal%20pop
I recently came across a jQuery plugin which does what I originally wanted https://github.com/briangonzalez/jquery.adaptive-backgrounds.js in regards to getting a dominiate color from an image.
Great answers here. If you're looking for the default view "Store Name" set in the Magento configuration:
Mage::app()->getStore()->getFrontendName()
Sure you can:
https://<organization>.slack.com/messages/<channel>/
for example: https://tikal.slack.com/messages/general/ (of course that for accessing it, you must be part of the team)
Today I try to use oracle client 64 and failed connect Connection Identifier which is defined at tnsnames.ora file. I assume that try to connect Oracle 32 Bit Server using SQL Developer 64 bit. That is why I install new jdk x86 and trying to change jdk path but this error happened:
Trying to download SQL Developer 32 Bit, but at the site said that the bundle support both 32 bit and 64 bit depend on java installed.
Windows 32-bit/64-bit: This archive. will work on a 32 or 64 bit Windows OS. The bit level of the JDK you install will determine if it runs as a 32 or 64 bit application. This download does not include the required Oracle Java JDK. You will need to install it if it's not already on your machine.
My java home is 64 bit. New installed 32 bit jdk is not set at java home.
I need to open $User_dir\AppData\Roaming\sqldeveloper\version\product.conf
Remove line SetJavaHome C:\Program Files\Java\jdk1.8.0_201
Start sqldeveloper.exe
instead of sqldeveloper64W.exe
New popup will shown and choose java home to new jdk version (32 bit mine) :
C:\Program Files (x86)\Java\jdk1.8.0_201
My fault, I pin sqldeveloper64W.exe
to taskbar, why that error occured then after I move cursor and it was sqldeveloper64W.exe
, I try to click sqldeveloper.exe
, then I found that my setting is goes well.
So check it maybe it was happened on your system too. If sqldeveloper.exe
does not working, try to choose sqldeveloper64W.exe
.
Now I can call my Connection Identifier which is defined at tnsnames.ora using new setting SQL developer 32 bit mode.
I forced to use a proxy and also forced to add proxy setting on gradle.properties as these:
systemProp.http.proxyHost=127.0.0.1
systemProp.http.proxyPort=1080
systemProp.https.proxyHost=127.0.0.1
systemProp.https.proxyPort=1080
And also forced to close and open studio64.exe
as administrator .
Now its all seems greate
Event log says
8:21:39 AM Platform and Plugin Updates: The following components are ready to update: Android Support Repository, Google Repository, Intel x86 Emulator Accelerator (HAXM installer), Android SDK Platform-Tools 24, Google APIs Intel x86 Atom System Image, Android SDK Tools 25.1.7
8:21:40 AM Gradle sync started
8:22:03 AM Gradle sync completed
8:22:04 AM Executing tasks: [:app:generateDebugSources, :app:generateDebugAndroidTestSources, :app:prepareDebugUnitTestDependencies, :app:mockableAndroidJar]
8:22:25 AM Gradle build finished in 21s 607ms
I'm using android studio 2.1.2 downloaded as exe setup file. it has its Gradle ( I also forced to use custom install to address the Gradle )
If you have the init value in the URL like mypage/id
, then in the controller of the angular JS you can use location.pathname
to find the id and assign it to the model you want.
Take a look at the Huffman algorithm.
https://codereview.stackexchange.com/questions/44473/huffman-code-implementation
The idea is that each character is replaced with sequence of bits, depending on their frequency in the text (the more frequent, the smaller the sequence).
You can read your entire text and build a table of codes, for example:
Symbol Code
a 0
s 10
e 110
m 111
The algorithm builds a symbol tree based on the text input. The more variety of characters you have, the worst the compression will be.
But depending on your text, it could be effective.
In Hive Sql you can do this:
set hive.support.quoted.identifiers=none;
select
`(unwanted_col1|unwanted_col2|unwanted_col3)?+.+`
from database.table
this gives you the rest cols
We can create object to Downcasting. In this type also. : calling the base class methods
Animal a=new Dog();
a.callme();
((Dog)a).callme2();
These answers don't cover very well MULTIPLE variables.
Doing the inline assignment in a stored procedure causes those results to ALSO be sent back in the resultset. That can be confusing. To using the SELECT...INTO syntax with multiple variables you do:
SELECT a, b INTO @a, @b FROM mytable LIMIT 1;
The SELECT must return only 1 row, hence LIMIT 1, although that isn't always necessary.
Others have already addressed the other issues, so I'll just look at one point: do you ever want to manually delete an object.
The answer is yes. @DavidSchwartz gave one example, but it's a fairly unusual one. I'll give an example that's under the hood of what a lot of C++ programmers use all the time: std::vector
(and std::deque
, though it's not used quite as much).
As most people know, std::vector
will allocate a larger block of memory when/if you add more items than its current allocation can hold. When it does this, however, it has a block of memory that's capable of holding more objects than are currently in the vector.
To manage that, what vector
does under the covers is allocate raw memory via the Allocator
object (which, unless you specify otherwise, means it uses ::operator new
). Then, when you use (for example) push_back
to add an item to the vector
, internally the vector uses a placement new
to create an item in the (previously) unused part of its memory space.
Now, what happens when/if you erase
an item from the vector? It can't just use delete
-- that would release its entire block of memory; it needs to destroy one object in that memory without destroying any others, or releasing any of the block of memory it controls (for example, if you erase
5 items from a vector, then immediately push_back
5 more items, it's guaranteed that the vector will not reallocate memory when you do so.
To do that, the vector directly destroys the objects in the memory by explicitly calling the destructor, not by using delete
.
If, perchance, somebody else were to write a container using contiguous storage roughly like a vector
does (or some variant of that, like std::deque
really does), you'd almost certainly want to use the same technique.
Just for example, let's consider how you might write code for a circular ring-buffer.
#ifndef CBUFFER_H_INC
#define CBUFFER_H_INC
template <class T>
class circular_buffer {
T *data;
unsigned read_pos;
unsigned write_pos;
unsigned in_use;
const unsigned capacity;
public:
circular_buffer(unsigned size) :
data((T *)operator new(size * sizeof(T))),
read_pos(0),
write_pos(0),
in_use(0),
capacity(size)
{}
void push(T const &t) {
// ensure there's room in buffer:
if (in_use == capacity)
pop();
// construct copy of object in-place into buffer
new(&data[write_pos++]) T(t);
// keep pointer in bounds.
write_pos %= capacity;
++in_use;
}
// return oldest object in queue:
T front() {
return data[read_pos];
}
// remove oldest object from queue:
void pop() {
// destroy the object:
data[read_pos++].~T();
// keep pointer in bounds.
read_pos %= capacity;
--in_use;
}
~circular_buffer() {
// first destroy any content
while (in_use != 0)
pop();
// then release the buffer.
operator delete(data);
}
};
#endif
Unlike the standard containers, this uses operator new
and operator delete
directly. For real use, you probably do want to use an allocator class, but for the moment it would do more to distract than contribute (IMO, anyway).
/bin/sh
is usually a link to the system's default shell, which is often bash
but on, e.g., Debian systems is the lighter weight dash
. Either way, the original Bourne shell is sh
, so if your script uses some bash
(2nd generation, "Bourne Again sh") specific features ([[ ]]
tests, arrays, various sugary things, etc.), then you should be more specific and use the later. This way, on systems where bash is not installed, your script won't run. I understand there may be an exciting trilogy of films about this evolution...but that could be hearsay.
Also note that when evoked as sh
, bash
to some extent behaves as POSIX standard sh
(see also the GNU docs about this).
Like ctrlplusb said, I recommend you to use the package dotenv
, but another way to do this is creating a js file and requiring it on the first line of your app server.
env.js:
process.env.VAR1="Some value"
process.env.VAR2="Another Value"
app.js:
require('env')
console.log(process.env.VAR1) // Some value
remove {{}} braces around foo.bar because angular expressions cannot be used in angular directives.
For More: https://docs.angularjs.org/api/ng/directive/ngShow
example
<body ng-app="changeExample">
<div ng-controller="ExampleController">
<p ng-show="foo.bar">I could be shown, or I could be hidden</p>
<p ng-hide="foo.bar">I could be shown, or I could be hidden</p>
</div>
</body>
<script>
angular.module('changeExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.foo ={};
$scope.foo.bar = true;
}]);
</script>