After asking a similar question I’ve created another package which uses Pygments, and offers quite a few more options than texments
. It’s called minted
and is quite stable and usable.
Just to show it off, here’s a code highlighted with minted:
This might not be the best way to do it. But it somehow worked for me, so i'm going to run with it.
In my php function that returns the data, one line before the return line, I add an echo statement, echoing the data I want to send.
Now sure why it worked, but it did.
You just need to install Android development kit from http://developer.android.com/sdk/installing/studio.html#Updating
and also Download and install Java JDK (Choose the Java platform)
define the environment variable in windows System setting https://confluence.atlassian.com/display/DOC/Setting+the+JAVA_HOME+Variable+in+Windows
Voila ! You are Donezo !
I find this, simple and efficient:
const express = require('express');
const fileUpload = require('express-fileupload');
const app = express();
// default options
app.use(fileUpload());
app.post('/upload', function(req, res) {
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send('No files were uploaded.');
}
// The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
let sampleFile = req.files.sampleFile;
// Use the mv() method to place the file somewhere on your server
sampleFile.mv('/somewhere/on/your/server/filename.jpg', function(err) {
if (err)
return res.status(500).send(err);
res.send('File uploaded!');
});
});
[EDIT 2020]-> Now I totally recommend the answer here, way easier using android studio, faster and no need to wright any code - the one below was back in the eclipse days :) -.
You can use this code in any activity. It will log the hashkey in the logcat, which is the debug key. This is easy, and it's a relief than using SSL.
PackageInfo info;
try {
info = getPackageManager().getPackageInfo("com.you.name", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md;
md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
String something = new String(Base64.encode(md.digest(), 0));
//String something = new String(Base64.encodeBytes(md.digest()));
Log.e("hash key", something);
}
} catch (NameNotFoundException e1) {
Log.e("name not found", e1.toString());
} catch (NoSuchAlgorithmException e) {
Log.e("no such an algorithm", e.toString());
} catch (Exception e) {
Log.e("exception", e.toString());
}
You can delete the code after knowing the key ;)
What works best for me is using quote()
and eval()
together.
For example, let's print each column using a for loop
:
Columns <- names(dat)
for (i in 1:ncol(dat)){
dat[, eval(quote(Columns[i]))] %>% print
}
Determine if string is a date, even if string is a non-standard format
(strtotime doesn't accept any custom format)
<?php
function validateDateTime($dateStr, $format)
{
date_default_timezone_set('UTC');
$date = DateTime::createFromFormat($format, $dateStr);
return $date && ($date->format($format) === $dateStr);
}
// These return true
validateDateTime('2001-03-10 17:16:18', 'Y-m-d H:i:s');
validateDateTime('2001-03-10', 'Y-m-d');
validateDateTime('2001', 'Y');
validateDateTime('Mon', 'D');
validateDateTime('March 10, 2001, 5:16 pm', 'F j, Y, g:i a');
validateDateTime('March 10, 2001, 5:16 pm', 'F j, Y, g:i a');
validateDateTime('03.10.01', 'm.d.y');
validateDateTime('10, 3, 2001', 'j, n, Y');
validateDateTime('20010310', 'Ymd');
validateDateTime('05-16-18, 10-03-01', 'h-i-s, j-m-y');
validateDateTime('Monday 8th of August 2005 03:12:46 PM', 'l jS \of F Y h:i:s A');
validateDateTime('Wed, 25 Sep 2013 15:28:57', 'D, d M Y H:i:s');
validateDateTime('17:03:18 is the time', 'H:m:s \i\s \t\h\e \t\i\m\e');
validateDateTime('17:16:18', 'H:i:s');
// These return false
validateDateTime('2001-03-10 17:16:18', 'Y-m-D H:i:s');
validateDateTime('2001', 'm');
validateDateTime('Mon', 'D-m-y');
validateDateTime('Mon', 'D-m-y');
validateDateTime('2001-13-04', 'Y-m-d');
You can use Recordmp3js from GitHub to achieve your requirements. You can record from user's microphone and then get the file as an mp3. Finally upload it to your server.
I used this in my demo. There is a already a sample available with the source code by the author in this location : https://github.com/Audior/Recordmp3js
The demo is here: http://audior.ec/recordmp3js/
But currently works only on Chrome and Firefox.
Seems to work fine and pretty simple. Hope this helps.
The answer given by Jeremy Ruten is great, but I think it's not exactly what Paul Wicks was searching for. If I understand correctly Paul asked about expression to match non-english words like können
or móc
. Jeremy's regex matches only non-english letters, so there's need for small improvement:
([^\x00-\x7F]|\w)+
or
([^\u0000-\u007F]|\w)+
This [^\x00-\x7F]
and this [^\u0000-\u007F]
parts allow regullar expression to match non-english letters.
This (|)
is logical or and \w
is english letter, so ([^\u0000-\u007F]|\w)
will match single english or non-english letter.
+
at the end of the expression means it could be repeated, so the whole expression allows all english or non-english letters to match.
Here you can test the first expression with various strings and here is the second.
As another poster macm
mentioned, the fastest way to create a tuple from a generator is tuple([generator])
.
List comprehension:
$ python3 -m timeit "a = [i for i in range(1000)]"
10000 loops, best of 3: 27.4 usec per loop
Tuple from list comprehension:
$ python3 -m timeit "a = tuple([i for i in range(1000)])"
10000 loops, best of 3: 30.2 usec per loop
Tuple from generator:
$ python3 -m timeit "a = tuple(i for i in range(1000))"
10000 loops, best of 3: 50.4 usec per loop
Tuple from unpacking:
$ python3 -m timeit "a = *(i for i in range(1000)),"
10000 loops, best of 3: 52.7 usec per loop
My version of python:
$ python3 --version
Python 3.6.3
So you should always create a tuple from a list comprehension unless performance is not an issue.
AssemblyVersion
Where other assemblies that reference your assembly will look. If this number changes, other assemblies have to update their references to your assembly! Only update this version, if it breaks backward compatibility. The AssemblyVersion
is required.
I use the format: major.minor. This would result in:
[assembly: AssemblyVersion("1.0")]
If you're following SemVer strictly then this means you only update when the major changes, so 1.0, 2.0, 3.0, etc.
AssemblyFileVersion
Used for deployment. You can increase this number for every deployment. It is used by setup programs. Use it to mark assemblies that have the same AssemblyVersion
, but are generated from different builds.
In Windows, it can be viewed in the file properties.
The AssemblyFileVersion is optional. If not given, the AssemblyVersion is used.
I use the format: major.minor.patch.build, where I follow SemVer for the first three parts and use the buildnumber of the buildserver for the last part (0 for local build). This would result in:
[assembly: AssemblyFileVersion("1.3.2.254")]
Be aware that System.Version names these parts as major.minor.build.revision
!
AssemblyInformationalVersion
The Product version of the assembly. This is the version you would use when talking to customers or for display on your website. This version can be a string, like '1.0 Release Candidate'.
The AssemblyInformationalVersion
is optional. If not given, the AssemblyFileVersion is used.
I use the format: major.minor[.patch] [revision as string]. This would result in:
[assembly: AssemblyInformationalVersion("1.0 RC1")]
In your case there are 3 extra y axis (4 in total) and the best code that could be used to achieve what you want and deal with other cases is illustrated above:
clear
clc
x = linspace(0,1,10);
N = numel(x);
y = rand(1,N);
y_extra_1 = 5.*rand(1,N)+5;
y_extra_2 = 50.*rand(1,N)+20;
Y = [y;y_extra_1;y_extra_2];
xLimit = [min(x) max(x)];
xWidth = xLimit(2)-xLimit(1);
numberOfExtraPlots = 2;
a = 0.05;
N_ = numberOfExtraPlots+1;
for i=1:N_
L=1-(numberOfExtraPlots*a)-0.2;
axesPosition = [(0.1+(numberOfExtraPlots*a)) 0.1 L 0.8];
if(i==1)
color = [rand(1),rand(1),rand(1)];
figure('Units','pixels','Position',[200 200 1200 600])
axes('Units','normalized','Position',axesPosition,...
'Color','w','XColor','k','YColor',color,...
'XLim',xLimit,'YLim',[min(Y(i,:)) max(Y(i,:))],...
'NextPlot','add');
plot(x,Y(i,:),'Color',color);
xlabel('Time (s)');
ylab = strcat('Values of dataset 0',num2str(i));
ylabel(ylab)
numberOfExtraPlots = numberOfExtraPlots - 1;
else
color = [rand(1),rand(1),rand(1)];
axes('Units','normalized','Position',axesPosition,...
'Color','none','XColor','k','YColor',color,...
'XLim',xLimit,'YLim',[min(Y(i,:)) max(Y(i,:))],...
'XTick',[],'XTickLabel',[],'NextPlot','add');
V = (xWidth*a*(i-1))/L;
b=xLimit+[V 0];
x_=linspace(b(1),b(2),10);
plot(x_,Y(i,:),'Color',color);
ylab = strcat('Values of dataset 0',num2str(i));
ylabel(ylab)
numberOfExtraPlots = numberOfExtraPlots - 1;
end
end
if you want to flip image you can use it.
.image{
width: 100%;
-webkit-animation:spin 3s linear infinite;
-moz-animation:spin 3s linear infinite;
animation:spin 3s linear infinite;
}
@-moz-keyframes spin { 50% { -moz-transform: rotateY(90deg); } }
@-webkit-keyframes spin { 50% { -webkit-transform: rotateY(90deg); } }
@keyframes spin { 50% { -webkit-transform: rotateY(90deg); transform:rotateY(90deg); } }
When you create a new window using open
, it returns a reference to the new window, you can use that reference to write to the newly opened window via its document
object.
Here is an example:
var newWin = open('url','windowName','height=300,width=300');
newWin.document.write('html to write...');
I was getting this error when I was updating the dictionary with the wrong syntax:
Try with these:
lineItem.values.update({attribute,value})
instead of
lineItem.values.update({attribute:value})
You can also use awk:
awk 'END {print NR,"lines"}' filename
Or
awk 'END {print NR}' filename
Using tips provided in https://www.tensorflow.org/api_docs/python/tf/print I use the log_d
function to print formatted strings.
import tensorflow as tf
def log_d(fmt, *args):
op = tf.py_func(func=lambda fmt_, *args_: print(fmt%(*args_,)),
inp=[fmt]+[*args], Tout=[])
return tf.control_dependencies([op])
# actual code starts now...
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)
with log_d('MAT1: %s, MAT2: %s', matrix1, matrix2): # this will print the log line
product = tf.matmul(matrix1, matrix2)
with tf.Session() as sess:
sess.run(product)
When your class implements Comparable, the compareTo
method of the class is defining the "natural" ordering of that object. That method is contractually obligated (though not demanded) to be in line with other methods on that object, such as a 0 should always be returned for objects when the .equals()
comparisons return true.
A Comparator is its own definition of how to compare two objects, and can be used to compare objects in a way that might not align with the natural ordering.
For example, Strings are generally compared alphabetically. Thus the "a".compareTo("b")
would use alphabetical comparisons. If you wanted to compare Strings on length, you would need to write a custom comparator.
In short, there isn't much difference. They are both ends to similar means. In general implement comparable for natural order, (natural order definition is obviously open to interpretation), and write a comparator for other sorting or comparison needs.
Recently, I had the same problem within .NET 3.5 (no dynamic available). Here is how I solved:
// pass anonymous object as argument
var args = new { Title = "Find", Type = typeof(FindCondition) };
using (frmFind f = new frmFind(args))
{
...
...
}
Adapted from somewhere on stackoverflow:
// Use a custom cast extension
public static T CastTo<T>(this Object x, T targetType)
{
return (T)x;
}
Now get back the object via cast:
public partial class frmFind: Form
{
public frmFind(object arguments)
{
InitializeComponent();
var args = arguments.CastTo(new { Title = "", Type = typeof(Nullable) });
this.Text = args.Title;
...
}
...
}
Give this a shot:
has_many :jobs, foreign_key: "user_id", class_name: "Task"
Note, that :as
is used for polymorphic associations.
Here is the batch file which should work for you:
@echo off
Title HOST: Installing updates on %computername%
echo %computername%
set Server=\\SERVERNAME or PATH\msifolder
:select
cls
echo Select one of the following MSI install folders for installation task.
echo.
dir "%Server%" /AD /ON /B
echo.
set /P "MSI=Please enter the MSI folder to install: "
set "Package=%Server%\%MSI%\%MSI%.msi"
if not exist "%Package%" (
echo.
echo The entered folder/MSI file does not exist ^(typing mistake^).
echo.
setlocal EnableDelayedExpansion
set /P "Retry=Try again [Y/N]: "
if /I "!Retry!"=="Y" endlocal & goto select
endlocal
goto :EOF
)
echo.
echo Selected installation: %MSI%
echo.
echo.
:verify
echo Is This Correct?
echo.
echo.
echo 0: ABORT INSTALL
echo 1: YES
echo 2: NO, RE-SELECT
echo.
set /p "choice=Select YES, NO or ABORT? [0,1,2]: "
if [%choice%]==[0] goto :EOF
if [%choice%]==[1] goto yes
goto select
:yes
echo.
echo Running %MSI% installation ...
start "Install MSI" /wait "%SystemRoot%\system32\msiexec.exe" /i /quiet "%Package%"
The characters listed on last page output on entering in a command prompt window either help cmd
or cmd /?
have special meanings in batch files. Here are used parentheses and square brackets also in strings where those characters should be interpreted literally. Therefore it is necessary to either enclose the string in double quotes or escape those characters with character ^
as it can be seen in code above, otherwise command line interpreter exits batch execution because of a syntax error.
And it is not possible to call a file with extension MSI. A *.msi file is not an executable. On double clicking on a MSI file, Windows looks in registry which application is associated with this file extension for opening action. And the application to use is msiexec
with the command line option /i
to install the application inside MSI package.
Run msiexec.exe /?
to get in a GUI window the available options or look at Msiexec (command-line options).
I have added already /quiet
additionally to required option /i
for a silent installation.
In batch code above command start
is used with option /wait
to start Windows application msiexec.exe
and hold execution of batch file until installation finished (or aborted).
I use http://www.spoon.net/browsers (Windows-only).
You can run IE8, IE7, IE6, Firefox 3.5, Firefox 3, Firefox 2, Safari 4, Safari 3, Opera 10, Opera 9, Chrome.
You just need to install a plugin, and then click on the corresponding icon. It will download and run the files needed to run each of the above mentioned browsers.
If you are doing this repeatedly, for example to pad values in an array, and performance is a factor, the following approach can give you nearly a 100x advantage in speed (jsPerf) over other solution that are currently discussed on the inter webs. The basic idea is that you are providing the pad function with a fully padded empty string to use as a buffer. The pad function just appends to string to be added to this pre-padded string (one string concat) and then slices or trims the result to the desired length.
function pad(pad, str, padLeft) {
if (typeof str === 'undefined')
return pad;
if (padLeft) {
return (pad + str).slice(-pad.length);
} else {
return (str + pad).substring(0, pad.length);
}
}
For example, to zero pad a number to a length of 10 digits,
pad('0000000000',123,true);
To pad a string with whitespace, so the entire string is 255 characters,
var padding = Array(256).join(' '), // make a string of 255 spaces
pad(padding,123,true);
See the jsPerf test here.
And this is faster than ES6 string.repeat
by 2x as well, as shown by the revised JsPerf here
jsPerf
is no longer onlinePlease note that the jsPerf site that we originally used to benchmark the various methods is no longer online. Unfortunately, this means we can't get to those test results. Sad but true.
Consider this:
file a.txt:
abcd
efgh
file b.txt:
abcd
You can find the difference with:
diff -a --suppress-common-lines -y a.txt b.txt
The output will be:
efgh
You can redirict the output in an output file (c.txt) using:
diff -a --suppress-common-lines -y a.txt b.txt > c.txt
This will answer your question:
"...which contains the lines in file1 which are not present in file2."
Find can be used to print out the file-size in bytes with %s as a printf. %h/%f prints the directory prefix and filename respectively. \n forces a newline.
Example
find . -size +10000k -printf "%h/%f,%s\n"
Output
./DOTT/extract/DOTT/TENTACLE.001,11358470
./DOTT/Day Of The Tentacle.nrg,297308316
./DOTT/foo.iso,297001116
On Mac, open a terminal and run the following two commands.
conda update conda
conda update anaconda
Make sure to run each command multiple times to update to the current version.
pull = fetch + merge.
You need to commit what you have done before merging.
So pull after commit.
Well, if you are going to iterate anyhow, why don't use the simplest method of all, df['Column'].values[i]
df['Column'] = ''
for i in range(len(df)):
df['Column'].values[i] = something/update/new_value
Or if you want to compare the new values with old or anything like that, why not store it in a list and then append in the end.
mylist, df['Column'] = [], ''
for <condition>:
mylist.append(something/update/new_value)
df['Column'] = mylist
I forgot to put correct arguments:
class LineInOffice(models.Model): # here
addressOfOffice = models.CharField("???????? ???",max_length= 200) #and here
...
in models.py and then it started to drop that annoying
No changes detected in app 'myApp '
Based on your own purposes, you can do that based on setOpaque(true/false) and setBorderPainted(true/false); try and combine them to fit your purpose
I found this (WPF Multithreading: Using the BackgroundWorker and Reporting the Progress to the UI. link) to contain the rest of the details which are missing from @Andrew's answer.
The one thing I found very useful was that the worker thread couldn't access the MainWindow's controls (in it's own method), however when using a delegate inside the main windows event handler it was possible.
worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args)
{
pd.Close();
// Get a result from the asynchronous worker
T t = (t)args.Result
this.ExampleControl.Text = t.BlaBla;
};
Try to get some debugging information, could be that the file path is wrong, for example.
Try these two things:- Add this line to the top of your sample page:
<?php error_reporting(E_ALL);?>
This will print all errors/warnings/notices in the page so if there is any problem you get a text message describing it instead of a blank page
Additionally you can change include() to require()
<?php require ('headings.php'); ?>
<?php require ('navbar.php'); ?>
<?php require ('image.php'); ?>
This will throw a FATAL error PHP is unable to load required pages, and should help you in getting better tracing what is going wrong..
You can post the error descriptions here, if you get any, and you are unable to figure out what it means..
The items with code "200 (cache)" were fulfilled directly from your browser cache, meaning that the original requests for the items were returned with headers indicating that the browser could cache them (e.g. future-dated Expires
or Cache-Control: max-age
headers), and that at the time you triggered the new request, those cached objects were still stored in local cache and had not yet expired.
304s, on the other hand, are the response of the server after the browser has checked if a file was modified since the last version it had cached (the answer being "no").
For most optimal web performance, you're best off setting a far-future Expires:
or Cache-Control: max-age
header for all assets, and then when an asset needs to be changed, changing the actual filename of the asset or appending a version string to requests for that asset. This eliminates the need for any request to be made unless the asset has definitely changed from the version in cache (no need for that 304 response). Google has more details on correct use of long-term caching.
If it is an absolute must to generate delay in a test CountDownLatch
is a simple solution. In your test class declare:
private final CountDownLatch waiter = new CountDownLatch(1);
and in the test where needed:
waiter.await(1000 * 1000, TimeUnit.NANOSECONDS); // 1ms
Maybe unnecessary to say but keeping in mind that you should keep wait times small and not cumulate waits to too many places.
I know this thread has been idle for a while, but I just wanted to add my two cents to supplement jariq's comment...
Per manual, you don't necessary want to use -password
option.
Let's say mykey.key
has a password and your want to protect iphone-dev.p12
with another password, this is what you'd use:
pkcs12 -export -inkey mykey.key -in developer_identity.pem -out iphone_dev.p12 -passin pass:password_for_mykey -passout pass:password_for_iphone_dev
Have fun scripting!!
In my case, @
caused some sort of encoding problem, I still prefer my old way:
curl -d "$(cat /path/to/file)" https://example.com
From Android's Developer Documentation on Managing Projects from Eclipse with ADT:
Next, set the project's Properties to indicate that it is a library project:
- In the Package Explorer, right-click the library project and select Properties.
- In the Properties window, select the "Android" properties group at left and locate the Library properties at right.
- Select the "is Library" checkbox and click Apply.
- Click OK to close the Properties window.
So, open your project properties, un-select the "Is Library" checkbox, and click Apply to make your project a normal Android project (not a library project).
In addition to the answers above:
If you created/edited your .sh script file in Windows, make sure it was saved with line ending in Unix format. By default many editors in Windows will convert Unix line endings to Windows format and Linux will not recognize shebang (#!/bin/sh) at the beginning of the file. So Linux will produce the error message like if there is no shebang.
Tips:
When using Flask (I am using it with flat pages)... I found that enabling explicitly (was not by default for some reason) 'attr_list' in extensions within the call to markdown does the trick - and then one can use the attributes (very useful also to access CSS - class="my class" for example...).
FLATPAGES_HTML_RENDERER = prerender_jinja
and the function:
def prerender_jinja(text):
prerendered_body = render_template_string(Markup(text))
pygmented_body = markdown.markdown(prerendered_body, extensions=['codehilite', 'fenced_code', 'tables', 'attr_list'])
return pygmented_body
And then in Markdown:
![image](https://octodex.github.com/images/yaktocat.png "This is a tooltip"){: width=200px}
public static boolean isPrime(int number) {
if(number < 2)
return false;
else if(number == 2 || number == 3)
return true;
else {
for(int i=2;i<=number/2;i++)
if(number%i == 0)
return false;
else if(i==number/2)
return true;
}
return false;
}
This only happens when you use the dev-tools, and won't happen for normal users accessing the production server.
In any case, I found it useful to simply disable this behavior in the dev-tools: open the settings and uncheck the "Enable source maps" option.
There will no longer be an attempt to access map files.
string abc= dt.Rows[0]["column name"].ToString();
I think that mergetool.meld.path
should point directly to the meld executable. Thus, the command you want is:
git config --global mergetool.meld.path c:/Progra~2/meld/bin/meld
I have the same warning (it's make my app cannot build). When I add C function
in Objective-C's .m file
, But forgot to declared it at .h
file.
I think that is controlled by the expose_php
setting in PHP.ini:
expose_php = off
Decides whether PHP may expose the fact that it is installed on the server (e.g. by adding its signature to the Web server header). It is no security threat in any way, but it makes it possible to determine whether you use PHP on your server or not.
There is no direct security risk, but as David C notes, exposing an outdated (and possibly vulnerable) version of PHP may be an invitation for people to try and attack it.
or sometimes it's very easy just type Process.Start("http://www.example.com/")
then change the http://www.example.com/")
In Angular p-checkbox,
Use all attributes of p-checkbox
<p-checkbox name="checkbox" value="isAC"
label="All Colors" [(ngModel)]="selectedAllColors"
[ngModelOptions]="{standalone: true}" id="al"
binary="true">
</p-checkbox>
And more importantly, don't forget to include [ngModelOptions]="{standalone: true}
as well as it SAVED MY DAY.
Use jQuery. Keep your checkbox elements hidden and create a list like this:
<ul id="list">
<li><a href="javascript:void(0)" id="link1">Happy face</a></li>
<li><a href="javascript:void(0)" id="link2">Sad face</a></li>
</ul>
<form action="file.php" method="post">
<!-- More code -->
<input type="radio" id="option1" name="radio1" value="happy" style="display:none"/>
<input type="radio" id="option2" name="radio1" value="sad" style="display:none"/>
<!-- More code -->
</form>
<script type="text/javascript">
$("#list li a").click(function() {
$('#list .active').removeClass("active");
var id = this.id;
var newselect = id.replace('link', 'option');
$('#'+newselect).attr('checked', true);
$(this).addClass("active").parent().addClass("active");
return false;
});
</script>
This code would add the checked attribute to your radio inputs in the background and assign class active to your list elements. Do not use inline styles of course, don't forget to include jQuery and everything should run out of the box after you customize it.
Cheers!
Try the jquery each
function to walk through your json object:
$.each(data,function(i,j){
content ='<span>'+j[i].Id+'<br />'+j[i].Name+'<br /></span>';
$('#ProductList').append(content);
});
findBy method in Symfony excepts two parameters. First is array of fields you want to search on and second array is the the sort field and its order
public function findSorted()
{
return $this->findBy(['name'=>'Jhon'], ['date'=>'DESC']);
}
Here's a fix for LoaderException errors you're likely to find if one of the types sublasses a type in another assembly:
// Setup event handler to resolve assemblies
AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(CurrentDomain_ReflectionOnlyAssemblyResolve);
Assembly a = System.Reflection.Assembly.ReflectionOnlyLoadFrom(filename);
a.GetTypes();
// process types here
// method later in the class:
static Assembly CurrentDomain_ReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args)
{
return System.Reflection.Assembly.ReflectionOnlyLoad(args.Name);
}
That should help with loading types defined in other assemblies.
Hope that helps!
<xsl:call-template>
is a close equivalent to calling a function in a traditional programming language.
You can define functions in XSLT, like this simple one that outputs a string.
<xsl:template name="dosomething">
<xsl:text>A function that does something</xsl:text>
</xsl:template>
This function can be called via <xsl:call-template name="dosomething">
.
<xsl:apply-templates>
is a little different and in it is the real power of XSLT: It takes any number of XML nodes (whatever you define in the select
attribute), iterates them (this is important: apply-templates works like a loop!) and finds matching templates for them:
<!-- sample XML snippet -->
<xml>
<foo /><bar /><baz />
</xml>
<!-- sample XSLT snippet -->
<xsl:template match="xml">
<xsl:apply-templates select="*" /> <!-- three nodes selected here -->
</xsl:template>
<xsl:template match="foo"> <!-- will be called once -->
<xsl:text>foo element encountered</xsl:text>
</xsl:template>
<xsl:template match="*"> <!-- will be called twice -->
<xsl:text>other element countered</xsl:text>
</xsl:template>
This way you give up a little control to the XSLT processor - not you decide where the program flow goes, but the processor does by finding the most appropriate match for the node it's currently processing.
If multiple templates can match a node, the one with the more specific match expression wins. If more than one matching template with the same specificity exist, the one declared last wins.
You can concentrate more on developing templates and need less time to do "plumbing". Your programs will become more powerful and modularized, less deeply nested and faster (as XSLT processors are optimized for template matching).
A concept to understand with XSLT is that of the "current node". With <xsl:apply-templates>
the current node moves on with every iteration, whereas <xsl:call-template>
does not change the current node. I.e. the .
within a called template refers to the same node as the .
in the calling template. This is not the case with apply-templates.
This is the basic difference. There are some other aspects of templates that affect their behavior: Their mode
and priority
, the fact that templates can have both a name
and a match
. It also has an impact whether the template has been imported (<xsl:import>
) or not. These are advanced uses and you can deal with them when you get there.
For any of you still having problems as of Sept. 2012, go here: http://support.microsoft.com/kb/2527041 ...and grab the SQLManagementStudio_x(32|64)_ENU.exe
(if you've already installed SQL Server 2008 Express R2), or SQL Server 2008 Express R2 with Tools, i.e. SQLEXPRWT_x64_ENU.exe or SQLEXPRWT_x32_ENU.exe
(if you haven't).
From there, follow similar instructions as above (i.e. use the "Perform new installation and add shared features" selection, as "Management Tools - Basic" is considered a "shared feature"), if you've already installed SQL Server Express 2008 R2 (as I had). And if you haven't done that yet, then of course you're going to follow this way as you need to install the new instance anyway.
This solved things for me, and hopefully it will for you, too!
I think using locally or globally should depend on the application.
Because, when we use the library locally, sometimes the code is going to be a real mess. Readability is going to low.
So, we should use libraries locally only when there is a possibility for conflicts.
I am not a more experienced person. So, let me know if I am wrong.
This is a bit nasty, but:
from datetime import datetime, timedelta
now = datetime.now().time()
# Just use January the first, 2000
d1 = datetime(2000, 1, 1, now.hour, now.minute, now.second)
d2 = d1 + timedelta(hours=1, minutes=23)
print d2.time()
The Java EE version of Eclipse is not installed, insted a standard SDK version is installed.
You can go to Help > Install New Software then select the Eclipse site from the dropdown (Helios, Kepler depending upon your revision). Then select the option that shows Java EE. Restart Eclipse and you should see the Server list, such as Apache, Oracle, IBM etc.
// get the data table
DataTable dt = ...;
// generate the data you want to insert
DataRow toInsert = dt.NewRow();
// insert in the desired place
dt.Rows.InsertAt(toInsert, index);
git diff branch_1..branch_2
That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:
git diff branch_1...branch_2
I think the most elegant solution is to pass a lambda function to "type", as mentioned by Chepner. In addition to this, if you do not know beforehand what the delimiter of your list will be, you can also pass multiple delimiters to re.split:
# python3 test.py -l "abc xyz, 123"
import re
import argparse
parser = argparse.ArgumentParser(description='Process a list.')
parser.add_argument('-l', '--list',
type=lambda s: re.split(' |, ', s),
required=True,
help='comma or space delimited list of characters')
args = parser.parse_args()
print(args.list)
# Output: ['abc', 'xyz', '123']
Learning C forces you to think harder about some issues such as explicit and implicit memory management or storage sizes of basic data types at the time you write your code.
Once you have reached a point where you feel comfortable around C's features and misfeatures, you will probably have less trouble learning and writing in C++.
It is entirely possible that the C++ code you have seen did not look much different from standard C, but that may well be because it was not object oriented and did not use exceptions, object-orientation, templates or other advanced features.
If you care about the speed use ujson (UltraJSON), which has the same API as json:
import ujson
ujson.dumps([{"key": "value"}, 81, True])
# '[{"key":"value"},81,true]'
ujson.loads("""[{"key": "value"}, 81, true]""")
# [{u'key': u'value'}, 81, True]
You can deal multipleViewTypes RecyclerAdapter
by making getItemViewType()
return the expected viewType
value for that position
I prepared an MultipleViewTypeAdapter
for constructing MCQ list for examinations which may throw a question that may have 2 or more valid answers (checkbox options) and a single answer questions (radiobutton options).
For this i get the type of Question from API response and i used that for deciding which view i have to show for that question .
public class MultiViewTypeAdapter extends RecyclerView.Adapter {
Context mContext;
ArrayList<Question> dataSet;
ArrayList<String> questions;
private Object radiobuttontype1;
//Viewholder to display Questions with checkboxes
public static class Checkboxtype2 extends RecyclerView.ViewHolder {
ImageView imgclockcheck;
CheckBox checkbox;
public Checkboxtype2(@NonNull View itemView) {
super(itemView);
imgclockcheck = (ImageView) itemView.findViewById(R.id.clockout_cbox_image);
checkbox = (CheckBox) itemView.findViewById(R.id.clockout_cbox);
}
}
//Viewholder to display Questions with radiobuttons
public static class Radiobuttontype1 extends RecyclerView.ViewHolder {
ImageView clockout_imageradiobutton;
RadioButton clockout_radiobutton;
TextView sample;
public radiobuttontype1(View itemView) {
super(itemView);
clockout_imageradiobutton = (ImageView) itemView.findViewById(R.id.clockout_imageradiobutton);
clockout_radiobutton = (RadioButton) itemView.findViewById(R.id.clockout_radiobutton);
sample = (TextView) itemView.findViewById(R.id.sample);
}
}
public MultiViewTypeAdapter(ArrayList<QueDatum> data, Context context) {
this.dataSet = data;
this.mContext = context;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
if (viewType.equalsIgnoreCase("1")) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.clockout_radio_list_row, viewGroup, false);
return new radiobuttontype1(view);
} else if (viewType.equalsIgnoreCase("2")) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.clockout_cbox_list_row, viewGroup, false);
view.setHorizontalFadingEdgeEnabled(true);
return new Checkboxtype2(view);
} else if (viewType.equalsIgnoreCase("3")) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.clockout_radio_list_row, viewGroup, false);
return new Radiobuttontype1(view);
} else if (viewType.equalsIgnoreCase("4")) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.clockout_radio_list_row, viewGroup, false);
return new Radiobuttontype1(view);
} else if (viewType.equalsIgnoreCase("5")) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.clockout_radio_list_row, viewGroup, false);
return new Radiobuttontype1(view);
}
return null;
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int viewType) {
if (viewType.equalsIgnoreCase("1")) {
options = dataSet.get(i).getOptions();
question = dataSet.get(i).getQuestion();
image = options.get(i).getValue();
((radiobuttontype1) viewHolder).clockout_radiobutton.setChecked(false);
((radiobuttontype1) viewHolder).sample.setText(question);
//loading image bitmap in the ViewHolder's View
Picasso.with(mContext)
.load(image)
.into(((radiobuttontype1) viewHolder).clockout_imageradiobutton);
} else if (viewType.equalsIgnoreCase("2")) {
options = (ArrayList<Clockout_questions_Option>) dataSet.get(i).getOptions();
question = dataSet.get(i).getQuestion();
image = options.get(i).getValue();
//loading image bitmap in the ViewHolder's View
Picasso.with(mContext)
.load(image)
.into(((Checkboxtype2) viewHolder).imgclockcheck);
} else if (viewType.equalsIgnoreCase("3")) {
//fit data to viewHolder for ViewType 3
} else if (viewType.equalsIgnoreCase("4")) {
//fit data to viewHolder for ViewType 4
} else if (viewType.equalsIgnoreCase("5")) {
//fit data to viewHolder for ViewType 5
}
}
@Override
public int getItemCount() {
return dataSet.size();
}
/**
* returns viewType for that position by picking the viewType value from the
* dataset
*/
@Override
public int getItemViewType(int position) {
return dataSet.get(position).getViewType();
}
}
You can avoid multiple conditional based viewHolder data fillings in onBindViewHolder()
by assigning same ids for the similar views across viewHolders which differ in their positioning.
Just put a line break into your text.
You don't add lines as a method. Multiline just supports the use of line breaks.
This question is quite older. The Questioner might have been turned into an experienced Java Developer by this time. Yet I want to add some opinion here which would help beginners.
For JDK 7 users, Here using
Objects.requireNotNull(object[, optionalMessage]);
is not safe. This function throws NullPointerException
if it finds null
object and which is a RunTimeException
.
That will terminate the whole program!!. So better check null
using ==
or !=
.
Also, use List
instead of Array
. Although access speed is same, yet using Collections
over Array
has some advantages like if you ever decide to change the underlying implementation later on, you can do it flexibly. For example, if you need synchronized access, you can change the implementation to a Vector
without rewriting all your code.
public static double calculateInventoryTotal(List<Book> books) {
if (books == null || books.isEmpty()) {
return 0;
}
double total = 0;
for (Book book : books) {
if (book != null) {
total += book.getPrice();
}
}
return total;
}
Also, I would like to upvote @1ac0 answer. We should understand and consider the purpose of the method too while writing. Calling method could have further logics to implement based on the called method's returned data.
Also if you are coding with JDK 8, It has introduced a new way to handle null check and protect the code from NullPointerException
. It defined a new class called Optional
. Have a look at this for detail
Finally, Pardon my bad English.
Like Unix shells, PowerShell supports >
redirects with most of the variations known from Unix, including 2>&1
(though weirdly, order doesn't matter - 2>&1 > file
works just like the normal > file 2>&1
).
Like most modern Unix shells, PowerShell also has a shortcut for redirecting both standard error and standard output to the same device, though unlike other redirection shortcuts that follow pretty much the Unix convention, the capture all shortcut uses a new sigil and is written like so: *>
.
So your implementation might be:
& myjob.bat *>> $logfile
Bubble sort with sort direction -
using System;
public class Program
{
public static void Main(string[] args)
{
var input = new[] { 800, 11, 50, 771, 649, 770, 240, 9 };
BubbleSort(input);
Array.ForEach(input, Console.WriteLine);
Console.ReadKey();
}
public enum Direction
{
Ascending = 0,
Descending
}
public static void BubbleSort(int[] input, Direction direction = Direction.Ascending)
{
bool swapped;
var length = input.Length;
do
{
swapped = false;
for (var index = 0; index < length - 1; index++)
{
var needSwap = direction == Direction.Ascending ? input[index] > input[index + 1] : input[index] < input[index + 1];
if (needSwap)
{
var temp = input[index];
input[index] = input[index + 1];
input[index + 1] = temp;
swapped = true;
}
}
} while (swapped);
}
}
Recently got the same problem and this is how i fixed it: On Visual Studio with your project in question open, Goto:
It will load whats missing in your project and all should be back on track.
=OFFSET(INDIRECT(ADDRESS(ROW(), COLUMN())),0,-1)
<content>(?:[^\n]*(\n+))+</content>
rsync command can do the trick only if the last directory in the destination path doesn't exist, e.g. for the destination path of ~/bar/baz/
if bar
exists but baz
doesn't, then the following command can be used:
rsync -av --remove-source-files foo.c ~/bar/baz/
-a, --archive archive mode; equals -rlptgoD (no -H,-A,-X)
-v, --verbose increase verbosity
--remove-source-files sender removes synchronized files (non-dir)
In this case baz
directory will be created if it doesn't exist. But if both bar
and baz
don't exist rsync will fail:
sending incremental file list
rsync: mkdir "/root/bar/baz" failed: No such file or directory (2)
rsync error: error in file IO (code 11) at main.c(657) [Receiver=3.1.2]
So basically it should be safe to use rsync -av --remove-source-files
as an alias for mv
.
I had the same problem. I checked netstat, other processes running, firewall and changed httpd.conf, stopped antivirus, But all my efforts were in vain. :(
So finally the solution was to stop the IIS. And it worked :)
I guess IIS and apache cant work together. If anybody know any work around let us know.
Delete C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\
After generation of woff files, you have to define font-family, which can be used later in all your css styles. Below is the code to define font families (for normal, bold, bold-italic, italic) typefaces. It is assumed, that there are 4 *.woff files (for mentioned typefaces), placed in fonts
subdirectory.
In CSS code:
@font-face {
font-family: "myfont";
src: url("fonts/awesome-font.woff") format('woff');
}
@font-face {
font-family: "myfont";
src: url("fonts/awesome-font-bold.woff") format('woff');
font-weight: bold;
}
@font-face {
font-family: "myfont";
src: url("fonts/awesome-font-boldoblique.woff") format('woff');
font-weight: bold;
font-style: italic;
}
@font-face {
font-family: "myfont";
src: url("fonts/awesome-font-oblique.woff") format('woff');
font-style: italic;
}
After having that definitions, you can just write, for example,
In HTML code:
<div class="mydiv">
<b>this will be written with awesome-font-bold.woff</b>
<br/>
<b><i>this will be written with awesome-font-boldoblique.woff</i></b>
<br/>
<i>this will be written with awesome-font-oblique.woff</i>
<br/>
this will be written with awesome-font.woff
</div>
In CSS code:
.mydiv {
font-family: myfont
}
The good tool for generation woff files, which can be included in CSS stylesheets is located here. Not all woff files work correctly under latest Firefox versions, and this generator produces 'correct' fonts.
This is a textbook case for a constructor function:
var myArray = [];
function myElement(id, value){
this.id = id
this.value = value
}
myArray[0] = new myElement(0,1)
myArray[1] = new myElement(2,3)
// or myArray.push(new myElement(1, 1))
Python started as a scripting language for Linux like Perl but less cryptic. Now it is used for both web and desktop applications and is available on Windows too. Desktop GUI APIs like GTK have their Python implementations and Python based web frameworks like Django are preferred by many over PHP et al. for web applications.
And by the way,
You can use MATCH
for instance.
Select the column from the first cell, for example cell A2 to cell A100 and insert a conditional formatting, using 'New Rule...' and the option to conditional format based on a formula.
In the entry box, put:
=MATCH(A2, 'Sheet2'!A:A, 0)
Pick the desired formatting (change the font to red or fill the cell background, etc) and click OK.
MATCH
takes the value A2
from your data table, looks into 'Sheet2'!A:A
and if there's an exact match (that's why there's a 0
at the end), then it'll return the row number.
Note: Conditional formatting based on conditions from other sheets is available only on Excel 2010 onwards. If you're working on an earlier version, you might want to get the list of 'Don't check' in the same sheet.
EDIT: As per new information, you will have to use some reverse matching. Instead of the above formula, try:
=SUM(IFERROR(SEARCH('Sheet2'!$A$1:$A$44, A2),0))
I have personally found pywinrm
library to be very effective. However, it does require some commands to be run on the machine and some other setup before it will work.
This will get selected value from multi-value select boxes: $("#id option:selected").val()
The CGRectZero
constant is equal to a rectangle at position (0,0)
with zero width and height. This is fine to use, and actually preferred, if you use AutoLayout, since AutoLayout will then properly place the view.
But, I expect you do not use AutoLayout. So the most simple solution is to specify the size of the custom view by providing a frame explicitly:
customView = MyCustomView(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
self.view.addSubview(customView)
Note that you also need to use addSubview
otherwise your view is not added to the view hierarchy.
I prefer to abuse ActiveSupport::JSON. Their approach is to convert the hash to yaml and then load it. Unfortunately the conversion to yaml isn't simple and you'd probably want to borrow it from AS if you don't have AS in your project already.
We also have to convert any symbols into regular string-keys as symbols aren't appropriate in JSON.
However, its unable to handle hashes that have a date string in them (our date strings end up not being surrounded by strings, which is where the big issue comes in):
string = '{'last_request_at' : 2011-12-28 23:00:00 UTC }'
ActiveSupport::JSON.decode(string.gsub(/:([a-zA-z])/,'\\1').gsub('=>', ' : '))
Would result in an invalid JSON string error when it tries to parse the date value.
Would love any suggestions on how to handle this case
Click on options on the connect to Server dialog and on the Connection Properties, you can choose the database to connect to on startup. Its better to leave it default which will make master as default. Otherwise you might inadvertently run sql on a wrong database after connecting to a database.
If you are use Raspberry Pi [Raspbian OS]
There are need to be install pip command at first
apt-get install python-pip
So that just install Sequently
apt-get install python-dev libmysqlclient-dev
apt-get install python-pip
pip install MySQL-python
I've taken @gauravsapiens answer with my comments inside to give you a reasonable apprehension of what the parameters will effect.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Background color -->
<solid android:color="@color/white" />
<!-- Stroke around the background, width and color -->
<stroke android:width="4dp" android:color="@color/drop_shadow"/>
<!-- The corners of the shape -->
<corners android:radius="4dp"/>
<!-- Padding for the background, e.g the Text inside a TextView will be
located differently -->
<padding android:left="10dp" android:right="10dp"
android:bottom="10dp" android:top="10dp" />
</shape>
If you're just looking to create a shape that rounds the corners, removing the padding and the stroke will do. If you remove the solid as well you will, in effect, have created rounded corners on a transparent background.
For the sake of being lazy I have created a shape underneath, which is just a solid white background with rounded corners - enjoy! :)
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Background color -->
<solid android:color="@color/white" />
<!-- The corners of the shape -->
<corners android:radius="4dp"/>
</shape>
Please see a link for more details.
Declare @Object as Int;
Declare @ResponseText as Varchar(8000);
Code Snippet
Exec sp_OACreate 'MSXML2.XMLHTTP', @Object OUT;
Exec sp_OAMethod @Object, 'open', NULL, 'get',
'http://www.webservicex.com/stockquote.asmx/GetQuote?symbol=MSFT', --Your Web Service Url (invoked)
'false'
Exec sp_OAMethod @Object, 'send'
Exec sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT
Select @ResponseText
Exec sp_OADestroy @Object
Now in rails 5 yu can do:
rails restart
This print by rails --tasks
Restart app by touching tmp/restart.txt
I think that is usefully if you run rails as a demon
This might be useful to someone also ..
i.e. For a data analyst and data profiling type of purposes ..(i.e. not grouped by) ..
Prior to the SQL*Server 2017 String_agg function existence ..
(i.e. returns just one row ..)
select distinct
SUBSTRING (
stuff(( select distinct ',' + [FieldB] from tablename order by 1 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)')
,1,0,'' )
,2,9999)
from
tablename
e.g. returns comma separated values A,B
Here is a version, basically the same as a couple of the other answers, but that you can copy paste into your SQL server Management Studio to test, (and without generating any unwanted tables), thanks to some inline values.
WITH [TestData]([ID],[SKU],[PRODUCT]) AS
(
SELECT *
FROM (
VALUES
(1, 'FOO-23', 'Orange'),
(2, 'BAR-23', 'Orange'),
(3, 'FOO-24', 'Apple'),
(4, 'FOO-25', 'Orange')
)
AS [TestData]([ID],[SKU],[PRODUCT])
)
SELECT * FROM [TestData] WHERE [ID] IN
(
SELECT MIN([ID])
FROM [TestData]
GROUP BY [PRODUCT]
)
Result
ID SKU PRODUCT
1 FOO-23 Orange
3 FOO-24 Apple
I have ignored the following ...
WHERE ([SKU] LIKE 'FOO-%')
as its only part of the authors faulty code and not part of the question. It's unlikely to be helpful to people looking here.
Use substring and concatenate:
if(str.length() > 50)
strOut = str.substring(0,7) + "...";
string[][]
is not a two-dimensional array, it's an array of arrays (a jagged array). That's something different.
To declare a two-dimensional array, use this syntax:
string[,] tablero = new string[3, 3];
If you really want a jagged array, you need to initialize it like this:
string[][] tablero = new string[][] { new string[3],
new string[3],
new string[3] };
The question I would ask is, why are you including the extra columns in your DataTable if they aren't required?
Maybe you should modify your SQL select statement so that it is looking at the specific criteria you are looking for as you are populating your DataTable.
You could also use LINQ to query your DataTable as Enumerable and create a List Object that represents only certain columns.
Other than that, hide the DataGridView Columns that you don't require.
The easiest solution is to simply tell Xcode to compile everything as Objective C++.
Set your project or target settings for Compile Sources As to Objective C++ and recompile.
Then you can use C++ or Objective C everywhere, for example:
void CPPObject::Function( ObjectiveCObject* context, NSView* view )
{
[context renderbufferStorage:GL_RENDERBUFFER fromDrawable:(CAEAGLLayer*)view.layer]
}
This has the same affect as renaming all your source files from .cpp or .m to .mm.
There are two minor downsides to this: clang cannot analyse C++ source code; some relatively weird C code does not compile under C++.
You can intercept the key press events, cancel the lowercase ones, and append their uppercase versions to the input:
window.onload = function () {
var input = document.getElementById("test");
input.onkeypress = function () {
// So that things work both on Firefox and Internet Explorer.
var evt = arguments[0] || event;
var char = String.fromCharCode(evt.which || evt.keyCode);
// Is it a lowercase character?
if (/[a-z]/.test(char)) {
// Append its uppercase version
input.value += char.toUpperCase();
// Cancel the original event
evt.cancelBubble = true;
return false;
}
}
};
This works in both Firefox and Internet Explorer. You can see it in action here.
I found this to be weird but I got a solution. I noticed that every once in a while my project folder went read-only and I couldn't save it from VS. So I read a suggestion to transfer NPM from local user PATH to system-wide PATH global variable, and it worked like a charm.
If you didn't specify a different fileformat
intentionally (say, :e ++ff=unix
for a Windows file), it's likely that the target file has mixed EOLs.
For example, if a file has some lines with <CR><NL>
endings and others with
<NL>
endings, and fileformat
is set to unix
automatically by Vim when reading it, ^M (<CR>)
will appear.
In such cases, fileformats
(note: there's an extra s
) comes into play. See :help ffs
for the details.
If you use Modernizr, it is very easy to use Modernizr.touch
as mentioned earlier.
However, I prefer using a combination of Modernizr.touch
and user agent testing, just to be safe.
var deviceAgent = navigator.userAgent.toLowerCase();
var isTouchDevice = Modernizr.touch ||
(deviceAgent.match(/(iphone|ipod|ipad)/) ||
deviceAgent.match(/(android)/) ||
deviceAgent.match(/(iemobile)/) ||
deviceAgent.match(/iphone/i) ||
deviceAgent.match(/ipad/i) ||
deviceAgent.match(/ipod/i) ||
deviceAgent.match(/blackberry/i) ||
deviceAgent.match(/bada/i));
if (isTouchDevice) {
//Do something touchy
} else {
//Can't touch this
}
If you don't use Modernizr, you can simply replace the Modernizr.touch
function above with ('ontouchstart' in document.documentElement)
Also note that testing the user agent iemobile
will give you broader range of detected Microsoft mobile devices than Windows Phone
.
$?
is a parameter like any other. You can save its value to use before ultimately calling exit
.
exit_status=$?
if [ $exit_status -eq 1 ]; then
echo "blah blah blah"
fi
exit $exit_status
This is my solution, although for sure you can use a lot of modules that give you the object as a promise or similar. Anyway, you were missing another callback
function getData(callbackData){
var http = require('http');
var str = '';
var options = {
host: 'www.random.org',
path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
};
callback = function(response) {
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
console.log(str);
callbackData(str);
});
//return str;
}
var req = http.request(options, callback).end();
// These just return undefined and empty
console.log(req.data);
console.log(str);
}
somewhere else
getData(function(data){
// YOUR CODE HERE!!!
})
I followed the sample code from @codeslord, but for some reason I had to access my screenshot data differently:
# Open the Firefox webdriver
driver = webdriver.Firefox()
# Find the element that you're interested in
imagepanel = driver.find_element_by_class_name("panel-height-helper")
# Access the data bytes for the web element
datatowrite = imagepanel.screenshot_as_png
# Write the byte data to a file
outfile = open("imagepanel.png", "wb")
outfile.write(datatowrite)
outfile.close()
(using Python 3.7, Selenium 3.141.0 and Mozilla Geckodriver 71.0.0.7222)
for mysql 'text':
@Column(columnDefinition = "TEXT")
private String description;
for mysql 'longtext':
@Lob
private String description;
>>> import os
>>> os.path.abspath("mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'
Also works if it is already an absolute path:
>>> import os
>>> os.path.abspath("C:/example/cwd/mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'
Here is a trick I use with GNU make for creating compiler-output directories. First define this rule:
%/.d:
mkdir -p $(@D)
touch $@
Then make all files that go into the directory dependent on the .d file in that directory:
obj/%.o: %.c obj/.d
$(CC) $(CFLAGS) -c -o $@ $<
Note use of $< instead of $^.
Finally prevent the .d files from being removed automatically:
.PRECIOUS: %/.d
Skipping the .d file, and depending directly on the directory, will not work, as the directory modification time is updated every time a file is written in that directory, which would force rebuild at every invocation of make.
If you're using selinux it might be because of security restrictions. Try setting this as root:
# setsebool -P httpd_can_network_connect on
I use a way that may look stupid but it works for me. I simply concat the columns I want to compare and use NOT IN:
SELECT *
FROM table1 t1
WHERE CONCAT(t1.first_name,t1.last_name) NOT IN (SELECT CONCAT(t2.first_name,t2.last_name) FROM table2 t2)
As stated before it shouldn't be done using client side Javascript but there's a framework for implementing what you want more securely.
Nodejs is a framework that allows you to code server connections in javascript so have a look into Nodejs and you'll probably learn a bit more about communicating with databases and grabbing data you need.
this.state = {_x000D_
name: "",_x000D_
email: ""_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
this.setState(() => ({ _x000D_
comments: comments //comments not available in state_x000D_
}))
_x000D_
2.Check the (this) if you doing setState inside any function (i.e handleChange) check whether the function bind to this or the function should be arrow function .
## 3 ways for binding this to the below function##
//3 ways for binding this to the below function_x000D_
_x000D_
handleNameChange(e) { _x000D_
this.setState(() => ({ name }))_x000D_
}_x000D_
_x000D_
// 1.Bind while callling function_x000D_
onChange={this.handleNameChange.bind(this)}_x000D_
_x000D_
_x000D_
//2.make it as arrow function_x000D_
handleNameChange((e)=> { _x000D_
this.setState(() => ({ name }))_x000D_
})_x000D_
_x000D_
//3.Bind in constuctor _x000D_
_x000D_
constructor(props) {_x000D_
super(props)_x000D_
this.state = {_x000D_
name: "",_x000D_
email: ""_x000D_
}_x000D_
this.handleNameChange = this.handleNameChange.bind(this)_x000D_
}
_x000D_
You could change the @RequestParam type to an Integer and make it not required. This would allow your request to succeed, but it would then be null. You could explicitly set it to your default value in the controller method:
@RequestMapping(value = "/test", method = RequestMethod.POST)
@ResponseBody
public void test(@RequestParam(value = "i", required=false) Integer i) {
if(i == null) {
i = 10;
}
// ...
}
I have removed the defaultValue from the example above, but you may want to include it if you expect to receive requests where it isn't set at all:
http://example.com/test
Node.js is a javascript motor for the server side.
In addition to all the js capabilities, it includes networking capabilities (like HTTP), and access to the file system.
This is different from client-side js where the networking tasks are monopolized by the browser, and access to the file system is forbidden for security reasons.
Something that runs in the server, understands HTTP and can access files sounds like a web server. But it isn't one.
To make node.js behave like a web server one has to program it: handle the incoming HTTP requests and provide the appropriate responses.
This is what Express does: it's the implementation of a web server in js.
Thus, implementing a web site is like configuring Express routes, and programming the site's specific features.
Serving pages involves a number of tasks. Many of those tasks are well known and very common, so node's Connect module (one of the many modules available to run under node) implements those tasks.
See the current impressing offering:
Connect is the framework and through it you can pick the (sub)modules you need.
The Contrib Middleware page enumerates a long list of additional middlewares.
Express itself comes with the most common Connect middlewares.
Install node.js.
Node comes with npm, the node package manager.
The command npm install -g express
will download and install express globally (check the express guide).
Running express foo
in a command line (not in node) will create a ready-to-run application named foo. Change to its (newly created) directory and run it with node with the command node <appname>
, then open http://localhost:3000
and see.
Now you are in.
I had issues with the page reloading but was able to avoid that with routerlink="."
:
<a routerLink="." (click)="myFunction()">My Function</a>
I received inspiration from the Angular Material docs on buttons: https://material.angular.io/components/button/examples
I wrote this simple function just pass
req.headers.cookie
and cookie name
const getCookieByName =(cookies,name)=>{
const arrOfCookies = cookies.split(' ')
let yourCookie = null
arrOfCookies.forEach(element => {
if(element.includes(name)){
yourCookie = element.replace(name+'=','')
}
});
return yourCookie
}
Have a look at ?"%in%"
.
dt[dt$fct %in% vc,]
fct X
1 a 2
3 c 3
5 c 5
7 a 7
9 c 9
10 a 1
12 c 2
14 c 4
You could also use ?is.element
:
dt[is.element(dt$fct, vc),]
Using "kill -9 [PID]" or "killall -9 node" worked for me where "kill -2 [PID]" did not work.
You can get all the information of active transaction by the help of below query
SELECT
trans.session_id AS [SESSION ID],
ESes.host_name AS [HOST NAME],login_name AS [Login NAME],
trans.transaction_id AS [TRANSACTION ID],
tas.name AS [TRANSACTION NAME],tas.transaction_begin_time AS [TRANSACTION
BEGIN TIME],
tds.database_id AS [DATABASE ID],DBs.name AS [DATABASE NAME]
FROM sys.dm_tran_active_transactions tas
JOIN sys.dm_tran_session_transactions trans
ON (trans.transaction_id=tas.transaction_id)
LEFT OUTER JOIN sys.dm_tran_database_transactions tds
ON (tas.transaction_id = tds.transaction_id )
LEFT OUTER JOIN sys.databases AS DBs
ON tds.database_id = DBs.database_id
LEFT OUTER JOIN sys.dm_exec_sessions AS ESes
ON trans.session_id = ESes.session_id
WHERE ESes.session_id IS NOT NULL
and it will give below similar result
and you close that transaction by the help below KILL query by refering session id
KILL 77
Try this one also...
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
_x000D_
<p>Click the button to join two arrays.</p>_x000D_
_x000D_
<button onclick="myFunction()">Try it</button>_x000D_
_x000D_
<p id="demo"></p>_x000D_
<p id="demo1"></p>_x000D_
<script>_x000D_
function myFunction() {_x000D_
var hege = [{_x000D_
1: "Cecilie",_x000D_
2: "Lone"_x000D_
}];_x000D_
var stale = [{_x000D_
1: "Emil",_x000D_
2: "Tobias"_x000D_
}];_x000D_
var hege = hege.concat(stale);_x000D_
document.getElementById("demo1").innerHTML = hege;_x000D_
document.getElementById("demo").innerHTML = stale;_x000D_
}_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Some of what is explained above is meant only for placing an SMS in a 'ready to launch' state.
as Senthil Mg said you can use sms manager to send the sms directly but SMSManager
has been moved to android.telephony.SmsManager
I know it's not a lot of more info, but it might help someone some day.
Also you can use a MessageBox
with OKCancel
options, but it requires many codes.
The if
block is for OK
, the else
block is for Cancel
. Here is the code:
if (MessageBox.Show("Are you sure you want to do this?", "Question", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
{
MessageBox.Show("You pressed OK!");
}
else
{
MessageBox.Show("You pressed Cancel!");
}
You can also use a MessageBox
with YesNo
options:
if (MessageBox.Show("Are you sure want to doing this?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
MessageBox.Show("You are pressed Yes!");
}
else
{
MessageBox.Show("You are pressed No!");
}
@echo on>out.txt
@echo off
setlocal enabledelayedexpansion
set "parentfolder=%CD%"
for /r . %%g in (*.*) do (
set "var=%%g"
set var=!var:%parentfolder%=!
echo !var! >> out.txt
)
For me it worked after manually copying the sqljdbc4-2.jar into WEB-INF/lib folder. So please have a try on this too.
The short answer to this question is that none of these values are a reliable indicator of how much memory an executable is actually using, and none of them are really appropriate for debugging a memory leak.
Private Bytes refer to the amount of memory that the process executable has asked for - not necessarily the amount it is actually using. They are "private" because they (usually) exclude memory-mapped files (i.e. shared DLLs). But - here's the catch - they don't necessarily exclude memory allocated by those files. There is no way to tell whether a change in private bytes was due to the executable itself, or due to a linked library. Private bytes are also not exclusively physical memory; they can be paged to disk or in the standby page list (i.e. no longer in use, but not paged yet either).
Working Set refers to the total physical memory (RAM) used by the process. However, unlike private bytes, this also includes memory-mapped files and various other resources, so it's an even less accurate measurement than the private bytes. This is the same value that gets reported in Task Manager's "Mem Usage" and has been the source of endless amounts of confusion in recent years. Memory in the Working Set is "physical" in the sense that it can be addressed without a page fault; however, the standby page list is also still physically in memory but not reported in the Working Set, and this is why you might see the "Mem Usage" suddenly drop when you minimize an application.
Virtual Bytes are the total virtual address space occupied by the entire process. This is like the working set, in the sense that it includes memory-mapped files (shared DLLs), but it also includes data in the standby list and data that has already been paged out and is sitting in a pagefile on disk somewhere. The total virtual bytes used by every process on a system under heavy load will add up to significantly more memory than the machine actually has.
So the relationships are:
There's another problem here; just as shared libraries can allocate memory inside your application module, leading to potential false positives reported in your app's Private Bytes, your application may also end up allocating memory inside the shared modules, leading to false negatives. That means it's actually possible for your application to have a memory leak that never manifests itself in the Private Bytes at all. Unlikely, but possible.
Private Bytes are a reasonable approximation of the amount of memory your executable is using and can be used to help narrow down a list of potential candidates for a memory leak; if you see the number growing and growing constantly and endlessly, you would want to check that process for a leak. This cannot, however, prove that there is or is not a leak.
One of the most effective tools for detecting/correcting memory leaks in Windows is actually Visual Studio (link goes to page on using VS for memory leaks, not the product page). Rational Purify is another possibility. Microsoft also has a more general best practices document on this subject. There are more tools listed in this previous question.
I hope this clears a few things up! Tracking down memory leaks is one of the most difficult things to do in debugging. Good luck.
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.vehicals_details_row, parent, false);
Button deleteImageView = (Button) row.findViewById(R.id.DeleteImageView);
deleteImageView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//...
}
});
}
But you can get an issue - listView row not clickable. Solution:
android:focusable="true"
android:focusable="false"
Microsoft SQL Server Database Publishing Wizard will generate all the necessary insert statements, and optionally schema information as well if you need that:
http://www.microsoft.com/downloads/details.aspx?familyid=56E5B1C5-BF17-42E0-A410-371A838E570A
From the official Swift programming guide:
Global variables are variables that are defined outside of any function, method, closure, or type context. Global constants and variables are always computed lazily.
You can define it in any file and can access it in current module
anywhere.
So you can define it somewhere in the file outside of any scope. There is no need for static
and all global variables are computed lazily.
var yourVariable = "someString"
You can access this from anywhere in the current module.
However you should avoid this as Global variables are not good for application state and mainly reason of bugs.
As shown in this answer, in Swift you can encapsulate them in struct
and can access anywhere.
You can define static variables or constant in Swift also. Encapsulate in struct
struct MyVariables {
static var yourVariable = "someString"
}
You can use this variable in any class or anywhere
let string = MyVariables.yourVariable
println("Global variable:\(string)")
//Changing value of it
MyVariables.yourVariable = "anotherString"
Either document.getElementById('i1')
, document.getElementById('i2')
, or document.getElementsByName("username")[0]
is returning no element. Check, that all elements exist.
I use system properties in log4j.xml:
...
<param name="File" value="${catalina.home}/logs/root.log"/>
...
and start tests with:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.16</version>
<configuration>
<systemProperties>
<property>
<name>catalina.home</name>
<value>${project.build.directory}</value>
</property>
</systemProperties>
</configuration>
</plugin>
There are several ways to create a favicon. The best way for you depends on various factors:
If you want to get the job done well and quickly, you can use a favicon generator. This one creates the pictures and HTML code for all major desktop and mobiles browsers. Full disclosure: I'm the author of this site.
Advantages of such solution: it's quick and all compatibility considerations were already addressed for you.
As you suggest, you can create a favicon.ico
file which contains 16x16 and 32x32 pictures (note that Microsoft recommends 16x16, 32x32 and 48x48).
Then, declare it in your HTML code:
<link rel="shortcut icon" href="/path/to/icons/favicon.ico">
This method will work with all desktop browsers, old and new. But most mobile browsers will ignore the favicon.
About your suggestion of placing the favicon.ico
file in the root and not declaring it: beware, although this technique works on most browsers, it is not 100% reliable. For example Windows Safari cannot find it (granted: this browser is somehow deprecated on Windows, but you get the point). This technique is useful when combined with PNG icons (for modern browsers).
In your question, you do not mention the mobile browsers. Most of them will ignore the favicon.ico
file. Although your site may be dedicated to desktop browsers, chances are that you don't want to ignore mobile browsers altogether.
You can achieve a good compatibility with:
favicon.ico
, see above.Declare them with
<link rel="shortcut icon" href="/path/to/icons/favicon.ico">
<link rel="icon" type="image/png" href="/path/to/icons/favicon-192x192.png" sizes="192x192">
<link rel="apple-touch-icon" sizes="180x180" href="/path/to/icons/apple-touch-icon-180x180.png">
This is not the full story, but it's good enough in most cases.
if digit is meant to be a Character
String numstr = Integer.toString( 123 );
Pattern.compile( "" ).splitAsStream( numstr ).map(
s -> s.charAt( 0 ) ).toArray( Character[]::new ); // [1, 2, 3]
and the following works correctly
numstr = "000123"
gets [0, 0, 0, 1, 2, 3]
numstr = "-123"
gets [-, 1, 2, 3]
You can create a extension method:
public static IEnumerable<T> Do<T>(this IEnumerable<T> self, Action<T> action) {
foreach(var item in self) {
action(item);
yield return item;
}
}
And then use it in code:
listofCompany.Do(d=>d.Id = 1);
listofCompany.Where(d=>d.Name.Contains("Inc")).Do(d=>d.Id = 1);
The solution given above worked for us as well for a long time:
mvn versions:set -DnewVersion=2.50.1-SNAPSHOT
However it stopped working yesterday, and we found it due to a recent bug in a the versions-maven-plugin
Our (temporary) workaround was to change the parent/pom.xml file as follows:
--- jackrabbit/oak/trunk/oak-parent/pom.xml 2020/08/13 13:43:11 1880829
+++ jackrabbit/oak/trunk/oak-parent/pom.xml 2020/08/13 15:17:59 1880830
@@ -329,6 +329,13 @@
<artifactId>spotbugs-maven-plugin</artifactId>
<version>3.1.11</version>
</plugin>
+
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>versions-maven-plugin</artifactId>
+ <version>2.7</version>
+ </plugin>
+
Yes,It's right.The first you should find out your service account of sqlserver,you can see it in Task Manager when you press ctrl+alt+delete at the same time;Then,you must give the read/write privilege of "C:\Murach\SQL Server 2008\Databases" to the service account.
Just use Hour
and Minute
properties
var date = DateTime.Now;
date.Hour;
date.Minute;
Or you can easily zero the seconds using
var zeroSecondDate = date.AddSeconds(-date.Second);
Here is the script I use:
@ECHO off
SETLOCAL ENABLEDELAYEDEXPANSION
mode con:cols=210 lines=50
ECHO Starting 1-way backup of MEDIA(M:) to BACKUP(G:)...
robocopy.exe M:\ G:\ *.* /E /PURGE /SEC /NP /NJH /NJS /XD "$RECYCLE.BIN" "System Volume Information" /TEE /R:5 /COPYALL /LOG:from_M_to_G.log
ECHO Finished with backup.
pause
As mentioned in the comments to the question, the JDBC-ODBC Bridge is - as the name indicates - only a mechanism for the JDBC layer to "talk to" the ODBC layer. Even if you had a JDBC-ODBC Bridge on your Mac you would also need to have
So, for most people, using JDBC-ODBC Bridge technology to manipulate ACE/Jet ("Access") databases is really a practical option only under Windows. It is also important to note that the JDBC-ODBC Bridge will be has been removed in Java 8 (ref: here).
There are other ways of manipulating ACE/Jet databases from Java, such as UCanAccess and Jackcess. Both of these are pure Java implementations so they work on non-Windows platforms. For details on how to use UCanAccess see
Since you're using jQuery, you just need to attach to some specific events and some pre defined animations:
$('#cat').hover(function()
{
// Mouse Over Callback
}, function()
{
// Mouse Leave callback
});
Then, to do the animation, you simply need to call the fadeOut / fadeIn animations:
$('#dog').fadeOut(750 /* Animation Time */, function()
{
// animation complete callback
$('#cat').fadeIn(750);
});
Combining the two together, you would simply insert the animations in the hover callbacks (something like so, use this as a reference point):
$('#cat').hover(function()
{
if($('#dog').is(':visible'))
$('#dog').fadeOut(750 /* Animation Time */, function()
{
// animation complete callback
$('#cat').fadeIn(750);
});
}, function()
{
// Mouse Leave callback
});
I like the Apache Commons IO library. Take a look at its version of ByteArrayOutputStream, which has a toString(String enc)
method as well as toByteArray()
. Using existing and trusted components like the Commons project lets your code be smaller and easier to extend and repurpose.
use this
<body onload = "if (location.search.length < 1){window.location.reload()}">
to implement this in algorithmic way, by not using any python inbuilt function . This can be implemented as
def find_pos(string,word):
for i in range(len(string) - len(word)+1):
if string[i:i+len(word)] == word:
return i
return 'Not Found'
string = "the dude is a cool dude"
word = 'dude1'
print(find_pos(string,word))
# output 4
You can try FakeHttpContext:
using (new FakeHttpContext())
{
HttpContext.Current.Session["CustomerId"] = "customer1";
}
Implement Comparable interface to Fruit.
public class Fruit implements Comparable<Fruit> {
It implements the method
@Override
public int compareTo(Fruit fruit) {
//write code here for compare name
}
Then do call sort method
Collections.sort(fruitList);
Before Rails 2.x the preferred way to get the current environment was using the RAILS_ENV
constant. Likewise, you can use RAILS_DEFAULT_LOGGER
to get the current logger or RAILS_ROOT
to get the path to the root folder.
Starting from Rails 2.x, Rails introduced the Rails
module with some special methods:
This isn't just a cosmetic change. The Rails module offers capabilities not available using the standard constants such as StringInquirer
support.
There are also some slight differences. Rails.root
doesn't return a simple String
buth a Path
instance.
Anyway, the preferred way is using the Rails
module. Constants are deprecated in Rails 3 and will be removed in a future release, perhaps Rails 3.1.
When you run make, add VERBOSE=1
to see the full command output. For example:
cmake .
make VERBOSE=1
Or you can add -DCMAKE_VERBOSE_MAKEFILE:BOOL=ON
to the cmake command for permanent verbose command output from the generated Makefiles.
cmake -DCMAKE_VERBOSE_MAKEFILE:BOOL=ON .
make
To reduce some possibly less-interesting output you might like to use the following options. The option CMAKE_RULE_MESSAGES=OFF
removes lines like [ 33%] Building C object..., while --no-print-directory
tells make to not print out the current directory filtering out lines like make[1]: Entering directory
and make[1]: Leaving directory
.
cmake -DCMAKE_RULE_MESSAGES:BOOL=OFF -DCMAKE_VERBOSE_MAKEFILE:BOOL=ON .
make --no-print-directory
Use Html.Raw()
. Phil Haack posted a nice syntax guide at http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx.
<div class='content'>
@Html.Raw( Model.Content )
</div>
Nothing in the example says that the "classes implementing the same interface". MovieCatalog
is a type and CustomerPreferenceDao
is another type. Spring can easily tell them apart.
In Spring 2.x, wiring of beans mostly happened via bean IDs or names. This is still supported by Spring 3.x but often, you will have one instance of a bean with a certain type - most services are singletons. Creating names for those is tedious. So Spring started to support "autowire by type".
What the examples show is various ways that you can use to inject beans into fields, methods and constructors.
The XML already contains all the information that Spring needs since you have to specify the fully qualified class name in each bean. You need to be a bit careful with interfaces, though:
This autowiring will fail:
@Autowired
public void prepare( Interface1 bean1, Interface1 bean2 ) { ... }
Since Java doesn't keep the parameter names in the byte code, Spring can't distinguish between the two beans anymore. The fix is to use @Qualifier
:
@Autowired
public void prepare( @Qualifier("bean1") Interface1 bean1,
@Qualifier("bean2") Interface1 bean2 ) { ... }
If you are using Json.Net attribute [JsonIgnore]
will simply ignore the field/property while serializing or deserialising.
public class Car
{
// included in JSON
public string Model { get; set; }
public DateTime Year { get; set; }
public List<string> Features { get; set; }
// ignored
[JsonIgnore]
public DateTime LastModified { get; set; }
}
Or you can use DataContract and DataMember attribute to selectively serialize/deserialize properties/fields.
[DataContract]
public class Computer
{
// included in JSON
[DataMember]
public string Name { get; set; }
[DataMember]
public decimal SalePrice { get; set; }
// ignored
public string Manufacture { get; set; }
public int StockCount { get; set; }
public decimal WholeSalePrice { get; set; }
public DateTime NextShipmentDate { get; set; }
}
Refer http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size for more details
You can get a public URL for your server running on a specific port on localhost.
At my work place I could access the local server by using the local IP address of my machine in the app, as most of the other answers suggest. But at home I wasn't able to do that for some reason. After trying many answers and spending many hours, I came across https://ngrok.com. It is pretty straight forward. Just download it from within the folder do:
ngrok portnumber
( from command prompt in windows)
./ngrok portnumber
(from terminal in linux)
This will give you a public URL for your local server running on that port number on localhost. You can include in your app and debug it using that URL.
You can securely expose a local web server to the internet and capture all traffic for detailed inspection. You can share the URL with your colleague developer also who might be working remotely and can debug the App/Server interaction.
Hope this saves someone's time someday.
Here is how I do it:
var hashTagActive = "";
$(".scroll").on("click touchstart" , function (event) {
if(hashTagActive != this.hash) { //this will prevent if the user click several times the same link to freeze the scroll.
event.preventDefault();
//calculate destination place
var dest = 0;
if ($(this.hash).offset().top > $(document).height() - $(window).height()) {
dest = $(document).height() - $(window).height();
} else {
dest = $(this.hash).offset().top;
}
//go to destination
$('html,body').animate({
scrollTop: dest
}, 2000, 'swing');
hashTagActive = this.hash;
}
});
Then you just need to create your anchor like this:
<a class="scroll" href="#destination1">Destination 1</a>
You can see it on my website.
A demo is also available here: http://jsfiddle.net/YtJcL/
Open the /etc/mysql/mysql.conf.d/mysqld.cnf
file and comment the
following line:
#bind-address = 127.0.0.1
std::vector<unsigned char> intToBytes(int value)
{
std::vector<unsigned char> result;
result.push_back(value >> 24);
result.push_back(value >> 16);
result.push_back(value >> 8);
result.push_back(value );
return result;
}
There are two typical ways of declaring a function. I prefer the second approach.
function function_name {
command...
}
or
function_name () {
command...
}
To call a function with arguments:
function_name "$arg1" "$arg2"
The function refers to passed arguments by their position (not by name), that is $1
, $2
, and so forth. $0
is the name of the script itself.
Example:
function_name () {
echo "Parameter #1 is $1"
}
Also, you need to call your function after it is declared.
#!/usr/bin/env sh
foo 1 # this will fail because foo has not been declared yet.
foo() {
echo "Parameter #1 is $1"
}
foo 2 # this will work.
Output:
./myScript.sh: line 2: foo: command not found
Parameter #1 is 2
PHP syntax is little different in case of concatenation from JavaScript.
Instead of (+) plus
a (.) period
is used for string concatenation.
<?php
$selectBox = '<select name="number">';
for ($i=1;$i<=100;$i++)
{
$selectBox += '<option value="' . $i . '">' . $i . '</option>'; // <-- (Wrong) Replace + with .
$selectBox .= '<option value="' . $i . '">' . $i . '</option>'; // <-- (Correct) Here + is replaced .
}
$selectBox += '</select>'; // <-- (Wrong) Replace + with .
$selectBox .= '</select>'; // <-- (Correct) Here + is replaced .
echo $selectBox;
?>
It's not clear what you're actually trying to achieve, but here are two alternatives:
class E
{
public:
struct X
{
int v;
};
// 1. (a) Instantiate an 'X' within 'E':
X x;
};
int main()
{
// 1. (b) Modify the 'x' within an 'E':
E e;
e.x.v = 9;
// 2. Instantiate an 'X' outside 'E':
E::X x;
x.v = 10;
}
I don't think it's the right way to use angular. If a framework method doesnt exist, don't create it! This means the framework (here angular) doesnt work this way.
With angular you should not manipulate DOM like this (the jquery way), but use angular helper such as
<div ng-show="isLoading" class="loader"></div>
Or create your own directive (your own DOM component) in order to have full control on it.
BTW, you can see here http://caniuse.com/#search=queryselector querySelector is well supported and so can be use safely.
Any Java collection can be made to be Thread-safe like so:
List newList = Collections.synchronizedList(oldList);
Or to create a brand new thread-safe list:
List newList = Collections.synchronizedList(new ArrayList());
I solved this issue on PHP 7.0.22-0ubuntu0.16.04.1 nginx
sudo apt-get install php7.0-soap
sudo systemctl restart php7.0-fpm
sudo systemctl restart nginx
Here is a stripped down example, using as little HTML markup as possible.
The overlay is provided by the :before
pseudo element on the .content
container.
No z-index is required, :before
is naturally layered over the video element.
The .content
container is position: relative
so that the position: absolute
overlay is positioned in relation to it.
The overlay is stretched to cover the entire .content
div width with left / right / bottom
and left
set to 0
.
The width of the video is controlled by the width of its container with width: 100%
.content {
position: relative;
width: 500px;
margin: 0 auto;
padding: 20px;
}
.content video {
width: 100%;
display: block;
}
.content:before {
content: '';
position: absolute;
background: rgba(0, 0, 0, 0.5);
border-radius: 5px;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
_x000D_
<div class="content">
<video id="player" src="https://upload.wikimedia.org/wikipedia/commons/transcoded/1/18/Big_Buck_Bunny_Trailer_1080p.ogv/Big_Buck_Bunny_Trailer_1080p.ogv.360p.vp9.webm" autoplay loop muted></video>
</div>
_x000D_
The best approach if you want to ALWAYS show two decimal places (even if your number only has one decimal place) is to use
yournumber.ToString("0.00");
java.util.Collections.sort(listOfCountryNames, Collator.getInstance());
The accepted answer gave me a good start, but brought in more classes and more processing than I would have liked; so this is my interpretation:
$xml_reader = new XMLReader;
$xml_reader->open($feed_url);
// move the pointer to the first product
while ($xml_reader->read() && $xml_reader->name != 'product');
// loop through the products
while ($xml_reader->name == 'product')
{
// load the current xml element into simplexml and we’re off and running!
$xml = simplexml_load_string($xml_reader->readOuterXML());
// now you can use your simpleXML object ($xml).
echo $xml->element_1;
// move the pointer to the next product
$xml_reader->next('product');
}
// don’t forget to close the file
$xml_reader->close();
Using jquery you can do this by following code:
<input type="text" id="tbxEmail" name="Email" placeholder="Some Text"/>
$('#tbxEmail').attr('placeholder','Some New Text');
There's a faster way, just use
YourActivity.setTitle("New Title");
You can also find it inside the onCreate() with this, for example:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.setTitle("My Title");
}
By the way, what you simply cannot do is call setTitle() in a static way without passing any Activity object.
As for guidelines... a random search from StackOverflow and the electric interweb...
It's important to note, that NULL doesn't equal NULL.
NULL
is not a value, and therefore cannot be compared to another value.
where x is null
checks whether x is a null value.
where x = null
is checking whether x equals NULL, which will never be true
I know this question is pretty old. But we can able to get root in Emulator with the help of Magisk by following https://github.com/shakalaca/MagiskOnEmulator
Basically, it patch initrd.img(if present) and ramdisk.img for working with Magisk.
For example:
$(document).on('click','span.external-link',function(){
var t = $(this),
URL = t.attr('data-href');
$('<a href="'+ URL +'" target="_blank">External Link</a>')[0].click();
});
Working example.
Just use it like it was an object you defined. i.e.
$trends = $json_output->trends;
Another example similar to those here
function fileSize(b) {
var u = 0, s=1024;
while (b >= s || -b >= s) {
b /= s;
u++;
}
return (u ? b.toFixed(1) + ' ' : b) + ' KMGTPEZY'[u] + 'B';
}
It measures negligibly better performance than the others with similar features.
If you have forked a repository fro Delete your forked copy and fork it again from master.
For the answer above, the default serial port is
serialParams.BaudRate = 9600;
serialParams.ByteSize = 8;
serialParams.StopBits = TWOSTOPBITS;
serialParams.Parity = NOPARITY;
You can use one of the following methods to determine the number of physical CPU cores.
Count the number of unique core ids (roughly equivalent to grep -P '^core id\t' /proc/cpuinfo | sort -u | wc -l
).
awk '/^core id\t/ {cores[$NF]++} END {print length(cores)}' /proc/cpuinfo
Multiply the number of 'cores per socket' by the number of sockets.
lscpu | awk '/^Core\(s\) per socket:/ {cores=$NF}; /^Socket\(s\):/ {sockets=$NF}; END{print cores*sockets}'
Count the number of unique logical CPU's as used by the Linux kernel. The -p
option generates output for easy parsing and is compatible with earlier versions of lscpu
.
lscpu -p | awk -F, '$0 !~ /^#/ {cores[$1]++} END {print length(cores)}'
Just to reiterate what others have said, there are a number of related properties.
To determine the number of processors available:
getconf _NPROCESSORS_ONLN
grep -cP '^processor\t' /proc/cpuinfo
To determine the number of processing units available (not necessarily the same as the number of cores). This is hyperthreading-aware.
nproc
I don't want to go too far down the rabbit-hole, but you can also determine the number of configured processors (as opposed to simply available/online processors) via getconf _NPROCESSORS_CONF
. To determine total number of CPU's (offline and online) you'd want to parse the output of lscpu -ap
.
That is exactly how you do it in C#, but the feature was first added in .NET 4.0
Even though this question has been answered in alot of helpful ways I just wanted to add that when I followed Rafal Maleks answer (using the hash keys on Google Play Console) I was NOT able to use the App Signing SHA1 key, still got the generic error from Facebook. Instead I needed to use the SHA-1 certificate fingerprint from the Upload Certificate part (just below the App Signing part on Google Play Console). Same process otherwise;
Copy the SHA-1 certificate fingerprint from Upload Certificate section in Google Play Console
Convert the SHA-1 using: http://tomeko.net/online_tools/hex_to_base64.php and copy the output (base64)
Paste it into the Key Hashes input on developer.facebook.com and save changes.
Hopefully this answer isn't to redundant and will help someone that can't get it to work with the App Signing certificate.
Now Facebook login works in my app both in debug and release mode.
You could do:
var numberOfChecked = $('input:checkbox:checked').length;
var totalCheckboxes = $('input:checkbox').length;
var numberNotChecked = totalCheckboxes - numberOfChecked;
EDIT
Or even simple
var numberNotChecked = $('input:checkbox:not(":checked")').length;
Use JQuery, its easy.
Include the JQuery library into your html file in the head as such:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
(Make sure that this script tag goes before your other script tags in your html file)
Target your id in your JavaScript file as such:
<script>
var youtubeimcsrc = $('#youtubeimg').attr('src');
//your var will be the src string that you're looking for
</script>
I've submitted a pull request (available in Ansible 2.2+) that will make this kinds of situations easier by adding jmespath query support on Ansible. In your case it would work like:
- debug: msg="{{ addresses | json_query(\"private_man[?type=='fixed'].addr\") }}"
would return:
ok: [localhost] => {
"msg": [
"172.16.1.100"
]
}
Unit testing involves breaking your program into pieces, and subjecting each piece to a series of tests.
Usually tests are run as separate programs, but the method of testing varies, depending on the language, and type of software (GUI, command-line, library).
Most languages have unit testing frameworks, you should look into one for yours.
Tests are usually run periodically, often after every change to the source code. The more often the better, because the sooner you will catch problems.
You can choose a cell to be markdown, then write latex code which gets interpreted by mathjax, as one of the responders say above.
Alternatively, Latex section of the iPython notebook tutorial explains this well.
You can either do:
from IPython.display import Latex
Latex(r"""\begin{eqnarray}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{eqnarray}""")
or do this:
%%latex
\begin{align}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{align}
More info found in this link
var postdata = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"};
var data = [];
data.push(postdata);
console.log(data);
If you login into the source control with the admin account, you will be able to force undo checkout, or check in with any file you provide.
Probably the simplest way is using subplot2grid
, described in Customizing Location of Subplot Using GridSpec.
ax = plt.subplot2grid((2, 2), (0, 0))
is equal to
import matplotlib.gridspec as gridspec
gs = gridspec.GridSpec(2, 2)
ax = plt.subplot(gs[0, 0])
so bmu's example becomes:
import numpy as np
import matplotlib.pyplot as plt
# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)
# plot it
fig = plt.figure(figsize=(8, 6))
ax0 = plt.subplot2grid((1, 3), (0, 0), colspan=2)
ax0.plot(x, y)
ax1 = plt.subplot2grid((1, 3), (0, 2))
ax1.plot(y, x)
plt.tight_layout()
plt.savefig('grid_figure.pdf')
From Postgres 9.1 Documentation:
ALTER TYPE name ADD VALUE new_enum_value [ { BEFORE | AFTER } existing_enum_value ]
Example:
ALTER TYPE user_status ADD VALUE 'PROVISIONAL' AFTER 'NORMAL'
Goto File -> Settings -> Compiler now check use external build
then rebuild project
Redis is better.
The Pros of Redis
are ,
LUA
scripting) supportWhereas Memcache
is an in-memory key value cache type system.
Building on Benjamin's, using pandas.Series
, and replacing MAD with IQR:
def reject_outliers(sr, iq_range=0.5):
pcnt = (1 - iq_range) / 2
qlow, median, qhigh = sr.dropna().quantile([pcnt, 0.50, 1-pcnt])
iqr = qhigh - qlow
return sr[ (sr - median).abs() <= iqr]
For instance, if you set iq_range=0.6
, the percentiles of the interquartile-range would become: 0.20 <--> 0.80
, so more outliers will be included.
It is possible in 12.1.
Find idea.properties in the BIN folder inside of wherever your IDE is installed, e.g. C:\Program Files (x86)\JetBrains\IntelliJ\bin
Add a new line to the end of that file:
auto.show.quick.doc=true
Start IDEA and just hover your mouse over something:
You need to escape the braces:
git stash pop stash@\{1\}
Sure, you could use HEREDOC, but as far as code readability goes it's not really any better than the first example, wrapping the string across multiple lines.
If you really want your multi-line string to look good and flow well with your code, I'd recommend concatenating strings together as such:
$text = "Hello, {$vars->name},\r\n\r\n"
. "The second line starts two lines below.\r\n"
. ".. Third line... etc";
This might be slightly slower than HEREDOC or a multi-line string, but it will flow well with your code's indentation and make it easier to read.
Improve on Andres Riofrio , to handle any number of arguments
var fs = require('fs');
var util = require('util');
var log_file = fs.createWriteStream(__dirname + '/debug.log', {flags : 'w'});
var log_stdout = process.stdout;
console.log = function(...args) {
var output = args.join(' ');
log_file.write(util.format(output) + '\r\n');
log_stdout.write(util.format(output) + '\r\n');
};
This is how you can submit your form to a specific controller and action method in Razor.
<input type="submit" value="Upload" onclick="location.href='@Url.Action("ActionName", "ControllerName")'" />
Just do it simple (tested with v1.3.15):
<article ng-controller="ctrl1 as c1">
<label>Change name here:</label>
<input ng-model="c1.sData.name" />
<h1>Control 1: {{c1.sData.name}}, {{c1.sData.age}}</h1>
</article>
<article ng-controller="ctrl2 as c2">
<label>Change age here:</label>
<input ng-model="c2.sData.age" />
<h1>Control 2: {{c2.sData.name}}, {{c2.sData.age}}</h1>
</article>
<script>
var app = angular.module("MyApp", []);
var dummy = {name: "Joe", age: 25};
app.controller("ctrl1", function () {
this.sData = dummy;
});
app.controller("ctrl2", function () {
this.sData = dummy;
});
</script>
When you use a blade echo {{ $data }}
it will automatically escape the output. It can only escape strings. In your data $data->ac
is an array and $data
is an object, neither of which can be echoed as is. You need to be more specific of how the data should be outputted. What exactly that looks like entirely depends on what you're trying to accomplish. For example to display the link you would need to do {{ $data->ac[0][0]['url'] }}
(not sure why you have two nested arrays but I'm just following your data structure).
@foreach($data->ac['0'] as $link)
<a href="{{ $link['url'] }}">This is a link</a>
@endforeach
If you're already using jquery, I don't see why you wouldn't also be able to use a lightweight overlay plugin. Other people have already written some nice ones in jquery, so why re-invent the wheel?
Just delete the user related data from mysql.db(maybe from other tables too), then recreate both.
It's as easy as:
delete object.keyname;
or
delete object["keyname"];
Use parseJSON
. Look at the doc
var obj = $.parseJSON(data);
Something like this:
$.ajax({
type: "POST",
url: '/admin/systemgoalssystemgoalupdate?format=html',
data: formdata,
success: function (data) {
console.log($.parseJSON(data)); //will log Object
}
});
I just added simple view to WindowManager
with the following steps:
// 1. Show view
private void showCustomPopupMenu()
{
windowManager = (WindowManager)getSystemService(WINDOW_SERVICE);
// LayoutInflater layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// View view = layoutInflater.inflate(R.layout.dummy_layout, null);
ViewGroup valetModeWindow = (ViewGroup) View.inflate(this, R.layout.dummy_layout, null);
int LAYOUT_FLAG;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
} else {
LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_PHONE;
}
WindowManager.LayoutParams params=new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
LAYOUT_FLAG,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity= Gravity.CENTER|Gravity.CENTER;
params.x=0;
params.y=0;
windowManager.addView(valetModeWindow, params);
}
// 2. Get permissions by asking
if (!Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, 1234);
}
With this you can add a view to WM.
Tested in Pie.
For example, i created a table :
DataTable dt = new DataTable ();
dt.Columns.Add("Title", typeof(string));
dt.Columns.Add("Value", typeof(int));
Add recorde to table :
DataRow row = dt.NewRow();
row["Title"] = "Price"
row["Value"] = 2000;
dt.Rows.Add(row);
or :
dt.Rows.Add("Price",2000);
finally :
combo.DataSource = dt;
combo.DisplayMember = "Title";
combo.ValueMember = "Value";
Nornally the tag is used for that, with a change in style.
Like
<p>This is my text <span class="highlight"> and these words are different</span></p>
,
You set the css in the header (or rather, in a separate css file) to make your "highlight" text assume the color you wish.
(e.g.: with
<style type="text/css">
.highlight {color: orange}
</style>
in the header. Avoid using the tag <font />
for that at all costs. :-)