In case you're using Gradle Kotlin syntax, you also can do:
tasks.taskName {
environment(mapOf("A" to 1, "B" to "C"))
}
So for test
task this would be:
tasks.test {
environment(mapOf("SOME_TEST_VAR" to "aaa"))
}
Another solution if you have installed android-studio-bundle-143.2915827-windows and gradle2.14
You can verify in C:\Program Files\Android\Android Studio\gradle if you have gradle-2.14.
Then you must go to C:\Users\\AndroidStudioProjects\android_app\
And in this build.gradle you put this code:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.2'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
Then, go to C:\Users\Raul\AndroidStudioProjects\android_app\Desnutricion_infantil\app
And in this build.gradle you put:
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion '24.0.0'
defaultConfig {
minSdkVersion 19
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
}
dependencies {
compile 'com.android.support:appcompat-v7:23.3.0'
}
You must check your sdk version and the buildTools. compileSdkVersion 23 buildToolsVersion '24.0.0'
Save all changes and restart AndroidStudio and all should be fine !
In a microservice infrastructure (does not fit the problem, I know ;)) you must not use:
server:
ssl:
trust-store: path-to-truststore...
trust-store-password: my-secret-password...
Instead the ribbon loadbalancer can be configuered:
ribbon:
TrustStore: keystore.jks
TrustStorePassword : example
ReadTimeout: 60000
IsSecure: true
MaxAutoRetries: 1
Here https://github.com/rajaramkushwaha/https-zuul-proxy-spring-boot-app you can find a working sample. There was also a github discussion about that, but I didn't find it anymore.
This error occurs because your Eclipse version is 64-bit. You should download and install 64-bit JRE and add the path to it in eclipse.ini
. For example:
...
--launcher.appendVmargs
-vm
C:\Program Files\Java\jre1.8.0_45\bin\javaw.exe
-vmargs
...
Note: The -vm
parameter should be just before -vmargs
and the path should be on a separate line. It should be the full path to the javaw.exe
file. Do not enclose the path in double quotes ("
).
If your Eclipse is 32-bit, install a 32-bit JRE and use the path to its javaw.exe
file.
Please check if you got the x64 edition of eclipse. Someone answered this just a few hours ago.
In your Eclipse
installation directory you should be able to find the file eclipse.ini
. Open it and find the -vmargs
section. Adjust the value of:
-Xmx1024m
In this example it is set to 1GB.
Disclosure: I am one of the lombok developers. I might be biased :-)
I strongly suggest installing Lombok via executing the lombok jar: java -jar lombok.jar
The spaces in the path might be a problem.
Also, you'll need to use lombok version 1.14.8 (or higher) to have Luna support.
Please check in the About Eclipse screen if lombok is installed correctly.
See also Cannot make Project Lombok work on Eclipse (Helios)
You can also try closing other programs. :)
It's pretty simple, but worked for me. In my case the VM just don't had enough memory to run, and i got the same message. So i had to clean up the ram, by closing unnecessary programs.
It is possible to increase heap size allocated by the Java Virtual Machine (JVM) by using command line options.
-Xms<size> set initial Java heap size
-Xmx<size> set maximum Java heap size
-Xss<size> set java thread stack size
If you are using the tomcat server, you can change the heap size by going to Eclipse/Run/Run Configuration and select Apache Tomcat/your_server_name/Arguments and under VM arguments section use the following:
-XX:MaxPermSize=256m
-Xms256m -Xmx512M
If you are not using any server, you can type the following on the command line before you run your code:
java -Xms64m -Xmx256m HelloWorld
More information on increasing the heap size can be found here
I think MAVEN_OPTS
would be most appropriate for you. See here: http://maven.apache.org/configure.html
In Unix:
Add the
MAVEN_OPTS
environment variable to specify JVM properties, e.g.export MAVEN_OPTS="-Xms256m -Xmx512m"
. This environment variable can be used to supply extra options to Maven.
In Win, you need to set environment variable via the dialogue box
Add ... environment variable by opening up the system properties (
WinKey + Pause
),... In the same dialog, add theMAVEN_OPTS
environment variable in the user variables to specify JVM properties, e.g. the value-Xms256m -Xmx512m
. This environment variable can be used to supply extra options to Maven.
Adding vm argument to .ini file worked for me
-vm
C:\Program Files\Java\jdk1.7.0_65\bin\javaw.exe
If you want to launch VM by sending arguments, you should send VM arguments and not Program arguments.
Program arguments are arguments that are passed to your application, which are accessible via the "args" String array parameter of your main method. VM arguments are arguments such as System properties that are passed to the JavaSW interpreter. The Debug configuration above is essentially equivalent to:
java -DsysProp1=sp1 -DsysProp2=sp2 test.ArgsTest pro1 pro2 pro3
The VM arguments go after the call to your Java interpreter (ie, 'java') and before the Java class. Program arguments go after your Java class.
Consider a program ArgsTest.java:
package test;
import java.io.IOException;
public class ArgsTest {
public static void main(String[] args) throws IOException {
System.out.println("Program Arguments:");
for (String arg : args) {
System.out.println("\t" + arg);
}
System.out.println("System Properties from VM Arguments");
String sysProp1 = "sysProp1";
System.out.println("\tName:" + sysProp1 + ", Value:" + System.getProperty(sysProp1));
String sysProp2 = "sysProp2";
System.out.println("\tName:" + sysProp2 + ", Value:" + System.getProperty(sysProp2));
}
}
If given input as,
java -DsysProp1=sp1 -DsysProp2=sp2 test.ArgsTest pro1 pro2 pro3
in the commandline, in project bin folder would give the following result:
Program Arguments: pro1 pro2 pro3 System Properties from VM Arguments Name:sysProp1, Value:sp1 Name:sysProp2, Value:sp2
STEPS TO SOLVE THE ISSUE :-
Open the eclipse.ini file from your eclipse folder.
It has some of add on configuration . Find the line –launcher.XXMaxPermSize.It will be the last line in this file. Now remove/delete the the default value 256m and save it.
I just had the same issue, and spend about an hour trying to solve the problem. In the end it was a '#' character in the path.
So I renamed "C:\# IDE\eclipse 3.7\" to "C:\+ IDE\eclipse 3.7\" and that solved the problem.
Here is how i increased the memory allocation of eclipse Juno:
I have a total of 4GB on my system and when im working on eclipse, i dont run any other heavy softwares along side it. So I allocated 2Gb.
The thing i noticed is that the difference between min and max values should be of 512. The next value should be let say 2048 min + 512 = 2560max
Here is the heap value inside eclipse after setting -Xms2048m -Xmx2560m
:
I also faced the same problem while working with eclips Neon. It got fixed after editing the .ini file with following content:
> -Dhttp.proxyPort=8080
> -Dhttp.proxyHost=myproxy
> -Dhttp.proxyUser=mydomain\myusername
> -Dhttp.proxyPassword=mypassword
> -Dhttp.nonProxyHosts=localhost|127.0.0.1
> -Djava.net.preferIPv4Stack=true
Note: Sometime it may also caused due to the issue with your Network configuration and device. So conform first that your windows firewall is allowing to connect your eclips to the outer world (internet). (Turn off the windows firewall for the instance of time that your computer take to install the file).
<HTML>
<HEAD>
<SCRIPT language=Javascript>
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
</SCRIPT>
</HEAD>
<BODY>
<INPUT id="txtChar" onkeypress="return isNumberKey(event)" type="text" name="txtChar">
</BODY>
</HTML>
This is not possible from HTML on. The closest what you can get is the accept-charset
attribute of the <form>
. Only MSIE browser adheres that, but even then it is doing it wrong (e.g. CP1252 is actually been used when it says that it has sent ISO-8859-1). Other browsers are fully ignoring it and they are using the charset as specified in the Content-Type
header of the response. Setting the character encoding right is basically fully the responsiblity of the server side. The client side should just send it back in the same charset as the server has sent the response in.
To the point, you should really configure the character encoding stuff entirely from the server side on. To overcome the inability to edit URIEncoding
attribute, someone here on SO wrote a (complex) filter: Detect the URI encoding automatically in Tomcat. You may find it useful as well (note: I haven't tested it).
Update:
Noted should be that the meta tag as given in your question is ignored when the content is been transferred over HTTP. Instead, the HTTP response Content-Type
header will be used to determine the content type and character encoding. You can determine the HTTP header with for example Firebug, in the Net panel.
var b = String(stringInterpolationSegment: a)
This works for me. You may have a try
accuracy_score is a classification metric, you cannot use it for a regression problem.
As explained by Alex's link you're probably missing the header Content-Disposition
on top of Content-Type
.
So something like this:
Content-Disposition: attachment; filename="MyFileName.ext"
we can use this type of snippet also we generally use this kind of code for testing and validating data for DB to API fields
class Db
{
private readonly static string ConnectionString =
ConfigurationManager.ConnectionStrings
["DbConnectionString"].ConnectionString;
public static List<string> GetValuesFromDB(string LocationCode)
{
List<string> ValuesFromDB = new List<string>();
string LocationqueryString = "select BELocationCode,CityLocation,CityLocationDescription,CountryCode,CountryDescription " +
$"from [CustomerLocations] where LocationCode='{LocationCode}';";
using (SqlConnection Locationconnection =
new SqlConnection(ConnectionString))
{
SqlCommand command = new SqlCommand(LocationqueryString, Locationconnection);
try
{
Locationconnection.Open();
SqlDataReader Locationreader = command.ExecuteReader();
while (Locationreader.Read())
{
for (int i = 0; i <= Locationreader.FieldCount - 1; i++)
{
ValuesFromDB.Add(Locationreader[i].ToString());
}
}
Locationreader.Close();
return ValuesFromDB;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
}
}
hope this might helpful
Note: you guys need connection string (in our case "DbConnectionString")
It depends on the context, but here's an example of "-and" in action:
get-childitem | where-object { $_.Name.StartsWith("f") -and $_.Length -gt 10kb }
So that's getting all the files bigger than 10kb in a directory whose filename starts with "f".
I was faced with this same issue, but rather than creating callbacks for a failed request, I simply returned an error with the json data object.
If possible, this seems like the easiest solution. Here's a sample of the Python code I used. (Using Flask, Flask's jsonify f and SQLAlchemy)
try:
snip = Snip.query.filter_by(user_id=current_user.get_id(), id=snip_id).first()
db.session.delete(snip)
db.session.commit()
return jsonify(success=True)
except Exception, e:
logging.debug(e)
return jsonify(error="Sorry, we couldn't delete that clip.")
Then you can check on Javascript like this;
$.getJSON('/ajax/deleteSnip/' + data_id,
function(data){
console.log(data);
if (data.success === true) {
console.log("successfully deleted snip");
$('.snippet[data-id="' + data_id + '"]').slideUp();
}
else {
//only shows if the data object was returned
}
});
In one line:
$('#selector').clone().attr('id','newid').appendTo('#newPlace');
No need to type in the password, just use any one of these commands (self explanatory):
mysqlcheck --all-databases -a #analyze
mysqlcheck --all-databases -r #repair
mysqlcheck --all-databases -o #optimize
Just see this page
in cmd type:
Command | clip
Then open a *.Txt
file and Paste
. That's it. Done.
Try to use https in repo url: https://repo1.maven.org/maven2
If you use jdk1.7 or above and your network restrict protocols to newer TLS version then enable TLS1.2: -Dhttps.protocols=TLSv1,TLSv1.1,TLSv1.2
As of Genymotion 2.10.0 and onwards, GApps can be installed from the emulator toolbar. Please refer to answer by @MichaelStoddart.
Next follows former answer kept here for historic reason:
Genymotion doesn't provide Google Apps. To install Google Apps:
Upgrade Genymotion and VirtualBox to the latest version.
Download two zip files:
- ARM Translation Installer v1.1
- Google Apps for your Android version: 2.3.7 - 4.4.4 or 4.4 - 6.0 (with platform and variant) You can also find the GApps list in the wbroek user GitHubGist page.
Open Genymotion emulator and go to home screen then drag and drop the first file Genymotion-ARM-Translation_v1.1.zip over the emulator. A dialog will appear and show as file transfer in progress, then another dialog will appear and ask that do you want to flash it on the emulator. Click OK and reboot the device by running adb reboot
from your terminal or command prompt.
Drag and drop the second file gapps-*-signed.zip and repeat the same steps as above. Run adb reboot
again and, once rebooted, Google Apps will be in the emulator.
At this point 'Google Apps Services' will crash frequently with the following message google play services has stopped working
. Open Google Play. After providing your account details, open Google Play and update your installed Google Apps. This seems to make Google Play realize you have an old Google Play Services and will ask you to update (in my case, updating Google Hangouts required a new version of Google Play Services). I've also heard that simply waiting will also prompt you to update. The 'Google Play Services' app doesn't seem to appear otherwise - you can't search for it. You should then see an offer to update Google Play Services. Once the new Google Play Services is installed you will now have stable, working access to Google Play
If you know English and know what trait
means, it is exactly what the name says. It is a class-less pack of methods and properties you attach to existing classes by typing use
.
Basically, you could compare it to a single variable. Closures functions can use
these variables from outside of the scope and that way they have the value inside. They are powerful and can be used in everything. Same happens to traits if they are being used.
Create an empty list of Character and then make a loop to get every character from the array and put them in the list one by one.
List<Character> characterList = new ArrayList<Character>();
char arrayChar[] = abc.toCharArray();
for (char aChar : arrayChar)
{
characterList.add(aChar); // autoboxing
}
You can use this statement:
if ($scope.$root.$$phase != '$apply' && $scope.$root.$$phase != '$digest') {
$scope.$apply();
}
Correct attribute value for Asp.Net MVC Core to prevent browser caching (including Internet Explorer 11) is:
[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
as described in Microsoft documentation:
Response caching in ASP.NET Core - NoStore and Location.None
math.log
is the natural logarithm:
math.log(x[, base]) With one argument, return the natural logarithm of x (to base e).
Your equation is therefore:
n = math.log((1 + (FV * r) / p) / math.log(1 + r)))
Note that in your code you convert n to a str
twice which is unnecessary
There can be errors/incorrect approach in two scenarios. Check both of it and figure it out
SCENARIO 1 :
Once you are running the VBoxLinuxAdditions.run or VBoxSolarisAdditions.pkg or VBoxWindowsAdditions.exe , check if all the modules are getting installed properly.
1.1.a. In case of VBoxLinuxAdditions, if
Building the VirtualBox Guest Additions kernel modules gets failed,
check the log file in /var/log/vboxadd-install.log . If the error is due to kernel version update your kernel and reboot the vm. In case of fedora,
1.1.b. yum update kernel*
1.1.c. reboot
1.2. If nothing gets failed, then all is fine. You are already having the expected kernel version
SCENARIO 2 :
If the VBoxGuestAdditions is installed (check for a folder /opt/VBoxGuestAdditions-* is present .... * represents version) you need to start it before mounting.
2.1. cd /opt/VBoxGuestAdditions-*/init && ./vboxadd start
You need to specify the user id and group id of your vm user as options to the mount command.
2.2.a. Getting uid and gid of a user:
id -u <'user'>
id -g <'user'>
2.2.b. Setting uid and gid in options of mount command:
mount -t vboxsf -o uid=x,gid=x shared_folder_name guest_folder
You can also use array_keys()
. Newbie friendly:
$keys = array_keys($arrayToWalk);
$arraySize = count($arrayToWalk);
for($i=0; $i < $arraySize; $i++) {
echo '<option value="' . $keys[$i] . '">' . $arrayToWalk[$keys[$i]] . '</option>';
}
Assume your code is looking for the file say app.properties. Copy this file to any dir and add this dir to classpath, by creating a setenv.sh in the bin dir of tomcat.
In your setenv.sh of tomcat( if this file is not existing, create one , tomcat will load this setenv.sh file.
#!/bin/sh
CLASSPATH="$CLASSPATH:/home/user/config_my_prod/"
You should not have your properties files in ./webapps//WEB-INF/classes/app.properties
Tomcat class loader will override the with the one from WEB-INF/classes/
A good read: https://tomcat.apache.org/tomcat-8.0-doc/class-loader-howto.html
In Oracle you can use LISTAGG aggregate function.
Original records
name type
------------
name1 type1
name2 type2
name2 type3
Sql
SELECT name, LISTAGG(type, '; ') WITHIN GROUP(ORDER BY name)
FROM table
GROUP BY name
Result in
name type
------------
name1 type1
name2 type2; type3
There is a third option: the x command, which allows you to set a different limit for the specific command instead of changing a global setting. To print the first 300 characters of a string you can use x/300s your_string
. The output might be a bit harder to read. For example printing a SQL query results in:
(gdb) x/300sb stmt.c_str() 0x9cd948: "SELECT article.r"... 0x9cd958: "owid FROM articl"... ..
Below i describe my method. I set event on input in input
, to call Masking() method, which will return an formatted string of that we insert in input
.
Html:
<input name="phone" pattern="+373 __ ___ ___" class="masked" required>
JQ: Here we set event on input:
$('.masked').on('input', function () {
var input = $(this);
input.val(Masking(input.val(), input.attr('pattern')));
});
JS: Function, which will format string by pattern;
function Masking (value, pattern) {
var out = '';
var space = ' ';
var any = '_';
for (var i = 0, j = 0; j < value.length; i++, j++) {
if (value[j] === pattern[i]) {
out += value[j];
}
else if(pattern[i] === any && value[j] !== space) {
out += value[j];
}
else if(pattern[i] === space && value[j] !== space) {
out += space;
j--;
}
else if(pattern[i] !== any && pattern[i] !== space) {
out += pattern[i];
j--;
}
}
return out;
}
The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:
A data frame of four rows:
df = pd.DataFrame({'A': [1,2,3,4]})
Now trying to assign a list/array of two elements to it:
df['B'] = [3,4] # or df['B'] = np.array([3,4])
Both errors out:
ValueError: Length of values does not match length of index
Because the data frame has four rows but the list and array has only two elements.
Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:
df['B'] = pd.Series([3,4])
df
# A B
#0 1 3.0
#1 2 4.0
#2 3 NaN # NaN because the value at index 2 and 3 doesn't exist in the Series
#3 4 NaN
For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:
df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))
# A B
#0 1 1.0
#1 2 5.0
#2 7 9.0
#3 8 NaN
I am not a cron specialist, but how about:
0 */72 * * *
It will run every 72 hours non-interrupted.
If need to copy from another table then need to copy structure first:
DataTable copyDt = existentDt.Clone();
copyDt.ImportRow(existentDt.Rows[0]);
Similar to Tervor, But I like to change the property on runtime.
Note that this need to be set before the first SimpleFormatter is created - as was written in the comments.
System.setProperty("java.util.logging.SimpleFormatter.format",
"%1$tF %1$tT %4$s %2$s %5$s%6$s%n");
++ This worked for me. It's vanilla javascirpt
and good for use cases such as de-cluttering when testing with ngMocks
library:
<!-- specRunner.html - keep this at the top of your <script> asset loading so that it is available readily -->
<!-- Frienly tip - have all JSON files in a json-data folder for keeping things organized-->
<script src="json-data/findByIdResults.js" charset="utf-8"></script>
<script src="json-data/movieResults.js" charset="utf-8"></script>
This is your javascript
file that contains the JSON
data
// json-data/JSONFindByIdResults.js
var JSONFindByIdResults = {
"Title": "Star Wars",
"Year": "1983",
"Rated": "N/A",
"Released": "01 May 1983",
"Runtime": "N/A",
"Genre": "Action, Adventure, Sci-Fi",
"Director": "N/A",
"Writer": "N/A",
"Actors": "Harrison Ford, Alec Guinness, Mark Hamill, James Earl Jones",
"Plot": "N/A",
"Language": "English",
"Country": "USA",
"Awards": "N/A",
"Poster": "N/A",
"Metascore": "N/A",
"imdbRating": "7.9",
"imdbVotes": "342",
"imdbID": "tt0251413",
"Type": "game",
"Response": "True"
};
Finally, work with the JSON data anywhere in your code
// working with JSON data in code
var findByIdResults = window.JSONFindByIdResults;
Note:- This is great for testing and even karma.conf.js
accepts these files for running tests as seen below. Also, I recommend this only for de-cluttering data and testing/development
environment.
// extract from karma.conf.js
files: [
'json-data/JSONSearchResultHardcodedData.js',
'json-data/JSONFindByIdResults.js'
...
]
Hope this helps.
++ Built on top of this answer https://stackoverflow.com/a/24378510/4742733
UPDATE
An easier way that worked for me is just include a function
at the bottom of the code returning whatever JSON
.
// within test code
let movies = getMovieSearchJSON();
.....
...
...
....
// way down below in the code
function getMovieSearchJSON() {
return {
"Title": "Bri Squared",
"Year": "2011",
"Rated": "N/A",
"Released": "N/A",
"Runtime": "N/A",
"Genre": "Comedy",
"Director": "Joy Gohring",
"Writer": "Briana Lane",
"Actors": "Brianne Davis, Briana Lane, Jorge Garcia, Gabriel Tigerman",
"Plot": "N/A",
"Language": "English",
"Country": "USA",
"Awards": "N/A",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjEzNDUxMDI4OV5BMl5BanBnXkFtZTcwMjE2MzczNQ@@._V1_SX300.jpg",
"Metascore": "N/A",
"imdbRating": "8.2",
"imdbVotes": "5",
"imdbID": "tt1937109",
"Type": "movie",
"Response": "True"
}
}
Transaction Isolation and Transaction Propagation although related but are clearly two very different concepts. In both cases defaults are customized at client boundary component either by using Declarative transaction management or Programmatic transaction management. Details of each isolation levels and propagation attributes can be found in reference links below.
For given two or more running transactions/connections to a database, how and when are changes made by queries in one transaction impact/visible to the queries in a different transaction. It also related to what kind of database record locking will be used to isolate changes in this transaction from other transactions and vice versa. This is typically implemented by database/resource that is participating in transaction.
.
In an enterprise application for any given request/processing there are many components that are involved to get the job done. Some of this components mark the boundaries (start/end) of a transaction that will be used in respective component and it's sub components. For this transactional boundary of components, Transaction Propogation specifies if respective component will or will not participate in transaction and what happens if calling component already has or does not have a transaction already created/started. This is same as Java EE Transaction Attributes. This is typically implemented by the client transaction/connection manager.
Reference:
It is like 5 years late, but I wanted to post here my promesify version which takes functions from callbacks API and turns them into promises
const promesify = fn => {
return (...params) => ({
then: cbThen => ({
catch: cbCatch => {
fn(...params, cbThen, cbCatch);
}
})
});
};
Take a look to this very simple version here: https://gist.github.com/jdtorregrosas/aeee96dd07558a5d18db1ff02f31e21a
Here´s something I tried. Basically, I put the "flexible" content (the td which contains lines that are too long) in a div container that´s one line high, with hidden overflow. Then I let the text wrap into the invisible. You get breaks at wordbreaks though, not just a smooth cut-off.
table {
width: 100%;
}
.hideend {
white-space: normal;
overflow: hidden;
max-height: 1.2em;
min-width: 50px;
}
.showall {
white-space:nowrap;
}
<table>
<tr>
<td><div class="showall">Show all</div></td>
<td>
<div class="hideend">Be a bit flexible about hiding stuff in a long sentence</div>
</td>
<td>
<div class="showall">Show all this too</div>
</td>
</tr>
</table>
I don't think there are any machine code decompilers that produce Pascal code. Most "Delphi decompilers" parse form and RTTI data, but do not actually decompile the machine code. I can only recommend using something like DeDe (or similar software) to extract symbol information in combination with a C decompiler, then translate the decompiled C code to Delphi (there are many source code converters out there).
Pre-increment means that the variable is incremented BEFORE it's evaluated in the expression. Post-increment means that the variable is incremented AFTER it has been evaluated for use in the expression.
Therefore, look carefully and you'll see that all three assignments are arithmetically equivalent.
Starting with MVC 5, you can also use Attribute Routing to move the URL parameter configuration to your controllers.
A detailed discussion is available here: http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx
Summary:
First you enable attribute routing
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
}
}
Then you can use attributes to define parameters and optionally data types
public class BooksController : Controller
{
// eg: /books
// eg: /books/1430210079
[Route("books/{isbn?}")]
public ActionResult View(string isbn)
UPDATE: this only tested with server side rendering ( universal Javascript ) here is my boilerplate.
With only file-loader you can load images dynamically - the trick is to use ES6 template strings so that Webpack can pick it up:
This will NOT work. :
const myImg = './cute.jpg'
<img src={require(myImg)} />
To fix this, just use template strings instead :
const myImg = './cute.jpg'
<img src={require(`${myImg}`)} />
webpack.config.js :
var HtmlWebpackPlugin = require('html-webpack-plugin')
var ExtractTextWebpackPlugin = require('extract-text-webpack-plugin')
module.exports = {
entry : './src/app.js',
output : {
path : './dist',
filename : 'app.bundle.js'
},
plugins : [
new ExtractTextWebpackPlugin('app.bundle.css')],
module : {
rules : [{
test : /\.css$/,
use : ExtractTextWebpackPlugin.extract({
fallback : 'style-loader',
use: 'css-loader'
})
},{
test: /\.js$/,
exclude: /(node_modules)/,
loader: 'babel-loader',
query: {
presets: ['react','es2015']
}
},{
test : /\.jpg$/,
exclude: /(node_modules)/,
loader : 'file-loader'
}]
}
}
I've used VideoCapX for our project. It will stream out as MMS/ASF stream which can be open by media player. You can then embed media player into your webpage.
If you won't need much control, or if you want to try out VideoCapX without writing a code, try U-Broadcast, they use VideoCapX behind the scene.
When you start playing around with custom request headers you will get a CORS preflight. This is a request that uses the HTTP OPTIONS
verb and includes several headers, one of which being Access-Control-Request-Headers
listing the headers the client wants to include in the request.
You need to reply to that CORS preflight with the appropriate CORS headers to make this work. One of which is indeed Access-Control-Allow-Headers
. That header needs to contain the same values the Access-Control-Request-Headers
header contained (or more).
https://fetch.spec.whatwg.org/#http-cors-protocol explains this setup in more detail.
I’ve been struggling with this for a while now. Dycey’s solution is correct in that specifying the src
multiple times outputs the same thing in your css file. However, this seems to break in OSX Firefox 23 (probably other versions too, but I don’t have time to test).
The cross-browser @font-face
solution from Font Squirrel looks like this:
@font-face {
font-family: 'fontname';
src: url('fontname.eot');
src: url('fontname.eot?#iefix') format('embedded-opentype'),
url('fontname.woff') format('woff'),
url('fontname.ttf') format('truetype'),
url('fontname.svg#fontname') format('svg');
font-weight: normal;
font-style: normal;
}
To produce the src
property with the comma-separated values, you need to write all of the values on one line, since line-breaks are not supported in Sass. To produce the above declaration, you would write the following Sass:
@font-face
font-family: 'fontname'
src: url('fontname.eot')
src: url('fontname.eot?#iefix') format('embedded-opentype'), url('fontname.woff') format('woff'), url('fontname.ttf') format('truetype'), url('fontname.svg#fontname') format('svg')
font-weight: normal
font-style: normal
I think it seems silly to write out the path a bunch of times, and I don’t like overly long lines in my code, so I worked around it by writing this mixin:
=font-face($family, $path, $svg, $weight: normal, $style: normal)
@font-face
font-family: $family
src: url('#{$path}.eot')
src: url('#{$path}.eot?#iefix') format('embedded-opentype'), url('#{$path}.woff') format('woff'), url('#{$path}.ttf') format('truetype'), url('#{$path}.svg##{$svg}') format('svg')
font-weight: $weight
font-style: $style
Usage: For example, I can use the previous mixin to setup up the Frutiger Light font like this:
+font-face('frutigerlight', '../fonts/frutilig-webfont', 'frutigerlight')
Wow, the other answers look complex - so I'm hoping I've not missed something obvious.
You can use OVER
/PARTITION BY
against aggregates, and they'll then do grouping/aggregating without a GROUP BY
clause. So I just modified your query to:
select T2.ID AS T2ID
,T2.Name as T2Name
,T2.Orders
,T1.ID AS T1ID
,T1.Name As T1Name
,T1Sum.Price
FROM @t2 T2
INNER JOIN (
SELECT Rel.t2ID
,Rel.t1ID
-- ,MAX(Rel.t1ID)AS t1ID
-- the MAX returns an arbitrary ID, what i need is:
,ROW_NUMBER()OVER(Partition By Rel.t2ID Order By Price DESC)As PriceList
,SUM(Price)OVER(PARTITION BY Rel.t2ID) AS Price
FROM @t1 T1
INNER JOIN @relation Rel ON Rel.t1ID=T1.ID
-- GROUP BY Rel.t2ID
)AS T1Sum ON T1Sum.t2ID = T2.ID
INNER JOIN @t1 T1 ON T1Sum.t1ID=T1.ID
where t1Sum.PriceList = 1
Which gives the requested result set.
Perhaps I am wrong, but you can open a workbook, and select a worksheet and change its property (Name) to whatever you need it to be. This overrides the "Sheetx" naming convention. These names are also displayed in the VBA Editor.
How to do this manually:
1. Select the sheet in a workbook (I tend to create templates).
2. Set its tab name to whatever you like ("foo").
3. Click on the Developer menu (which you previously enabled, right?).
4. Locate "Properties" and click on it, bringing up that worksheet's properties window.
5. The very first item in the Alphabetic listing is (Name) and at the right of (Name) is "Sheetx".
6. Click on that field and change it (how about we use "MyFav").
7. Close the properties window.
8. Go to the Visual Basic editor.
9. Review the sheets in the workbook you just modified.
10. Observe that the MicroSoft Excel Objects shows the name you just changed "MyFav", and to the right of that, in parenthesis, the worksheet tab name ("foo").
You can change the .CodeName programmatically if you would rather. I use non-Sheet names to facilitate my template manipulation. You are not forced to use the generic default of "Sheetx".
Check this link , and last comment , You have to use WebChromeClient
for your purpose.
OK, now I feel stupid. The first two definitely do not work but the second two do. Not sure how I convinced my self that I had tried them. Sorry for wasting everyone's time.
In case this helps anyone else, this can occur when you are trying to make a new file in a directory that does not exist.
If you using Plesk, try it, First, Open PHP Settings, at the bottom of page, change date.timezone from DEFAULT to UTC.
C++ inline function is powerful concept that is commonly used with classes. If a function is inline, the compiler places a copy of the code of that function at each point where the function is called at compile time.
Any change to an inline function could require all clients of the function to be recompiled because compiler would need to replace all the code once again otherwise it will continue with old functionality.
To inline a function, place the keyword inline before the function name and define the function before any calls are made to the function. The compiler can ignore the inline qualifier in case defined function is more than a line.
A function definition in a class definition is an inline function definition, even without the use of the inline specifier.
Following is an example, which makes use of inline function to return max of two numbers
#include <iostream>
using namespace std;
inline int Max(int x, int y) { return (x > y)? x : y; }
// Main function for the program
int main() {
cout << "Max (100,1010): " << Max(100,1010) << endl;
return 0;
}
for more information see here.
It's because you aren't giving the un-hovered state a right
attribute.
right
isn't set so it's trying to go from nothing to 0px
. Obviously because it has nothing to go to, it just 'warps' over.
If you give the unhovered state a right:90%;
, it will transition how you like.
Just as a side note, if you still want it to be on the very left of the page, you can use the calc
css function.
Example:
right: calc(100% - 100px)
^ width of div
You don't have to use left
then.
Also, you can't transition using left
or right
auto
and will give the same 'warp' effect.
div {_x000D_
width:100px;_x000D_
height:100px;_x000D_
background:red;_x000D_
transition:2s;_x000D_
-webkit-transition:2s;_x000D_
-moz-transition:2s;_x000D_
position:absolute;_x000D_
right:calc(100% - 100px);_x000D_
}_x000D_
div:hover {_x000D_
right:0;_x000D_
}
_x000D_
<p>_x000D_
<b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions._x000D_
</p>_x000D_
<div></div>_x000D_
<p>Hover over the red square to see the transition effect.</p>
_x000D_
CanIUse says that the calc()
function only works on IE10
+
For Entity Framework and Linq to SQL we can achieve this by defining an extension method which modifies an Expression
passed to IQueryable<T>.Max(...)
method:
static class Extensions
{
public static TResult MaxOrDefault<T, TResult>(this IQueryable<T> source,
Expression<Func<T, TResult>> selector)
where TResult : struct
{
UnaryExpression castedBody = Expression.Convert(selector.Body, typeof(TResult?));
Expression<Func<T, TResult?>> lambda = Expression.Lambda<Func<T,TResult?>>(castedBody, selector.Parameters);
return source.Max(lambda) ?? default(TResult);
}
}
Usage:
int maxId = dbContextInstance.Employees.MaxOrDefault(employee => employee.Id);
// maxId is equal to 0 if there is no records in Employees table
The generated query is identical, it works just like a normal call to IQueryable<T>.Max(...)
method, but if there is no records it returns a default value of type T instead of throwing an exeption
PostgreSQL does not define round(double precision, integer)
. For reasons @Mike Sherrill 'Cat Recall' explains in the comments, the version of round that takes a precision is only available for numeric
.
regress=> SELECT round( float8 '3.1415927', 2 );
ERROR: function round(double precision, integer) does not exist
regress=> \df *round*
List of functions
Schema | Name | Result data type | Argument data types | Type
------------+--------+------------------+---------------------+--------
pg_catalog | dround | double precision | double precision | normal
pg_catalog | round | double precision | double precision | normal
pg_catalog | round | numeric | numeric | normal
pg_catalog | round | numeric | numeric, integer | normal
(4 rows)
regress=> SELECT round( CAST(float8 '3.1415927' as numeric), 2);
round
-------
3.14
(1 row)
(In the above, note that float8
is just a shorthand alias for double precision
. You can see that PostgreSQL is expanding it in the output).
You must cast the value to be rounded to numeric
to use the two-argument form of round
. Just append ::numeric
for the shorthand cast, like round(val::numeric,2)
.
If you're formatting for display to the user, don't use round
. Use to_char
(see: data type formatting functions in the manual), which lets you specify a format and gives you a text
result that isn't affected by whatever weirdness your client language might do with numeric
values. For example:
regress=> SELECT to_char(float8 '3.1415927', 'FM999999999.00');
to_char
---------------
3.14
(1 row)
to_char
will round numbers for you as part of formatting. The FM
prefix tells to_char
that you don't want any padding with leading spaces.
The accepted answer does not tell the entire story.
Yes, whenever you see zeros, a NULL
pointer is involved. That is because NULL
is by definition zero. So calling zero NULL
may not be saying much.
What is interesting about the message you get is the fact that NULL
is mentioned twice. In fact, the message you report looks a little bit like the messages Windows-brand operating systems show the user.
The message says the address NULL
tried to read NULL
. So what does that mean? Specifically, how does an address read itself?
We typically think of the instructions at an address reading and writing from memory at certain addresses. Knowing that allows us to parse the error message. The message is trying to articulate that the instruction at address NULL
tried to read NULL
.
Of course, there is no instruction at address NULL
, that is why we think of NULL
as special in our code. But every instruction can be thought of as commencing with the attempt to read itself. If the CPUs EIP
register is at address NULL
, then the CPU will attempt to read the opcode for an instruction from address 0x00000000 (NULL
). This attempt to read NULL
will fail, and generate the message you have received.
In the debugger, notice that EIP
equals 0x00000000 when you receive this message. This confirms the description I have given you.
The question then becomes, "why does my program attempt to execute the NULL
address." There are three possibilities which spring to mind:
NULL
, never initialized otherwise, and are dereferencing.NULL
entry in the object's vtable. These are created in your code with the syntax virtual function_name()=0
.ret
instruction, the value 0x00000000 (NULL
) is loaded from the overwritten memory spot. This type of error, stack overflow, is the eponym of our forum.Since you mention that you are calling a third-party library, I will point out that it may be a situation of the library expecting you to provide a non-NULL
function pointer as input to some API. These are sometimes known as "call back" functions.
You will have to use the debugger to narrow down the cause of your problem further, but the above possiblities should help you solve the riddle.
I just want to add that this nearly identical post provides the very useful alternative of using an echo pipe if no force or quiet switch is available. For instance, I think it's the only way to bypass the Y/N prompt in this example.
Echo y|NETDOM COMPUTERNAME WorkComp /Add:Work-Comp
In a general sense you should first look at your command switches for /f, /q, or some variant thereof (for example, Netdom RenameComputer uses /Force, not /f). If there is no switch available, then use an echo pipe.
If you just wanted to change the example and put the table at the top, then loc='top'
in the table declaration is what you need,
the_table = ax.table(cellText=cell_text,
rowLabels=rows,
rowColours=colors,
colLabels=columns,
loc='top')
Then adjusting the plot with,
plt.subplots_adjust(left=0.2, top=0.8)
A more flexible option is to put the table in its own axis using subplots,
import numpy as np
import matplotlib.pyplot as plt
fig, axs =plt.subplots(2,1)
clust_data = np.random.random((10,3))
collabel=("col 1", "col 2", "col 3")
axs[0].axis('tight')
axs[0].axis('off')
the_table = axs[0].table(cellText=clust_data,colLabels=collabel,loc='center')
axs[1].plot(clust_data[:,0],clust_data[:,1])
plt.show()
which looks like this,
You are then free to adjust the locations of the axis as required.
I was doing something for a list which is a set of strings and you want to remove all lines that have a certain substring you can do this
import re
def RemoveInList(sub,LinSplitUnOr):
indices = [i for i, x in enumerate(LinSplitUnOr) if re.search(sub, x)]
A = [i for j, i in enumerate(LinSplitUnOr) if j not in indices]
return A
where sub
is a patter that you do not wish to have in a list of lines LinSplitUnOr
for example
A=['Apple.good','Orange.good','Pear.bad','Pear.good','Banana.bad','Potato.bad']
sub = 'good'
A=RemoveInList(sub,A)
Then A
will be
If you have multiple ul and want to empty specific ul then use id eg:
<ul id="randomName">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<script>
$('#randomName').empty();
</script>
$('input').click(function() {_x000D_
$('#randomName').empty()_x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<ul id="randomName">_x000D_
<li>1</li>_x000D_
<li>2</li>_x000D_
<li>3</li>_x000D_
</ul>_x000D_
_x000D_
<ul>_x000D_
<li>4</li>_x000D_
<li>5</li>_x000D_
</ul>_x000D_
<input type="button" value="click me" />
_x000D_
I highly recommend the reading of a lecture in SciPy-lectures organization:
https://scipy-lectures.org/intro/language/reusing_code.html
It explains all the commented doubts.
But, new paths can be easily added and avoiding duplication with the following code:
import sys
new_path = 'insert here the new path'
if new_path not in sys.path:
sys.path.append(new_path)
import funcoes_python #Useful python functions saved in a different script
You can find your Arduino via Terminal with
ls /dev/tty.*
then you can read that serial port using the screen command, like this
screen /dev/tty.[yourSerialPortName] [yourBaudRate]
for example:
screen /dev/tty.usbserial-A6004byf 9600
At a place where you want javadoc, type in /**
<NEWLINE> and it will create the template.
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
TextView textView = (TextView) navigation.findViewById(R.id.navigation_home).findViewById(R.id.smallLabel);
textView.setTypeface(Typeface.DEFAULT_BOLD);
textView = (TextView) navigation.findViewById(R.id.navigation_home).findViewById(R.id.largeLabel);
textView.setTypeface(Typeface.DEFAULT_BOLD);
It's pretty strange for FB not to be loaded in your javascript if you have the script tag there correctly. Check that you don't have any javascript blockers, ad blockers, tracking blockers etc installed in your browser that are neutralizing your FB Connect code.
.class {
/* Fallback for web browsers that doesn't support RGBa */
background: rgb(0, 0, 0);
/* RGBa with 0.6 opacity */
background: rgba(0, 0, 0, 0.6);
}
It is the CSS child selector. Example:
div > p
selects all paragraphs that are direct children of div.
See this
@Ciro
You can break the inline svg code with back-slash "\"
Tested with the code below in Chrome 54 and Firefox 50
body {
background: transparent;
background-attachment:fixed;
background-image: url(
"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' width='170px' height='50px'> \
<rect x='0' y='0' width='170' height='50' style='stroke:white; fill:gray; stroke-opacity: 0.3; stroke-width: 3px; fill-opacity: 0.7; stroke-dasharray: 10 5; stroke-linecap=round; '/> \
<text x='85' y='30' style='fill:lightBlue; text-anchor: middle' font-size='16' transform='rotate(10,85,25)'>I love SVG!</text></svg>");
}
I even Tested this,
background-image: url("\
data:image/svg+xml;utf8, \
<svg xmlns='http://www.w3.org/2000/svg' version='1.1' width='170px' height='50px'> \
<rect x='0' y='0' width='170' height='50'\
style='stroke:white; stroke-width: 3px; stroke-opacity: 0.3; \
stroke-dasharray: 10 5; stroke-linecap=round; \
fill:gray; fill-opacity: 0.7; '/> \
<text x='85' y='30' \
style='fill:lightBlue; text-anchor: middle' font-size='16' \
transform='rotate(10,85,25)'> \
I love SVG! \
</text> \
</svg>\
");
and it works (at least in Chrome 54 & Firefox 50 ==> usage in NWjs & Electron guarenteed)
I've dealing with a similar scenario for an application developed with Django web web framework and these are the steps that worked perfectly for me:
[mlazo@srvjenkins project_textile]$ cat docker/Dockerfile.debug
FROM malazo/project_textile_ubuntu:latest
ENV PROJECT_DIR=/proyectos/project_textile PROJECT_NAME=project_textile WRAPPER_PATH=/usr/share/virtualenvwrapper/virtualenvwrapper.sh
COPY . ${PROJECT_DIR}/
WORKDIR ${PROJECT_DIR}
RUN echo "source ${WRAPPER_PATH}" > ~/.bashrc
SHELL ["/bin/bash","-c","-l"]
RUN mkvirtualenv -p $(which python3) ${PROJECT_NAME} && \
workon ${PROJECT_NAME} && \
pip3 install -r requirements.txt
EXPOSE 8000
ENTRYPOINT ["tests/container_entrypoint.sh"]
CMD ["public/manage.py","runserver","0:8000"]
[mlazo@srvjenkins project_textile]$ cat tests/container_entrypoint.sh
#!/bin/bash
# *-* encoding : UTF-8 *-*
sh tests/deliver_env.sh
source ~/.virtualenvs/project_textile/bin/activate
exec python "$@"
[mlazo@srvjenkins project_textile]$ cat ./tests/container_deployment.sh
#!/bin/bash
CONT_NAME="cont_app_server"
IMG_NAME="malazo/project_textile_app"
[ $(docker ps -a |grep -i ${CONT_NAME} |wc -l) -gt 0 ] && docker rm -f ${CONT_NAME}
docker run --name ${CONT_NAME} -p 8000:8000 -e DEBUG=${DEBUG} -e MYSQL_USER=${MYSQL_USER} -e MYSQL_PASSWORD=${MYSQL_PASSWORD} -e MYSQL_HOST=${MYSQL_HOST} -e MYSQL_DATABASE=${MYSQL_DATABASE} -e MYSQL_PORT=${MYSQL_PORT} -d ${IMG_NAME}
I really hope this would be helpful for somebody else.
Greetings,
My few cents on the subject. Assuming that kubectl
is working then the closest command that would be equivalent to the docker command that you mentioned in your question, would be something like this.
$ kubectl run ubuntu --image=ubuntu --restart=Never --command sleep infinity
Above command will create a single Pod
in default
namespace and, it will execute sleep
command with infinity
argument -this way you will have a process that runs in foreground keeping container alive.
Afterwords, you can interact with Pod
by running kubectl exec
command.
$ kubectl exec ubuntu -it -- bash
This technique is very useful for creating a Pod resource and ad-hoc debugging.
Warning: Don't do this if you've already pushed
You want to do:
git reset HEAD~
If you don't want the changes and blow everything away:
git reset --hard HEAD~
You can use lapply
to pass each column to str_length
, then cbind
it to your original data.frame
...
library(stringr)
out <- lapply( df , str_length )
df <- cbind( df , out )
# col1 col2 col1 col2
#1 abc adf qqwe 3 8
#2 abcd d 4 1
#3 a e 1 1
#4 abcdefg f 7 1
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.waist2height); {
final EditText edit = (EditText)findViewById(R.id.editText);
final RadioButton rb1 = (RadioButton) findViewById(R.id.radioCM);
final RadioButton rb2 = (RadioButton) findViewById(R.id.radioFT);
if(rb1.isChecked()){
edit.setVisibility(View.VISIBLE);
}
else if(rb2.isChecked()){
edit.setVisibility(View.INVISIBLE);
}
}
There's nothing missing. Float was designed for the case where you want an image (for example) to sit beside several paragraphs of text, so the text flows around the image. That wouldn't happen if the text "stretched" the container. Your first paragraph would end, and then your next paragraph would begin under the image (possibly several hundred pixels below).
And that's why you're getting the result you are.
The first thing to have is the actual function that will detect whether you have a collision between the ball and the object.
For the sake of performance it will be great to implement some crude collision detecting technique, e.g., bounding rectangles, and a more accurate one if needed in case you have collision detected, so that your function will run a little bit quicker but using exactly the same loop.
Another option that can help to increase performance is to do some pre-processing with the objects you have. For example you can break the whole area into cells like a generic table and store the appropriate object that are contained within the particular cells. Therefore to detect the collision you are detecting the cells occupied by the ball, get the objects from those cells and use your collision-detecting function.
To speed it up even more you can implement 2d-tree, quadtree or R-tree.
The best and clean way to do this is within the Item_Created Event :
protected void rptSummary_ItemCreated(Object sender, RepeaterItemEventArgs e)
{
switch (e.Item.ItemType)
{
case ListItemType.AlternatingItem:
break;
case ListItemType.EditItem:
break;
case ListItemType.Footer:
e.Item.FindControl(ctrl);
break;
case ListItemType.Header:
break;
case ListItemType.Item:
break;
case ListItemType.Pager:
break;
case ListItemType.SelectedItem:
break;
case ListItemType.Separator:
break;
default:
break;
}
}
Set the window start style as maximized. Then, hide the minimize and maximize buttons.
There are two ways to get the length of "something" on a computer.
The first way is to store a count - this requires anything that touches the file/data to modify it (or a class that only exposes interfaces -- but it boils down to the same thing).
The other way is to iterate over it and count how big it is.
Method 1:
If the method DoSomethingBeta was static you need only call:
Beta.DoSomethingBeta();
Method 2:
If Alpha extends from Beta you could call DoSomethingBeta() directly.
public class Alpha extends Beta{
public void DoSomethingAlpha() {
DoSomethingBeta(); //?
}
}
Method 3:
Alternatively you need to have access to an instance of Beta to call the methods from it.
public class Alpha {
public void DoSomethingAlpha() {
Beta cbeta = new Beta();
cbeta.DoSomethingBeta(); //?
}
}
Incidentally is this homework?
I believe this is the simplest example:
header := w.Header()
header.Add("Access-Control-Allow-Origin", "*")
header.Add("Access-Control-Allow-Methods", "DELETE, POST, GET, OPTIONS")
header.Add("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With")
You can also add a header for Access-Control-Max-Age
and of course you can allow any headers and methods that you wish.
Finally you want to respond to the initial request:
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
Edit (June 2019): We now use gorilla for this. Their stuff is more actively maintained and they have been doing this for a really long time. Leaving the link to the old one, just in case.
Old Middleware Recommendation below: Of course it would probably be easier to just use middleware for this. I don't think I've used it, but this one seems to come highly recommended.
I have written two simple functions that give the same functionality as $stmt->get_result();
, but they don't require the mysqlnd driver.
You simply replace
$result = $stmt->get_result();
with $fields = bindAll($stmt);
and
$row= $stmt->get_result();
with $row = fetchRowAssoc($stmt, $fields);
.
(To get the numbers of returned rows you can use $stmt->num_rows
.)
You just have to place these two functions I have written somewhere in your PHP Script. (for example right at the bottom)
function bindAll($stmt) {
$meta = $stmt->result_metadata();
$fields = array();
$fieldRefs = array();
while ($field = $meta->fetch_field())
{
$fields[$field->name] = "";
$fieldRefs[] = &$fields[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $fieldRefs);
$stmt->store_result();
//var_dump($fields);
return $fields;
}
function fetchRowAssoc($stmt, &$fields) {
if ($stmt->fetch()) {
return $fields;
}
return false;
}
How it works:
My code uses the $stmt->result_metadata();
function to figure out how many and which fields are returned and then automatically binds the fetched results to pre-created references. Works like a charm!
If based on click here it is:
ng-click="orderReverse = orderReverse ? false : true"
It is not possible to get HTTP Response code by using Selenium WebDriver directly. The code can be got by using Java code and that can be used in Selenium WebDriver.
To get HTTP Response code by java:
public static int getResponseCode(String urlString) throws MalformedURLException, IOException{
URL url = new URL(urlString);
HttpURLConnection huc = (HttpURLConnection)url.openConnection();
huc.setRequestMethod("GET");
huc.connect();
return huc.getResponseCode();
}
Now you can write your Selenium WebDriver code as below:
private static int statusCode;
public static void main(String... args) throws IOException{
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://www.google.com/");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
List<WebElement> links = driver.findElements(By.tagName("a"));
for(int i = 0; i < links.size(); i++){
if(!(links.get(i).getAttribute("href") == null) && !(links.get(i).getAttribute("href").equals(""))){
if(links.get(i).getAttribute("href").contains("http")){
statusCode= getResponseCode(links.get(i).getAttribute("href").trim());
if(statusCode == 403){
System.out.println("HTTP 403 Forbidden # " + i + " " + links.get(i).getAttribute("href"));
}
}
}
}
}
This question has been answered over and over again :-) but why not.
First using tput
is more portable in modern environments than manually injecting ASCII codes through echo -E
Here's a quick bash function:
say() {
echo "$@" | sed \
-e "s/\(\(@\(red\|green\|yellow\|blue\|magenta\|cyan\|white\|reset\|b\|u\)\)\+\)[[]\{2\}\(.*\)[]]\{2\}/\1\4@reset/g" \
-e "s/@red/$(tput setaf 1)/g" \
-e "s/@green/$(tput setaf 2)/g" \
-e "s/@yellow/$(tput setaf 3)/g" \
-e "s/@blue/$(tput setaf 4)/g" \
-e "s/@magenta/$(tput setaf 5)/g" \
-e "s/@cyan/$(tput setaf 6)/g" \
-e "s/@white/$(tput setaf 7)/g" \
-e "s/@reset/$(tput sgr0)/g" \
-e "s/@b/$(tput bold)/g" \
-e "s/@u/$(tput sgr 0 1)/g"
}
Now you can use:
say @b@green[[Success]]
to get:
tput
First time tput(1)
source code was uploaded in September 1986
tput(1)
has been available in X/Open curses semantics in 1990s (1997 standard has the semantics mentioned below).
So, it's (quite) ubiquitous.
From the docs
In the Java programming language, every application must contain a main method whose signature is:
public static void main(String[] args)
The modifiers public and static can be written in either order (public static or static public), but the convention is to use public static as shown above. You can name the argument anything you want, but most programmers choose "args" or "argv".
As you say:
error: missing method body, or declare abstract public static void main(String[] args); ^ this is what i got after i added it after the class name
You probably haven't declared main with a body (as ';" would suggest in your error).
You need to have main method with a body, which means you need to add { and }:
public static void main(String[] args) {
}
Add it inside your class definition.
Although sometimes error messages are not very clear, most of the time they contain enough information to point to the issue. Worst case, you can search internet for the error message. Also, documentation can be really helpful.
if status
is of type Status
enum, status.name()
will give you its defined name.
With angular4 we just need to organise routes together in hierarchy
const appRoutes: Routes = [
{
path: '',
component: MainPageComponent
},
{
path: 'car/details',
component: CarDetailsComponent
},
{
path: 'car/details/platforms-products',
component: CarProductsComponent
},
{
path: 'car/details/:id',
component: CadDetailsComponent
},
{
path: 'car/details/:id/platforms-products',
component: CarProductsComponent
}
];
This works for me . This way router know what is the next route based on option id parameters.
As has been mentioned by others, std::unique_lock tracks the locked status of the mutex, so you can defer locking until after construction of the lock, and unlock before destruction of the lock. std::lock_guard does not permit this.
There seems no reason why the std::condition_variable wait functions should not take a lock_guard as well as a unique_lock, because whenever a wait ends (for whatever reason) the mutex is automatically reacquired so that would not cause any semantic violation. However according to the standard, to use a std::lock_guard with a condition variable you have to use a std::condition_variable_any instead of std::condition_variable.
Edit: deleted "Using the pthreads interface std::condition_variable and std::condition_variable_any should be identical". On looking at gcc's implementation:
Git can search diffs with the -S option (it's called pickaxe in the docs)
git log -S password
This will find any commit that added or removed the string password
. Here a few options:
-p
: will show the diffs. If you provide a file (-p file
), it will generate a patch for you.-G
: looks for differences whose added or removed line matches the given regexp, as opposed to -S
, which "looks for differences that introduce or remove an instance of string".--all
: searches over all branches and tags; alternatively, use --branches[=<pattern>]
or --tags[=<pattern>]
One possibility is when installed sql server data tools Bi, while sql server was already set up.
Solution:- 1.Just Repair the sql server with the set up instance
if solution does not work , than its worth your time meddling with services.msc
Add these 2 lines
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
So you have:
// Do any additional setup after loading the view, typically from a nib.
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom: 10, right: 0)
layout.itemSize = CGSize(width: screenWidth/3, height: screenWidth/3)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
collectionView!.collectionViewLayout = layout
That will remove all the spaces and give you a grid layout:
If you want the first column to have a width equal to the screen width then add the following function:
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
if indexPath.row == 0
{
return CGSize(width: screenWidth, height: screenWidth/3)
}
return CGSize(width: screenWidth/3, height: screenWidth/3);
}
Grid layout will now look like (I've also added a blue background to first cell):
There are a lot of ways you can call a shell command from a Perl script, such as:
ls
which captures the output and gives back to you.Refer #17 here: Perl programming tips
You could unregister the control with
regsvr32 /u badboy.ocx
at the command line. Though i would suggest testing these things in a vmware.
does
$('#elem').css('-webkit-transition','none !important');
in your js kill it?
obviously repeat for each.
Technically, I have seen HTTP GET will have issues if the URL length goes beyond 2000 characters. In that case, it's better to use HTTP POST or split the URL.
SELECT ... INTO ...
only works if the table specified in the INTO clause does not exist - otherwise, you have to use:
INSERT INTO dbo.TABLETWO
SELECT col1, col2
FROM dbo.TABLEONE
WHERE col3 LIKE @search_key
This assumes there's only two columns in dbo.TABLETWO - you need to specify the columns otherwise:
INSERT INTO dbo.TABLETWO
(col1, col2)
SELECT col1, col2
FROM dbo.TABLEONE
WHERE col3 LIKE @search_key
That's simple, in Java
your_component.setRotation(15);
or
your_component.setRotation(295.18f);
in XML
<Button android:rotation="15" />
If you have access to a linux box with mdbtools installed, you can use this Bash shell script (save as mdbconvert.sh):
#!/bin/bash
TABLES=$(mdb-tables -1 $1)
MUSER="root"
MPASS="yourpassword"
MDB="$2"
MYSQL=$(which mysql)
for t in $TABLES
do
$MYSQL -u $MUSER -p$MPASS $MDB -e "DROP TABLE IF EXISTS $t"
done
mdb-schema $1 mysql | $MYSQL -u $MUSER -p$MPASS $MDB
for t in $TABLES
do
mdb-export -D '%Y-%m-%d %H:%M:%S' -I mysql $1 $t | $MYSQL -u $MUSER -p$MPASS $MDB
done
To invoke it simply call it like this:
./mdbconvert.sh accessfile.mdb mysqldatabasename
It will import all tables and all data.
Standard way of passing data from one activity to another:
If you want to send large number of data from one activity to another activity then you can put data in a bundle and then pass it using putExtra()
method.
//Create the `intent`
Intent i = new Intent(this, ActivityTwo.class);
String one="xxxxxxxxxxxxxxx";
String two="xxxxxxxxxxxxxxxxxxxxx";
//Create the bundle
Bundle bundle = new Bundle();
//Add your data to bundle
bundle.putString(“ONE”, one);
bundle.putString(“TWO”, two);
//Add the bundle to the intent
i.putExtras(bundle);
//Fire that second activity
startActivity(i);
otherwise you can use putExtra()
directly with intent to send data and getExtra()
to get data.
Intent i=new Intent(this, ActivityTwo.class);
i.putExtra("One",one);
i.putExtra("Two",two);
startActivity(i);
You can try something like this
list = ["a", "b", "C", "d", "e", "f", "r"]
for i in range(0, len(list), 2):
print list[i]
if len(list) % 2 == 1 and i == len(list)-1:
break
print list[i+1];
I use max function:
max(None, '') #Returns blank
max("Hello",'') #Returns Hello
Works like a charm ;) Just put your string in the first parameter of the function.
$("input").datepicker({ dateFormat: 'dd, mm, yy' });
later in your code when the date is set you could get it by
dateVariable = $("input").val();
dateString = $.datepicker.formatDate('dd, MM, yy', new Date("20 April 2012"));
I've updated the jsfiddle for experimenting with this
Funny, I was just researching this yesterday!
I personally use Monaco 10 or 11 for the Mac, but a good cross platform font would have to be Droid Sans Mono: http://damieng.com/blog/2007/11/14/droid-sans-mono-great-coding-font Or DejaVu sans mono is another great one (goes under a lot of different names, will be Menlo on SNow leopard and is really just a repackaged Prima/Vera) check it out here: Prima/Vera... Check it out here: http://dejavu-fonts.org/wiki/index.php?title=Download
Check this: http://jsfiddle.net/h7kRt/1/,
you should change in jsfiddle on top-left to No-wrap in <head>
Your code looks good and it will work inside a normal page. In jsfiddle your function was being defined inside a load handler and thus is in a different scope. By changing to No-wrap you have it in the global scope and can use it as you wanted.
If input stream is not closed properly then this exception may happen. make sure : If inputstream used is not used "Before" in some way then where you are intended to read. i.e if read 2nd time from same input stream in single operation then 2nd call will get this exception. Also make sure to close input stream in finally block or something like that.
You're setting overflow: hidden
. This will hide anything that's too large for the <div>
, meaning scrollbars won't be shown. Give your <div>
an explicit width and/or height, and change overflow
to auto
:
.scroll {
width: 200px;
height: 400px;
overflow: scroll;
}
If you only want to show a scrollbar if the content is longer than the <div>
, change overflow
to overflow: auto
. You can also only show one scrollbar by using overflow-y
or overflow-x
.
Sharer.php no longer allows you to customize. The page you share will be scraped for OG Tags and that data will be shared.
To properly customize, use FB.UI
which comes with the JS-SDK.
Ok so the key for me was to use the .FlattenHierarchy BindingFlag. I don't really know why I just added it on a hunch and it started working. So the final solution that allows me to get Public Instance or Static Properties is:
obj.GetType.GetProperty(propName, Reflection.BindingFlags.Public _
Or Reflection.BindingFlags.Static Or Reflection.BindingFlags.Instance Or _
Reflection.BindingFlags.FlattenHierarchy)
For Xcode 6.3:
cell.selectionStyle = UITableViewCellSelectionStyle.None;
String[] w = {"a", "b", "c", "d", "e"};
List<String> wL = Arrays.asList(w);
Never use .onclick()
, or similar attributes from a userscript! (It's also poor practice in a regular web page).
The reason is that userscripts operate in a sandbox ("isolated world"), and onclick
operates in the target-page scope and cannot see any functions your script creates.
Always use addEventListener()
Doc (or an equivalent library function, like jQuery .on()).
So instead of code like:
something.outerHTML += '<input onclick="resetEmotes()" id="btnsave" ...>'
You would use:
something.outerHTML += '<input id="btnsave" ...>'
document.getElementById ("btnsave").addEventListener ("click", resetEmotes, false);
For the loop, you can't pass data to an event listener like that See the doc. Plus every time you change innerHTML
like that, you destroy the previous event listeners!
Without refactoring your code much, you can pass data with data attributes. So use code like this:
for (i = 0; i < EmoteURLLines.length; i++) {
if (checkIMG (EmoteURLLines[i])) {
localStorage.setItem ("nameEmotes", JSON.stringify (EmoteNameLines));
localStorage.setItem ("urlEmotes", JSON.stringify (EmoteURLLines));
localStorage.setItem ("usageEmotes", JSON.stringify (EmoteUsageLines));
if (i == 0) {
console.log (resetSlot ());
}
emoteTab[2].innerHTML += '<span style="cursor:pointer;" id="'
+ EmoteNameLines[i]
+ '" data-usage="' + EmoteUsageLines[i] + '">'
+ '<img src="' + EmoteURLLines[i] + '" /></span>'
;
} else {
alert ("The maximum emote (" + EmoteNameLines[i] + ") size is (36x36)");
}
}
//-- Only add events when innerHTML overwrites are done.
var targetSpans = emoteTab[2].querySelectorAll ("span[data-usage]");
for (var J in targetSpans) {
targetSpans[J].addEventListener ("click", appendEmote, false);
}
Where appendEmote is like:
function appendEmote (zEvent) {
//-- this and the parameter are special in event handlers. see the linked doc.
var emoteUsage = this.getAttribute ("data-usage");
shoutdata.value += emoteUsage;
}
.outerHTML
or .innerHTML
, you trash any event handlers on the affected nodes. If you use this method beware of that fact.You can't do compareAndSet
, getAndSet
as atomic operation with volatile boolean (unless of course you synchronize it).
After much struggle with this same issue I was able to solve the problem by installing the 32 bit version of the 2010 Access Database Engine. For some reason the 64bit version generates this error...
Try this
AppDomain.CurrentDomain.SetupInformation.ConfigurationFile
Although this is an old document, but it helped me resolve the problem of 'HintPath' being ignored on another machine. It was because the referenced DLL needed to be in source control as well:
Excerpt:
To include and then reference an outer-system assembly 1. In Solution Explorer, right-click the project that needs to reference the assembly,,and then click Add Existing Item. 2. Browse to the assembly, and then click OK. The assembly is then copied into the project folder and automatically added to VSS (assuming the project is already under source control). 3. Use the Browse button in the Add Reference dialog box to set a file reference to assembly in the project folder.
From the id Selector jQuery page:
Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on, however; a document with more than one element using the same ID is invalid.
Naughty Google. But they don't even close their <html>
and <body>
tags I hear. The question is though, why Misha's 2nd and 3rd queries return 2 and not 1 as well.
Couldn't we do something like this:
public class Singleton {
private int x;
// Private constructor prevents instantiation from other classes
private Singleton() {}
/**
* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance(int x) {
Singleton instance = SingletonHolder.INSTANCE;
instance.x = x;
return instance;
}
}
OK so I know I'm a little late and some of the above answers are great stuff.
As little extra though, while in any PHPMyAdmin page:
this will then show your last entered query.
The InnoDB engine does not store deleted data. As you insert and delete rows, unused space is left allocated within the InnoDB storage files. Over time, the overall space will not decrease, but over time the 'deleted and freed' space will be automatically reused by the DB server.
You can further tune and manage the space used by the engine through an manual re-org of the tables. To do this, dump the data in the affected tables using mysqldump, drop the tables, restart the mysql service, and then recreate the tables from the dump files.
You can only call instance method like do()
(which is an illegal method name, incidentally) against an instance of the class:
public static void main(String[] args){
new Foo().doSomething();
}
public void doSomething(){}
Alternatively, make doSomething()
static as well, if that works for your design.
Add the following in the config file, and it will be caught in try catch block. Word of caution... try to avoid this situation, as this means some kind of violation is happening.
<configuration>
<runtime>
<legacyCorruptedStateExceptionsPolicy enabled="true" />
</runtime>
</configuration>
You could try a different approach like read the file line by line instead of dealing with all this nl2br / explode stuff.
$fh = fopen("employees.txt", "r"); if ($fh) { while (($line = fgets($fh)) !== false) { $line = trim($line); echo "<option value='".$line."'>".$line."</option>"; } } else { // error opening the file, do something }
Also maybe just doing a trim (remove whitespace from beginning/end of string) is your issue?
And maybe people are just misunderstanding what you mean by "submitting results to a spreadsheet" -- are you doing this with code? or a copy/paste from an HTML page into a spreadsheet? Maybe you can explain that in more detail. The delimiter for which you split the lines of the file shouldn't be displaying in the output anyway unless you have unexpected output for some other reason.
you cant ALTER/MODIFY your TYPE. You have to drop the existing and re-create it with correct name/datatype or add a new column/s
I had problems with most of the tools in other answers as they are all very outdated.
If you need a solution that will "just work", pack a bare-bones version of php with your project in a WinRar SFX archive, set it to extract everything to a temporary directory and execute php your_script.php
.
To run a basic script, the only files required are php.exe
and php5.dll
(or php5ts.dll
depending on version).
To add extensions, pack them along with a php.ini file:
[PHP]
extension_dir = "."
extension=php_curl.dll
extension=php_xxxx.dll
...
public static boolean doCollectionsContainSameElements(
Collection<Integer> c1, Collection<Integer> c2){
if (c1 == null || c2 == null) {
return false;
}
else if (c1.size() != c2.size()) {
return false;
} else {
return c1.containsAll(c2) && c2.containsAll(c1);
}
}
To Save your bitmap in sdcard use the following code
Store Image
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
To Get the Path for Image Storage
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
EDIT From Your comments i have edited the onclick view in this the button1 and button2 functions will be executed separately.
public onClick(View v){
switch(v.getId()){
case R.id.button1:
//Your button 1 function
break;
case R.id. button2:
//Your button 2 function
break;
}
}
For SQL statements you can try reverse snowflakes. You can join at sourceforge or the demo site at http://snowflakejoins.com/.
You can modify the formData by catching the 'sending' event from your dropzone.
dropZone.on('sending', function(data, xhr, formData){
formData.append('fieldname', 'value');
});
great one... now i have stopped using % he he he... except for the main container as shown below:
<div id="divContainer">
<div id="divHeader">
</div>
<div id="divContentArea">
<div id="divContentLeft">
</div>
<div id="divContentRight">
</div>
</div>
<div id="divFooter">
</div>
</div>
and here is the css:
#divContainer {
width: 100%;
height: 100%;
}
#divHeader {
position: absolute;
left: 0px;
top: 0px;
right: 0px;
height: 28px;
}
#divContentArea {
position: absolute;
left: 0px;
top: 30px;
right: 0px;
bottom: 30px;
}
#divContentLeft {
position: absolute;
top: 0px;
left: 0px;
width: 250px;
bottom: 0px;
}
#divContentRight {
position: absolute;
top: 0px;
left: 254px;
right: 0px;
bottom: 0px;
}
#divFooter {
position: absolute;
height: 28px;
left: 0px;
bottom: 0px;
right: 0px;
}
i tested this in all known browsers and is working fine. Are there any drawbacks using this way?
I removed the _SUCCESS file from the EMR output path in S3 and it worked fine.
Since Spring 4.0+, the best solution is to annotate the test method with @WithMockUser
@Test
@WithMockUser(username = "user1", password = "pwd", roles = "USER")
public void mytest1() throws Exception {
mockMvc.perform(get("/someApi"))
.andExpect(status().isOk());
}
Remember to add the following dependency to your project
'org.springframework.security:spring-security-test:4.2.3.RELEASE'
This expands upon the answer by Robert, applying to when the values in the dict aren't unique.
class ReversibleDict(dict):
def reversed(self):
"""
Return a reversed dict, with common values in the original dict
grouped into a list in the returned dict.
Example:
>>> d = ReversibleDict({'a': 3, 'c': 2, 'b': 2, 'e': 3, 'd': 1, 'f': 2})
>>> d.reversed()
{1: ['d'], 2: ['c', 'b', 'f'], 3: ['a', 'e']}
"""
revdict = {}
for k, v in self.iteritems():
revdict.setdefault(v, []).append(k)
return revdict
The implementation is limited in that you cannot use reversed
twice and get the original back. It is not symmetric as such. It is tested with Python 2.6. Here is a use case of how I am using to print the resultant dict.
If you'd rather use a set
than a list
, and there could exist unordered applications for which this makes sense, instead of setdefault(v, []).append(k)
, use setdefault(v, set()).add(k)
.
I was having the same problem , I have just copied the code to new project and started the build . Some other error started coming. error C4996: 'fopen': This function or variable may be unsafe. Consider using fopen_s instead
To solve this problem again, I have added my one property in the Project project as below. Project -> Properties -> Configuration property -> c/c++ . In this category there is field name Preprocessor Definitions I have added _CRT_SECURE_NO_WARNINGS this to solve the problem Hope it will help ...
Thank You
It can be accomplished like this docs
$('input').trigger("keydown", {which: 50});
Try this:
DateTime date = DateTime.ParseExact(
"Tue, 1 Jan 2008 00:00:00 UTC",
"ddd, d MMM yyyy HH:mm:ss UTC",
CultureInfo.InvariantCulture);
As of Python 3.6 you can just do
>>> strng = 'hi'
>>> f'{strng: <10}'
with literal string interpolation.
Or, if your padding size is in a variable, like this (thanks @Matt M.!):
>>> to_pad = 10
>>> f'{strng: <{to_pad}}'
Just in case someone else stumbles on this. I was running someone else's code - make sure they are not handling the signal, so they can gracefully exit. I commented out the handling, and got the core dump.
In my case, the simplified solution worked fine. The override method must be in your custom viewpager adapter to override TouchEvent listeners and make'em freeze;
@Override
public boolean onTouchEvent(MotionEvent event) {
return this.enabled && super.onTouchEvent(event);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
return this.enabled && super.onInterceptTouchEvent(event);
}
I saved NSDictionary normally and able to get it correctly.
dictForaddress = placemark.addressDictionary! as NSDictionary
let userDefaults = UserDefaults.standard
userDefaults.set(dictForaddress, forKey:Constants.kAddressOfUser)
// For getting data from NSDictionary.
let userDefaults = UserDefaults.standard
let dictAddress = userDefaults.object(forKey: Constants.kAddressOfUser) as! NSDictionary
I used mkdir -p /root/.android && touch /root/.android/repositories.cfg to make it works
Either use window.onload
this way
<script>
window.onload = function() {
// ...
}
</script>
or alternatively
<script>
window.onload = functionName;
</script>
(yes, without the parentheses)
Or just put the script at the very bottom of page, right before </body>
. At that point, all HTML DOM elements are ready to be accessed by document
functions.
<body>
...
<script>
functionName();
</script>
</body>
Could use Tortoise:
http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-branchtag.html
You can't use php code client-side. You need to use javascript.
<input type="button" value="Home" class="homebutton" id="btnHome"
onClick="document.location.href='some/page'" />
However, you really shouldn't be using inline js (like onclick here). Study about this here: https://www.google.com/search?q=Why+is+inline+js+bad%3F
Here's a clean way of doing this: Live demo (click).
Markup:
<button id="myBtn">Redirect</button>
JavaScript:
var btn = document.getElementById('myBtn');
btn.addEventListener('click', function() {
document.location.href = 'some/page';
});
If you need to write in the location with php:
<button id="myBtn">Redirect</button>
<script>
var btn = document.getElementById('myBtn');
btn.addEventListener('click', function() {
document.location.href = '<?php echo $page; ?>';
});
</script>
Lucas's answer about core dumps is good. In my .cshrc I have:
alias core 'ls -lt core; echo where | gdb -core=core -silent; echo "\n"'
to display the backtrace by entering 'core'. And the date stamp, to ensure I am looking at the right file :(.
Added: If there is a stack corruption bug, then the backtrace applied to the core dump is often garbage. In this case, running the program within gdb can give better results, as per the accepted answer (assuming the fault is easily reproducible). And also beware of multiple processes dumping core simultaneously; some OS's add the PID to the name of the core file.
This works fine for me:
while True:
answer = input('Do you want to continue?:')
if answer.lower().startswith("y"):
print("ok, carry on then")
elif answer.lower().startswith("n"):
print("sayonara, Robocop")
exit()
edit: use input
in python 3.2 instead of raw_input
change the background color of cell B5 based on the value of another cell - C5. If C5 is greater than 80% then the background color is green but if it's below, it will be amber/red.
There is no mention that B5 contains any value so assuming 80%
is .8
formatted as percentage without decimals and blank counts as "below":
Select B5, colour "amber/red" with standard fill then Format - Conditional formatting..., Custom formula is and:
=C5>0.8
with green fill and Done.
Take attention on -e ssh and jenkins@localhost: in next example:
rsync -r -e ssh --chown=jenkins:admin --exclude .git --exclude Jenkinsfile --delete ./ jenkins@localhost:/home/admin/web/xxx/public
That helped me
P.S. Today, i realized that when you change (add) jenkins user to some group, permission will apply after slave (agent) restart. And my solution (-e ssh and jenkins@localhost:) need only when you can't restart agent/server.
Simple answer : free(testPerson)
is enough .
Remember you can use free()
only when you have allocated memory using malloc
, calloc
or realloc
.
In your case you have only malloced memory for testPerson
so freeing that is sufficient.
If you have used char * firstname , *last surName
then in that case to store name you must have allocated the memory and that's why you had to free each member individually.
Here is also a point it should be in the reverse order; that means, the memory allocated for elements is done later so free()
it first then free the pointer to object.
Freeing each element you can see the demo shown below:
typedef struct Person
{
char * firstname , *last surName;
}Person;
Person *ptrobj =malloc(sizeof(Person)); // memory allocation for struct
ptrobj->firstname = malloc(n); // memory allocation for firstname
ptrobj->surName = malloc(m); // memory allocation for surName
.
. // do whatever you want
free(ptrobj->surName);
free(ptrobj->firstname);
free(ptrobj);
The reason behind this is, if you free the ptrobj
first, then there will be memory leaked which is the memory allocated by firstname
and suName
pointers.
For me such trick made a job:
height: calc(100vh - calc(100vh - 100%))
In 2018 and thenceforth we shall use [...Array(500)]
to that end.
Javascript which runs on the client machine can't access the local disk file system due to security restrictions.
If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.
Use os.path.getsize(path)
which will
Return the size, in bytes, of path. Raise
OSError
if the file does not exist or is inaccessible.
import os
os.path.getsize('C:\\Python27\\Lib\\genericpath.py')
Or use os.stat(path).st_size
import os
os.stat('C:\\Python27\\Lib\\genericpath.py').st_size
Or use Path(path).stat().st_size
(Python 3.4+)
from pathlib import Path
Path('C:\\Python27\\Lib\\genericpath.py').stat().st_size
TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
tbx.Text = "found!";
If Controls.Find is not found "textBox1" => error. You must add code.
If(tbx != null)
Edit:
TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
If(tbx != null)
tbx.Text = "found!";
I'll give a slightly advanced answer. In Python, functions are first-class objects. This means they can be "dynamically created, destroyed, passed to a function, returned as a value, and have all the rights as other variables in the programming language have."
Calling a function/class instance in Python means invoking the __call__
method of that object. For old-style classes, class instances are also callable but only if the object which creates them has a __call__
method. The same applies for new-style classes, except there is no notion of "instance" with new-style classes. Rather they are "types" and "objects".
As quoted from the Python 2 Data Model page, for function objects, class instances(old style classes), and class objects(new-style classes), "x(arg1, arg2, ...)
is a shorthand for x.__call__(arg1, arg2, ...)
".
Thus whenever you define a function with the shorthand def funcname(parameters):
you are really just creating an object with a method __call__
and the shorthand for __call__
is to just name the instance and follow it with parentheses containing the arguments to the call. Because functions are first class objects in Python, they can be created on the fly with dynamic parameters (and thus accept dynamic arguments). This comes into handy with decorator functions/classes which you will read about later.
For now I suggest reading the Official Python Tutorial.
This is a silly answer, but the problem for me was that I failed to realize I already had been issued an active oAuth token for my google user which I failed to store. The solution in this case is to go to the api console and reset the client secret.
There are numerous other answers on SO to this effect for example Reset Client Secret OAuth2 - Do clients need to re-grant access?
We had the same issue, working from JS code (i.e. not from HTML anchor). This is how we solved that:
If needed, virtually alter current URL through $location
service. This might be useful if your destination is just a variation on the current URL, so that you can take advantage of $location
helper methods. E.g. we ran $location.search(..., ...)
to just change value of a querystring paramater.
Build up the new destination URL, using current $location.url()
if needed. In order to work, this new one had to include everything after schema, domain and port. So e.g. if you want to move to:
http://yourdomain.com/YourAppFolder/YourAngularApp/#/YourArea/YourAction?culture=en
then you should set URL as in:
var destinationUrl = '/YourAppFolder/YourAngularApp/#/YourArea/YourAction?culture=en';
(with the leading '/'
as well).
Assign new destination URL at low-level: $window.location.href = destinationUrl;
Force reload, still at low-level: $window.location.reload();
$(info your_text)
: Information. This doesn't stop the execution.
$(warning your_text)
: Warning. This shows the text as a warning.
$(error your_text)
: Fatal Error. This will stop the execution.
I had the same problem when I was trying to upgrade from ADT 20.0.x to ADT 23.0.x on Eclipse Indigo.
To fix the issue, I had to uninstall the ADT plugin (remove feature) from Eclipse, then reinstall the newer versions.
This maybe done by going to Help->Install New Software
. Then at the bottom of the page, click What is already installed?
All what is left now is to install the newer versions as usual from help->Install New Software
.
class Item{
bool IsNullOrZero{ get{return ((this.Rate ?? 0) == 0);}}
}
This is created using the reference of http://gitignore.io/ Where you can create the latest updated gitignore file for any project. For Android http://gitignore.io/api/androidstudio. Hope this helps. Currently I am using Android Studio 3.6.3
# Created by https://www.gitignore.io/api/androidstudio
# Edit at https://www.gitignore.io/?templates=androidstudio
### AndroidStudio ###
# Covers files to be ignored for android development using Android Studio.
# Built application files
*.apk
*.ap_
# Files for the ART/Dalvik VM
*.dex
# Java class files
*.class
# Generated files
bin/
gen/
out/
# Gradle files
.gradle
.gradle/
build/
# Signing files
.signing/
# Local configuration file (sdk path, etc)
local.properties
# Proguard folder generated by Eclipse
proguard/
# Log Files
*.log
# Android Studio
/*/build/
/*/local.properties
/*/out
/*/*/build
/*/*/production
captures/
.navigation/
*.ipr
*~
*.swp
# Android Patch
gen-external-apklibs
# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild
# NDK
obj/
# IntelliJ IDEA
*.iml
*.iws
/out/
# User-specific configurations
.idea/caches/
.idea/libraries/
.idea/shelf/
.idea/workspace.xml
.idea/tasks.xml
.idea/.name
.idea/compiler.xml
.idea/copyright/profiles_settings.xml
.idea/encodings.xml
.idea/misc.xml
.idea/modules.xml
.idea/scopes/scope_settings.xml
.idea/dictionaries
.idea/vcs.xml
.idea/jsLibraryMappings.xml
.idea/datasources.xml
.idea/dataSources.ids
.idea/sqlDataSources.xml
.idea/dynamic.xml
.idea/uiDesigner.xml
.idea/assetWizardSettings.xml
# OS-specific files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
# Legacy Eclipse project files
.classpath
.project
.cproject
.settings/
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.war
*.ear
# virtual machine crash logs (Reference: http://www.java.com/en/download/help/error_hotspot.xml)
hs_err_pid*
## Plugin-specific files:
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Mongo Explorer plugin
.idea/mongoSettings.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
### AndroidStudio Patch ###
!/gradle/wrapper/gradle-wrapper.jar
# End of https://www.gitignore.io/api/androidstudio
The datasource is by default .\SQLEXPRESS (its the instance where databases are placed by default) or if u changed the name of the instance during installation of sql server so i advise you to do this :
connectionString="Data Source=.\\yourInstance(defaulT Data source is SQLEXPRESS);
Initial Catalog=databaseName;
User ID=theuser if u use it;
Password=thepassword if u use it;
integrated security=true(if u don t use user and pass; else change it false)"
Without to knowing your instance, I could help with this one. Hope it helped
--Code for same server
USE [mydb1]
GO
INSERT INTO dbo.mytable1 (
column1
,column2
,column3
,column4
)
SELECT column1
,column2
,column3
,column4
FROM [mydb2].dbo.mytable2 --WHERE any condition
/*
steps-
1- [mydb1] means our opend connection database
2- mytable1 the table in mydb1 database where we want insert record
3- mydb2 another database.
4- mytable2 is database table where u fetch record from it.
*/
--Code for different server
USE [mydb1]
SELECT *
INTO mytable1
FROM OPENDATASOURCE (
'SQLNCLI'
,'Data Source=XXX.XX.XX.XXX;Initial Catalog=mydb2;User ID=XXX;Password=XXXX'
).[mydb2].dbo.mytable2
/* steps -
1- [mydb1] means our opend connection database
2- mytable1 means create copy table in mydb1 database where we want
insert record
3- XXX.XX.XX.XXX - another server name.
4- mydb2 another server database.
5- write User id and Password of another server credential
6- mytable2 is another server table where u fetch record from it. */
I tried following this, and got the error
TypeError: ufunc 'true_divide' output (typecode 'd') could not be coerced to provided output parameter (typecode 'l') according to the casting rule ''same_kind''
The numpy
array I was trying to normalize was an integer
array. It seems they deprecated type casting in versions > 1.10
, and you have to use numpy.true_divide()
to resolve that.
arr = np.array(img)
arr = np.true_divide(arr,[255.0],out=None)
img
was an PIL.Image
object.
I have run into a similar problem on Mac.
Looking at the log under Help -> Show logs in Finder I found the following entry.
You have JVM property "https.proxyHost" set to "127.0.0.1".
This may lead to incorrect behaviour. Proxy should be set in Settings | HTTP Proxy
This JVM property is old and its usage is not recommended by Oracle.
(Note: It could have been assigned by some code dynamically.)
and it turned out I had Charles as a network proxy running. Shutting down Charles solved the problem.
Try passing width=200
as additional paramater when creating the Label.
This should work in creating label with specified width.
If you want to change it later, you can use:
label.config(width=200)
As you want to change the size of font itself you can try:
label.config(font=("Courier", 44))
For those using npm to install packages, you can install jquery via npm install jquery
and then use elixir to compile jquery and your other npm packages into one file (e.g. vendor.js). Here's a sample gulpfile.js
var elixir = require('laravel-elixir');
elixir(function(mix) {
mix
.scripts([
'jquery/dist/jquery.min.js',
// list your other npm packages here
],
'public/js/vendor.js', // 2nd param is the output file
'node_modules') // 3rd param is saying "look in /node_modules/ for these scripts"
.scripts([
'scripts.js' // your custom js file located in default location: /resources/assets/js/
], 'public/js/app.js') // looks in default location since there's no 3rd param
.version([ // optionally append versioning string to filename
'js/vendor.js', // compiled files will be in /public/build/js/
'js/app.js'
]);
});
window.location
adds an item to your history in that you can (or should be able to) click "Back" and go back to the current page.
window.location.replace
replaces the current history item so you can't go back to it.
See window.location
:
assign(url)
: Load the document at the provided URL.
replace(url)
:Replace the current document with the one at the provided URL. The difference from theassign()
method is that after usingreplace()
the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.
Oh and generally speaking:
window.location.href = url;
is favoured over:
window.location = url;
Because of the GDPR it makes no sense to use the iframe, you should rather use the object tag with the embed tag and also use the embed link.
<object width="100%" height="333">
<param name="movie" value="https://www.youtube-nocookie.com/embed/Sdg0ef2PpBw">
<embed src="https://www.youtube-nocookie.com/embed/Sdg0ef2PpBw" width="100%" height="333">
</object>
_x000D_
You should also activate the extended data protection mode function to receive the no cookie url.
type="application/x-shockwave-flash"
flash does not have to be used
Nocookie, however, means that data is still being transmitted, namely the thumbnail that is loaded from YouTube. But at least data is no longer passed on to advertising networks (as example DoubleClick). And no user data is stored on your website by youtube.
Many times the bolded text is regarded in an information architecture way on another level and thus not have bolded and regular in one line, so you can split it to two labels/textViews, one regular and on bold italic. And use the editor to choose the font styles.
Create a custom return type that will propagate the checked exception. This is an alternative to creating a new interface that mirrors the existing functional interface with the slight modification of a "throws exception" on the functional interface's method.
public static interface CheckedValueSupplier<V> {
public V get () throws Exception;
}
public class CheckedValue<V> {
private final V v;
private final Optional<Exception> opt;
public Value (V v) {
this.v = v;
}
public Value (Exception e) {
this.opt = Optional.of(e);
}
public V get () throws Exception {
if (opt.isPresent()) {
throw opt.get();
}
return v;
}
public Optional<Exception> getException () {
return opt;
}
public static <T> CheckedValue<T> returns (T t) {
return new CheckedValue<T>(t);
}
public static <T> CheckedValue<T> rethrows (Exception e) {
return new CheckedValue<T>(e);
}
public static <V> CheckedValue<V> from (CheckedValueSupplier<V> sup) {
try {
return CheckedValue.returns(sup.get());
} catch (Exception e) {
return Result.rethrows(e);
}
}
public static <V> CheckedValue<V> escalates (CheckedValueSupplier<V> sup) {
try {
return CheckedValue.returns(sup.get());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
// Don't use this pattern with FileReader, it's meant to be an
// example. FileReader is a Closeable resource and as such should
// be managed in a try-with-resources block or in another safe
// manner that will make sure it is closed properly.
// This will not compile as the FileReader constructor throws
// an IOException.
Function<String, FileReader> sToFr =
(fn) -> new FileReader(Paths.get(fn).toFile());
// Alternative, this will compile.
Function<String, CheckedValue<FileReader>> sToFr = (fn) -> {
return CheckedValue.from (
() -> new FileReader(Paths.get("/home/" + f).toFile()));
};
// Single record usage
// The call to get() will propagate the checked exception if it exists.
FileReader readMe = pToFr.apply("/home/README").get();
// List of records usage
List<String> paths = ...; //a list of paths to files
Collection<CheckedValue<FileReader>> frs =
paths.stream().map(pToFr).collect(Collectors.toList());
// Find out if creation of a file reader failed.
boolean anyErrors = frs.stream()
.filter(f -> f.getException().isPresent())
.findAny().isPresent();
A single functional interface that throws a checked exception is created (CheckedValueSupplier
). This will be the only functional interface which allows checked exceptions. All other functional interfaces will leverage the CheckedValueSupplier
to wrap any code that throws a checked exception.
The CheckedValue
class will hold the result of executing any logic that throws a checked exception. This prevents propagation of a checked exception until the point at which code attempts to access the value that an instance of CheckedValue
contains.
CheckedValue#get()
is called.Some functional interfaces (Consumer
for example) must be handled in a different manner as they don't provide a return value.
One approach is to use a function instead of a consumer, which applies when handling streams.
List<String> lst = Lists.newArrayList();
// won't compile
lst.stream().forEach(e -> throwyMethod(e));
// compiles
lst.stream()
.map(e -> CheckedValueSupplier.from(
() -> {throwyMethod(e); return e;}))
.filter(v -> v.getException().isPresent()); //this example may not actually run due to lazy stream behavior
Alternatively, you can always escalate to a RuntimeException
. There are other answers that cover escalation of a checked exception from within a Consumer
.
Just avoid functional interfaces all together and use a good-ole-fashioned for loop.
Another variation of Iftah
var counter = 10;
var checkExist = setInterval(function() {
console.log(counter);
counter--
if ($('#the-canvas').length || counter === 0) {
console.log("by bye!");
clearInterval(checkExist);
}
}, 200);
Just in case the element is never shown, so we don't check infinitely.
Just in case someone stumbles here, I did it this way
componentDidMount(){
const node = this.refs.trackerRef;
node && node.scrollIntoView({block: "end", behavior: 'smooth'})
}
componentDidUpdate() {
const node = this.refs.trackerRef;
node && node.scrollIntoView({block: "end", behavior: 'smooth'})
}
render() {
return (
<div>
{messages.map((msg, index) => {
return (
<Message key={index} msgObj={msg}
{/*<p>some test text</p>*/}
</Message>
)
})}
<div style={{height: '30px'}} id='#tracker' ref="trackerRef"></div>
</div>
)
}
scrollIntoView
is native DOM feature link
It will always shows tracker
div
What the others said, but also note that you do not have to declare the destructor virtual in the derived class. Once you declare a destructor virtual, as you do in the base class, all derived destructors will be virtual whether you declare them so or not. In other words:
struct A {
virtual ~A() {}
};
struct B : public A {
virtual ~B() {} // this is virtual
};
struct C : public A {
~C() {} // this is virtual too
};
There is a plugin for that, jquery-formatcurrency.
You can set the decimal separator (default .
) and currency symbol (default $
) for custom formatting or use the built in International Support. The format for Bahasa Indonesia (Indonesia) - Indonesian (Indonesia) coded id-ID looks closest to what you have provided.
I liked @KyleMit's answer on how to make an unstyled input group, but in my case, I only wanted the right side unstyled - I still wanted to use an input-group-addon on the left side and have it look like normal bootstrap. So, I did this:
css
.input-group.input-group-unstyled-right input.form-control {
border-top-right-radius: 4px;
border-bottom-right-radius: 4px;
}
.input-group-unstyled-right .input-group-addon.input-group-addon-unstyled {
border-radius: 4px;
border: 0px;
background-color: transparent;
}
html
<div class="input-group input-group-unstyled-right">
<span class="input-group-addon">
<i class="fa fa-envelope-o"></i>
</span>
<input type="text" class="form-control">
<span class="input-group-addon input-group-addon-unstyled">
<i class="fa fa-check"></i>
</span>
</div>
You have to call the super.paintComponent();
as well, to allow the Java API draw the original background. The super refers to the original JPanel code.
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.red);
g.fillOval(player.getxCenter(), player.getyCenter(), player.getRadius(), player.getRadius());
}
Try this:
<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
The first matches any number of digits within your string (allows other characters too, i.e.: "039330a29"). The second allows only 45 digits (and not less). So just take the better from both:
^\d{1,45}$
where \d
is the same like [0-9]
.
The problem setting the layer's borderWidth
and borderColor
is that the when you touch the button the border doesn't animate the highlight effect.
Of course, you can observe the button's events and change the border color accordingly but that feels unnecessary.
Another option is to create a stretchable UIImage and setting it as the button's background image. You can create an Image set in your Images.xcassets like this:
Then, you set it as the button's background image:
If your image is a template image you can set tint color of the button and the border will change:
Now the border will highlight with the rest of the button when touched.
there are two ways to do this in jquery depending what you are looking for..
using jquery you can do
//this will wait for the text assets to be loaded before calling this (the dom.. css.. js)
$(document).ready(function(){...});
//this will wait for all the images and text assets to finish loading before executing
$(window).load(function(){...});
Sometimes yes they are related, and sometimes no they are not related, actually we sometimes use more space to get faster algorithms as in dynamic programming https://www.codechef.com/wiki/tutorial-dynamic-programming dynamic programming uses memoization or bottom-up, the first technique use the memory to remember the repeated solutions so the algorithm needs not to recompute it rather just get them from a list of solutions. and the bottom-up approach start with the small solutions and build upon to reach the final solution. Here two simple examples, one shows relation between time and space, and the other show no relation: suppose we want to find the summation of all integers from 1 to a given n integer: code1:
sum=0
for i=1 to n
sum=sum+1
print sum
This code used only 6 bytes from memory i=>2,n=>2 and sum=>2 bytes therefore time complexity is O(n), while space complexity is O(1) code2:
array a[n]
a[1]=1
for i=2 to n
a[i]=a[i-1]+i
print a[n]
This code used at least n*2 bytes from the memory for the array therefore space complexity is O(n) and time complexity is also O(n)
I was running in to the same issue, but have just managed a full uninstall by means of trusty old CMD:
D:\vs_ultimate.exe /uninstall /force
Where D: is the location of your installation media (mounted iso, etc).
You could also pass /passive (no user input required - just progress displayed) or /quiet to the above command line.
EDIT: Adding link below to MSDN article mentioning that this forcibly removes ALL installed components.
Also, to ensure link rot doesn't invalidate this, adding brief text below from original article.
Starting with Visual Studio 2013, you can forcibly remove almost all components. A few core components – like the .NET Framework and VC runtimes – are left behind because of their ubiquity, though you can remove those separately from Programs and Features if you really want.
Warning: This will remove all components regardless of whether other products require them. This may cause other products to function incorrectly or not function at all.
Good luck!
$(document).keydown(function(e) {_x000D_
if ((e.key == 's' || e.key == 'S' ) && (e.ctrlKey || e.metaKey))_x000D_
{_x000D_
e.preventDefault();_x000D_
alert("Ctrl-s pressed");_x000D_
return false;_x000D_
}_x000D_
return true;_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
Try pressing ctrl+s somewhere.
_x000D_
This is an up-to-date version of @AlanBellows's answer, replacing which
with key
. It also works even with Chrome's capital key glitch (where if you press Ctrl+S it sends capital S instead of s). Works in all modern browsers.
In case a large chunk of data is deleted from a collection and the collection never uses the deleted space for new documents, this space needs to be returned to the operating system so that it can be used by other databases or collections. You will need to run a compact or repair operation in order to defragment the disk space and regain the usable free space.
Behavior of compaction process is dependent on MongoDB engine as follows
db.runCommand({compact: collection-name })
MMAPv1
Compaction operation defragments data files & indexes. However, it does not release space to the operating system. The operation is still useful to defragment and create more contiguous space for reuse by MongoDB. However, it is of no use though when the free disk space is very low.
An additional disk space up to 2GB is required during the compaction operation.
A database level lock is held during the compaction operation.
WiredTiger
The WiredTiger engine provides compression by default which consumes less disk space than MMAPv1.
The compact process releases the free space to the operating system. Minimal disk space is required to run the compact operation. WiredTiger also blocks all operations on the database as it needs database level lock.
For MMAPv1 engine, compact doest not return the space to operating system. You require to run repair operation to release the unused space.
db.runCommand({repairDatabase: 1})
install pip, securely download get-pip.py
Then run the following:
python get-pip.py
On Windows, to get Pandas running,follow the step given in following link
https://github.com/svaksha/PyData-Workshop-Sprint/wiki/windows-install-pandas
You need to use the document.getElementsByClassName('class_name');
and dont forget that the returned value is an array of elements so if you want the first one use:
document.getElementsByClassName('class_name')[0]
UPDATE
Now you can use:
document.querySelector(".class_name")
to get the first element with the class_name
CSS class (null
will be returned if non of the elements on the page has this class name)
or document.querySelectorAll(".class_name")
to get a NodeList of elements with the class_name
css class (empty NodeList will be returned if non of. the elements on the the page has this class name).
Another solution, since April 2015 is Git Large File Storage (LFS) (by GitHub).
It uses git-lfs (see git-lfs.github.com) and tested with a server supporting it: lfs-test-server:
You can store metadata only in the git repo, and the large file elsewhere.
@isaacs answer is correct, but if you need more specific or cleaner error stack, you can use this function:
function getCleanerStack() {
var err = new Error();
Error.captureStackTrace(err, getStack);
return err.stack;
}
This function is inspired directly from the console.trace
function in NodeJS.
Source code: Recent version or Old version.
Personally, I do the following:
session_start();
setcookie(session_name(), '', 100);
session_unset();
session_destroy();
$_SESSION = array();
That way, it kills the cookie, destroys all data stored internally, and destroys the current instance of the session information (which is ignored by session_destroy
).
First add an Enrty
and Category
class:
public class Entry { public string Id { get; set; } public string Title { get; set; } public string Updated { get; set; } public string Summary { get; set; } public string GPoint { get; set; } public string GElev { get; set; } public List<string> Categories { get; set; } } public class Category { public string Label { get; set; } public string Term { get; set; } }
Then use LINQ to XML
XDocument xDoc = XDocument.Load("path"); List<Entry> entries = (from x in xDoc.Descendants("entry") select new Entry() { Id = (string) x.Element("id"), Title = (string)x.Element("title"), Updated = (string)x.Element("updated"), Summary = (string)x.Element("summary"), GPoint = (string)x.Element("georss:point"), GElev = (string)x.Element("georss:elev"), Categories = (from c in x.Elements("category") select new Category { Label = (string)c.Attribute("label"), Term = (string)c.Attribute("term") }).ToList(); }).ToList();
I've adjusted Glenn Moss' answer to account for the fact that overflow div might not be at the top of the page.
parentDiv.scrollTop(parentDiv.scrollTop() + (innerListItem.position().top - parentDiv.position().top) - (parentDiv.height()/2) + (innerListItem.height()/2) )
I was using this on a google maps application with a responsive template. On resolution > 800px, the list was on the left side of the map. On resolution < 800 the list was below the map.
If you want them to be displayed side by side, why is sideContent the child of mainContent? make them siblings then use:
float:left; display:inline; width: 49%;
on both of them.
#mainContent, #sideContent {float:left; display:inline; width: 49%;}
Use the lag function:
SELECT value - lag(value) OVER (ORDER BY Id) FROM table
Sequences used for Ids can skip values, so Id-1 does not always work.
It's the ternary form of the if-else operator. The above statement basically reads like this:
if ($add_review) then {
return FALSE; //$add_review evaluated as True
} else {
return $arg //$add_review evaluated as False
}
See here for more details on ternary op in PHP: http://www.addedbytes.com/php/ternary-conditionals/
When working with 4 large Db2 tables I have not only found the limit but it caused me to look really bad to a boss who thought that I could append all four tables (each with over 900,000 rows) to one large table. the real life result was that regardless of how many times I tried the Table (which had exactly 34 columns - 30 text and 3 integer) would spit out some cryptic message "Cannot open database unrecognized format or the file may be corrupted". Bottom Line is Less than 1,500,000 records and just a bit more than 1,252,000 with 34 rows.
myApp.directive("clickme",function(){
return function(scope,element,attrs){
element.bind("mousedown",function(){
<<call the Controller function>>
scope.loadEditfrm(attrs.edtbtn);
});
};
});
this will act as onclick events on the attribute clickme
Suppose the pattern you want is abc+d. You want to match the second occurrence of this pattern in a string.
You would construct the following regex:
abc+d.*?(abc+d)
This would match strings of the form: <your-pattern>...<your-pattern>
. Since we're using the reluctant qualifier *? we're safe that there cannot be another match of between the two. Using matcher groups which pretty much all regex implementations provide you would then retrieve the string in the bracketed group which is what you want.
You haven't posted the findvertex
method, but Access Reading Violation with an offset like 0x00000048
means that the Vertex* f;
in your getCost function is receiving null, and when trying to access the member adj
in the null
Vertex pointer (that is, in f
), it is offsetting to adj
(in this case, 72 bytes ( 0x48 bytes in decimal )), it's reading near the 0
or null
memory address.
Doing a read like this violates Operating-System protected memory, and more importantly means whatever you're pointing at isn't a valid pointer. Make sure findvertex
isn't returning null, or do a comparisong for null on f
before using it to keep yourself sane (or use an assert):
assert( f != null ); // A good sanity check
EDIT:
If you have a map
for doing something like a find, you can just use the map's find
method to make sure the vertex exists:
Vertex* Graph::findvertex(string s)
{
vmap::iterator itr = map1.find( s );
if ( itr == map1.end() )
{
return NULL;
}
return itr->second;
}
Just make sure you're still careful to handle the error case where it does return NULL
. Otherwise, you'll keep getting this access violation.
Please don't put members into an interface; though it's correct in phrasing. Please don't "delete" an interface.
class IInterface()
{
Public:
Virtual ~IInterface(){};
…
}
Class ClassImpl : public IInterface
{
…
}
Int main()
{
IInterface* pInterface = new ClassImpl();
…
delete pInterface; // Wrong in OO Programming, correct in C++.
}
You can just create an Image
object and put the base64 as its src
, including the data:image...
part like this:
var image = new Image();
image.src = 'data:image/png;base64,iVBORw0K...';
document.body.appendChild(image);
It's what they call "Data URIs" and here's the compatibility table for inner peace.
add #include <iostream>
to the start of io.cpp
too.
One solution: add isAdmin: 0/1 flag to your post collection document.
Other solution: use DBrefs
You get this error when you try to run a 32-bit build on your 64-bit Linux.
Also contrast what file
had to say on the binary you tried (ie: 32-bit) with what you get for your /bin/gzip
:
$ file /bin/gzip
/bin/gzip: ELF 64-bit LSB executable, x64-64, version 1 (SYSV), \
dynamically linked (uses shared libs), for GNU/Linux 2.6.15, stripped
which is what I get on Ubuntu 9.10 for amd64 aka x86_64.
Edit: Your expanded post shows that as the readelf
output also reflects a 32-bit build.
along with answer of this link
https://stackoverflow.com/a/19844531/6767365
rename these files. I renamed my project to MvcMovie and it works fine
$regex = '#<code>(.*?)</code>#';
Using #
as the delimiter instead of /
because then we don't need to escape the /
in </code>
As Phoenix posted below, .*?
is used to make the .*
("anything") match as few characters as possible before it comes across a </code>
(known as a "non-greedy quantifier"). That way, if your string is
<code>hello</code> something <code>again</code>
you'll match hello
and again
instead of just matching hello</code> something <code>again
.