Actually Windows does have a utility that encodes and decodes base64 - CERTUTIL
I'm not sure what version of Windows introduced this command.
To encode a file:
certutil -encode inputFileName encodedOutputFileName
To decode a file:
certutil -decode encodedInputFileName decodedOutputFileName
There are a number of available verbs and options available to CERTUTIL.
To get a list of nearly all available verbs:
certutil -?
To get help on a particular verb (-encode for example):
certutil -encode -?
To get complete help for nearly all verbs:
certutil -v -?
Mysteriously, the -encodehex
verb is not listed with certutil -?
or certutil -v -?
. But it is described using certutil -encodehex -?
. It is another handy function :-)
Regarding David Morales' comment, there is a poorly documented type option to the -encodehex
verb that allows creation of base64 strings without header or footer lines.
certutil [Options] -encodehex inFile outFile [type]
A type of 1 will yield base64 without the header or footer lines.
See https://www.dostips.com/forum/viewtopic.php?f=3&t=8521#p56536 for a brief listing of the available type formats. And for a more in depth look at the available formats, see https://www.dostips.com/forum/viewtopic.php?f=3&t=8521#p57918.
Not investigated, but the -decodehex
verb also has an optional trailing type argument.
Try this:
function removeClassDelayed(jqObj, c, to) {
setTimeout(function() { jqObj.removeClass(c); }, to);
}
removeClassDelayed($("#div"), "error", 1000);
I would suggest you use an ArrayList as you won't have to worry about the length anymore. Once created, you can't modify an array size:
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.
(Source)
You probably need to either open up the port to access it in your LAN (or outside of it) or bind the network address to the port (make PostgreSQL listen on your LAN instead of just on localhost)
The solutions here are old and now deprecated: https://github.com/uuidjs/uuid#deep-requires-now-deprecated
Use this:
npm install uuid
//add these lines to your code
const { v4: uuidv4 } = require('uuid');
var your_uuid = uuidv4();
console.log(your_uuid);
Use a LEFT JOIN checking the right side for nulls.
SELECT a.Id
FROM TableA a
LEFT JOIN TableB on a.Id = b.Id
WHERE b.Id IS NULL
The above would match up TableA and TableB based on the Id column in each, and then give you the rows where the B side is empty.
try this
var x= [
{name: "Joe", age: 22},
{name: "Kevin", age: 24},
{name: "Peter", age: 21}
]
function joinObj(a, attr) {
var out = [];
for (var i=0; i<a.length; i++) {
out.push(a[i][attr]);
}
return out.join(", ");
}
var z = joinObj(x,'name');
z > "Joe, Kevin, Peter"
var y = joinObj(x,'age');
y > "22, 24, 21"
You can still install and use Query Analyzer from previous SQL Server versions.
A view helps us in get rid of utilizing database space all the time. If you create a table it is stored in database and holds some space throughout its existence. Instead view is utilized when a query runs hence saving the db space. And we cannot create big tables all the time joining different tables though we could but its depends how big the table is to save the space. So view just temporarily create a table with joining different table at the run time. Experts,Please correct me if I am wrong.
Try this:
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Path\To\Xml\File.xml");
Or alternatively if you have the XML in a string use the LoadXml
method.
Once you have it loaded, you can use SelectNodes
and SelectSingleNode
to query specific values, for example:
XmlNode node = doc.SelectSingleNode("//Company/Email/text()");
// node.Value contains "[email protected]"
Finally, note that your XML is invalid as it doesn't contain a single root node. It must be something like this:
<Data>
<Employee>
<Name>Test</Name>
<ID>123</ID>
</Employee>
<Company>
<Name>ABC</Name>
<Email>[email protected]</Email>
</Company>
</Data>
$('#thisElement').find('.classToSelect')
will find any descendents of #thisElement
with class classToSelect
.
Instead of redis-cli
you can simply use nc
!
nc -v --ssl redis.mydomain.com 6380
Then submit the commands.
In my opinion, Sergiy's answer should be the selected answer for the given question. I'm sharing my understanding.
I was looking to autoload my package files using composer which I have under the dir structure given below.
<web-root>
|--------src/
| |--------App/
| |
| |--------Test/
|
|---------library/
|
|---------vendor/
| |
| |---------composer/
| | |---------autoload_psr4.php
| |
| |----------autoload.php
|
|-----------composer.json
|
I'm using psr-4 autoloading specification.
Had to add below lines to the project's composer.json. I intend to place my class files inside src/App , src/Test and library directory.
"autoload": {
"psr-4": {
"OrgName\\AppType\\AppName\\": ["src/App", "src/Test", "library/"]
}
}
This is pretty much self explaining. OrgName\AppType\AppName is my intended namespace prefix. e.g for class User in src/App/Controller/Provider/User.php -
namespace OrgName\AppType\AppName\Controller\Provider; // namespace declaration
use OrgName\AppType\AppName\Controller\Provider\User; // when using the class
Also notice "src/App", "src/Test" .. are from your web-root that is where your composer.json is. Nothing to do with the vendor dir. take a look at vendor/autoload.php
Now if composer is installed properly all that is required is #composer update
After composer update my classes loaded successfully. What I observed is that composer is adding a line in vendor/composer/autoload_psr4.php
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'),
'OrgName\\AppType\\AppName\\' => array($baseDir . '/src/App', $baseDir . '/src/Test', $baseDir . '/library'),
);
This is how composer maps. For psr-0 mapping is in vendor/composer/autoload_classmap.php
use float: left;
and clear: left;
.text span {
background: rgba(165, 220, 79, 0.8);
float: left;
clear: left;
padding: 7px 10px;
color: #fff;
}
If anyone is using Maven, you'll need to add the dependency in the POM.XML file. The latest version as of this post is below:
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
An abstract class can be used instead of an interface (in C# 7.3).
// Like interface
abstract class IIO
{
public virtual async Task<string> DoOperation(string Name)
{
throw new NotImplementedException(); // throwing exception
// return await Task.Run(() => { return ""; }); // or empty do
}
}
// Implementation
class IOImplementation : IIO
{
public override async Task<string> DoOperation(string Name)
{
return await await Task.Run(() =>
{
if(Name == "Spiderman")
return "ok";
return "cancel";
});
}
}
By the way. whenever my forms call the formclosed or form closing event I close the applciation with a this.Hide() function. Does that affect how my application is behaving now?
In short, yes. The entire application will end when the main form (the form started via Application.Run
in the Main
method) is closed (not hidden).
If your entire application should always fully terminate whenever your main form is closed then you should just remove that form closed handler. By not canceling that event and just letting them form close when the user closes it you will get your desired behavior. As for all of the other forms, if you don't intend to show that same instance of the form again you just just let them close, rather than preventing closure and hiding them. If you are showing them again, then hiding them may be fine.
If you want to be able to have the user click the "x" for your main form, but have another form stay open and, in effect, become the "new" main form, then it's a bit more complicated. In such a case you will need to just hide your main form rather than closing it, but you'll need to add in some sort of mechanism that will actually close the main form when you really do want your app to end. If this is the situation that you're in then you'll need to add more details to your question describing what types of applications should and should not actually end the program.
While there is no functional difference between os.environ.get
and os.getenv
, there is a massive difference between os.putenv
and setting entries on os.environ
. os.putenv
is broken, so you should default to os.environ.get
simply to avoid the way os.getenv
encourages you to use os.putenv
for symmetry.
os.putenv
changes the actual OS-level environment variables, but in a way that doesn't show up through os.getenv
, os.environ
, or any other stdlib way of inspecting environment variables:
>>> import os
>>> os.environ['asdf'] = 'fdsa'
>>> os.environ['asdf']
'fdsa'
>>> os.putenv('aaaa', 'bbbb')
>>> os.getenv('aaaa')
>>> os.environ.get('aaaa')
You'd probably have to make a ctypes call to the C-level getenv
to see the real environment variables after calling os.putenv
. (Launching a shell subprocess and asking it for its environment variables might work too, if you're very careful about escaping and --norc
/--noprofile
/anything else you need to do to avoid startup configuration, but it seems a lot harder to get right.)
Following the Java like enum implementation proposed by Aaron Maenpaa, I came out with the following. The idea was to make it generic and parseable.
class Enum:
#'''
#Java like implementation for enums.
#
#Usage:
#class Tool(Enum): name = 'Tool'
#Tool.DRILL = Tool.register('drill')
#Tool.HAMMER = Tool.register('hammer')
#Tool.WRENCH = Tool.register('wrench')
#'''
name = 'Enum' # Enum name
_reg = dict([]) # Enum registered values
@classmethod
def register(cls, value):
#'''
#Registers a new value in this enum.
#
#@param value: New enum value.
#
#@return: New value wrapper instance.
#'''
inst = cls(value)
cls._reg[value] = inst
return inst
@classmethod
def parse(cls, value):
#'''
#Parses a value, returning the enum instance.
#
#@param value: Enum value.
#
#@return: Value corresp instance.
#'''
return cls._reg.get(value)
def __init__(self, value):
#'''
#Constructor (only for internal use).
#'''
self.value = value
def __str__(self):
#'''
#str() overload.
#'''
return self.value
def __repr__(self):
#'''
#repr() overload.
#'''
return "<" + self.name + ": " + self.value + ">"
As explained in the accepted answer, https://stackoverflow.com/a/18665488/4038790, you need to check via a server.
Because there's no reliable way to check this in the browser, I suggest you build yourself a quick server endpoint that you can use to check if any url is loadable via iframe. Once your server is up and running, just send a AJAX request to it to check any url by providing the url in the query string as url
(or whatever your server desires). Here's the server code in NodeJs:
const express = require('express')_x000D_
const app = express()_x000D_
_x000D_
app.get('/checkCanLoadIframeUrl', (req, res) => {_x000D_
const request = require('request')_x000D_
const Q = require('q')_x000D_
_x000D_
return Q.Promise((resolve) => {_x000D_
const url = decodeURIComponent(req.query.url)_x000D_
_x000D_
const deafultTimeout = setTimeout(() => {_x000D_
// Default to false if no response after 10 seconds_x000D_
resolve(false)_x000D_
}, 10000)_x000D_
_x000D_
request({_x000D_
url,_x000D_
jar: true /** Maintain cookies through redirects */_x000D_
})_x000D_
.on('response', (remoteRes) => {_x000D_
const opts = (remoteRes.headers['x-frame-options'] || '').toLowerCase()_x000D_
resolve(!opts || (opts !== 'deny' && opts !== 'sameorigin'))_x000D_
clearTimeout(deafultTimeout)_x000D_
})_x000D_
.on('error', function() {_x000D_
resolve(false)_x000D_
clearTimeout(deafultTimeout)_x000D_
})_x000D_
}).then((result) => {_x000D_
return res.status(200).json(!!result)_x000D_
})_x000D_
})_x000D_
_x000D_
app.listen(process.env.PORT || 3100)
_x000D_
If you need it for knowing someone's age for trivial reasons then Timespan is OK but if you need for calculating superannuation, long term deposits or anything else for financial, scientific or legal purposes then I'm afraid Timespan won't be accurate enough because Timespan assumes that every year has the same number of days, same # of hours and same # of seconds).
In reality the length of some years will vary (for different reasons that are outside the scope of this answer). To get around Timespan's limitation then you can mimic what Excel does which is:
public int GetDifferenceInYears(DateTime startDate, DateTime endDate)
{
//Excel documentation says "COMPLETE calendar years in between dates"
int years = endDate.Year - startDate.Year;
if (startDate.Month == endDate.Month &&// if the start month and the end month are the same
endDate.Day < startDate.Day// AND the end day is less than the start day
|| endDate.Month < startDate.Month)// OR if the end month is less than the start month
{
years--;
}
return years;
}
try to check if your have installed in the settings.py
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',)
In the template the data are formatted with the csrf_token:
<form>{% csrf_token %}
</form>
SQL Server stored procedure:
CREATE PROCEDURE [dbo].[INS_MEM_BASIC]
@na varchar(50),
@occ varchar(50),
@New_MEM_BASIC_ID int OUTPUT
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO Mem_Basic
VALUES (@na, @occ)
SELECT @New_MEM_BASIC_ID = SCOPE_IDENTITY()
END
C# code:
public int CreateNewMember(string Mem_NA, string Mem_Occ )
{
// values 0 --> -99 are SQL reserved.
int new_MEM_BASIC_ID = -1971;
SqlConnection SQLconn = new SqlConnection(Config.ConnectionString);
SqlCommand cmd = new SqlCommand("INS_MEM_BASIC", SQLconn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter outPutVal = new SqlParameter("@New_MEM_BASIC_ID", SqlDbType.Int);
outPutVal.Direction = ParameterDirection.Output;
cmd.Parameters.Add(outPutVal);
cmd.Parameters.Add("@na", SqlDbType.Int).Value = Mem_NA;
cmd.Parameters.Add("@occ", SqlDbType.Int).Value = Mem_Occ;
SQLconn.Open();
cmd.ExecuteNonQuery();
SQLconn.Close();
if (outPutVal.Value != DBNull.Value) new_MEM_BASIC_ID = Convert.ToInt32(outPutVal.Value);
return new_MEM_BASIC_ID;
}
I hope these will help to you ....
You can also use this if you want ...
public int CreateNewMember(string Mem_NA, string Mem_Occ )
{
using (SqlConnection con=new SqlConnection(Config.ConnectionString))
{
int newID;
var cmd = "INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) VALUES(@na,@occ);SELECT CAST(scope_identity() AS int)";
using(SqlCommand cmd=new SqlCommand(cmd, con))
{
cmd.Parameters.AddWithValue("@na", Mem_NA);
cmd.Parameters.AddWithValue("@occ", Mem_Occ);
con.Open();
newID = (int)insertCommand.ExecuteScalar();
if (con.State == System.Data.ConnectionState.Open) con.Close();
return newID;
}
}
}
On OSX Snow Leopard
launchctl unload /System/Library/LaunchDaemons/org.mysql.mysqld.plist
You can use the CSS property max-width
and use it with ch
unit.
And, as this is a <span>
, use a display: inline-block;
(or block).
Here is an example:
<span style="
display:inline-block;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 13ch;">
Lorem ipsum dolor sit amet
</span>
Which outputs:
Lorem ipsum...
<span style="_x000D_
display:inline-block;_x000D_
white-space: nowrap;_x000D_
overflow: hidden;_x000D_
text-overflow: ellipsis;_x000D_
max-width: 13ch;">_x000D_
Lorem ipsum dolor sit amet_x000D_
</span>
_x000D_
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
Instead of System.exit(1) Just use System.exit(0)
if you want read and write on your extra field, you can use a new custom serializer, that extends serializers.Serializer, and use it like this
class ExtraFieldSerializer(serializers.Serializer):
def to_representation(self, instance):
# this would have the same as body as in a SerializerMethodField
return 'my logic here'
def to_internal_value(self, data):
# This must return a dictionary that will be used to
# update the caller's validation data, i.e. if the result
# produced should just be set back into the field that this
# serializer is set to, return the following:
return {
self.field_name: 'Any python object made with data: %s' % data
}
class MyModelSerializer(serializers.ModelSerializer):
my_extra_field = ExtraFieldSerializer(source='*')
class Meta:
model = MyModel
fields = ['id', 'my_extra_field']
i use this in related nested fields with some custom logic
create trigger doct_trigger
after delete on doctor
for each row
delete from patient where patient.PrimaryDoctor_SSN=doctor.SSN ;
The code should be like given below
String selectSQL = "SELECT IFNULL(tbl.column, \"\") AS column FROM MySQL_table AS tbl";
Statement st = ...;
Result set rs = st.executeQuery(selectSQL);
Unless I am greatly mistaken, the answer is, "No, there is no way."
The basic problem in situations like that is the fact that you are calling a MySQL function and you're not actually setting a value. CI escapes values so that you can do a clean insert but it does not test to see if those values happen to be calling functions like aes_encrypt
, md5
, or (in this case) now()
. While in most situations this is wonderful, for those situations raw sql is the only recourse.
On a side, date('Y-m-d');
should work as a PHP version of NOW()
for MySQL. (It won't work for all versions of SQL though).
add:
import math
at beginning. and then use:
math.sqrt(num) # or any other function you deem neccessary
Embed the video player and use CSS to hide the video. If you do it properly you may even be able to hide only the video and not the controls below it.
However, I'd recommend against it, because it will be a violation of YouTube TOS. Use your own server instead if you really want to play only audio.
This:
string clean = Regex.Replace(dirty, "[^a-zA-Z0-9\x20]", String.Empty);
\x20 is ascii hex for 'space' character
you can add more individual characters that you want to be allowed. If you want for example "?" to be ok in the return string add \x3f.
You need to move it to another file (rather than a folder), this can also be used to rename.
Move:
File.Move(@"c:\test\SomeFile.txt", @"c:\test\Test\SomeFile.txt");
Rename:
File.Move(@"c:\test\SomeFile.txt", @"c:\test\SomeFile2.txt");
The reason it says "File already exists" in your example, is because C:\test\Test
tries to create a file Test
without an extension, but cannot do so as a folder already exists with the same name.
In my case, adding a dtype attribute changed dtype of the array to a smaller type(from float64 to uint8), decreasing array size enough to not throw MemoryError in Windows(64 bit).
from
mask = np.zeros(edges.shape)
to
mask = np.zeros(edges.shape,dtype='uint8')
For "strings and numbers", I think that the partial regular expression for numbers:
-?(?:0|[1-9]\d*)(?:\.\d+)(?:[eE][+-]\d+)?
should be instead:
-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+\-]?\d+)?
since the decimal part of the number is optional, and also it is probably safer to escape the -
symbol in [+-]
since it has a special meaning between brackets
In combination with what Guffa described, you could use the technique described in
Explanation of <script type = "text/template"> ... </script> to store the HTML document in a special script
element (see the link for an explanation on how this works). That's a lot easier than storing the HTML document in a string.
For Python
Connect to drive,
from google.colab import drive
drive.mount('/content/drive')
Check for directory
!ls
and !pwd
For unzip
!unzip drive/"My Drive"/images.zip
you can add the 1px border to just the sides and bottom of each row. the first value is the top border, the second is the right border, the third is the bottom border, and the fourth is the left border.
div.row {
border: 0px 1px 1px 1px solid;
}
The str.split
method will automatically remove all white space between items:
>>> str1 = "a b c d"
>>> str1.split()
['a', 'b', 'c', 'd']
Docs are here: http://docs.python.org/library/stdtypes.html#str.split
This is the simple one to perform substring in Go
package main
import "fmt"
var p = fmt.Println
func main() {
value := "address;bar"
// Take substring from index 2 to length of string
substring := value[2:len(value)]
p(substring)
}
i managed to turn off mine with just
lineColor: 'transparent',
tickLength: 0
AppSettings.Set
does not persist the changes to your configuration file. It just changes it in memory. If you put a breakpoint on System.Configuration.ConfigurationManager.AppSettings.Set("lang", lang);
, and add a watch for System.Configuration.ConfigurationManager.AppSettings[0]
you will see it change from "English" to "Russian" when that line of code runs.
The following code (used in a console application) will persist the change.
class Program
{
static void Main(string[] args)
{
UpdateSetting("lang", "Russian");
}
private static void UpdateSetting(string key, string value)
{
Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
configuration.AppSettings.Settings[key].Value = value;
configuration.Save();
ConfigurationManager.RefreshSection("appSettings");
}
}
From this post: http://vbcity.com/forums/t/152772.aspx
One major point to note with the above is that if you are running this from the debugger (within Visual Studio) then the app.config file will be overwritten each time you build. The best way to test this is to build your application and then navigate to the output directory and launch your executable from there. Within the output directory you will also find a file named YourApplicationName.exe.config which is your configuration file. Open this in Notepad to see that the changes have in fact been saved.
From the structure of your source Object, I would try:
containerObject= new JSONObject(container);
if(containerObject.has("LabelData")){
JSONObject innerObject = containerObject.getJSONObject("LabelData");
if(innerObject.has("video")){
//Do with video
}
}
android.webkit.URLUtil
has the method guessUrl(String)
working perfectly fine (even with file://
or data://
) since Api level 1
(Android 1.0). Use as:
String url = URLUtil.guessUrl(link);
// url.com -> http://url.com/ (adds http://)
// http://url -> http://url.com/ (adds .com)
// https://url -> https://url.com/ (adds .com)
// url -> http://www.url.com/ (adds http://www. and .com)
// http://www.url.com -> http://www.url.com/
// https://url.com -> https://url.com/
// file://dir/to/file -> file://dir/to/file
// data://dataline -> data://dataline
// content://test -> content://test
In the Activity call:
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(URLUtil.guessUrl(download_link)));
if (intent.resolveActivity(getPackageManager()) != null)
startActivity(intent);
Check the complete guessUrl
code for more info.
Once you're logged in as postgres
, you should be able to write:
psql -t -d database_name -c $'SELECT c_defaults FROM user_info WHERE c_uid = \'testuser\';'
to print out just the value of that field, which means that you can capture it to (for example) save in a Bash variable:
testuser_defaults="$(psql -t -d database_name -c $'SELECT c_defaults FROM user_info WHERE c_uid = \'testuser\';')"
To handle the logging in as postgres
, I recommend using sudo
. You can give a specific user the permission to run
sudo -u postgres /path/to/this/script.sh
so that they can run just the one script as postgres
.
You likely want to use onupdate=datetime.now
so that UPDATEs also change the last_updated
field.
SQLAlchemy has two defaults for python executed functions.
default
sets the value on INSERT, only onceonupdate
sets the value to the callable result on UPDATE as well.It is not possible to use relative paths for AuthUserFile:
File-path is the path to the user file. If it is not absolute (i.e., if it doesn't begin with a slash), it is treated as relative to the
ServerRoot
.
You have to accept and work around that limitation.
We're using IfDefine
together with an apache2 command line parameter:
.htaccess
(suitable for both development and live systems):<IfDefine !development>
AuthType Basic
AuthName "Say the secret word"
AuthUserFile /var/www/hostname/.htpasswd
Require valid-user
</IfDefine>
Append the following to /etc/apache2/envvars
:
export APACHE_ARGUMENTS=-Ddevelopment
Restart your apache afterwards and you'll get a password prompt only when you're not on the development server.
You can of course add another IfDefine for the development server, just copy the block and remove the !
.
Assuming your dataframe is mydf:
mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))
function findVowels(str) {
return str.match(/[aeiou]/ig);
}
findVowels('abracadabra'); // 'aaaaa'
Basically it returns all the vowels in a given string.
I think you will have fewer problems if you declared a Property that implements INotifyPropertyChanged, then databind IsChecked
, SelectedIndex
(using IValueConverter) and Fill
(using IValueConverter) to it instead of using the Checked Event to toggle SelectedIndex
and Fill
.
try
echo 0 > /selinux/enforce
Nearly verbatim from Iterate over pairs in a list (circular fashion) in Python:
def pairs(seq):
i = iter(seq)
prev = next(i)
for item in i:
yield prev, item
prev = item
As the official document: As of 1.9, a string is only considered to be HTML if it starts with a less-than ("<") character. The Migrate plugin can be used to restore the pre-1.9 behavior.
If a string is known to be HTML but may start with arbitrary text that is not an HTML tag, pass it to jQuery.parseHTML() which will return an array of DOM nodes representing the markup. A jQuery collection can be created from this, for example: $($.parseHTML(htmlString))
. This would be considered best practice when processing HTML templates for example. Simple uses of literal strings such as $("<p>Testing</p>").appendTo("body")
are unaffected by this change.
You can either use the eval function as in some other answers. (Don't forget the extra braces.) You will know why when you dig deeper), or simply use the jQuery function parseJSON
:
var response = '{"result":true , "count":1}';
var parsedJSON = $.parseJSON(response);
OR
You can use this below code.
var response = '{"result":true , "count":1}';
var jsonObject = JSON.parse(response);
And you can access the fields using jsonObject.result
and jsonObject.count
.
Update:
If your output is undefined
then you need to follow THIS answer. Maybe your json string has an array format. You need to access the json object properties like this
var response = '[{"result":true , "count":1}]'; // <~ Array with [] tag
var jsonObject = JSON.parse(response);
console.log(jsonObject[0].result); //Output true
console.log(jsonObject[0].count); //Output 1
Because SQL Server performs integer division. Try this:
select 1 * 1.0 / 3
This is helpful when you pass integers as params.
select x * 1.0 / y
When you start SSMS, it allows you to choose a Server Type and Server Name. In the server type dropdown, choose "Integration Services" and connect to the server.
Then you'll be able to see what packages are in the db.
So I have gotten that message before as well, when doing an ajax call. So what it's basically asking for is a constructor in that model class that is being called by the contoller, doesn't have any parameter.
Here is an example
public class MyClass{
public MyClass(){} // so here would be your parameterless constructor
}
Yes you can handle with the catch operator like this and show alert as you want but firstly you have to import Rxjs
for the same like this way
import {Observable} from 'rxjs/Rx';
return this.http.request(new Request(this.requestoptions))
.map((res: Response) => {
if (res) {
if (res.status === 201) {
return [{ status: res.status, json: res }]
}
else if (res.status === 200) {
return [{ status: res.status, json: res }]
}
}
}).catch((error: any) => {
if (error.status === 500) {
return Observable.throw(new Error(error.status));
}
else if (error.status === 400) {
return Observable.throw(new Error(error.status));
}
else if (error.status === 409) {
return Observable.throw(new Error(error.status));
}
else if (error.status === 406) {
return Observable.throw(new Error(error.status));
}
});
}
also you can handel error (with err block) that is throw by catch block while .map
function,
like this -
...
.subscribe(res=>{....}
err => {//handel here});
as required for any status without checking particluar one you can try this: -
return this.http.request(new Request(this.requestoptions))
.map((res: Response) => {
if (res) {
if (res.status === 201) {
return [{ status: res.status, json: res }]
}
else if (res.status === 200) {
return [{ status: res.status, json: res }]
}
}
}).catch((error: any) => {
if (error.status < 400 || error.status ===500) {
return Observable.throw(new Error(error.status));
}
})
.subscribe(res => {...},
err => {console.log(err)} );
Since I do not prefer to rely on external libraries and/or other programs, I have extended your solution so that it works. The actual change here is using the GetFromClipboard function instead of Paste which is mainly used to paste a range of cells. Of course, the downside is that the user must not change focus or intervene during the whole process.
Dim pathPDF As String, textPDF As String
Dim openPDF As Object
Dim objPDF As MsForms.DataObject
pathPDF = "C:\some\path\data.pdf"
Set openPDF = CreateObject("Shell.Application")
openPDF.Open (pathPDF)
'TIME TO WAIT BEFORE/AFTER COPY AND PASTE SENDKEYS
Application.Wait Now + TimeValue("00:00:2")
SendKeys "^a"
Application.Wait Now + TimeValue("00:00:2")
SendKeys "^c"
Application.Wait Now + TimeValue("00:00:1")
AppActivate ActiveWorkbook.Windows(1).Caption
objPDF.GetFromClipboard
textPDF = objPDF.GetText(1)
MsgBox textPDF
If you're interested see my project in github.
You can find where the my.cnf
file has been provided by the specific package, e.g.
brew list mysql # or: mariadb
In addition to verify if that file is read, you can run:
sudo fs_usage | grep my.cnf
which will show you filesystem activity in real-time related to that file.
Manual method works well with import android.util.Base64, but be sure to set Base64.NO_WRAP on calling encode:
String basicAuth = "Basic " + new String(Base64.encode("user:pass".getBytes(),Base64.NO_WRAP ));
connection.setRequestProperty ("Authorization", basicAuth);
Just for completion sake, I would like to add that you indeed can create an operator ostream& operator << (ostream& os)
inside a class and it can work. From what I know it's not a good idea to use it, because it's very convoluted and unintuitive.
Let's assume we have this code:
#include <iostream>
#include <string>
using namespace std;
struct Widget
{
string name;
Widget(string _name) : name(_name) {}
ostream& operator << (ostream& os)
{
return os << name;
}
};
int main()
{
Widget w1("w1");
Widget w2("w2");
// These two won't work
{
// Error: operand types are std::ostream << std::ostream
// cout << w1.operator<<(cout) << '\n';
// Error: operand types are std::ostream << Widget
// cout << w1 << '\n';
}
// However these two work
{
w1 << cout << '\n';
// Call to w1.operator<<(cout) returns a reference to ostream&
w2 << w1.operator<<(cout) << '\n';
}
return 0;
}
So to sum it up - you can do it, but you most probably shouldn't :)
the algorithm : ((x1 - x2) ^ 2 + (y1 - y2) ^ 2) < 25
I have been searching for this same answer all morning and have pretty much found out that it's probably impossible to verify if every email address you ever need to check actually exists at the time you need to verify it. So as a work around, I kind of created a simple PHP
script to verify that the email address is formatted correct and it also verifies that the domain name used is correct as well.
GitHub
here https://github.com/DukeOfMarshall/PHP---JSON-Email-Verification/tree/master
<?php
# What to do if the class is being called directly and not being included in a script via PHP
# This allows the class/script to be called via other methods like JavaScript
if(basename(__FILE__) == basename($_SERVER["SCRIPT_FILENAME"])){
$return_array = array();
if($_GET['address_to_verify'] == '' || !isset($_GET['address_to_verify'])){
$return_array['error'] = 1;
$return_array['message'] = 'No email address was submitted for verification';
$return_array['domain_verified'] = 0;
$return_array['format_verified'] = 0;
}else{
$verify = new EmailVerify();
if($verify->verify_formatting($_GET['address_to_verify'])){
$return_array['format_verified'] = 1;
if($verify->verify_domain($_GET['address_to_verify'])){
$return_array['error'] = 0;
$return_array['domain_verified'] = 1;
$return_array['message'] = 'Formatting and domain have been verified';
}else{
$return_array['error'] = 1;
$return_array['domain_verified'] = 0;
$return_array['message'] = 'Formatting was verified, but verification of the domain has failed';
}
}else{
$return_array['error'] = 1;
$return_array['domain_verified'] = 0;
$return_array['format_verified'] = 0;
$return_array['message'] = 'Email was not formatted correctly';
}
}
echo json_encode($return_array);
exit();
}
class EmailVerify {
public function __construct(){
}
public function verify_domain($address_to_verify){
// an optional sender
$record = 'MX';
list($user, $domain) = explode('@', $address_to_verify);
return checkdnsrr($domain, $record);
}
public function verify_formatting($address_to_verify){
if(strstr($address_to_verify, "@") == FALSE){
return false;
}else{
list($user, $domain) = explode('@', $address_to_verify);
if(strstr($domain, '.') == FALSE){
return false;
}else{
return true;
}
}
}
}
?>
You can do it in one line as below:
YourClass obj = (YourClass)Convert.ChangeType(YourValue, typeof(YourClass));
Happy coding ;)
Here's my variant to solve the problem of viewable area's limitation.
google.maps.event.addListener(this.map, 'idle', function() {
var minLat = strictBounds.getSouthWest().lat();
var minLon = strictBounds.getSouthWest().lng();
var maxLat = strictBounds.getNorthEast().lat();
var maxLon = strictBounds.getNorthEast().lng();
var cBounds = self.map.getBounds();
var cMinLat = cBounds.getSouthWest().lat();
var cMinLon = cBounds.getSouthWest().lng();
var cMaxLat = cBounds.getNorthEast().lat();
var cMaxLon = cBounds.getNorthEast().lng();
var centerLat = self.map.getCenter().lat();
var centerLon = self.map.getCenter().lng();
if((cMaxLat - cMinLat > maxLat - minLat) || (cMaxLon - cMinLon > maxLon - minLon))
{ //We can't position the canvas to strict borders with a current zoom level
self.map.setZoomLevel(self.map.getZoomLevel()+1);
return;
}
if(cMinLat < minLat)
var newCenterLat = minLat + ((cMaxLat-cMinLat) / 2);
else if(cMaxLat > maxLat)
var newCenterLat = maxLat - ((cMaxLat-cMinLat) / 2);
else
var newCenterLat = centerLat;
if(cMinLon < minLon)
var newCenterLon = minLon + ((cMaxLon-cMinLon) / 2);
else if(cMaxLon > maxLon)
var newCenterLon = maxLon - ((cMaxLon-cMinLon) / 2);
else
var newCenterLon = centerLon;
if(newCenterLat != centerLat || newCenterLon != centerLon)
self.map.setCenter(new google.maps.LatLng(newCenterLat, newCenterLon));
});
strictBounds
is an object of new google.maps.LatLngBounds()
type. self.gmap
stores a Google Map object (new google.maps.Map()
).
It really works but don't only forget to take into account the haemorrhoids with crossing 0th meridians and parallels if your bounds cover them.
Remember load jquery before bootstrap js
You can try to publish the application by changing the version of the build. I was also having the same problem and tried the same by just changing tIt may help you too.
config/database.php
strict
key inside mysql
connection settingsfalse
You want to feed the create.sql
into sqlite3
from the shell, not from inside SQLite itself:
$ sqlite3 auction.db < create.sql
SQLite's version of SQL doesn't understand <
for files, your shell does.
var tasks = [];_x000D_
var descs = [];_x000D_
_x000D_
// Get the modal_x000D_
var modal = document.getElementById('myModal');_x000D_
_x000D_
// Get the button that opens the modal_x000D_
var btn = document.getElementById("myBtn");_x000D_
_x000D_
// Get the <span> element that closes the modal_x000D_
var span = document.getElementsByClassName("close")[0];_x000D_
_x000D_
// When the user clicks the button, open the modal _x000D_
btn.onclick = function() {_x000D_
modal.style.display = "block";_x000D_
}_x000D_
_x000D_
// When the user clicks on <span> (x), close the modal_x000D_
span.onclick = function() {_x000D_
modal.style.display = "none";_x000D_
}_x000D_
_x000D_
// When the user clicks anywhere outside of the modal, close it_x000D_
window.onclick = function(event) {_x000D_
if (event.target == modal) {_x000D_
modal.style.display = "none";_x000D_
}_x000D_
}_x000D_
var rowCount = 1;_x000D_
_x000D_
function addTasks() {_x000D_
var temp = 'style .fa fa-trash';_x000D_
tasks.push(document.getElementById("taskname").value);_x000D_
descs.push(document.getElementById("taskdesc").value);_x000D_
var table = document.getElementById("tasksTable");_x000D_
var row = table.insertRow(rowCount);_x000D_
var cell1 = row.insertCell(0);_x000D_
var cell2 = row.insertCell(1);_x000D_
var cell3 = row.insertCell(2);_x000D_
var cell4 = row.insertCell(3);_x000D_
cell1.innerHTML = tasks[rowCount - 1];_x000D_
cell2.innerHTML = descs[rowCount - 1];_x000D_
cell3.innerHTML = getDate();_x000D_
cell4.innerHTML = '<td class="fa fa-trash"></td>';_x000D_
rowCount++;_x000D_
modal.style.display = "none";_x000D_
}_x000D_
_x000D_
_x000D_
function getDate() {_x000D_
var today = new Date();_x000D_
var dd = today.getDate();_x000D_
var mm = today.getMonth() + 1; //January is 0!_x000D_
_x000D_
var yyyy = today.getFullYear();_x000D_
_x000D_
if (dd < 10) {_x000D_
dd = '0' + dd;_x000D_
}_x000D_
if (mm < 10) {_x000D_
mm = '0' + mm;_x000D_
}_x000D_
var today = dd + '-' + mm + '-' + yyyy.toString().slice(2);_x000D_
return today;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
<!-- Trigger/Open The Modal -->_x000D_
<div style="background-color:#0F0F8C ;height:45px">_x000D_
<h2 style="color: white">LOGO</h2>_x000D_
</div>_x000D_
<div>_x000D_
<button id="myBtn"> + Add Task  </button>_x000D_
</div>_x000D_
<div>_x000D_
<table id="tasksTable">_x000D_
<thead>_x000D_
<tr style="background-color:rgba(201, 196, 196, 0.86)">_x000D_
<th style="width: 150px;">Name</th>_x000D_
<th style="width: 250px;">Desc</th>_x000D_
<th style="width: 120px">Date</th>_x000D_
<th style="width: 120px class=fa fa-trash"></th>_x000D_
</tr>_x000D_
_x000D_
</thead>_x000D_
<tbody></tbody>_x000D_
</table>_x000D_
</div>_x000D_
<!-- The Modal -->_x000D_
<div id="myModal" class="modal">_x000D_
_x000D_
<!-- Modal content -->_x000D_
<div class="modal-content">_x000D_
_x000D_
<div class="modal-header">_x000D_
_x000D_
<span class="close">×</span>_x000D_
<h3> Add Task</h3>_x000D_
</div>_x000D_
_x000D_
<div class="modal-body">_x000D_
<table style="padding: 28px 50px">_x000D_
<tr>_x000D_
<td style="width:150px">Name:</td>_x000D_
<td><input type="text" name="name" id="taskname" style="width: -webkit-fill-available"></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>_x000D_
Desc:_x000D_
</td>_x000D_
<td>_x000D_
<textarea name="desc" id="taskdesc" cols="60" rows="10"></textarea>_x000D_
</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
_x000D_
<div class="modal-footer">_x000D_
<button type="submit" value="submit" style="float: right;" onclick="addTasks()">SUBMIT</button>_x000D_
<br>_x000D_
<br>_x000D_
<br>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
For Python 2.7
Add the environment variable PYTHONWARNINGS as key and the corresponding value to be ignored like:
os.environ['PYTHONWARNINGS']="ignore:Unverified HTTPS request"
I'd prefer mapping after making sure the value is available
private String getStringIfObjectIsPresent(Optional<Object> object) {
Object ob = object.orElseThrow(MyCustomException::new);
// do your mapping with ob
String result = your-map-function(ob);
return result;
}
or one liner
private String getStringIfObjectIsPresent(Optional<Object> object) {
return your-map-function(object.orElseThrow(MyCustomException::new));
}
The following code makes the window always stay on top as well as make it frameless.
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace StayOnTop
{
public partial class Form1 : Form
{
private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
private const UInt32 SWP_NOSIZE = 0x0001;
private const UInt32 SWP_NOMOVE = 0x0002;
private const UInt32 TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE;
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
public Form1()
{
InitializeComponent();
FormBorderStyle = FormBorderStyle.None;
TopMost = true;
}
private void Form1_Load(object sender, EventArgs e)
{
SetWindowPos(this.Handle, HWND_TOPMOST, 100, 100, 300, 300, TOPMOST_FLAGS);
}
protected override void WndProc(ref Message m)
{
const int RESIZE_HANDLE_SIZE = 10;
switch (m.Msg)
{
case 0x0084/*NCHITTEST*/ :
base.WndProc(ref m);
if ((int)m.Result == 0x01/*HTCLIENT*/)
{
Point screenPoint = new Point(m.LParam.ToInt32());
Point clientPoint = this.PointToClient(screenPoint);
if (clientPoint.Y <= RESIZE_HANDLE_SIZE)
{
if (clientPoint.X <= RESIZE_HANDLE_SIZE)
m.Result = (IntPtr)13/*HTTOPLEFT*/ ;
else if (clientPoint.X < (Size.Width - RESIZE_HANDLE_SIZE))
m.Result = (IntPtr)12/*HTTOP*/ ;
else
m.Result = (IntPtr)14/*HTTOPRIGHT*/ ;
}
else if (clientPoint.Y <= (Size.Height - RESIZE_HANDLE_SIZE))
{
if (clientPoint.X <= RESIZE_HANDLE_SIZE)
m.Result = (IntPtr)10/*HTLEFT*/ ;
else if (clientPoint.X < (Size.Width - RESIZE_HANDLE_SIZE))
m.Result = (IntPtr)2/*HTCAPTION*/ ;
else
m.Result = (IntPtr)11/*HTRIGHT*/ ;
}
else
{
if (clientPoint.X <= RESIZE_HANDLE_SIZE)
m.Result = (IntPtr)16/*HTBOTTOMLEFT*/ ;
else if (clientPoint.X < (Size.Width - RESIZE_HANDLE_SIZE))
m.Result = (IntPtr)15/*HTBOTTOM*/ ;
else
m.Result = (IntPtr)17/*HTBOTTOMRIGHT*/ ;
}
}
return;
}
base.WndProc(ref m);
}
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.Style |= 0x20000; // <--- use 0x20000
return cp;
}
}
}
}
Please note that the authors of seaborn
only want seaborn.heatmap
to work with categorical dataframes. It's not general.
If your index and columns are numeric and/or datetime values, this code will serve you well.
Matplotlib heat-mapping function pcolormesh
requires bins instead of indices, so there is some fancy code to build bins from your dataframe indices (even if your index isn't evenly spaced!).
The rest is simply np.meshgrid
and plt.pcolormesh
.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def conv_index_to_bins(index):
"""Calculate bins to contain the index values.
The start and end bin boundaries are linearly extrapolated from
the two first and last values. The middle bin boundaries are
midpoints.
Example 1: [0, 1] -> [-0.5, 0.5, 1.5]
Example 2: [0, 1, 4] -> [-0.5, 0.5, 2.5, 5.5]
Example 3: [4, 1, 0] -> [5.5, 2.5, 0.5, -0.5]"""
assert index.is_monotonic_increasing or index.is_monotonic_decreasing
# the beginning and end values are guessed from first and last two
start = index[0] - (index[1]-index[0])/2
end = index[-1] + (index[-1]-index[-2])/2
# the middle values are the midpoints
middle = pd.DataFrame({'m1': index[:-1], 'p1': index[1:]})
middle = middle['m1'] + (middle['p1']-middle['m1'])/2
if isinstance(index, pd.DatetimeIndex):
idx = pd.DatetimeIndex(middle).union([start,end])
elif isinstance(index, (pd.Float64Index,pd.RangeIndex,pd.Int64Index)):
idx = pd.Float64Index(middle).union([start,end])
else:
print('Warning: guessing what to do with index type %s' %
type(index))
idx = pd.Float64Index(middle).union([start,end])
return idx.sort_values(ascending=index.is_monotonic_increasing)
def calc_df_mesh(df):
"""Calculate the two-dimensional bins to hold the index and
column values."""
return np.meshgrid(conv_index_to_bins(df.index),
conv_index_to_bins(df.columns))
def heatmap(df):
"""Plot a heatmap of the dataframe values using the index and
columns"""
X,Y = calc_df_mesh(df)
c = plt.pcolormesh(X, Y, df.values.T)
plt.colorbar(c)
Call it using heatmap(df)
, and see it using plt.show()
.
Using window.location.href
it's not possible to send a POST request.
What you have to do is to set up a form
tag with data fields in it, set the action
attribute of the form to the URL and the method
attribute to POST, then call the submit
method on the form
tag.
Simpler approach? A little more Pythonic?
>>> ok = "0123456789abcdef"
>>> all(c in ok for c in "123456abc")
True
>>> all(c in ok for c in "hello world")
False
It certainly isn't the most efficient, but it's sure readable.
You can try this.
Workbooks("Tire.xls").Activate
ThisWorkbook.Sheets("Sheet1").Select
Cells(2,24).value=24
Note: This answer predates the Unicode requirement; see the comments.
Just cast it:
CString s;
const TCHAR* x = (LPCTSTR) s;
It works because CString has a cast operator to do exactly this.
Using TCHAR makes your code Unicode-independent; if you're not concerned about Unicode you can simply use char
instead of TCHAR
.
In C++ you would use std::find
, and check if the resultant pointer points to the end of the range, like this:
Foo array[10];
... // Init the array here
Foo *foo = std::find(std::begin(array), std::end(array), someObject);
// When the element is not found, std::find returns the end of the range
if (foo != std::end(array)) {
cerr << "Found at position " << std::distance(array, foo) << endl;
} else {
cerr << "Not found" << endl;
}
Think of it like an archive. MyDB.Bak contains MyDB.mdf and MyDB.ldf.
Restore with Move to say HerDB basically grabs MyDB.mdf (and ldf) from the back up, and copies them as HerDB.mdf and ldf.
So if you already had a MyDb on the server instance you are restoring to it wouldn't be touched.
ugh don't use eval for anything. Well, there are certain things, but they're extremely rare. Rather, you would do this:
document.getElementById("test").onchange()
Look here for more options: http://jehiah.cz/archive/firing-javascript-events-properly
Bash has built in features to access the last command executed. But that's the last whole command (e.g. the whole case
command), not individual simple commands like you originally requested.
!:0
= the name of command executed.
!:1
= the first parameter of the previous command
!:*
= all of the parameters of the previous command
!:-1
= the final parameter of the previous command
!!
= the previous command line
etc.
So, the simplest answer to the question is, in fact:
echo !!
...alternatively:
echo "Last command run was ["!:0"] with arguments ["!:*"]"
Try it yourself!
echo this is a test
echo !!
In a script, history expansion is turned off by default, you need to enable it with
set -o history -o histexpand
There are errors here :
var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");
The code must change to:
var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");
By the way, there is another error at line 129 :
var createLi.appendChild(createSubList);
Replace it with:
createLi.appendChild(createSubList);
I put together a little test here:
\documentclass[10pt,twocolumn]{article}
\title{Article Title}
\author{
First Author\\
Department\\
school\\
email@edu
\and
Second Author\\
Department\\
school\\
email@edu
\and
Third Author\\
Department\\
school\\
email@edu
\and
Fourth Author\\
Department\\
school\\
email@edu
}
\date{\today}
\begin{document}
\maketitle
\begin{abstract}
\ldots
\end{abstract}
\section{Introduction}
\ldots
\end{document}
Things to note, the title, author and date fields are declared before \begin{document}
. Also, the multicol package is likely unnecessary in this case since you have declared twocolumn
in the document class.
This example puts all four authors on the same line, but if your authors have longer names, departments or emails, this might cause it to flow over onto another line. You might be able to change the font sizes around a little bit to make things fit. This could be done by doing something like {\small First Author}
. Here's a more detailed article on \LaTeX
font sizes:
https://engineering.purdue.edu/ECN/Support/KB/Docs/LaTeXChangingTheFont
To italicize you can use {\it First Name}
or \textit{First Name}
.
Be careful though, if the document is meant for publication often times journals or conference proceedings have their own formatting guidelines so font size trickery might not be allowed.
At first, open your Bash Profile in your home directory. The easiest way to open & edit your bash_profile using your default editor.
For example, I open it using the VS Code using this command: code .bash_profile.
Then just paste the following codes to your Bash.
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1="\u@\h \W\[\033[32m\]\$(parse_git_branch)\[\033[00m\] $ "
The function
parse_git_branch()
will fetch the branch name & then through PS1 you can show it in your terminal.
Here,
\u = Username
@ = Static Text
\h = Computer Name
\w = Current Directory
$ = Static Text
You can change or remove these variables for more customization.
If you use Git for the first time in terminal or instantly after configuration, maybe sometimes you can not see the branch name.
If you get this problem, don't worry. In that case, just make a sample repository and commit it after some changes. When the commit command will execute once, the terminal will find git branch from then.
There is a scala way (if you have a enough memory on working machine):
val arr = df.select("column").rdd.collect
println(arr(100))
If dataframe schema is unknown, and you know actual type of "column"
field (for example double), than you can get arr
as following:
val arr = df.select($"column".cast("Double")).as[Double].rdd.collect
If you want to create a file and write and append data to it many times, then use the below code, it will create file if not exits and will append data if it exists.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd");
Date now = new Date();
String fileName = formatter.format(now) + ".txt";//like 2016_01_12.txt
try
{
File root = new File(Environment.getExternalStorageDirectory()+File.separator+"Music_Folder", "Report Files");
//File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists())
{
root.mkdirs();
}
File gpxfile = new File(root, fileName);
FileWriter writer = new FileWriter(gpxfile,true);
writer.append(sBody+"\n\n");
writer.flush();
writer.close();
Toast.makeText(this, "Data has been written to Report File", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
}
The following example show you how to define a function in jQuery. You will see a button “Click here”, when you click on it, we call our function “myFunction()”.
$(document).ready(function(){
$.myFunction = function(){
alert('You have successfully defined the function!');
}
$(".btn").click(function(){
$.myFunction();
});
});
You can see an example here: How to define a function in jQuery?
You can find what you're looking for in the information schema: SQL Server 2005 System Tables and Views I think you need SQL Server 2005 or higher to use the approach described in this article, but a similar method can be used for earlier versions.
Swift 4 provides merging(_:uniquingKeysWith:)
, so for your case:
let combinedDict = dict1.merging(dict2) { $1 }
The shorthand closure returns $1
, therefore dict2's value will be used when there is a conflict with the keys.
Initially starting with a pyspark dataframes - I got type conversion errors (when converting to pandas df's and then appending to csv) given the schema/column types in my pyspark dataframes
Solved the problem by forcing all columns in each df to be of type string and then appending this to csv as follows:
with open('testAppend.csv', 'a') as f:
df2.toPandas().astype(str).to_csv(f, header=False)
According to the flask.Request.args documents.
flask.Request.args
A MultiDict with the parsed contents of the query string. (The part in the URL after the question mark).
So the args.get()
is method get()
for MultiDict, whose prototype is as follows:
get(key, default=None, type=None)
Update:
In newer version of flask (v1.0.x and v1.1.x), flask.Request.args
is an ImmutableMultiDict
(an immutable MultiDict
), so the prototype and specific method above is still valid.
TLDR; MySql does not have an equivalent concept of varchar(max)
, this is a MS SQL Server feature.
varchar(max)
is a feature of Microsoft SQL Server.
The amount of data that a column could store in Microsoft SQL server versions prior to version 2005 was limited to 8KB. In order to store more than 8KB you would have to use TEXT
, NTEXT
, or BLOB
columns types, these column types stored their data as a collection of 8K pages separate from the table data pages; they supported storing up to 2GB per row.
The big caveat to these column types was that they usually required special functions and statements to access and modify the data (e.g. READTEXT
, WRITETEXT
, and UPDATETEXT
)
In SQL Server 2005, varchar(max)
was introduced to unify the data and queries used to retrieve and modify data in large columns. The data for varchar(max)
columns is stored inline with the table data pages.
As the data in the MAX column fills an 8KB data page an overflow page is allocated and the previous page points to it forming a linked list. Unlike TEXT
, NTEXT
, and BLOB
the varchar(max)
column type supports all the same query semantics as other column types.
So varchar(MAX)
really means varchar(AS_MUCH_AS_I_WANT_TO_STUFF_IN_HERE_JUST_KEEP_GROWING)
and not varchar(MAX_SIZE_OF_A_COLUMN)
.
In order to get the same amount of storage as a varchar(max)
in MySql you would still need to resort to a BLOB
column type. This article discusses a very effective method of storing large amounts of data in MySql efficiently.
I think is only an authentication problem...
That's all :)
It is because it did not find sql connector. try:
pip install mysqlclient
This issue occured a few days ago with my Bitbucket repositories. I was able to fix it by setting the remote url to http rather than https.
I also tried setting https proxies in the command line and git config but this didn't work.
$ git pull
fatal: unable to access 'https://[email protected]/sacgf/x.git/': Received HTTP code 407 from proxy after CONNECT
Note that we are using https:
$ git remote -v
origin https://[email protected]/sacgf/x.git (fetch)
origin https://[email protected]/sacgf/x.git (push)
Replace https url with http url:
$ git remote set-url origin http://[email protected]/sacgf/x.git
$ git pull
Username for 'https://bitbucket.org': username
Password for 'https://[email protected]':
remote: Counting objects: 43, done.
remote: Compressing objects: 100% (42/42), done.
remote: Total 43 (delta 31), reused 0 (delta 0)
Unpacking objects: 100% (43/43), done.
From http://bitbucket.org/sacgf/x
a41eb87..ead1a92 master -> origin/master
First, rewinding head to replay your work on top of it...
Fast-forwarded master to ead1a920caf60dd11e4d1a021157d3b9854a9374.
d
The built-in string constructor will automatically call obj.__str__
:
''.join(map(str,list))
if you have multiple parameters use the syntax as below. I have a bat file with script as below:
start "dummyTitle" [/options] D:\path\ProgramName.exe Param1 Param2 Param3
start "dummyTitle" [/options] D:\path\ProgramName.exe Param4 Param5 Param6
This will open multiple consoles.
In my case CORS error was happening only in POST requests with file attachments other than small files.
After many wasted hours we found out request was blocked for users who were using Kaspersky Total Control.
It's possible that other antivirus or firewall software may cause similar problems. Kaspersky run some security tests for requests, but omits them for websites with SSL EV certificate, so obtaining such certificate should resolve this issue properly.
Disabling protection for your domain is a bit tricky, so here are required steps (as for December 2020): Settings -> Network Settings -> Manage exclusions -> Add -> your domain -> Save
The good thing is you can detect such blocked request. The error is empty – it doesn't have status and response. This way you can assume it was blocked by third party software and show some info.
See sys.exit
. That function will quit your program with the given exit status.
When writing CMake scripts there is a lot you need to know about the syntax and how to use variables in CMake.
Strings using set()
:
set(MyString "Some Text")
set(MyStringWithVar "Some other Text: ${MyString}")
set(MyStringWithQuot "Some quote: \"${MyStringWithVar}\"")
Or with string()
:
string(APPEND MyStringWithContent " ${MyString}")
Lists using set()
:
set(MyList "a" "b" "c")
set(MyList ${MyList} "d")
Or better with list()
:
list(APPEND MyList "a" "b" "c")
list(APPEND MyList "d")
Lists of File Names:
set(MySourcesList "File.name" "File with Space.name")
list(APPEND MySourcesList "File.name" "File with Space.name")
add_excutable(MyExeTarget ${MySourcesList})
set()
Commandstring()
Commandlist()
CommandFirst there are the "Normal Variables" and things you need to know about their scope:
CMakeLists.txt
they are set in and everything called from there (add_subdirectory()
, include()
, macro()
and function()
).add_subdirectory()
and function()
commands are special, because they open-up their own scope.
set(...)
there are only visible there and they make a copy of all normal variables of the scope level they are called from (called parent scope).set(... PARENT_SCOPE)
function(xyz _resultVar)
is setting set(${_resultVar} 1 PARENT_SCOPE)
include()
or macro()
scripts will modify variables directly in the scope of where they are called from. Second there is the "Global Variables Cache". Things you need to know about the Cache:
CMakeCache.txt
file in your binary output directory.The values in the Cache can be modified in CMake's GUI application before they are generated. Therefore they - in comparison to normal variables - have a type
and a docstring
. I normally don't use the GUI so I use set(... CACHE INTERNAL "")
to set my global and persistant values.
Please note that the INTERNAL
cache variable type does imply FORCE
In a CMake script you can only change existing Cache entries if you use the set(... CACHE ... FORCE)
syntax. This behavior is made use of e.g. by CMake itself, because it normally does not force Cache entries itself and therefore you can pre-define it with another value.
cmake -D var:type=value
, just cmake -D var=value
or with cmake -C CMakeInitialCache.cmake
.unset(... CACHE)
.The Cache is global and you can set them virtually anywhere in your CMake scripts. But I would recommend you think twice about where to use Cache variables (they are global and they are persistant). I normally prefer the set_property(GLOBAL PROPERTY ...)
and set_property(GLOBAL APPEND PROPERTY ...)
syntax to define my own non-persistant global variables.
To avoid pitfalls you should know the following about variables:
find_...
commands - if successful - do write their results as cached variables "so that no call will search again"set(MyVar a b c)
is "a;b;c"
and set(MyVar "a b c")
is "a b c"
list()
command for handling listsfunctions()
instead of macros()
because you don't want your local variables to show up in the parent scope. project()
and enable_language()
calls. So it could get important to set some variables before those commands are used.Sometimes only debugging variables helps. The following may help you:
printf
debugging style by using the message()
command. There also some ready to use modules shipped with CMake itself: CMakePrintHelpers.cmake, CMakePrintSystemInformation.cmakeCMakeCache.txt
file in your binary output directory. This file is even generated if the actual generation of your make environment fails.cmake --trace ...
to see the CMake's complete parsing process. That's sort of the last reserve, because it generates a lot of output.$ENV{...}
and write set(ENV{...} ...)
environment variables$<...>
are only evaluated when CMake's generator writes the make environment (it comparison to normal variables that are replaced "in-place" by the parser)${${...}}
you can give variable names in a variable and reference its content.if()
command)
if(MyVariable)
you can directly check a variable for true/false (no need here for the enclosing ${...}
)1
, ON
, YES
, TRUE
, Y
, or a non-zero number. 0
, OFF
, NO
, FALSE
, N
, IGNORE
, NOTFOUND
, the empty string, or ends in the suffix -NOTFOUND
.if(MSVC)
, but it can be confusing for someone who does not know this syntax shortcut.set(CMAKE_${lang}_COMPILER ...)
if()
commands. Here is an example where CMAKE_CXX_COMPILER_ID
is "MSVC"
and MSVC
is "1"
:
if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
is true, because it evaluates to if("1" STREQUAL "1")
if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
is false, because it evaluates to if("MSVC" STREQUAL "1")
if(MSVC)
cmake_policy(SET CMP0054 NEW)
to "only interpret if()
arguments as variables or keywords when unquoted."option()
command
ON
or OFF
and they allow some special handling like e.g. dependenciesoption
with the set
command. The value given to option
is really only the "initial value" (transferred once to the cache during the first configuration step) and is afterwards meant to be changed by the user through CMake's GUI.Using "List" you can prevent casting errors. It is very useful to avoid a runtime casting error.
Example:
Here (using ArrayList) you can compile this code but you will see an execution error later.
// Create a new ArrayList
System.Collections.ArrayList mixedList = new System.Collections.ArrayList();
// Add some numbers to the list
mixedList.Add(7);
mixedList.Add(21);
// Add some strings to the list
mixedList.Add("Hello");
mixedList.Add("This is going to be a problem");
System.Collections.ArrayList intList = new System.Collections.ArrayList();
System.Collections.ArrayList strList = new System.Collections.ArrayList();
foreach (object obj in mixedList)
{
if (obj.GetType().Equals(typeof(int)))
{
intList.Add(obj);
}
else if (obj.GetType().Equals(typeof(string)))
{
strList.Add(obj);
}
else
{
// error.
}
}
Use
SELECT * FROM table WHERE DATE(2012-05-05 00:00:00) = '2012-05-05'
The problem is that you are passing a nullable type to a non-nullable type.
You can do any of the following solution:
A. Declare your dt
as nullable
DateTime? dt = dateTime;
B. Use Value
property of the the DateTime? datetime
DateTime dt = datetime.Value;
C. Cast it
DateTime dt = (DateTime) datetime;
I assume you want to center them on one line and not on two separate lines based on your fiddle. If that is the case, try the following css:
div { background:red;
overflow:hidden;
}
span { display:block;
margin:0 auto;
width:200px;
}
span a { padding:5px 10px;
color:#fff;
background:#222;
}
I removed the float since you want to center it, and then made the span surrounding the links centered by adding margin:0 auto to them. Finally, I added a static width to the span. This centers the links on one line within the red div.
I found my I had built my object incorrectly. I used http://json2csharp.com/ to generate me my object class from the JSON. Once I had the correct Oject I was able to cast without issue. Norbit, Noob mistake. Thought I'd add it in case you have the same issue.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>JQuery</title>
<script src="jquery.js" type="text/javascript"> </script>
<style type="text/css">
#box{
width: 68px;
height: 27px;
background: url(images/home1.gif);
cursor: pointer;
}
</style>
<script type="text/javascript">
$(function(){
$('#box').hover( function(){
$('#box').css('background', 'url(images/home2.gif)');
});
$('#box').mouseout( function(){
$('#box').css('background', 'url(images/home1.gif)');
});
});
</script>
</head>
<body>
<div id="box" onclick="location.href='index.php';"></div>
</body>
</html>
When you read()
the file, you may get a newline character '\n'
in your string. Try either
if UserInput.strip() == 'List contents':
or
if 'List contents' in UserInput:
Also note that your second file open
could also use with
:
with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile: if UserInput.strip() == 'List contents': # or if s in f: UserInputFile.write("ls") else: print "Didn't work"
If this occurs trying to delete a folder (on *nix) and Refresh does not help, open a terminal and look for a symlink below the folder you are trying to delete and remove this manually. This solved my issues.
Add a border
to the regular item, the same color
as the background
, so that it cannot be seen. That way the item has a border: 1px
whether it is being hovered or not.
document.getElementById('textbox1').value
MySQL really dislikes mixing collations unless it can coerce them to the same one (which clearly is not feasible in your case). Can't you just force the same collation to be used via a COLLATE clause? (or the simpler BINARY
shortcut if applicable...).
Use Control.ControlCollection.Find.
TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
tbx.Text = "found!";
EDIT for asker:
Control[] tbxs = this.Controls.Find(txtbox_and_message[0,0], true);
if (tbxs != null && tbxs.Length > 0)
{
tbxs[0].Text = "Found!";
}
I think I see your problem, you need to use the @
syntax to define parameters you will pass in this way, also I'm not sure what loginID or password are doing you don't seem to define them anywhere and they are not being used as URL parameters so are they being sent as query parameters?
This is what I can suggest based on what I see so far:
.factory('MagComments', function ($resource) {
return $resource('http://localhost/dooleystand/ci/api/magCommenct/:id', {
loginID : organEntity,
password : organCommpassword,
id : '@magId'
});
})
The @magId
string will tell the resource to replace :id
with the property magId
on the object you pass it as parameters.
I'd suggest reading over the documentation here (I know it's a bit opaque) very carefully and looking at the examples towards the end, this should help a lot.
It's method syntax (which I find easier to read) but this might do it
Updated post comment
Use .FirstOrDefault()
instead of .First()
With regard to the dates average, you may have to drop that ordering for the moment as I am unable to get to an IDE at the moment
var groupByReference = context.Measurements
.GroupBy(m => m.Reference)
.Select(g => new {Creation = g.FirstOrDefault().CreationTime,
// Avg = g.Average(m => m.CreationTime.Ticks),
Items = g })
.OrderBy(x => x.Creation)
// .ThenBy(x => x.Avg)
.Take(numOfEntries)
.ToList();
(only usable if you don't need recursive deptch)
Use bookmarklet. Drag this link in bookmarks, then edit and paste this code:
(function(){ var arr=[], l=document.links; var ext=prompt("select extension for download (all links containing that, will be downloaded.", ".mp3"); for(var i=0; i<l.length; i++) { if(l[i].href.indexOf(ext) !== false){ l[i].setAttribute("download",l[i].text); l[i].click(); } } })();
and go on page (from where you want to download files), and click that bookmarklet.
Actually, it appears that urllib2 can do an HTTP HEAD request.
The question that @reto linked to, above, shows how to get urllib2 to do a HEAD request.
Here's my take on it:
import urllib2
# Derive from Request class and override get_method to allow a HEAD request.
class HeadRequest(urllib2.Request):
def get_method(self):
return "HEAD"
myurl = 'http://bit.ly/doFeT'
request = HeadRequest(myurl)
try:
response = urllib2.urlopen(request)
response_headers = response.info()
# This will just display all the dictionary key-value pairs. Replace this
# line with something useful.
response_headers.dict
except urllib2.HTTPError, e:
# Prints the HTTP Status code of the response but only if there was a
# problem.
print ("Error code: %s" % e.code)
If you check this with something like the Wireshark network protocol analazer, you can see that it is actually sending out a HEAD request, rather than a GET.
This is the HTTP request and response from the code above, as captured by Wireshark:
HEAD /doFeT HTTP/1.1
Accept-Encoding: identity
Host: bit.ly
Connection: close
User-Agent: Python-urllib/2.7HTTP/1.1 301 Moved
Server: nginx
Date: Sun, 19 Feb 2012 13:20:56 GMT
Content-Type: text/html; charset=utf-8
Cache-control: private; max-age=90
Location: http://www.kidsidebyside.org/?p=445
MIME-Version: 1.0
Content-Length: 127
Connection: close
Set-Cookie: _bit=4f40f738-00153-02ed0-421cf10a;domain=.bit.ly;expires=Fri Aug 17 13:20:56 2012;path=/; HttpOnly
However, as mentioned in one of the comments in the other question, if the URL in question includes a redirect then urllib2 will do a GET request to the destination, not a HEAD. This could be a major shortcoming, if you really wanted to only make HEAD requests.
The request above involves a redirect. Here is request to the destination, as captured by Wireshark:
GET /2009/05/come-and-draw-the-circle-of-unity-with-us/ HTTP/1.1
Accept-Encoding: identity
Host: www.kidsidebyside.org
Connection: close
User-Agent: Python-urllib/2.7
An alternative to using urllib2 is to use Joe Gregorio's httplib2 library:
import httplib2
url = "http://bit.ly/doFeT"
http_interface = httplib2.Http()
try:
response, content = http_interface.request(url, method="HEAD")
print ("Response status: %d - %s" % (response.status, response.reason))
# This will just display all the dictionary key-value pairs. Replace this
# line with something useful.
response.__dict__
except httplib2.ServerNotFoundError, e:
print (e.message)
This has the advantage of using HEAD requests for both the initial HTTP request and the redirected request to the destination URL.
Here's the first request:
HEAD /doFeT HTTP/1.1
Host: bit.ly
accept-encoding: gzip, deflate
user-agent: Python-httplib2/0.7.2 (gzip)
Here's the second request, to the destination:
HEAD /2009/05/come-and-draw-the-circle-of-unity-with-us/ HTTP/1.1
Host: www.kidsidebyside.org
accept-encoding: gzip, deflate
user-agent: Python-httplib2/0.7.2 (gzip)
Can also be thought of as the number of ways of choosing pairs of nodes n choose 2 = n(n-1)/2. True if only any pair can have only one edge. Multiply by 2 otherwise
Based on your comment in MindingData's answer, it has nothing to do with your CORS, it's working fine.
Your Controller action is returning the wrong data. HttpCode 415 means, "Unsupported Media type". This happens when you either pass the wrong format to the controller (i.e. XML to a controller which only accepts json) or when you return a wrong type (return Xml in a controller which is declared to only return xml).
For later one check existence of [Produces("...")]
attribute on your action
I use Globalize so work with many date formats so use the following:
@Html.TextBoxFor(m => m.DateOfBirth, "{0:d}")
This will automatically adjust the date format to the browser's locale settings.
The easiest way is to use the 'plumbing' command update-ref
to delete the current branch.
You can't use git branch -D
as it has a safety valve to stop you deleting the current branch.
This puts you back into the 'initial commit' state where you can start with a fresh initial commit.
git update-ref -d refs/heads/master
git commit -m "New initial commit"
You can potentially roll your own Stream
variant by wrapping your lambda to throw an unchecked exception and then later unwrapping that unchecked exception on terminal operations:
@FunctionalInterface
public interface ThrowingPredicate<T, X extends Throwable> {
public boolean test(T t) throws X;
}
@FunctionalInterface
public interface ThrowingFunction<T, R, X extends Throwable> {
public R apply(T t) throws X;
}
@FunctionalInterface
public interface ThrowingSupplier<R, X extends Throwable> {
public R get() throws X;
}
public interface ThrowingStream<T, X extends Throwable> {
public ThrowingStream<T, X> filter(
ThrowingPredicate<? super T, ? extends X> predicate);
public <R> ThrowingStream<T, R> map(
ThrowingFunction<? super T, ? extends R, ? extends X> mapper);
public <A, R> R collect(Collector<? super T, A, R> collector) throws X;
// etc
}
class StreamAdapter<T, X extends Throwable> implements ThrowingStream<T, X> {
private static class AdapterException extends RuntimeException {
public AdapterException(Throwable cause) {
super(cause);
}
}
private final Stream<T> delegate;
private final Class<X> x;
StreamAdapter(Stream<T> delegate, Class<X> x) {
this.delegate = delegate;
this.x = x;
}
private <R> R maskException(ThrowingSupplier<R, X> method) {
try {
return method.get();
} catch (Throwable t) {
if (x.isInstance(t)) {
throw new AdapterException(t);
} else {
throw t;
}
}
}
@Override
public ThrowingStream<T, X> filter(ThrowingPredicate<T, X> predicate) {
return new StreamAdapter<>(
delegate.filter(t -> maskException(() -> predicate.test(t))), x);
}
@Override
public <R> ThrowingStream<R, X> map(ThrowingFunction<T, R, X> mapper) {
return new StreamAdapter<>(
delegate.map(t -> maskException(() -> mapper.apply(t))), x);
}
private <R> R unmaskException(Supplier<R> method) throws X {
try {
return method.get();
} catch (AdapterException e) {
throw x.cast(e.getCause());
}
}
@Override
public <A, R> R collect(Collector<T, A, R> collector) throws X {
return unmaskException(() -> delegate.collect(collector));
}
}
Then you could use this the same exact way as a Stream
:
Stream<Account> s = accounts.values().stream();
ThrowingStream<Account, IOException> ts = new StreamAdapter<>(s, IOException.class);
return ts.filter(Account::isActive).map(Account::getNumber).collect(toSet());
This solution would require quite a bit of boilerplate, so I suggest you take a look at the library I already made which does exactly what I have described here for the entire Stream
class (and more!).
Your error is in UpdaterServiceManager in onCreate and showNotification method.
You are trying to show notification
from Service using Activity Context
. Whereas Every Service has its own Context,
just use the that. You don't need to pass a Service an Activity's Context.
I don't see why you need a specific Activity's Context to show Notification.
Put your createNotification method in UpdateServiceManager.class. And remove CreateNotificationActivity not from Service.
You cannot display an application window/dialog through a Context that is not an Activity. Try passing a valid activity reference
If possible you should change the data type of the column to a number if you only store numbers anyway.
If you can't do that then cast your column value to an integer
explicitly with
select col from yourtable
order by cast(col as unsigned)
or implicitly for instance with a mathematical operation which forces a conversion to number
select col from yourtable
order by col + 0
BTW MySQL converts strings from left to right. Examples:
string value | integer value after conversion
--------------+--------------------------------
'1' | 1
'ABC' | 0 /* the string does not contain a number, so the result is 0 */
'123miles' | 123
'$123' | 0 /* the left side of the string does not start with a number */
The easiest way is to use the ``
feature in Perl. This will execute what is inside and return what was printed to stdout:
my $pid = 5892;
my $var = `top -H -p $pid -n 1 | grep myprocess | wc -l`;
print "not = $var\n";
This should do it.
If the to-be-updated component is not inside the same NamingContainer
component (ui:repeat
, h:form
, h:dataTable
, etc), then you need to specify the "absolute" client ID. Prefix with :
(the default NamingContainer
separator character) to start from root.
<p:ajax process="@this" update="count :subTotal"/>
To be sure, check the client ID of the subTotal
component in the generated HTML for the actual value. If it's inside for example a h:form
as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.
<p:ajax process="@this" update="count :formId:subTotal"/>
Space separation of IDs is more recommended as <f:ajax>
doesn't support comma separation and starters would otherwise get confused.
CREATE OR REPLACE FUNCTION save_user(_id integer, _name character varying)
RETURNS boolean AS
$BODY$
BEGIN
UPDATE users SET name = _name WHERE id = _id;
IF FOUND THEN
RETURN true;
END IF;
BEGIN
INSERT INTO users (id, name) VALUES (_id, _name);
EXCEPTION WHEN OTHERS THEN
UPDATE users SET name = _name WHERE id = _id;
END;
RETURN TRUE;
END;
$BODY$
LANGUAGE plpgsql VOLATILE STRICT
Have you considered using stringstreams?
#include <string>
#include <sstream>
std::ostringstream oss;
oss << "sometext" << somevar << "sometext" << somevar;
std::string var = oss.str();
A subclass in java, is a class that inherits from another class.
Inheritance is a way for classes to add specialized behavior ontop of generalized behavior. This is often represented by the phrase "is a" relationship.
For example, a Triangle
is a Shape
, so it might make sense to implement a Shape class, and have the Triangle class inherit from it. In this example, Shape
is the superclass of Triangle
and Triangle
is the subclass of Shape
You can set data to session simply like this in Codeigniter:
$this->load->library('session');
$this->session->set_userdata(array(
'user_id' => $user->uid,
'username' => $user->username,
'groupid' => $user->groupid,
'date' => $user->date_cr,
'serial' => $user->serial,
'rec_id' => $user->rec_id,
'status' => TRUE
));
and you can get it like this:
$u_rec_id = $this->session->userdata('rec_id');
$serial = $this->session->userdata('serial');
Generally git pull
is enough, but I'm not sure what layout you have chosen (or has github chosen for you).
Check out SQL For Smarties. I thought I was pretty good with SQL too, until I read that book... Goes into tons of depth, talks about things I've not seen elsewhere (I.E. difference between 3'rd and 4'th normal form, Boyce Codd Normal Form, etc)...
I think the correct way to do is
brew upgrade mongodb
It will upgrade the mongodb formula. If you want to upgrade all outdated formula, simply
brew upgrade
Wherever you are trying to check NULL value of a column, you should use
IS NULL and IS NOT NULL
You should not use =NULL or ==NULL
Example(NULL)
select * from user_registration where registered_time IS NULL
will return the rows with registered_time
value is NULL
Example(NOT NULL)
select * from user_registration where registered_time IS NOT NULL
will return the rows with registered_time
value is NOT NULL
Note: The keyword null
, not null
and is
are not case sensitive
.
Someone asked about adding attributes (specifically, 'rows' and 'cols'). If you're using Razor, you could just do this:
@Html.TextAreaFor(model => model.Text, new { cols = 35, @rows = 3 })
That works for me. The '@' is used to escape keywords so they are treated as variables/properties.
Using Regexp with groups:
Pattern pattern = Pattern.compile("(0*)(.*)");
String result = "";
Matcher matcher = pattern.matcher(content);
if (matcher.matches())
{
// first group contains 0, second group the remaining characters
// 000abcd - > 000, abcd
result = matcher.group(2);
}
return result;
Kotlin code is a lot simpler:
if(isVisable) {
clearButton.visibility = View.INVISIBLE
}
else {
clearButton.visibility = View.VISIBLE
}
If you need to redirect out of your angular application use $window.location
. That was my case; hopefully someone will find it useful.
If you are using the NestJS framework, you can get code coverage using this command:
npm run test:cov
How about this, which I managed to achieve thanks, in part, to this post.
You want to find several files, lets say logs with different names but a pattern (e.g. filename=logfile.DATE
), inside several directories with a pattern (e.g. /logsapp1, /logsapp2
).
Each file has a pattern you want to grep (e.g. "init time"
), and you want to have the "init time"
of each file, but knowing which file it belongs to.
find ./logsapp* -name logfile* | xargs -I{} grep "init time" {} \dev\null | tee outputfilename.txt
Then the outputfilename.txt
would be something like
./logsapp1/logfile.22102015: init time: 10ms
./logsapp1/logfile.21102015: init time: 15ms
./logsapp2/logfile.21102015: init time: 17ms
./logsapp2/logfile.22102015: init time: 11ms
In general
find ./path_pattern/to_files* -name filename_pattern* | xargs -I{} grep "grep_pattern" {} \dev\null | tee outfilename.txt
Explanation:
find
command will search the filenames based in the pattern
then, pipe xargs -I{}
will redirect the find
output to the {}
which will be the input for grep ""pattern" {}
Then the trick to make grep
display the filenames \dev\null
and finally, write the output in file with tee outputfile.txt
This worked for me in grep
version 9.0.5 build 1989.
Stopwatch
measures time elapsed.
// Create new stopwatch
Stopwatch stopwatch = new Stopwatch();
// Begin timing
stopwatch.Start();
Threading.Thread.Sleep(500)
// Stop timing
stopwatch.Stop();
Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);
Here is a DEMO
.
Use option bty = "n"
in legend
to remove the box around the legend. For example:
legend(1, 5,
"This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",
bty = "n")
The correct scheme should be:
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.org/Sport"
xmlns:tns="http://www.example.org/Sport"
elementFormDefault="qualified"
xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
jaxb:version="2.0">
<complexType name="sportType">
<simpleContent>
<extension base="string">
<attribute name="type" type="string" />
<attribute name="gender" type="string" />
</extension>
</simpleContent>
</complexType>
<element name="sports">
<complexType>
<sequence>
<element name="sport" minOccurs="0" maxOccurs="unbounded"
type="tns:sportType" />
</sequence>
</complexType>
</element>
Code generated for SportType will be:
package org.example.sport;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "sportType")
public class SportType {
@XmlValue
protected String value;
@XmlAttribute
protected String type;
@XmlAttribute
protected String gender;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getType() {
return type;
}
public void setType(String value) {
this.type = value;
}
public String getGender() {
return gender;
}
public void setGender(String value) {
this.gender = value;
}
}
Basically unmanaged code is code which does not run under the .NET CLR (aka not VB.NET, C#, etc.). My guess is that NUnit has a runner/wrapper which is not .NET code (aka C++).
you first would need to convert string into datetime tuple, and then convert that datetime tuple to string, it would go like this:
lastconnection = datetime.strptime("21/12/2008", "%d/%m/%Y").strftime('%Y-%m-%d')
What system are you running on? Do you have access to some sort of debugger (gdb, visual studio's debugger, etc.)?
That would give us valuable information, like the line of code where the program crashes... Also, the amount of memory may be prohibitive.
Additionally, may I recommend that you replace the numeric limits by named definitions?
As such:
#define DIM1_SZ 1000
#define DIM2_SZ 1000000
Use those whenever you wish to refer to the array dimension limits. It will help avoid typing errors.
In typescript:
export class WebsocketUtils {
public static websocketUrlByPath(path) {
return this.websocketProtocolByLocation() +
window.location.hostname +
this.websocketPortWithColonByLocation() +
window.location.pathname +
path;
}
private static websocketProtocolByLocation() {
return window.location.protocol === "https:" ? "wss://" : "ws://";
}
private static websocketPortWithColonByLocation() {
const defaultPort = window.location.protocol === "https:" ? "443" : "80";
if (window.location.port !== defaultPort) {
return ":" + window.location.port;
} else {
return "";
}
}
}
Usage:
alert(WebsocketUtils.websocketUrlByPath("/websocket"));
The best approach it is to use Hash.to_params which is the one working fine with arrays.
{a: 1, b: [1,2,3]}.to_param
"a=1&b[]=1&b[]=2&b[]=3"
You can plot several columns at once by supplying a list of column names to the plot
's y
argument.
df.plot(x="X", y=["A", "B", "C"], kind="bar")
This will produce a graph where bars are sitting next to each other.
In order to have them overlapping, you would need to call plot
several times, and supplying the axes to plot to as an argument ax
to the plot.
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
y = np.random.rand(10,4)
y[:,0]= np.arange(10)
df = pd.DataFrame(y, columns=["X", "A", "B", "C"])
ax = df.plot(x="X", y="A", kind="bar")
df.plot(x="X", y="B", kind="bar", ax=ax, color="C2")
df.plot(x="X", y="C", kind="bar", ax=ax, color="C3")
plt.show()
When non of the above works, and still mails looks like ª הודפסה ×•× ×©×œ
:
$mail->addCustomHeader('Content-Type', 'text/plain;charset=utf-8');
$mail->Subject = '=?UTF-8?B?' . base64_encode($subject) . '?=';;
Won't you need the ensure the area where you display the Arabic is Right-to-Left orientated also?
e.g.
<p dir="rtl">
Here are some tidyverse
and custom function options that might work depending on your needs:
library(tidyverse)
# custom function to generate, filter, and mutate the data:
combine_dfs <- function(i){
data_frame(x = rnorm(5), y = runif(5)) %>%
filter(x < y) %>%
mutate(x_plus_y = x + y) %>%
mutate(i = i)
}
df <- 1:5 %>% map_df(~combine_dfs(.))
df <- map_df(1:5, ~combine_dfs(.)) # both give the same results
> df %>% head()
# A tibble: 6 x 4
x y x_plus_y i
<dbl> <dbl> <dbl> <int>
1 -0.973 0.673 -0.300 1
2 -0.553 0.0463 -0.507 1
3 0.250 0.716 0.967 2
4 -0.745 0.0640 -0.681 2
5 -0.736 0.228 -0.508 2
6 -0.365 0.496 0.131 3
You could do something similar if you had a directory of files that needed to be combined:
dir_path <- '/path/to/data/test_directory/'
list.files(dir_path)
combine_files <- function(path, file){
read_csv(paste0(path, file)) %>%
filter(a < b) %>%
mutate(a_plus_b = a + b) %>%
mutate(file_name = file)
}
df <- list.files(dir_path, '\\.csv$') %>%
map_df(~combine_files(dir_path, .))
# or if you have Excel files, using the readxl package:
combine_xl_files <- function(path, file){
readxl::read_xlsx(paste0(path, file)) %>%
filter(a < b) %>%
mutate(a_plus_b = a + b) %>%
mutate(file_name = file)
}
df <- list.files(dir_path, '\\.xlsx$') %>%
map_df(~combine_xl_files(dir_path, .))
A subquery is a select statement that is embedded in a clause of another select statement.
EX:
select ename, sal
from emp where sal > (select sal
from emp where ename ='FORD');
A Correlated subquery is a subquery that is evaluated once for each row processed by the outer query or main query. Execute the Inner query based on the value fetched by the Outer query all the values returned by the main query are matched. The INNER Query is driven by the OUTER Query.
Ex:
select empno,sal,deptid
from emp e
where sal=(select avg(sal)
from emp where deptid=e.deptid);
DIFFERENCE
The inner query executes first and finds a value, the outer query executes once using the value from the inner query (subquery)
Fetch by the outer query, execute the inner query using the value of the outer query, use the values resulting from the inner query to qualify or disqualify the outer query (correlated)
For more information : http://www.oraclegeneration.com/2014/01/sql-interview-questions.html
I faced the problem with display:none
I have several horizontal bars with transition effects but I wanted to show only part of that container and fold the rest while maintaining the effects. I reproduced a small demo here
The obvious was to wrap those hidden animated bars in a div then toggle that element's height and opacity
.hide{
opacity: 0;
height: 0;
}
.bars-wrapper.expanded > .hide{
opacity: 1;
height: auto;
}
The animation works well but the issue was that these hidden bars were still consuming space on my page and overlapping other elements
so adding display:none
to the hidden wrapper .hide
solves the margin issue but not the transition, neither applying display:none
or height:0;opacity:0
works on the children elements.
So my final workaround was to give those hidden bars a negative and absolute position and it worked well with CSS transitions.
It depends. You could
string.match(/^abc$/)
But that would not match the following string: 'the first 3 letters of the alphabet are abc. not abc123'
I think you would want to use \b
(word boundaries):
var str = 'the first 3 letters of the alphabet are abc. not abc123';_x000D_
var pat = /\b(abc)\b/g;_x000D_
console.log(str.match(pat));
_x000D_
Live example: http://jsfiddle.net/uu5VJ/
If the former solution works for you, I would advise against using it.
That means you may have something like the following:
var strs = ['abc', 'abc1', 'abc2']
for (var i = 0; i < strs.length; i++) {
if (strs[i] == 'abc') {
//do something
}
else {
//do something else
}
}
While you could use
if (str[i].match(/^abc$/g)) {
//do something
}
It would be considerably more resource-intensive. For me, a general rule of thumb is for a simple string comparison use a conditional expression, for a more dynamic pattern use a regular expression.
More on JavaScript regexes: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions
The problem is on the initialization step.
for i in range (0,m):
matrix[i] = columns
This code actually makes every row of your matrix
refer to the same columns
object. If any item in any column changes - every other column will change:
>>> for i in range (0,m):
... matrix[i] = columns
...
>>> matrix
[[0, 0, 0], [0, 0, 0]]
>>> matrix[1][1] = 2
>>> matrix
[[0, 2, 0], [0, 2, 0]]
You can initialize your matrix in a nested loop, like this:
matrix = []
for i in range(0,m):
matrix.append([])
for j in range(0,n):
matrix[i].append(0)
or, in a one-liner by using list comprehension:
matrix = [[0 for j in range(n)] for i in range(m)]
or:
matrix = [x[:] for x in [[0]*n]*m]
See also:
Hope that helps.
Just as a matter of fact:
data_joined = dat1.join(dat2)
print(data_joined)
Try:
document.getElementById("yourH1_element_Id").innerHTML = "yourTextHere";
return n
from main
is equivalent to exit(n)
.
The valid returned is the rest of your program. It's meaning is OS dependent. On unix, 0 means normal termination and non-zero indicates that so form of error forced your program to terminate without fulfilling its intended purpose.
It's unusual that your example returns 0 (normal termination) when it seems to have run out of memory.
Beside using loop and for comprehension, you could also use map
lst = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")]
mylst = map(lambda each:each.strip("8"), lst)
print mylst
I just compared Apache Commons Math with jlapack.
Test: singular value decomposition of a random 1024x1024 matrix.
Machine: Intel(R) Core(TM)2 Duo CPU E6750 @ 2.66GHz, linux x64
Octave code: A=rand(1024); tic;[U,S,V]=svd(A);toc
results execution time --------------------------------------------------------- Octave 36.34 sec JDK 1.7u2 64bit jlapack dgesvd 37.78 sec apache commons math SVD 42.24 sec JDK 1.6u30 64bit jlapack dgesvd 48.68 sec apache commons math SVD 50.59 sec Native routines Lapack* invoked from C: 37.64 sec Intel MKL 6.89 sec(!)
My conclusion is that jlapack called from JDK 1.7 is very close to the native binary performance of lapack. I used the lapack binary library coming with linux distro and invoked the dgesvd routine to get the U,S and VT matrices as well. All tests were done using double precision on exactly the same matrix each run (except Octave).
Disclaimer - I'm not an expert in linear algebra, not affiliated to any of the libraries above and this is not a rigorous benchmark. It's a 'home-made' test, as I was interested comparing the performance increase of JDK 1.7 to 1.6 as well as commons math SVD to jlapack.
Just check the packaging, the simplest answer I can provide is that your package has been mislabeled (within a class).
Also, you may have some weird characters. Try white-flushing the code in a Notepad (or Gedit) and then pasting it into a newly created class with your IDE.
The best way with the HTML you have would probably be to use the next
function, like so:
var div = $(this).next('.class2');
Since the click handler is happening to the <a>
, you could also traverse up to the parent DIV, then search down for the second DIV. You would do this with a combination of parent
and children
. This approach would be best if the HTML you put up is not exactly like that and the second DIV could be in another location relative to the link:
var div = $(this).parent().children('.class2');
If you wanted the "search" to not be limited to immediate children, you would use find
instead of children
in the example above.
Also, it is always best to prepend your class selectors with the tag name if at all possible. ie, if only <div>
tags are going to have those classes, make the selector be div.class1
, div.class2
.
spans not have the value in html
one is the id
for span
tag
in javascript use
document.getElementById('one').innerText;
in jQuery use
$('#one').text()
function check() {
var content = document.getElementById("one").innerText;
alert(content);
}
or
function check() {
var content = $('#one').text();
alert(content);
}
It looks like Angular has support for this now.
From the latest (v1.2.0) docs for $routeProvider.when(path, route)
:
path
can contain optional named groups with a question mark (:name?
)
By "camera position," it sounds like you want to adjust the elevation and the azimuth angle that you use to view the 3D plot. You can set this with ax.view_init
. I've used the below script to first create the plot, then I determined a good elevation, or elev
, from which to view my plot. I then adjusted the azimuth angle, or azim
, to vary the full 360deg around my plot, saving the figure at each instance (and noting which azimuth angle as I saved the plot). For a more complicated camera pan, you can adjust both the elevation and angle to achieve the desired effect.
from mpl_toolkits.mplot3d import Axes3D
ax = Axes3D(fig)
ax.scatter(xx,yy,zz, marker='o', s=20, c="goldenrod", alpha=0.6)
for ii in xrange(0,360,1):
ax.view_init(elev=10., azim=ii)
savefig("movie%d.png" % ii)
window.location.href.slice(window.location.href.indexOf('?') + 1);
The proper way to organize your code is to use separate directories in place of namespaces. Each class will be in it's own file, in it's respective namespace folder. index.ts will only re-export each file; no actual code should be in the index.ts file. Organizing your code like this makes it far easier to navigate, and is self-documenting based on directory structure.
// index.ts
import * as greeter from './greeter';
import * as somethingElse from './somethingElse';
export {greeter, somethingElse};
// greeter/index.ts
export * from './greetings.js';
...
// greeter/greetings.ts
export const helloWorld = "Hello World";
You would then use it as such:
import { greeter } from 'your-package'; //Import it like normal, be it from an NPM module or from a directory.
// You can also use the following syntax, if you prefer:
import * as package from 'your-package';
console.log(greeter.helloWorld);
Googling around, the popular answer seems to be "just turn off safe mode":
SET SQL_SAFE_UPDATES = 0;
DELETE FROM instructor WHERE salary BETWEEN 13000 AND 15000;
SET SQL_SAFE_UPDATES = 1;
If I'm honest, I can't say I've ever made a habit of running in safe mode. Still, I'm not entirely comfortable with this answer since it just assumes you should go change your database config every time you run into a problem.
So, your second query is closer to the mark, but hits another problem: MySQL applies a few restrictions to subqueries, and one of them is that you can't modify a table while selecting from it in a subquery.
Quoting from the MySQL manual, Restrictions on Subqueries:
In general, you cannot modify a table and select from the same table in a subquery. For example, this limitation applies to statements of the following forms:
DELETE FROM t WHERE ... (SELECT ... FROM t ...); UPDATE t ... WHERE col = (SELECT ... FROM t ...); {INSERT|REPLACE} INTO t (SELECT ... FROM t ...);
Exception: The preceding prohibition does not apply if you are using a subquery for the modified table in the FROM clause. Example:
UPDATE t ... WHERE col = (SELECT * FROM (SELECT ... FROM t...) AS _t ...);
Here the result from the subquery in the FROM clause is stored as a temporary table, so the relevant rows in t have already been selected by the time the update to t takes place.
That last bit is your answer. Select target IDs in a temporary table, then delete by referencing the IDs in that table:
DELETE FROM instructor WHERE id IN (
SELECT temp.id FROM (
SELECT id FROM instructor WHERE salary BETWEEN 13000 AND 15000
) AS temp
);
This is the best video about Object-Oriented JavaScript on the internet:
The Definitive Guide to Object-Oriented JavaScript
Watch from beginning to end!!
Basically, Javascript is a Prototype-based language which is quite different than the classes in Java, C++, C#, and other popular friends. The video explains the core concepts far better than any answer here.
With ES6 (released 2015) we got a "class" keyword which allows us to use Javascript "classes" like we would with Java, C++, C#, Swift, etc.
Screenshot from the video showing how to write and instantiate a Javascript class/subclass:
Ways to hide Navigation Bar in Swift:
self.navigationController?.setNavigationBarHidden(true, animated: true)
self.navigationController?.navigationBar.isHidden = true
self.navigationController?.isNavigationBarHidden = true
If you don't want Vim to mangle formatting in incoming pasted text, you might also want to consider using: :set paste
. This will prevent Vim from re-tabbing your code. When done pasting, :set nopaste
will return to the normal behavior.
It's also possible to toggle the mode with a single key, by adding something like set pastetoggle=<F2>
to your .vimrc. More details on toggling auto-indent are here.
Use DATESTR
>> datestr(40189)
ans =
12-Jan-0110
Unfortunately, Excel starts counting at 1-Jan-1900. Find out how to convert serial dates from Matlab to Excel by using DATENUM
>> datenum(2010,1,11)
ans =
734149
>> datenum(2010,1,11)-40189
ans =
693960
>> datestr(40189+693960)
ans =
11-Jan-2010
In other words, to convert any serial Excel date, call
datestr(excelSerialDate + 693960)
EDIT
To get the date in mm/dd/yyyy format, call datestr
with the specified format
excelSerialDate = 40189;
datestr(excelSerialDate + 693960,'mm/dd/yyyy')
ans =
01/11/2010
Also, if you want to get rid of the leading zero for the month, you can use REGEXPREP to fix things
excelSerialDate = 40189;
regexprep(datestr(excelSerialDate + 693960,'mm/dd/yyyy'),'^0','')
ans =
1/11/2010
@Comment for ID:14. It's for me rather easier to write:
out.append it
instead of
out.println it
println did on my machine only write the first file of the ArrayList, with append I get the whole List written into the file.
Kindly anyway for the quick-and-dirty-solution.
Fixing must override a super class method error is not difficult, You just need to change Java source version to 1.6 because from Java 1.6 @Override annotation can be used along with interface method. In order to change source version to 1.6 follow below steps :
The default limit for the length of the request line is 8192 bytes = 8* 1024. It you want to change the limit, you have to add or update in your tomcat server.xml the attribut maxHttpHeaderSize.
as:
<Connector port="8080" maxHttpHeaderSize="65536" protocol="HTTP/1.1" ... />
In this example I set the limite to 65536 bytes= 64*1024.
Hope this will help.
Daniel A. White Solution works great for classes.
I've got a situation where I had to find input fields like donee_1_card where 1 is an index.
My solution has been
$("input[name^='donee']" && "input[name*='card']")
Though I am not sure how optimal it is.
In your template
template <void (*T)(int &)>
void doOperation()
The parameter T
is a non-type template parameter. This means that the behaviour of the template function changes with the value of the parameter (which must be fixed at compile time, which function pointer constants are).
If you want somthing that works with both function objects and function parameters you need a typed template. When you do this, though, you also need to provide an object instance (either function object instance or a function pointer) to the function at run time.
template <class T>
void doOperation(T t)
{
int temp=0;
t(temp);
std::cout << "Result is " << temp << std::endl;
}
There are some minor performance considerations. This new version may be less efficient with function pointer arguments as the particular function pointer is only derefenced and called at run time whereas your function pointer template can be optimized (possibly the function call inlined) based on the particular function pointer used. Function objects can often be very efficiently expanded with the typed template, though as the particular operator()
is completely determined by the type of the function object.
It means that trackDAO
should not be serialized.
Here's what worked for me: right click the project-> source -> format After that just drag and drop the source folder into eclipse under the project and select link.
good luck!
var object = { "a": 1, "b": 2};_x000D_
$.each(object, function(key, value){_x000D_
console.log(key + ": " + object[key]);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
_x000D_
//output
a: 1
b: 2
To set the height of ActionBar
you can create new Theme
like this one:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.FixedSize" parent="Theme.Sherlock.Light.DarkActionBar">
<item name="actionBarSize">48dip</item>
<item name="android:actionBarSize">48dip</item>
</style>
</resources>
and set this Theme
to your Activity
:
android:theme="@style/Theme.FixedSize"
Add "type": "module"
to your package.json
{
// ...
"type": "module",
// ...
}
before start make sure of installation:
yum install -y xorg-x11-server-Xorg xorg-x11-xauth xorg-x11-apps
xming
or cygwin
cat /etc/ssh/sshd_config | grep X
X11Forwarding yes
X11DisplayOffset 10
AddressFamily inet
blablaco@blablaco01 ~
$ xhost 192.168.2.223
192.168.2.223 being added to access control list
blablaco@blablaco01 ~
$ ssh -l root 192.168.2.223
[email protected] password:
Last login: Sat May 22 18:59:04 2010 from etcetc
[root@oel5u5 ~]# export DISPLAY=192.168.2.2:0.0
[root@oel5u5 ~]# echo $DISPLAY
192.168.2.2:0.0
[root@oel5u5 ~]# xclock&
Then the xclock application must launch.
Check it on putty or mobaxterm and don't check in remote desktop Manager software. Be careful for user that sudo in.
It's worth noting that when running in web-app mode (using the apple-mobile-web-app-capable
meta tag) the user agent changes from:
Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B405 Safari/531.21.10
to:
Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405
Tested in IE7 - 9 and Firefox: http://jsfiddle.net/WCaKg/. Markup:
<ul>
<li><li></li>
<li><li></li>
<li><li>
<ul>
<li><li></li>
<li><li></li>
<li><li></li>
<li><li></li>
</ul>
</li>
<li><li></li>
<li><li></li>
<li><li></li>
</ul>
CSS:
* {
margin: 0;
padding: 0;
}
body {
font: 200%/1.5 Optima, 'Lucida Grande', Lucida, 'Lucida Sans Unicode', sans-serif;
}
ul {
width: 9em;
list-style-type: none;
font-size: 0.75em;
}
li {
float: left;
margin: 0 4px 4px 0;
background: #60c;
background: rgba(102, 0, 204, 0.66);
border: 4px solid #60c;
color: #fff;
}
li:hover {
position: relative;
}
ul ul {
z-index: 1;
position: absolute;
left: -999em;
width: auto;
background: #ccc;
background: rgba(204, 204, 204, 0.33);
}
li:hover ul {
top: 2em;
left: 3px;
}
li li {
margin: 0 0 3px 0;
background: #909;
background: rgba(153, 0, 153, 0.66);
border: 3px solid #909;
}
Without using eval('function()')
you could to create a new function using new Function(strName)
. The below code was tested using FF, Chrome, IE.
<html>
<body>
<button onclick="test()">Try it</button>
</body>
</html>
<script type="text/javascript">
function test() {
try {
var fnName = "myFunction()";
var fn = new Function(fnName);
fn();
} catch (err) {
console.log("error:"+err.message);
}
}
function myFunction() {
console.log('Executing myFunction()');
}
</script>
I fixed my need belove
manifest permissions
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
<!-- Read Contacts from phone -->
<uses-permission android:name="android.permission.read_contacts" />
<uses-permission android:name="android.permission.read_phone_state" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
Note: After giving permissions at manifest some mobile phones can deny if so you need to go Settings--> Applications--> find your application click on it and turn On the permissions needed
btn_readallcontacks.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
List<User> userList = new ArrayList<User>();
while (phones.moveToNext()) {
User user = new User();
user.setNamee(phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
user.setPhone(phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
userList.add(user);
Log.d(TAG, "Name : " + user.getNamee().toString());
Log.d(TAG, "Phone : " + user.getPhone().toString());
}
phones.close();
}
});
This works for me!
<label for="reason">Reason:</label>
<select name="reason" size="1" id="name" >
<option value="NG" selected="SELECTED"><?php if (!(strcmp("NG", $_POST["reason"]))) {echo "selected=\"selected\"";} ?>Selection a reason below</option>
<option value="General"<?php if (!(strcmp("General", $_POST["reason"]))) {echo "selected=\"selected\"";} ?>>General Question</option>
<option value="Account"<?php if (!(strcmp("Account", $_POST["reason"]))) {echo "selected=\"selected\"";} ?>>Account Question</option>
<option value="Other"<?php if (!(strcmp("Other", $_POST["reason"]))) {echo "selected=\"selected\"";} ?>>Other</option>
</select>
The NA can actually be due to 2 reasons. One is that there is a NA in your data. Another one is due to there being one of the values being constant. This results in standard deviation being equal to zero and hence the cor function returns NA.
I think troelskn is close. I would do this instead:
class ClassToTest
{
protected function testThisMethod()
{
// Implement stuff here
}
}
Then, implement something like this:
class TestClassToTest extends ClassToTest
{
public function testThisMethod()
{
return parent::testThisMethod();
}
}
You then run your tests against TestClassToTest.
It should be possible to automatically generate such extension classes by parsing the code. I wouldn't be surprised if PHPUnit already offers such a mechanism (though I haven't checked).
on the web site box, you have selected .NETFramework 4.5 and it doesn show, so click there and choose the 3.5...i hope it helps.
Silly answer: write to a temporary file so you can use the venerable
File.ReadLines
var s = "Hello\r\nWorld";
var path = Path.GetTempFileName();
using (var writer = new StreamWriter(path))
{
writer.Write(s);
}
var lines = File.ReadLines(path);
In python3 the variable i will be out of scope when you try to print it.
To get the value you want you should store the result of your operation inside a new variable:
my_list = ["one","two","three"]
result=[(i) for i in my_list if i=="two"]
print(result)
you will then the following output
['two']