This is really just a syntax switch. OK, so we have this method call:
[NSPredicate predicateWithFormat:@"name contains[c] %@", searchText];
In Swift, constructors skip the "blahWith…" part and just use the class name as a function and then go straight to the arguments, so [NSPredicate predicateWithFormat: …]
would become NSPredicate(format: …)
. (For another example, [NSArray arrayWithObject: …]
would become NSArray(object: …)
. This is a regular pattern in Swift.)
So now we just need to pass the arguments to the constructor. In Objective-C, NSString literals look like @""
, but in Swift we just use quotation marks for strings. So that gives us:
let resultPredicate = NSPredicate(format: "name contains[c] %@", searchText)
And in fact that is exactly what we need here.
(Incidentally, you'll notice some of the other answers instead use a format string like "name contains[c] \(searchText)"
. That is not correct. That uses string interpolation, which is different from predicate formatting and will generally not work for this.)
The RemoveAll()
methods accept a Predicate<T>
delegate (until here nothing new). A predicate points to a method that simply returns true or false. Of course, the RemoveAll
will remove from the collection all the T
instances that return True with the predicate applied.
C# 3.0 lets the developer use several methods to pass a predicate to the RemoveAll
method (and not only this one…). You can use:
Lambda expressions
vehicles.RemoveAll(vehicle => vehicle.EnquiryID == 123);
Anonymous methods
vehicles.RemoveAll(delegate(Vehicle v) {
return v.EnquiryID == 123;
});
Normal methods
vehicles.RemoveAll(VehicleCustomPredicate);
private static bool
VehicleCustomPredicate (Vehicle v) {
return v.EnquiryID == 123;
}
FluentWait throws a NoSuchElementException is case of the confusion
org.openqa.selenium.NoSuchElementException;
with
java.util.NoSuchElementException
in
.ignoring(NoSuchElementException.class)
You could use a generator expression with a default value and then next
it:
next((x for x in seq if predicate(x)), None)
Although for this one-liner you need to be using Python >= 2.6.
This rather popular article further discusses this issue: Cleanest Python find-in-list function?.
A predicate is a function that returns a true/false (i.e. boolean) value, as opposed to a proposition which is a true/false (i.e. boolean) value. In Java, one cannot have standalone functions, and so one creates a predicate by creating an interface for an object that represents a predicate and then one provides a class that implements that interface. An example of an interface for a predicate might be:
public interface Predicate<ARGTYPE>
{
public boolean evaluate(ARGTYPE arg);
}
And then you might have an implementation such as:
public class Tautology<E> implements Predicate<E>
{
public boolean evaluate(E arg){
return true;
}
}
To get a better conceptual understanding, you might want to read about first-order logic.
Edit
There is a standard Predicate interface (java.util.function.Predicate) defined in the Java API as of Java 8. Prior to Java 8, you may find it convenient to reuse the com.google.common.base.Predicate interface from Guava.
Also, note that as of Java 8, it is much simpler to write predicates by using lambdas. For example, in Java 8 and higher, one can pass p -> true
to a function instead of defining a named Tautology subclass like the above.
Simply -> they provide True/False values based on condition mostly used for querying. mostly used with delegates
consider example of list
List<Program> blabla= new List<Program>();
blabla.Add(new Program("shubham", 1));
blabla.Add(new Program("google", 3));
blabla.Add(new Program("world",5));
blabla.Add(new Program("hello", 5));
blabla.Add(new Program("bye", 2));
contains names and ages. Now say we want to find names on condition So I Will use,
Predicate<Program> test = delegate (Program p) { return p.age > 3; };
List<Program> matches = blabla.FindAll(test);
Action<Program> print = Console.WriteLine;
matches.ForEach(print);
tried to Keep it Simple!
Predicate.not( … )
java-11 offers a new method Predicate#not
So you can negate the method reference:
Stream<String> s = ...;
long nonEmptyStrings = s.filter(Predicate.not(String::isEmpty)).count();
Predicate<T>
is a functional construct providing a convenient way of basically testing if something is true of a given T
object.
For example suppose I have a class:
class Person {
public string Name { get; set; }
public int Age { get; set; }
}
Now let's say I have a List<Person> people
and I want to know if there's anyone named Oscar in the list.
Without using a Predicate<Person>
(or Linq, or any of that fancy stuff), I could always accomplish this by doing the following:
Person oscar = null;
foreach (Person person in people) {
if (person.Name == "Oscar") {
oscar = person;
break;
}
}
if (oscar != null) {
// Oscar exists!
}
This is fine, but then let's say I want to check if there's a person named "Ruth"? Or a person whose age is 17?
Using a Predicate<Person>
, I can find these things using a LOT less code:
Predicate<Person> oscarFinder = (Person p) => { return p.Name == "Oscar"; };
Predicate<Person> ruthFinder = (Person p) => { return p.Name == "Ruth"; };
Predicate<Person> seventeenYearOldFinder = (Person p) => { return p.Age == 17; };
Person oscar = people.Find(oscarFinder);
Person ruth = people.Find(ruthFinder);
Person seventeenYearOld = people.Find(seventeenYearOldFinder);
Notice I said a lot less code, not a lot faster. A common misconception developers have is that if something takes one line, it must perform better than something that takes ten lines. But behind the scenes, the Find
method, which takes a Predicate<T>
, is just enumerating after all. The same is true for a lot of Linq's functionality.
So let's take a look at the specific code in your question:
Predicate<int> pre = delegate(int a){ return a % 2 == 0; };
Here we have a Predicate<int> pre
that takes an int a
and returns a % 2 == 0
. This is essentially testing for an even number. What that means is:
pre(1) == false;
pre(2) == true;
And so on. This also means, if you have a List<int> ints
and you want to find the first even number, you can just do this:
int firstEven = ints.Find(pre);
Of course, as with any other type that you can use in code, it's a good idea to give your variables descriptive names; so I would advise changing the above pre
to something like evenFinder
or isEven
-- something along those lines. Then the above code is a lot clearer:
int firstEven = ints.Find(evenFinder);
<span ng-if="verifyName.indicator == 1"><i class="fa fa-check"></i></span>
<span ng-if="verifyName.indicator == 0"><i class="fa fa-times"></i></span>
try this code. here verifyName.indicator value is coming from controller. this works for me.
Printing the STACK trace, logging it or send message to the user, are very bad ways to process the exceptions. Does any one can describe solutions to fix the exception in proper steps then can trying the broken instruction again?
$('#foo').children('div').length
How about this?
INSERT OR IGNORE INTO EVENTTYPE (EventTypeName) VALUES 'ANI Received'
(Untested as I don't have SQLite... however this link is quite descriptive.)
Additionally, this should also work:
INSERT INTO EVENTTYPE (EventTypeName)
SELECT 'ANI Received'
WHERE NOT EXISTS (SELECT 1 FROM EVENTTYPE WHERE EventTypeName = 'ANI Received');
You can get the attributes of an XML element by calling the attributes() function on an XML node. You can then var_dump the return value of the function.
More info at php.net http://php.net/simplexmlelement.attributes
Example code from that page:
$xml = simplexml_load_string($string);
foreach($xml->foo[0]->attributes() as $a => $b) {
echo $a,'="',$b,"\"\n";
}
Using the command "where git" find out how command prompt picks up the version. Once you have the path, you can go ahead and uninstall / delete previous version completely. Then if you install and make sure the new installed location is in the path, it should just work fine.
Using git-friendly tools like cmder will make your life much easier. You don't really have to use dual boot or cygwin anymore since the support for git in windows is already top-notch now. (Git for windows installs msysgit which includes all necessary unix tools from MinGW. MinGW has been there for a while and is pretty stable. If you want you can install the full version of msysgit rather than Git for Windows. msysgit is available on Git for windows page at the bottom.)
I had the same issue. What I did is to run mongodb
command in another terminal. Then, run my application in another tab. This resolved my problem. Though, I am trying other solution such as creating a script to run mongodb
before connection is made.
As Mitch mentioned, backing data up is the best method.
However, it maybe possible to extract the lost data partially depending on the situation or DB server used. For most part, you are out of luck if you don't have any backup.
Use double quote to enclose the quote or escape it.
newTemp = mystring.replace(/"/g, "'");
or
newTemp = mystring.replace(/"/g, '\'');
I already have this code handling well my cors situation in php:
header( 'Access-Control-Allow-Origin: '.CMSConfig::ALLOW_DOMAIN );
header( 'Access-Control-Allow-Headers: '.CMSConfig::ALLOW_DOMAIN );
header( 'Access-Control-Allow-Credentials: true' );
And it was working fine locally and remotely, but not for uploads when remote.
Something happen with apache/php OR my code, I didn't bother to search it, when you request OPTIONS it returns my header with cors rules but with 302 result. Therefore my browser doesn't recognise as an acceptable situation.
What I did, based on @Mark McDonald answer, is just put this code after my header:
if( $_SERVER['REQUEST_METHOD'] === 'OPTIONS' )
{
header("HTTP/1.1 202 Accepted");
exit;
}
Now, when requesting OPTIONS
it will just send the header and 202 result.
A) What do I not understand about how the Google Apps Script console works with respect to printing so that I can see if my code is accomplishing what I'd like?
The code on .gs files of a Google Apps Script project run on the server rather than on the web browser. The way to log messages was to use the Class Logger.
B) Is it a problem with the code?
As the error message said, the problem was that console
was not defined but nowadays the same code will throw other error:
ReferenceError: "playerArray" is not defined. (line 12, file "Code")
That is because the playerArray is defined as local variable. Moving the line out of the function will solve this.
var playerArray = [];
function addplayerstoArray(numplayers) {
for (i=0; i<numplayers; i++) {
playerArray.push(i);
}
}
addplayerstoArray(7);
console.log(playerArray[3])
Now that the code executes without throwing errors, instead to look at the browser console we should look at the Stackdriver Logging. From the Google Apps Script editor UI click on View > Stackdriver Logging.
On 2017 Google released to all scripts Stackdriver Logging and added the Class Console, so including something like console.log('Hello world!')
will not throw an error but the log will be on Google Cloud Platform Stackdriver Logging Service instead of the browser console.
From Google Apps Script Release Notes 2017
June 23, 2017
Stackdriver Logging has been moved out of Early Access. All scripts now have access to Stackdriver logging.
From Logging > Stackdriver logging
The following example shows how to use the console service to log information in Stackdriver.
function measuringExecutionTime() { // A simple INFO log message, using sprintf() formatting. console.info('Timing the %s function (%d arguments)', 'myFunction', 1); // Log a JSON object at a DEBUG level. The log is labeled // with the message string in the log viewer, and the JSON content // is displayed in the expanded log structure under "structPayload". var parameters = { isValid: true, content: 'some string', timestamp: new Date() }; console.log({message: 'Function Input', initialData: parameters}); var label = 'myFunction() time'; // Labels the timing log entry. console.time(label); // Starts the timer. try { myFunction(parameters); // Function to time. } catch (e) { // Logs an ERROR message. console.error('myFunction() yielded an error: ' + e); } console.timeEnd(label); // Stops the timer, logs execution duration. }
You have to dot source
them:
. .\build_funtions.ps1
. .\build_builddefs.ps1
Note the extra .
This heyscriptingguy
article should be of help - How to Reuse Windows PowerShell Functions in Scripts
$("#LeNomDeMaBaliseID").prop('id', 'LeNouveauNomDeMaBaliseID');
you can use the following command to list the process
ps aux | grep -c myProcessName
if you need to check the count of that process then run
ps aux | grep -c myProcessName |grep -v grep
after which you can kill the process using
kill -9 $(ps aux | grep -e myProcessName | awk '{ print $2 }')
It has already been answered, the best way work-around is to convert the Stored Procedure into an SQL Function or a View.
The short answer, just as mentioned above, is that you cannot directly JOIN a Stored Procedure in SQL, not unless you create another stored procedure or function using the stored procedure's output into a temporary table and JOINing the temporary table, as explained above.
I will answer this by converting your Stored Procedure into an SQL function and show you how to use it inside a query of your choice.
CREATE FUNCTION fnMyFunc()
RETURNS TABLE AS
RETURN
(
SELECT tenant.ID AS TenantID,
SUM(ISNULL(trans.Amount,0)) AS TenantBalance
FROM tblTenant tenant
LEFT JOIN tblTransaction trans ON tenant.ID = trans.TenantID
GROUP BY tenant.ID
)
Now to use that function, in your SQL...
SELECT t.TenantName,
t.CarPlateNumber,
t.CarColor,
t.Sex,
t.SSNO,
t.Phone,
t.Memo,
u.UnitNumber,
p.PropertyName
FROM tblTenant t
LEFT JOIN tblRentalUnit u ON t.UnitID = u.ID
LEFT JOIN tblProperty p ON u.PropertyID = p.ID
LEFT JOIN dbo.fnMyFunc() AS a
ON a.TenantID = t.TenantID
ORDER BY p.PropertyName, t.CarPlateNumber
If you wish to pass parameters into your function from within the above SQL, then I recommend you use CROSS APPLY
or CROSS OUTER APPLY
.
Read up on that here.
Cheers
For those using CanCan. People might be experiencing this if they use CanCan with Rails 4+. Try AntonTrapps's rather clean workaround solution here until CanCan gets updated:
In the ApplicationController
:
before_filter do
resource = controller_name.singularize.to_sym
method = "#{resource}_params"
params[resource] &&= send(method) if respond_to?(method, true)
end
and in the resource controller (for example NoteController):
private
def note_params
params.require(:note).permit(:what, :ever)
end
Update:
Here's a continuation project for CanCan called CanCanCan, which looks promising:
I usually go with varchar(255) (255 being the maximum length of a varchar type in MySQL).
You can also provide a negative number as an argument to the round
method to round to the nearest multiple of 10, 100 and so on.
# Round to the nearest multiple of 10.
12.3453.round(-1) # Output: 10
# Round to the nearest multiple of 100.
124.3453.round(-2) # Output: 100
python manage.py flush
deleted old db contents,
Don't forget to create new superuser:
python manage.py createsuperuser
I agree that a data structure like a List is the best way to go:
List<Integer> values = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
int value;
int numValues = 0;
do {
value = in.nextInt();
values.add(value);
} while (value >= 1) && (value <= 100);
Or you can just allocate an array of a max size and load values into it:
int maxValues = 100;
int [] values = new int[maxValues];
Scanner in = new Scanner(System.in);
int value;
int numValues = 0;
do {
value = in.nextInt();
values[numValues++] = value;
} while (value >= 1) && (value <= 100) && (numValues < maxValues);
buildup on nawfal 's answer.
when using his answer there was a missing variable aggrEx, I added it.
file ExceptionExtenstions.class:
// example usage:
// try{ ... } catch(Exception e) { MessageBox.Show(e.ToFormattedString()); }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YourNamespace
{
public static class ExceptionExtensions
{
public static IEnumerable<Exception> GetAllExceptions(this Exception exception)
{
yield return exception;
if (exception is AggregateException )
{
var aggrEx = exception as AggregateException;
foreach (Exception innerEx in aggrEx.InnerExceptions.SelectMany(e => e.GetAllExceptions()))
{
yield return innerEx;
}
}
else if (exception.InnerException != null)
{
foreach (Exception innerEx in exception.InnerException.GetAllExceptions())
{
yield return innerEx;
}
}
}
public static string ToFormattedString(this Exception exception)
{
IEnumerable<string> messages = exception
.GetAllExceptions()
.Where(e => !String.IsNullOrWhiteSpace(e.Message))
.Select(exceptionPart => exceptionPart.Message.Trim() + "\r\n" + (exceptionPart.StackTrace!=null? exceptionPart.StackTrace.Trim():"") );
string flattened = String.Join("\r\n\r\n", messages); // <-- the separator here
return flattened;
}
}
}
I think the simplest way to achieve your goal is this:
var str = 'asd-0.testing';
var regex = /(asd-)(\d)(\.\w+)/;
var anyNumber = 1;
var res = str.replace(regex, `$1${anyNumber}$3`);
Meanwhile you can use the isSameOrAfter
method:
moment('2010-10-20').isSameOrAfter('2010-10-20', 'day');
Use multibranch pipeline job type, not the plain pipeline job type. The multibranch pipeline jobs do posess the environment variable env.BRANCH_NAME
which describes the branch.
In my script..
stage('Build') {
node {
echo 'Pulling...' + env.BRANCH_NAME
checkout scm
}
}
Yields...
Pulling...master
@hexacyanide's answer is almost a complete one.
On Windows command prince
could be prince.exe
, prince.cmd
, prince.bat
or just prince
(I'm no aware of how gems are bundled, but npm bins come with a sh script and a batch script - npm
and npm.cmd
).
If you want to write a portable script that would run on Unix and Windows, you have to spawn the right executable.
Here is a simple yet portable spawn function:
function spawn(cmd, args, opt) {
var isWindows = /win/.test(process.platform);
if ( isWindows ) {
if ( !args ) args = [];
args.unshift(cmd);
args.unshift('/c');
cmd = process.env.comspec;
}
return child_process.spawn(cmd, args, opt);
}
var cmd = spawn("prince", ["-v", "builds/pdf/book.html", "-o", "builds/pdf/book.pdf"])
// Use these props to get execution results:
// cmd.stdin;
// cmd.stdout;
// cmd.stderr;
Here is another go at it .. Adding more to the accepted answer possibly more comprehensive .. of course switch -case will make it look for elegant.
function parseGeoLocationResults(result) {
const parsedResult = {}
const {address_components} = result;
for (var i = 0; i < address_components.length; i++) {
for (var b = 0; b < address_components[i].types.length; b++) {
if (address_components[i].types[b] == "street_number") {
//this is the object you are looking for
parsedResult.street_number = address_components[i].long_name;
break;
}
else if (address_components[i].types[b] == "route") {
//this is the object you are looking for
parsedResult.street_name = address_components[i].long_name;
break;
}
else if (address_components[i].types[b] == "sublocality_level_1") {
//this is the object you are looking for
parsedResult.sublocality_level_1 = address_components[i].long_name;
break;
}
else if (address_components[i].types[b] == "sublocality_level_2") {
//this is the object you are looking for
parsedResult.sublocality_level_2 = address_components[i].long_name;
break;
}
else if (address_components[i].types[b] == "sublocality_level_3") {
//this is the object you are looking for
parsedResult.sublocality_level_3 = address_components[i].long_name;
break;
}
else if (address_components[i].types[b] == "neighborhood") {
//this is the object you are looking for
parsedResult.neighborhood = address_components[i].long_name;
break;
}
else if (address_components[i].types[b] == "locality") {
//this is the object you are looking for
parsedResult.city = address_components[i].long_name;
break;
}
else if (address_components[i].types[b] == "administrative_area_level_1") {
//this is the object you are looking for
parsedResult.state = address_components[i].long_name;
break;
}
else if (address_components[i].types[b] == "postal_code") {
//this is the object you are looking for
parsedResult.zip = address_components[i].long_name;
break;
}
else if (address_components[i].types[b] == "country") {
//this is the object you are looking for
parsedResult.country = address_components[i].long_name;
break;
}
}
}
return parsedResult;
}
Go to "Manage Jenkins" > "Script Console" to run a script on your server to interrupt the hanging thread.
You can get all the live threads with Thread.getAllStackTraces()
and interrupt the one that's hanging.
Thread.getAllStackTraces().keySet().each() {
t -> if (t.getName()=="YOUR THREAD NAME" ) { t.interrupt(); }
}
UPDATE:
The above solution using threads may not work on more recent Jenkins versions. To interrupt frozen pipelines refer to this solution (by alexandru-bantiuc) instead and run:
Jenkins.instance.getItemByFullName("JobName")
.getBuildByNumber(JobNumber)
.finish(
hudson.model.Result.ABORTED,
new java.io.IOException("Aborting build")
);
public ActionResult CreatePerson(int id) //controller
window.location.href = '@Url.Action("CreatePerson", "Person")?id=' + id;
Or
var id = 'some value';
window.location.href = '@Url.Action("CreatePerson", "Person", new {id = id})';
There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.
Similarity::Similarity()
or Similarity::~Similarity()
are just missing and you have defined the others incorrectly,
void Similarity::readData(Scanner& inStream){
}
not
void readData(Scanner& inStream){
}
etc. etc.
The second one is a function called readData, only the first is the readData method of the Similarity class.
To be clear about this, in Similarity.h
void readData(Scanner& inStream);
but in Similarity.cpp
void Similarity::readData(Scanner& inStream){
}
I have also come across this need for my database project. I decided to share my findings here.
1) There is no way to a NOT NULL field without a default when data already exists (Can I add a not null column without DEFAULT value)
2) This topic has been addressed for a long time. Here is a 2008 question (Add a column with a default value to an existing table in SQL Server)
3) The DEFAULT constraint is used to provide a default value for a column. The default value will be added to all new records IF no other value is specified. (https://www.w3schools.com/sql/sql_default.asp)
4) The Visual Studio Database Project that I use for development is really good about generating change scripts for you. This is the change script created for my DB promotion:
GO
PRINT N'Altering [dbo].[PROD_WHSE_ACTUAL]...';
GO
ALTER TABLE [dbo].[PROD_WHSE_ACTUAL]
ADD [DATE] DATE DEFAULT getdate() NOT NULL;
-
Here are the steps I took to update my database using Visual Studio for development.
1) Add default value (Visual Studio SSDT: DB Project: table designer)
2) Use the Schema Comparison tool to generate the change script.
code already provided above
This is your code:
<?php
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "");
define("DB_DATABASE", "databasename");
$db = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
?>
The only error that causes this message is that:
DB_USER
but you're calling after as DB_USERNAME
.Please be more careful next time.
It is better for an entry-level programmer that wants to start coding in PHP
not to use what he or she does not know very well.
ONLY as advice, please try to use (for the first time) code more ubiquitous.
ex: do not use the define()
statement, try to use variables declaration as $db_user = 'root';
Have a nice experience :)
It is bad practice to perform network operations on the main thread, which is why you are seeing the NetworkOnMainThreadException
. It is prevented by the policy. If you really must do it for testing, put the following in your OnCreate:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Please remember that is is very bad practice to do this, and should ideally move your network code to an AsyncTask
or a Thread
.
Calling toDate will create a copy (the documentation is down-right wrong about it not being a copy), of the underlying JS Date object. JS Date object is stored in UTC and will always print to eastern time. Without getting into whether .utc() modifies the underlying object that moment wraps use the code below.
You don't need moment for this.
new Date().getTime()
This works, because JS Date at its core is in UTC from the Unix Epoch. It's extraordinarily confusing and I believe a big flaw in the interface to mix local and UTC times like this with no descriptions in the methods.
Here's a proof by induction, considering N
terms, but it's the same for N - 1
:
For N = 0
the formula is obviously true.
Suppose 1 + 2 + 3 + ... + N = N(N + 1) / 2
is true for some natural N
.
We'll prove 1 + 2 + 3 + ... + N + (N + 1) = (N + 1)(N + 2) / 2
is also true by using our previous assumption:
1 + 2 + 3 + ... + N + (N + 1) = (N(N + 1) / 2) + (N + 1)
= (N + 1)((N / 2) + 1)
= (N + 1)(N + 2) / 2
.
So the formula holds for all N
.
You may give a shot at using itoa. Another alternative is to use sprintf.
A bit shorter answer since PHP >= 5.3.0:
$csvFile = file('../somefile.csv');
$data = [];
foreach ($csvFile as $line) {
$data[] = str_getcsv($line);
}
I started coding pretty much the about the time Hungarian notation was invented and the first time I was forced to use it on a project I hated it.
After a while I realised that when it was done properly it did actually help and these days I love it.
But like all things good, it has to be learnt and understood and to do it properly takes time.
It worked for me:
Products.find({}).then(a => console.log(a.map(p => p.toJSON())))
also if you want use getters, you should add its option also (on defining schema):
new mongoose.Schema({...}, {toJSON: {getters: true}})
You need to check the keycloak admin console for fronted configuration. It must be wrongly configured for redirect url and web origins.
The Python reference manual includes several string literals that can be used in a string. These special sequences of characters are replaced by the intended meaning of the escape sequence.
Here is a table of some of the more useful escape sequences and a description of the output from them.
Escape Sequence Meaning
\t Tab
\\ Inserts a back slash (\)
\' Inserts a single quote (')
\" Inserts a double quote (")
\n Inserts a ASCII Linefeed (a new line)
Basic Example
If i wanted to print some data points separated by a tab space I could print this string.
DataString = "0\t12\t24"
print (DataString)
Returns
0 12 24
Example for Lists
Here is another example where we are printing the items of list and we want to sperate the items by a TAB.
DataPoints = [0,12,24]
print (str(DataPoints[0]) + "\t" + str(DataPoints[1]) + "\t" + str(DataPoints[2]))
Returns
0 12 24
Raw Strings
Note that raw strings (a string which include a prefix "r"), string literals will be ignored. This allows these special sequences of characters to be included in strings without being changed.
DataString = r"0\t12\t24"
print (DataString)
Returns
0\t12\t24
Which maybe an undesired output
String Lengths
It should also be noted that string literals are only one character in length.
DataString = "0\t12\t24"
print (len(DataString))
Returns
7
The raw string has a length of 9.
I didnt try Sumama Waheed's answer but what worked for me was replacing the bin/catalina.jar with a working jar (I disposed of an older tomcat) and after adding in NetBeans, I put the original catalina.jar again.
Suppose logical address space is **32 bit so total possible logical entries will be 2^32 and other hand suppose each page size is 4 byte then size of one page is *2^2*2^10=2^12...* now we know that no. of pages in page table is pages=total possible logical address entries/page size so pages=2^32/2^12 =2^20 Now suppose that each entry in page table takes 4 bytes then total size of page table in *physical memory will be=2^2*2^20=2^22=4mb***
Organize your files in hierarchical directories and then just use relative paths.
Demo:
HTML (index.html)
<a href='inner/file.html'>link</a>
Directory structure:
base/
base/index.html
base/inner/file.html
....
Based on my other post here, I have made a reusable directive.
Check out the GitHub repository
(function () {_x000D_
_x000D_
angular_x000D_
.module("checkbox-select", [])_x000D_
.directive("checkboxModel", ["$compile", function ($compile) {_x000D_
return {_x000D_
restrict: "A",_x000D_
link: function (scope, ele, attrs) {_x000D_
// Defining updateSelection function on the parent scope_x000D_
if (!scope.$parent.updateSelections) {_x000D_
// Using splice and push methods to make use of _x000D_
// the same "selections" object passed by reference to the _x000D_
// addOrRemove function as using "selections = []" _x000D_
// creates a new object within the scope of the _x000D_
// function which doesn't help in two way binding._x000D_
scope.$parent.updateSelections = function (selectedItems, item, isMultiple) {_x000D_
var itemIndex = selectedItems.indexOf(item)_x000D_
var isPresent = (itemIndex > -1)_x000D_
if (isMultiple) {_x000D_
if (isPresent) {_x000D_
selectedItems.splice(itemIndex, 1)_x000D_
} else {_x000D_
selectedItems.push(item)_x000D_
}_x000D_
} else {_x000D_
if (isPresent) {_x000D_
selectedItems.splice(0, 1)_x000D_
} else {_x000D_
selectedItems.splice(0, 1, item)_x000D_
}_x000D_
}_x000D_
} _x000D_
}_x000D_
_x000D_
// Adding or removing attributes_x000D_
ele.attr("ng-checked", attrs.checkboxModel + ".indexOf(" + attrs.checkboxValue + ") > -1")_x000D_
var multiple = attrs.multiple ? "true" : "false"_x000D_
ele.attr("ng-click", "updateSelections(" + [attrs.checkboxModel, attrs.checkboxValue, multiple].join(",") + ")")_x000D_
_x000D_
// Removing the checkbox-model attribute, _x000D_
// it will avoid recompiling the element infinitly_x000D_
ele.removeAttr("checkbox-model")_x000D_
ele.removeAttr("checkbox-value")_x000D_
ele.removeAttr("multiple")_x000D_
_x000D_
$compile(ele)(scope)_x000D_
}_x000D_
}_x000D_
}])_x000D_
_x000D_
// Defining app and controller_x000D_
angular_x000D_
.module("APP", ["checkbox-select"])_x000D_
.controller("demoCtrl", ["$scope", function ($scope) {_x000D_
var dc = this_x000D_
dc.list = [_x000D_
"selection1",_x000D_
"selection2",_x000D_
"selection3"_x000D_
]_x000D_
_x000D_
// Define the selections containers here_x000D_
dc.multipleSelections = []_x000D_
dc.individualSelections = []_x000D_
}])_x000D_
_x000D_
})()
_x000D_
label {_x000D_
display: block; _x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<link rel="stylesheet" href="style.css" />_x000D_
_x000D_
</head>_x000D_
_x000D_
<body ng-app="APP" ng-controller="demoCtrl as dc">_x000D_
<h1>checkbox-select demo</h1>_x000D_
_x000D_
<h4>Multiple Selections</h4>_x000D_
<label ng-repeat="thing in dc.list">_x000D_
<input type="checkbox" checkbox-model="dc.multipleSelections" checkbox-value="thing" multiple>_x000D_
{{thing}}_x000D_
</label>_x000D_
<p>dc.multipleSelecitons:- {{dc.multipleSelections}}</p>_x000D_
_x000D_
<h4>Individual Selections</h4>_x000D_
<label ng-repeat="thing in dc.list">_x000D_
<input type="checkbox" checkbox-model="dc.individualSelections" checkbox-value="thing">_x000D_
{{thing}}_x000D_
</label>_x000D_
<p>dc.individualSelecitons:- {{dc.individualSelections}}</p>_x000D_
_x000D_
<script data-require="[email protected]" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>_x000D_
<script data-require="[email protected]" data-semver="1.5.6" src="https://code.angularjs.org/1.5.6/angular.min.js"></script>_x000D_
<script src="script.js"></script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Since 7-zip version 9.25 alpha there is a new -spf
switch that can be used to store the full file paths including drive letter to the archive.
7zG.exe a -spf c:\BAckup\backup.zip @c:\temp\tmpFileList.txt
should be working just fine now.
To emphasize a point made by @MatteoItalia, the efficiency difference is where the data is stored. Heap memory (required with vector
) requires a call to the system to allocate memory and this can be expensive if you are counting cycles. Stack memory (possible for array
) is virtually "zero-overhead" in terms of time, because the memory is allocated by just adjusting the stack pointer and it is done just once on entry to a function. The stack also avoids memory fragmentation. To be sure, std::array
won't always be on the stack; it depends on where you allocate it, but it will still involve one less memory allocation from the heap compared to vector. If you have a
definitely use a std::array
over a vector. If any of those requirements is not true, then use a std::vector
.
Another option is to put all of the fields that you want on a single line within a single form-group
.
<form class="form-horizontal">
<div class="form-group">
<label for="name" class="col-xs-2 control-label">Name</label>
<div class="col-xs-10">
<input type="text" class="form-control col-sm-10" name="name" placeholder="name"/>
</div>
</div>
<div class="form-group">
<label for="birthday" class="col-xs-3 col-sm-2 control-label">Birthday</label>
<div class="col-xs-3">
<input type="text" class="form-control" placeholder="year"/>
</div>
<div class="col-xs-3">
<input type="text" class="form-control" placeholder="month"/>
</div>
<div class="col-xs-3">
<input type="text" class="form-control" placeholder="day"/>
</div>
</div>
</form>
You could do:
var numberOfChecked = $('input:checkbox:checked').length;
var totalCheckboxes = $('input:checkbox').length;
var numberNotChecked = totalCheckboxes - numberOfChecked;
EDIT
Or even simple
var numberNotChecked = $('input:checkbox:not(":checked")').length;
If your dictionaries are deeply nested and if they contain different types of collections, you could convert them to json string and compare.
import json
match = (json.dumps(dict1) == json.dumps(dict2))
caveat- this solution may not work if your dictionaries have binary strings in the values as this is not json serializable
You need to escape the backslash \
:
println yourString.replace("\\", "/")
If you call printStackTrace()
on an exception the trace is written to System.err
and it's hard to route it elsewhere (or filter it). Instead of doing this you are adviced to use a logging framework (or a wrapper around multiple logging frameworks, like Apache Commons Logging) and log the exception using that framework (e.g. logger.error("some exception message", e)
).
Doing that allows you to:
On Ubuntu Server 16, I have the same problem with python27. Try this:
Change
from pip import main
if __name__ == '__main__':
sys.exit(main())
To
from pip._internal import main
if __name__ == '__main__':
sys.exit(main())
To read a line from a file, you should use the fgets
function: It reads a string from the specified file up to either a newline character or EOF
.
The use of sscanf
in your code would not work at all, as you use filename
as your format string for reading from line
into a constant string literal %s
.
The reason for SEGV is that you write into the non-allocated memory pointed to by line
.
To be more C# like, define the Nullable
type like this:
type Nullable<T> = T | null;
interface Employee{
id: number;
name: string;
salary: Nullable<number>;
}
Bonus:
To make Nullable
behave like a built in Typescript type, define it in a global.d.ts
definition file in the root source folder. This path worked for me: /src/global.d.ts
You may need to call frame.repaint()
as well to force the frame to actually redraw itself. I've had issues before where I tried to repaint a component and it wasn't updating what was displayed until the parent's repaint() method was called.
Both CopyTo() and Clone() make shallow copy. Clone() method makes a clone of the original array. It returns an exact length array.
On the other hand, CopyTo() copies the elements from the original array to the destination array starting at the specified destination array index. Note that, this adds elements to an already existing array.
The following code will contradict the postings saying that CopyTo() makes a deep copy:
public class Test
{
public string s;
}
// Write Main() method and within it call test()
private void test()
{
Test[] array = new Test[1];
array[0] = new Test();
array[0].s = "ORIGINAL";
Test[] copy = new Test[1];
array.CopyTo(copy, 0);
// Next line displays "ORIGINAL"
MessageBox.Show("array[0].s = " + array[0].s);
copy[0].s = "CHANGED";
// Next line displays "CHANGED", showing that
// changing the copy also changes the original.
MessageBox.Show("array[0].s = " + array[0].s);
}
Let me explain it a bit. If the elements of the array are of reference types, then the copy (both for Clone() and CopyTo()) will be made upto the first(top) level. But the lower level doesn't get copied. If we need copy of lower level also, we have to do it explicitly. That's why after Cloning or Copying of reference type elements, each element in the Cloned or Copied array refers to the same memory location as referred by the corresponding element in the original array. This clearly indicates that no separate instance is created for lower level. And if it were so then changing the value of any element in the Copied or Cloned array would not have effect in the corresponding element of the original array.
I think that my explanation is exhaustive but I found no other way to make it understandable.
Yes, the space is usually encoded to "%20" though. Any parameters that pass to a URL should be encoded, simply for safety reasons.
Match against one class that has whitespace.
<div class="hello "></div>
//div[normalize-space(@class)="hello"]
The vertical-align attribute is for inline elements only. It will have no effect on block level elements, like a div. Also text-top only moves the text to the top of the current font size. If you would like to vertically align an inline element to the top just use this.
vertical-align: top;
The paragraph tag is not outdated. Also, the vertical-align attribute applied to a span element may not display as intended in some mozilla browsers.
You can also load the content with cURL, if file_get_contents insn't enabled on your server.
Example:
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,"http://feeds.bbci.co.uk/sport/0/football/rss.xml?edition=int");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$output = curl_exec($ch);
curl_close($ch);
$items = simplexml_load_string($output);
Node.js doesn't enforce any file naming conventions (except index.js
). And the Javascript language in general doesn't either. You can find dozens of threads here which suggest camelCase, hyphens and underscores, any of which work perfectly well. So its up to you. Choose one and stick with it.
The answers that suggest git pull
or git fetch
are correct.
The message is generated when git status
sees a difference between .git/FETCH_HEAD
and .git/refs/remotes/<repository>/<branch>
(e.g. .git/refs/remotes/origin/master
).
The latter file records the HEAD from the last fetch (for the repository/branch). Doing git fetch
updates both files to the branch's current HEAD.
Of course if there is nothing to fetch (because the local repository is already up-to-date) then .git/FETCH_HEAD
doesn't change.
you can do something like that:
where regexp_like(name, 'string$', 'i');
<script type="text/javascript">
$(document).ready(function() {
var asdf = $('.capsf').text();
$('.capsf').text(asdf.toLowerCase());
});
</script>
<div style="text-transform: capitalize;" class="capsf">sd GJHGJ GJHgjh gh hghhjk ku</div>
In order to initially set up any Git server, you have to export an existing repository into a new bare repository — a repository that doesn’t contain a working directory. This is generally straightforward to do. In order to clone your repository to create a new bare repository, you run the clone command with the --bare
option. By convention, bare repository directories end in .git
, like so:
$ git clone --bare my_project my_project.git
Initialized empty Git repository in /opt/projects/my_project.git/
This command takes the Git repository by itself, without a working directory, and creates a directory specifically for it alone.
Now that you have a bare copy of your repository, all you need to do is put it on a server and set up your protocols. Let’s say you’ve set up a server called git.example.com
that you have SSH access to, and you want to store all your Git repositories under the /opt/git
directory. You can set up your new repository by copying your bare repository over:
$ scp -r my_project.git [email protected]:/opt/git
At this point, other users who have SSH access to the same server which has read-access to the /opt/git
directory can clone your repository by running
$ git clone [email protected]:/opt/git/my_project.git
If a user SSHs into a server and has write access to the /opt/git/my_project.git
directory, they will also automatically have push access. Git will automatically add group write permissions to a repository properly if you run the git init command with the --shared
option.
$ ssh [email protected]
$ cd /opt/git/my_project.git
$ git init --bare --shared
It is very easy to take a Git repository, create a bare version, and place it on a server to which you and your collaborators have SSH access. Now you’re ready to collaborate on the same project.
If you want something lightweight (jar size ~ 20 kb) and simple to use, you can try argument-parser. It can be used in most of the use cases, supports specifying arrays in the argument and has no dependency on any other library. It works for Java 1.5 or above. Below excerpt shows an example on how to use it:
public static void main(String[] args) {
String usage = "--day|-d day --mon|-m month [--year|-y year][--dir|-ds directoriesToSearch]";
ArgumentParser argParser = new ArgumentParser(usage, InputData.class);
InputData inputData = (InputData) argParser.parse(args);
showData(inputData);
new StatsGenerator().generateStats(inputData);
}
More examples can be found here
I think you need WaitHandler.WaitAll. Here is an example:
public static void Main(string[] args)
{
int numOfThreads = 10;
WaitHandle[] waitHandles = new WaitHandle[numOfThreads];
for (int i = 0; i < numOfThreads; i++)
{
var j = i;
// Or you can use AutoResetEvent/ManualResetEvent
var handle = new EventWaitHandle(false, EventResetMode.ManualReset);
var thread = new Thread(() =>
{
Thread.Sleep(j * 1000);
Console.WriteLine("Thread{0} exits", j);
handle.Set();
});
waitHandles[j] = handle;
thread.Start();
}
WaitHandle.WaitAll(waitHandles);
Console.WriteLine("Main thread exits");
Console.Read();
}
FCL has a few more convenient functions.
(1) Task.WaitAll, as well as its overloads, when you want to do some tasks in parallel (and with no return values).
var tasks = new[]
{
Task.Factory.StartNew(() => DoSomething1()),
Task.Factory.StartNew(() => DoSomething2()),
Task.Factory.StartNew(() => DoSomething3())
};
Task.WaitAll(tasks);
(2) Task.WhenAll when you want to do some tasks with return values. It performs the operations and puts the results in an array. It's thread-safe, and you don't need to using a thread-safe container and implement the add operation yourself.
var tasks = new[]
{
Task.Factory.StartNew(() => GetSomething1()),
Task.Factory.StartNew(() => GetSomething2()),
Task.Factory.StartNew(() => GetSomething3())
};
var things = Task.WhenAll(tasks);
To check if an object o
is a string type of a subclass of a string type:
isinstance(o, basestring)
because both str
and unicode
are subclasses of basestring
.
To check if the type of o
is exactly str
:
type(o) is str
To check if o
is an instance of str
or any subclass of str
:
isinstance(o, str)
The above also work for Unicode strings if you replace str
with unicode
.
However, you may not need to do explicit type checking at all. "Duck typing" may fit your needs. See http://docs.python.org/glossary.html#term-duck-typing.
See also What’s the canonical way to check for type in python?
You can also do that by :sus
to fall into shell and back by fg
.
You have to cast the selected item to your custom class (ComboboxItem) Try this:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cmb = (ComboBox)sender;
int selectedIndex = cmb.SelectedIndex;
string selectedText = this.comboBox1.Text;
string selectedValue = ((ComboboxItem)cmb.SelectedItem).Value.ToString();
ComboboxItem selectedCar = (ComboboxItem)cmb.SelectedItem;
MessageBox.Show(String.Format("Index: [{0}] CarName={1}; Value={2}", selectedIndex, selectedCar.Text, selecteVal));
}
Change CI index.php file to:
if ($_SERVER['SERVER_NAME'] == 'local_server_name') {
define('ENVIRONMENT', 'development');
} else {
define('ENVIRONMENT', 'production');
}
if (defined('ENVIRONMENT')){
switch (ENVIRONMENT){
case 'development':
error_reporting(E_ALL);
break;
case 'testing':
case 'production':
error_reporting(0);
break;
default:
exit('The application environment is not set correctly.');
}
}
IF PHP errors are off, but any MySQL errors are still going to show, turn these off in the /config/database.php file. Set the db_debug option to false:
$db['default']['db_debug'] = FALSE;
Also, you can use active_group as development and production to match the environment https://www.codeigniter.com/user_guide/database/configuration.html
$active_group = 'development';
$db['development']['hostname'] = 'localhost';
$db['development']['username'] = '---';
$db['development']['password'] = '---';
$db['development']['database'] = '---';
$db['development']['dbdriver'] = 'mysql';
$db['development']['dbprefix'] = '';
$db['development']['pconnect'] = TRUE;
$db['development']['db_debug'] = TRUE;
$db['development']['cache_on'] = FALSE;
$db['development']['cachedir'] = '';
$db['development']['char_set'] = 'utf8';
$db['development']['dbcollat'] = 'utf8_general_ci';
$db['development']['swap_pre'] = '';
$db['development']['autoinit'] = TRUE;
$db['development']['stricton'] = FALSE;
$db['production']['hostname'] = 'localhost';
$db['production']['username'] = '---';
$db['production']['password'] = '---';
$db['production']['database'] = '---';
$db['production']['dbdriver'] = 'mysql';
$db['production']['dbprefix'] = '';
$db['production']['pconnect'] = TRUE;
$db['production']['db_debug'] = FALSE;
$db['production']['cache_on'] = FALSE;
$db['production']['cachedir'] = '';
$db['production']['char_set'] = 'utf8';
$db['production']['dbcollat'] = 'utf8_general_ci';
$db['production']['swap_pre'] = '';
$db['production']['autoinit'] = TRUE;
$db['production']['stricton'] = FALSE;
You could use Role Strategy plugin for that purpose. It works like a charm, just setup some roles and assign them. Even on project-specific level.
I was having the same problem. That's what i tried and it works. I am sharing my xml and java code. Hope this will help someone.
Here is the xml
<?xml version="1.0" encoding="utf-8"?>
< NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/iv_thumbnail"
android:layout_width="match_parent"
android:layout_height="200dp" />
<TextView
android:id="@+id/tv_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Description" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Buy" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Reviews" />
<android.support.v7.widget.RecyclerView
android:id="@+id/rc_reviews"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
</NestedScrollView >
Here is the related java code. It works like a charm.
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setNestedScrollingEnabled(false);
The problem is the indexing subplot
is using. Subplots are counted starting with 1!
Your code thus needs to read
fig=plt.figure(figsize=(15, 6),facecolor='w', edgecolor='k')
for i in range(10):
#this part is just arranging the data for contourf
ind2 = py.find(zz==i+1)
sfr_mass_mat = np.reshape(sfr_mass[ind2],(pixmax_x,pixmax_y))
sfr_mass_sub = sfr_mass[ind2]
zi = griddata(massloclist, sfrloclist, sfr_mass_sub,xi,yi,interp='nn')
temp = 251+i # this is to index the position of the subplot
ax=plt.subplot(temp)
ax.contourf(xi,yi,zi,5,cmap=plt.cm.Oranges)
plt.subplots_adjust(hspace = .5,wspace=.001)
#just annotating where each contour plot is being placed
ax.set_title(str(temp))
Note the change in the line where you calculate temp
Also, one things that may help to understand:
math.js
this.add = function (a, b) {
return a + b;
};
client.js
var math = require('./math');
console.log(math.add(2,2); // 4;
Great, in this case:
console.log(this === module.exports); // true
console.log(this === exports); // true
console.log(module.exports === exports); // true
Thus, by default, "this" is actually equals to module.exports.
However, if you change your implementation to:
math.js
var add = function (a, b) {
return a + b;
};
module.exports = {
add: add
};
In this case, it will work fine, however, "this" is not equal to module.exports anymore, because a new object was created.
console.log(this === module.exports); // false
console.log(this === exports); // true
console.log(module.exports === exports); // false
And now, what will be returned by the require is what was defined inside the module.exports, not this or exports, anymore.
Another way to do it would be:
math.js
module.exports.add = function (a, b) {
return a + b;
};
Or:
math.js
exports.add = function (a, b) {
return a + b;
};
Unlike C/C++ Long in Python have unlimited precision. Refer the section Numeric Types in python for more information.To determine the max value of integer you can just refer sys.maxint
. You can get more details from the documentation of sys.
Just using strings, for me is a good solution, less problems with mysql. Detects the current format and changes it if necessary, this solution is only for spanish/french format and english format, without use php datetime function.
class dateTranslator {
public static function translate($date, $lang) {
$divider = '';
if (empty($date)){
return null;
}
if (strpos($date, '-') !== false) {
$divider = '-';
} else if (strpos($date, '/') !== false) {
$divider = '/';
}
//spanish format DD/MM/YYYY hh:mm
if (strcmp($lang, 'es') == 0) {
$type = explode($divider, $date)[0];
if (strlen($type) == 4) {
$date = self::reverseDate($date,$divider);
}
if (strcmp($divider, '-') == 0) {
$date = str_replace("-", "/", $date);
}
//english format YYYY-MM-DD hh:mm
} else {
$type = explode($divider, $date)[0];
if (strlen($type) == 2) {
$date = self::reverseDate($date,$divider);
}
if (strcmp($divider, '/') == 0) {
$date = str_replace("/", "-", $date);
}
}
return $date;
}
public static function reverseDate($date) {
$date2 = explode(' ', $date);
if (count($date2) == 2) {
$date = implode("-", array_reverse(preg_split("/\D/", $date2[0]))) . ' ' . $date2[1];
} else {
$date = implode("-", array_reverse(preg_split("/\D/", $date)));
}
return $date;
}
USE
dateTranslator::translate($date, 'en')
Set the max allowed packet size using MySql Workbench and restart the server
found a paper at: http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1924044 that suggests a formula to calculate the downloads:
d_iPad=13,516*rank^(-0.903)
d_iPhone=52,958*rank^(-0.944)
e.g. you're using php and $filepath contains pdf file path.
so you can write javascript like to to emulate download dialog box.
<script language="javascript">
window.location.href = '<?php echo $filepath; ?>';
</script
Above code sends browser to pdf file by its url "http://www.domain.com/files/filename.pdf". So at last, browser will show download dialog box to where to save this file on your machine.
In my case, my xml had multiple namespaces and attributes. So I used this site to generate the objects - https://xmltocsharp.azurewebsites.net/
And used the below code to deserialize
XmlDocument doc = new XmlDocument();
doc.Load("PathTo.xml");
User obj;
using (TextReader textReader = new StringReader(doc.OuterXml))
{
using (XmlTextReader reader = new XmlTextReader(textReader))
{
XmlSerializer serializer = new XmlSerializer(typeof(User));
obj = (User)serializer.Deserialize(reader);
}
}
var dt = new Date();
dt.getFullYear() + "/" + (dt.getMonth() + 1) + "/" + dt.getDate();
Since month index are 0 based you have to increment it by 1.
Edit
For a complete list of date object functions see
getMonth()
Returns the month (0-11) in the specified date according to local time.
getUTCMonth()
Returns the month (0-11) in the specified date according to universal time.
<% %>
executes the code in there but does not print the result, for eg:
We can use it for if else in an erb file.
<% temp = 1 %>
<% if temp == 1%>
temp is 1
<% else %>
temp is not 1
<%end%>
Will print temp is 1
<%= %>
executes the code and also prints the output, for eg:
We can print the value of a rails variable.
<% temp = 1 %>
<%= temp %>
Will print 1
<% -%>
It makes no difference as it does not print anything, -%>
only makes sense with <%= -%>
, this will avoid a new line.
<%# %>
will comment out the code written within this.
I figured there's no way except going into the file system to find out if text.txt is a directory or just a file. If you wanted something simple, maybe you can just use:
s.Substring(s.LastIndexOf(@"\"));
.html always for new files. .htm is a throwback to dos days.
I Would suggest the following:
var="any given string"
N=${#var}
G=${var//g/}
G=${#G}
(( G = N - G ))
echo "$G"
No call to any other program
You could use lists()
:
test::where('id' ,'>' ,0)->lists('id')->toArray();
NOTE : Better if you define your models in Studly Case
format, e.g Test
.
You could also use get()
:
test::where('id' ,'>' ,0)->get('id');
UPDATE: (For versions >= 5.2)
The lists()
method was deprecated in the new versions >= 5.2
, now you could use pluck()
method instead :
test::where('id' ,'>' ,0)->pluck('id')->toArray();
NOTE: If you need a string, for example in a blade, you can use function without the toArray() part, like:
test::where('id' ,'>' ,0)->pluck('id');
You can also use functions with $filter('filter')
:
var foo = $filter('filter')($scope.results.subjects, function (item) {
return item.grade !== 'A';
});
Waking up a dead question here but the answers provided will not work with jdk 7 (I read somewhere that a bug is open for this for Oracle Engineers but not fixed yet). Along with the link that @Ryan provided, you will have to also add :
System.setProperty("jsse.enableSNIExtension", "false");
(Courtesy to many stackoverflow answers combined together to figure this out)
The complete code will look as follows which worked for me (without setting the system property the Client Config did not work for me):
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.client.urlconnection.HTTPSProperties;
public class ClientHelper
{
public static ClientConfig configureClient()
{
System.setProperty("jsse.enableSNIExtension", "false");
TrustManager[] certs = new TrustManager[]
{
new X509TrustManager()
{
@Override
public X509Certificate[] getAcceptedIssuers()
{
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException
{
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException
{
}
}
};
SSLContext ctx = null;
try
{
ctx = SSLContext.getInstance("SSL");
ctx.init(null, certs, new SecureRandom());
}
catch (java.security.GeneralSecurityException ex)
{
}
HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
ClientConfig config = new DefaultClientConfig();
try
{
config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(
new HostnameVerifier()
{
@Override
public boolean verify(String hostname, SSLSession session)
{
return true;
}
},
ctx));
}
catch (Exception e)
{
}
return config;
}
public static Client createClient()
{
return Client.create(ClientHelper.configureClient());
}
This solution worked for me:
tabBarOptions: {
showIcon: true,
showLabel: false,
style: {
backgroundColor: '#000',
borderTopLeftRadius: 40,
borderTopRightRadius: 40,
position: 'relative',
zIndex: 2,
marginTop: -48
}
}
The answer posted by Craig White has a big performance penalty
SELECT * FROM `table` WHERE BINARY `column` = 'value'
because it doesn't use indexes. So, either you need to change the table collation like mention here https://dev.mysql.com/doc/refman/5.7/en/case-sensitivity.html.
OR
Easiest fix, you should use a BINARY of value.
SELECT * FROM `table` WHERE `column` = BINARY 'value'
E.g.
mysql> EXPLAIN SELECT * FROM temp1 WHERE BINARY col1 = "ABC" AND col2 = "DEF" ;
+----+-------------+--------+------+---------------+------+---------+------+--------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+--------+------+---------------+------+---------+------+--------+-------------+
| 1 | SIMPLE | temp1 | ALL | NULL | NULL | NULL | NULL | 190543 | Using where |
+----+-------------+--------+------+---------------+------+---------+------+--------+-------------+
VS
mysql> EXPLAIN SELECT * FROM temp1 WHERE col1 = BINARY "ABC" AND col2 = "DEF" ;
+----+-------------+-------+-------+---------------+---------------+---------+------+------+------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+-------+---------------+---------------+---------+------+------+------------------------------------+
| 1 | SIMPLE | temp1 | range | col1_2e9e898e | col1_2e9e898e | 93 | NULL | 2 | Using index condition; Using where |
+----+-------------+-------+-------+---------------+---------------+---------+------+------+------------------------------------+
enter code here
1 row in set (0.00 sec)
you can make that using transform and transform origins.
Combining various transfroms gives similar result. I hope you find it helpful. :) See these examples for simpler transforms. this has left point :
div { _x000D_
width: 300px;_x000D_
height:200px;_x000D_
background-image: url('data:image/gif;base64,R0lGODdhLAHIANUAAKqqqgAAAO7u7uXl5bKysru7u93d3czMzMPDw9TU1BUVFdDQ0B0dHaurqywsLHJyclVVVTc3N5SUlBkZGcHBwRYWFmpqasjIyDAwMJubm39/fyoqKhcXF4qKikJCQnd3d0ZGRhoaGoWFhV1dXVlZWZ+fn7m5uT8/Py4uLqWlpWFhYUlJSTMzM4+Pj25ubkxMTBgYGBwcHG9vbwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAALAHIAAAG/kCAcEgsGo/IpHLJbDqf0Kh0Sq1ar9isdsvter/gsHhMLpvP6LR6zW673/C4fE6v2+/4vH7P7/v/gIGCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnp+goaKjpKWmp6ipqqusra6vsLGys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNzs/Q0dLT1NXW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8AAwocSLCgwYMIEypcyLChw4cQI0qcSLGixYsYM2rcyLGjx48gQ4ocSbKkyZMoU6pcybKlS3gBYsZUIESDggAKLBCxiVOn/hQNG2JCKMIz55CiPlUKWLqAQQMAEjg0ENAggAYhUadWvRoFhIsFC14kzUrVKlSpZbmydPCgAAAPbQEU+ABCCFy3c+tGSXCAAIEEMIbclUv3bdy8LSFEOCAkBIEhBEI0fiwkspETajWcSCIhxhDHkCWDrix5pYQJFIYEoAwgQwAhq4e4NpIAhQSoKBIkkTEUNuvZsYXMXukgQAWfryEnT16ZOZEUDiQ4SJ0EhgnVRAi8dq6dpQEBFzDoDHAbOwDyRJwPKdAhQAfWRiBAYI0ee33YLglQeM1AxBAJDAjR338BHqECCSskocEE1w0xIFYBPghVgS1lECAEIwxBQm8Y+WrYG1EsJGCBWkRkBV+HQmwIAIoAqNiSBg48VYJZCzY441U1GhFVagfYZoQDLbhFxI0A5EhkjioFFQAHHeAV1ZINUFbAk1LBZ1cLlKXgQRFKyrQelVHKBaaVJn0nwAAIDIHAAGcKKcSabR6RQJpCFKAbEWYuJQARcA7gZp9uviTooIQWauihiCaq6KKMNuroo5BGKumklFZq6aWYZqrpppx26umnoIYq6qiklmrqqaimquqqrLbq6quwxirrrLTWauutuOaq66689urrr8AGK+ywxBZr7LHIJqvsssw26+yz0EYr7bTUVmvttdhmq+223Hbr7bfghhtPEAA7');_x000D_
-webkit-transform: perspective(300px) rotateX(-30deg);_x000D_
-o-transform: perspective(300px) rotateX(-30deg);_x000D_
-moz-transform: perspective(300px) rotateX(-30deg);_x000D_
-webkit-transform-origin: 100% 50%;_x000D_
-moz-transform-origin: 100% 50%;_x000D_
-o-transform-origin: 100% 50%;_x000D_
transform-origin: 100% 50%;_x000D_
margin: 10px 90px;_x000D_
}
_x000D_
<div></div>
_x000D_
This has right skew point :
div { _x000D_
width: 300px;_x000D_
height:200px;_x000D_
background-image: url('data:image/gif;base64,R0lGODdhLAHIANUAAKqqqgAAAO7u7uXl5bKysru7u93d3czMzMPDw9TU1BUVFdDQ0B0dHaurqywsLHJyclVVVTc3N5SUlBkZGcHBwRYWFmpqasjIyDAwMJubm39/fyoqKhcXF4qKikJCQnd3d0ZGRhoaGoWFhV1dXVlZWZ+fn7m5uT8/Py4uLqWlpWFhYUlJSTMzM4+Pj25ubkxMTBgYGBwcHG9vbwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAALAHIAAAG/kCAcEgsGo/IpHLJbDqf0Kh0Sq1ar9isdsvter/gsHhMLpvP6LR6zW673/C4fE6v2+/4vH7P7/v/gIGCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnp+goaKjpKWmp6ipqqusra6vsLGys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNzs/Q0dLT1NXW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8AAwocSLCgwYMIEypcyLChw4cQI0qcSLGixYsYM2rcyLGjx48gQ4ocSbKkyZMoU6pcybKlS3gBYsZUIESDggAKLBCxiVOn/hQNG2JCKMIz55CiPlUKWLqAQQMAEjg0ENAggAYhUadWvRoFhIsFC14kzUrVKlSpZbmydPCgAAAPbQEU+ABCCFy3c+tGSXCAAIEEMIbclUv3bdy8LSFEOCAkBIEhBEI0fiwkspETajWcSCIhxhDHkCWDrix5pYQJFIYEoAwgQwAhq4e4NpIAhQSoKBIkkTEUNuvZsYXMXukgQAWfryEnT16ZOZEUDiQ4SJ0EhgnVRAi8dq6dpQEBFzDoDHAbOwDyRJwPKdAhQAfWRiBAYI0ee33YLglQeM1AxBAJDAjR338BHqECCSskocEE1w0xIFYBPghVgS1lECAEIwxBQm8Y+WrYG1EsJGCBWkRkBV+HQmwIAIoAqNiSBg48VYJZCzY441U1GhFVagfYZoQDLbhFxI0A5EhkjioFFQAHHeAV1ZINUFbAk1LBZ1cLlKXgQRFKyrQelVHKBaaVJn0nwAAIDIHAAGcKKcSabR6RQJpCFKAbEWYuJQARcA7gZp9uviTooIQWauihiCaq6KKMNuroo5BGKumklFZq6aWYZqrpppx26umnoIYq6qiklmrqqaimquqqrLbq6quwxirrrLTWauutuOaq66689urrr8AGK+ywxBZr7LHIJqvsssw26+yz0EYr7bTUVmvttdhmq+223Hbr7bfghhtPEAA7');_x000D_
-webkit-transform: perspective(300px) rotateX(-30deg);_x000D_
-o-transform: perspective(300px) rotateX(-30deg);_x000D_
-moz-transform: perspective(300px) rotateX(-30deg);_x000D_
-webkit-transform-origin: 0% 50%;_x000D_
-moz-transform-origin: 0% 50%;_x000D_
-o-transform-origin: 0% 50%;_x000D_
transform-origin: 0% 50%;_x000D_
margin: 10px 90px;_x000D_
}
_x000D_
<div></div>
_x000D_
what transform: 0% 50%;
does is it sets the origin to vertical middle and horizontal left of the element. so the perspective is not visible at the left part of the image, so it looks flat. Perspective effect is there at the right part, so it looks slanted.
Just putting .encode('utf-8')
at the end of object will do the job in recent versions of Python.
I believe in Oracle it means order by column #1
The slidingExpiration=true value is basically saying that after every request made, the timer is reset and as long as the user makes a request within the timeout value, he will continue to be authenticated.
This is not correct. The authentication cookie timeout will only be reset if half the time of the timeout has passed.
See for example https://support.microsoft.com/de-ch/kb/910439/en-us or https://itworksonmymachine.wordpress.com/2008/07/17/forms-authentication-timeout-vs-session-timeout/
Here is a manual way to do git remote set-url origin [new repo URL]
:
git clone <old remote>
Open <repository>/.git/config
$ git config -e
[core]
repositoryformatversion = 0
filemode = false
bare = false
logallrefupdates = true
symlinks = false
ignorecase = true
[remote "origin"]
url = <old remote>
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
remote = origin
merge = refs/heads/master
and change the remote (the url option)
[remote "origin"]
url = <new remote>
fetch = +refs/heads/*:refs/remotes/origin/*
Push the repository to GitHub: git push
You can also use both/multiple remotes.
There is a simple but practical solution.
As DSM said, tuples are immutable, but we know Lists are mutable. So if you change a tuple to a list, it will be mutable. Then you can delete the items by the condition, then after changing the type to a tuple again. That’s it.
Please look at the codes below:
tuplex = list(tuplex)
for x in tuplex:
if (condition):
tuplex.pop(tuplex.index(x))
tuplex = tuple(tuplex)
print(tuplex)
For example, the following procedure will delete all even numbers from a given tuple.
tuplex = (1, 2, 3, 4, 5, 6, 7, 8, 9)
tuplex = list(tuplex)
for x in tuplex:
if (x % 2 == 0):
tuplex.pop(tuplex.index(x))
tuplex = tuple(tuplex)
print(tuplex)
if you test the type of the last tuplex, you will find it is a tuple.
Finally, if you want to define an index counter as you did (i.e., n), you should initialize it before the loop, not in the loop.
select A, B, 'c' as C
from MyTable
The usual way to test for a NaN is to see if it's equal to itself:
def isNaN(num):
return num != num
Your HTML file is not going to interact with C# directly, but you can write some C# to behave as if it were the HTML file.
For example: there is a class called System.Net.WebClient with simple methods:
using System.Net;
using System.Collections.Specialized;
...
using(WebClient client = new WebClient()) {
NameValueCollection vals = new NameValueCollection();
vals.Add("test", "test string");
client.UploadValues("http://www.someurl.com/page.php", vals);
}
For more documentation and features, refer to the MSDN page.
Try this jQuery,
$("#ddlid option:selected").text();
or this javascript,
var selID=document.getElementById("ddlid");
var text=selID.options[selID.selectedIndex].text;
If you need to access the value and not the text then try using val()
method instead of text()
.
Check out the below fiddle links.
you can use this too
.parent:hover * {
/* ... */
}
_x000D_
We can do same Springboard behavior using UICollectionView and for that we need to write code for custom layout.
I have achieved it with my custom layout class implementation with "SMCollectionViewFillLayout"
Code repository:
https://github.com/smindia1988/SMCollectionViewFillLayout
Output as below:
1.png
2_Code_H-Scroll_V-Fill.png
As far as I know, shouldOverrideUrlLoading is not called for images but rather for hyperlinks... I think the appropriate method is
@Override
public void onLoadResource(WebView view, String url)
This method is called for every resource (image, styleesheet, script) that's loaded by the webview, but since it's a void, I haven't found a way to change that url and replace it so that it loads a local resource ...
You can you use .on()
with hover
by doing what the Additional Notes section says:
Although strongly discouraged for new code, you may see the pseudo-event-name "hover" used as a shorthand for the string "mouseenter mouseleave". It attaches a single event handler for those two events, and the handler must examine event.type to determine whether the event is mouseenter or mouseleave. Do not confuse the "hover" pseudo-event-name with the .hover() method, which accepts one or two functions.
That would be to do the following:
$("#foo").on("hover", function(e) {
if (e.type === "mouseenter") { console.log("enter"); }
else if (e.type === "mouseleave") { console.log("leave"); }
});
EDIT (note for jQuery 1.8+ users):
Deprecated in jQuery 1.8, removed in 1.9: The name "hover" used as a shorthand for the string "mouseenter mouseleave". It attaches a single event handler for those two events, and the handler must examine event.type to determine whether the event is mouseenter or mouseleave. Do not confuse the "hover" pseudo-event-name with the .hover() method, which accepts one or two functions.
This is your code
$q = $this -> db
-> select('id')
-> where('email', $email)
-> limit(1)
-> get('users');
Try this
$id = $q->result()[0]->id;
or this one, it's simpler
$id = $q->row()->id;
I found two things:
First
textarea{resize: none}
This is a CSS 3, which is not released yet, compatible with Firefox 4 (and later), Chrome, and Safari.
Another format feature is to overflow: auto
to get rid of the right scrollbar, taking into account the dir attribute.
Basic HTML
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<textarea style="overflow:auto;resize:none" rows="13" cols="20"></textarea>
</body>
</html>
Some browsers
I know this question is old, but I'm taking a crack at it. Very similar to bobince's answer but with working code example.
Make each product an inline-block. Center the contents of the container. Done.
http://jsfiddle.net/rgbk/6Z2Re/
<style>
.products{
text-align:center;
}
.product{
display:inline-block;
text-align:left;
background-image: url('http://www.color.co.uk/wp-content/uploads/2013/11/New_Product.jpg');
background-size:25px;
padding-left:25px;
background-position:0 50%;
background-repeat:no-repeat;
}
.price {
margin: 6px 2px;
width: 137px;
color: #666;
font-size: 14pt;
font-style: normal;
border: 1px solid #CCC;
background-color: #EFEFEF;
}
</style>
<div class="products">
<div class="product">
<div class="price">R$ 0,01</div>
</div>
<div class="product">
<div class="price">R$ 0,01</div>
</div>
<div class="product">
<div class="price">R$ 0,01</div>
</div>
<div class="product">
<div class="price">R$ 0,01</div>
</div>
<div class="product">
<div class="price">R$ 0,01</div>
</div>
<div class="product">
<div class="price">R$ 0,01</div>
</div>
</div>
One way to get this error is to forget to use the 'new' keyword when instantiating your Date in javascript like this:
> d = Date();
'Tue Mar 15 2016 20:05:53 GMT-0400 (EDT)'
> typeof(d);
'string'
> d.getFullYear();
TypeError: undefined is not a function
Had you used the 'new' keyword, it would have looked like this:
> el@defiant $ node
> d = new Date();
Tue Mar 15 2016 20:08:58 GMT-0400 (EDT)
> typeof(d);
'object'
> d.getFullYear(0);
2016
Another way to get that error is to accidentally re-instantiate a variable in javascript between when you set it and when you use it, like this:
el@defiant $ node
> d = new Date();
Tue Mar 15 2016 20:12:13 GMT-0400 (EDT)
> d.getFullYear();
2016
> d = 57 + 23;
80
> d.getFullYear();
TypeError: undefined is not a function
you can also covert int to str first and assign index to it then again convert it to int like this:
int(str(x)[n]) //where x is an integer value
Chiming in historically.
When I was a much younger man (1970s) assembler was important, in my experience, more for the size of the code than the speed of the code.
If a module in a higher-level language was, say, 1300 bytes of code, but an assembler version of the module was 300 bytes, that 1K bytes was very important when you were trying to fit the application into 16K or 32K of memory.
Compilers were not great at the time.
In old-timey Fortran
X = (Y - Z)
IF (X .LT. 0) THEN
... do something
ENDIF
The compiler at the time did a SUBTRACT instruction, then a TEST instruction on X. In assembler, you would just check the condition code (LT zero, zero, GT zero) after the subtract.
For modern systems and compilers none of that is a concern.
I do think that understanding what the compiler is doing is still important. When you code in a higher-level language, you should understand what allows or prevents the compiler to do loop-unroll.
And with pipe-lining and look-ahead computation involving conditionals, when the compiler does a "branch-likley"
Assembler is still needed when doing things not allowed by a higher-level language, like reading or writing to processor-specific registers.
But largely, it is no longer needed for the general programmer, except to have a basic understanding of how the code might be compiled and executed.
There is a simpler way to get the application data directory with min API 4+. From any Context (e.g. Activity, Application):
getApplicationInfo().dataDir
http://developer.android.com/reference/android/content/Context.html#getApplicationInfo()
I haven't really found a good way to do that natively, so I just use a utility called hstart which does it for me. If there's a neater way to do it, that would be nice.
this fails:
DECLARE @vPortalUID NVARCHAR(32)
SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
DECLARE @nPortalUID AS UNIQUEIDENTIFIER
SET @nPortalUID = CAST(@vPortalUID AS uniqueidentifier)
PRINT @nPortalUID
this works
DECLARE @vPortalUID NVARCHAR(36)
SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
DECLARE @nPortalUID AS UNIQUEIDENTIFIER
SET @nPortalUID = CAST(@vPortalUID AS UNIQUEIDENTIFIER)
PRINT @nPortalUID
the difference is NVARCHAR(36)
, your input parameter is too small!
This one throw me for a spin. Angular 7, Webpack I found this article so I want to give credit to the Article https://www.edc4it.com/blog/web/helloworld-angular2.html
What the solution is: //on your component file. use template as webpack will treat it as text template: require('./process.component.html')
for karma to interpret it npm install add html-loader --save-dev { test: /.html$/, use: "html-loader" },
Hope this helps somebody
Or, even cleaner:
when(mockFoo.someMethod()).thenReturn(obj1, obj2);
Suppose you store float value in "X"
and you are storing integer value in "Y"
.
Var Y = Int(x);
or
var myIntValue = Int(myFloatValue)
You have to change the format of the date string you are supplying in order to be able to insert it using the STRFTIME function. Reason being, there is no option for a month abbreviation:
%d day of month: 00
%f fractional seconds: SS.SSS
%H hour: 00-24
%j day of year: 001-366
%J Julian day number
%m month: 01-12
%M minute: 00-59
%s seconds since 1970-01-01
%S seconds: 00-59
%w day of week 0-6 with sunday==0
%W week of year: 00-53
%Y year: 0000-9999
%% %
The alternative is to format the date/time into an already accepted format:
Reference: SQLite Date & Time functions
Borrowing from Michael Jasper's and Jon Hendershot's solutions, I offer the following:
$('address').each(function() {
var text = $(this).text();
var q = $.trim(text).replace(/\r?\n/, ',').replace(/\s+/g, ' ');
var link = '<a href="http://maps.google.com/maps?q=' + encodeURIComponent(q) + '" target="_blank"></a>';
return $(this).wrapInner(link);
});
This solution offers the following benefits over solutions previously offered:
<br>
tags) within <address>
, so formatting is preserved<a><address></address></a>
which is invalid because block-level elements such as <address>
are not permitted within inline elements such as <a>
.Caveat: If your <address>
tag contains block-level elements like <p>
or <div>
, then this JavaScript code will produce in invalid markup (because the <a>
tag will contain those block-level elements). But if you're just doing stuff like this:
<address>
The White House
<br>
1600 Pennsylvania Ave NW
<br>
Washington, D.C. 20500
</address>
Then it'll work just fine.
Tuples cannot efficiently be appended like a list.
So a tuple comprehension would need to use a list internally and then convert to a tuple.
That would be the same as what you do now : tuple( [ comprehension ] )
Here's my solution:
@arr = ['<p>Hello World</p>', '<p>This is a test</p>']
@arr.reduce(:+)
=> <p>Hello World</p><p>This is a test</p>
One line code:
System.out.println(new Gson().fromJson(jsonLine,JsonObject.class).getAsJsonObject().get("data").getAsJsonObject().get("translations").getAsJsonArray().get(0).getAsJsonObject().get("translatedText").getAsString());
In Summary:
conda list
(It will provide all the libraries along with version details).
And:
pip show tensorflow
(It gives complete library details).
Try adding these two lines to your code. I hope it will work. It worked for me :)
display.setLineWrap(true);
display.setWrapStyleWord(true);
Picture of output is shown below
Instead of changing the ticks, why not change the units instead? Make a separate array X
of x-values whose units are in nm. This way, when you plot the data it is already in the correct format! Just make sure you add a xlabel
to indicate the units (which should always be done anyways).
from pylab import *
# Generate random test data in your range
N = 200
epsilon = 10**(-9.0)
X = epsilon*(50*random(N) + 1)
Y = random(N)
# X2 now has the "units" of nanometers by scaling X
X2 = (1/epsilon) * X
subplot(121)
scatter(X,Y)
xlim(epsilon,50*epsilon)
xlabel("meters")
subplot(122)
scatter(X2,Y)
xlim(1, 50)
xlabel("nanometers")
show()
To load a .docx file:
if let htmlFile = Bundle.main.path(forResource: "fileName", ofType: "docx") {
let url = URL(fileURLWithPath: htmlFile)
do{
let data = try Data(contentsOf: url)
self.webView.load(data, mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", textEncodingName: "UTF-8", baseURL: url)
}catch{
print("errrr")
}
}
I got this answer from the book Programming iOS 7, section Bar Position and Bar Metrics
If a navigation bar or toolbar — or a search bar (discussed earlier in this chapter) — is to occupy the top of the screen, the iOS 7 convention is that its height should be increased to underlap the transparent status bar. To make this possible, iOS 7 introduces the notion of a bar position.
Specifies that the bar is at the top of the screen, as well as its containing view. Bars with this position draw their background extended upwards, allowing their background content to show through the status bar. Available in iOS 7.0 and later.
Maybe .text
instead of .html
?
Convert interface{}
into any type.
Syntax:
result := interface.(datatype)
Example:
var employee interface{} = []string{"Jhon", "Arya"}
result := employee.([]string) //result type is []string.
As an option, you can create abstract test class covering logic inside abstract class and extend it for each subclass test. So that in this way you can ensure this logic will be tested for each child separately.
If you use Hibernate 5.2.10.Final, you should change
<provider>org.hibernate.ejb.HibernatePersistence</provider>
to
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
in your persistence.xml
According to Hibernate 5.2.2: No Persistence provider for EntityManager
Include only INSERTs
sqlite3 database.db3 .dump | grep '^INSERT INTO "tablename"'
Easy to implement but it will fail if any of your columns include new lines
SQLite insert mode
for t in $(sqlite3 $DB .tables); do
echo -e ".mode insert $t\nselect * from $t;"
done | sqlite3 $DB > backup.sql
This is a nice and customizable solution, but it doesn't work if your columns have blob objects like 'Geometry' type in spatialite
Diff the dump with the schema
sqlite3 some.db .schema > schema.sql
sqlite3 some.db .dump > dump.sql
grep -v -f schema.sql dump > data.sql
Not sure why, but is not working for me
Probably there is not a best answer to this question, but one that is working for me is grep the inserts taking into account that be new lines in the column values with an expression like this
grep -Pzo "(?s)^INSERT.*\);[ \t]*$"
To select the tables do be dumped .dump
admits a LIKE argument to match the table names, but if this is not enough probably a simple script is better option
TABLES='table1 table2 table3'
echo '' > /tmp/backup.sql
for t in $TABLES ; do
echo -e ".dump ${t}" | sqlite3 database.db3 | grep -Pzo "(?s)^INSERT.*?\);$" >> /tmp/backup.sql
done
or, something more elaborated to respect foreign keys and encapsulate all the dump in only one transaction
TABLES='table1 table2 table3'
echo 'BEGIN TRANSACTION;' > /tmp/backup.sql
echo '' >> /tmp/backup.sql
for t in $TABLES ; do
echo -e ".dump ${t}" | sqlite3 $1 | grep -Pzo "(?s)^INSERT.*?\);$" | grep -v -e 'PRAGMA foreign_keys=OFF;' -e 'BEGIN TRANSACTION;' -e 'COMMIT;' >> /tmp/backup.sql
done
echo '' >> /tmp/backup.sql
echo 'COMMIT;' >> /tmp/backup.sql
Take into account that the grep expression will fail if );
is a string present in any of the columns
To restore it (in a database with the tables already created)
sqlite3 -bail database.db3 < /tmp/backup.sql
setting the font size might not be practical though, since setting
ctx.font = ''
will use the one defined by CSS as well as any embedded font tags. If you use the CSS font you have no idea what the height is from a programmatic way, using the measureText method, which is very short sighted. On another note though, IE8 DOES return the width and height.
Use psexec -s
The s switch will cause it to run under system account which is the same as running an elevated admin prompt. just used it to enable WinRM remotely.
This is an edit of the answer from @kgiannakakis:
The original code is wrong because it does not correctly close the InputStream after Properties.load(InputStream)
is called. From the Javadocs: The specified stream remains open after this method returns.
================================
I believe that the configure method expects an absolute path. Anyhow, you may also try to load a Properties object first:
Properties props = new Properties();
InputStream is = new FileInputStream("log4j.properties");
try {
props.load(is);
}
finally {
try {
is.close();
}
catch (Exception e) {
// ignore this exception
}
}
PropertyConfigurator.configure(props);
If the properties file is in the jar, then you could do something like this:
Properties props = new Properties();
InputStream is = getClass().getResourceAsStream("/log4j.properties");
try {
props.load(is);
}
finally {
try {
is.close();
}
catch (Exception e) {
// ignore this exception
}
}
PropertyConfigurator.configure(props);
The above assumes that the log4j.properties is in the root folder of the jar file.
If you really want a totally empty file, without any output to stdout, you can cheat a little:
copy nul file.txt > nul
Just redirect stdout to nul, and the output from copy disappears.
This worked for me (though it's for reactjs & tachyons used as inline CSS)
<div className="pa2 cf vh-100-ns" style={{backgroundImage: `url(${a6})`}}>
........
</div>
This takes in css as height: 100vh
Solution described here helped me (webarchive link).
First of all, you can add border to all elements to see what causes a new page to be appended (maybe some margins, paddings, etc).
div { border: 1px solid black;}
And the solution itself was to add the following styles:
html, body { height: auto; }
Decoding is redundant
You only had this "error" in the first place, because of a misunderstanding of what's happening.
You get the b
because you encoded to utf-8
and now it's a bytes object.
>> type("text".encode("utf-8"))
>> <class 'bytes'>
Fixes:
I encountered difficulties with Roi-Kyi Bryant's solution when multiple add-ins tried to modify the ribbon. I also don't have admin access on my work-computer, which ruled out installing the Custom UI Editor
. So, if you're in the same boat as me, here's an alternative example to customising the ribbon using only Excel. Note, my solution is derived from the Microsoft guide.
.xlam
files, Chart Tools.xlam
and Priveleged UDFs.xlam
, to demonstrate how multiple add-ins can interact with the Ribbon. customUI
and _rels
folder.customUI
folder, create a customUI.xml
file. The customUI.xml
file details how Excel files interact with the ribbon. Part 2 of the Microsoft guide covers the elements in the customUI.xml
file.My customUI.xml
file for Chart Tools.xlam
looks like this
<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" xmlns:x="sao">
<ribbon>
<tabs>
<tab idQ="x:chartToolsTab" label="Chart Tools">
<group id="relativeChartMovementGroup" label="Relative Chart Movement" >
<button id="moveChartWithRelativeLinksButton" label="Copy and Move" imageMso="ResultsPaneStartFindAndReplace" onAction="MoveChartWithRelativeLinksCallBack" visible="true" size="normal"/>
<button id="moveChartToManySheetsWithRelativeLinksButton" label="Copy and Distribute" imageMso="OutlineDemoteToBodyText" onAction="MoveChartToManySheetsWithRelativeLinksCallBack" visible="true" size="normal"/>
</group >
<group id="chartDeletionGroup" label="Chart Deletion">
<button id="deleteAllChartsInWorkbookSharingAnAddressButton" label="Delete Charts" imageMso="CancelRequest" onAction="DeleteAllChartsInWorkbookSharingAnAddressCallBack" visible="true" size="normal"/>
</group>
</tab>
</tabs>
</ribbon>
</customUI>
My customUI.xml
file for Priveleged UDFs.xlam
looks like this
<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" xmlns:x="sao">
<ribbon>
<tabs>
<tab idQ="x:privelgedUDFsTab" label="Privelged UDFs">
<group id="privelgedUDFsGroup" label="Toggle" >
<button id="initialisePrivelegedUDFsButton" label="Activate" imageMso="TagMarkComplete" onAction="InitialisePrivelegedUDFsCallBack" visible="true" size="normal"/>
<button id="deInitialisePrivelegedUDFsButton" label="De-Activate" imageMso="CancelRequest" onAction="DeInitialisePrivelegedUDFsCallBack" visible="true" size="normal"/>
</group >
</tab>
</tabs>
</ribbon>
</customUI>
.zip
to their file name. In my case, I renamed Chart Tools.xlam
to Chart Tools.xlam.zip
, and Privelged UDFs.xlam
to Priveleged UDFs.xlam.zip
..zip
file, and navigate to the _rels
folder. Copy the .rels
file to the _rels
folder you created in Step 3. Edit each .rels
file with a text editor. From the Microsoft guideBetween the final
<Relationship>
element and the closing<Relationships>
element, add a line that creates a relationship between the document file and the customization file. Ensure that you specify the folder and file names correctly.
<Relationship Type="http://schemas.microsoft.com/office/2006/
relationships/ui/extensibility" Target="/customUI/customUI.xml"
Id="customUIRelID" />
My .rels
file for Chart Tools.xlam
looks like this
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>
<Relationship Type="http://schemas.microsoft.com/office/2006/relationships/ui/extensibility" Target="/customUI/customUI.xml" Id="chartToolsCustomUIRel" />
</Relationships>
My .rels
file for Priveleged UDFs
looks like this.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>
<Relationship Type="http://schemas.microsoft.com/office/2006/relationships/ui/extensibility" Target="/customUI/customUI.xml" Id="privelegedUDFsCustomUIRel" />
</Relationships>
.rels
files in each .zip
file with the .rels
file/files you modified in the previous step..customUI
folder you created into the home directory of the .zip
file/files..zip
file extension from the Excel files you created..xlam
files, back in Excel, add them to your Excel add-ins.onAction
keywords in my buttons. The onAction
keyword indicates that, when the containing element is triggered, the Excel application will trigger the sub-routine encased in quotation marks directly after the onAction
keyword. This is known as a callback. In my .xlam
files, I have a module called CallBacks
where I've included my callback sub-routines.My CallBacks
module for Chart Tools.xlam
looks like
Option Explicit
Public Sub MoveChartWithRelativeLinksCallBack(ByRef control As IRibbonControl)
MoveChartWithRelativeLinks
End Sub
Public Sub MoveChartToManySheetsWithRelativeLinksCallBack(ByRef control As IRibbonControl)
MoveChartToManySheetsWithRelativeLinks
End Sub
Public Sub DeleteAllChartsInWorkbookSharingAnAddressCallBack(ByRef control As IRibbonControl)
DeleteAllChartsInWorkbookSharingAnAddress
End Sub
My CallBacks
module for Priveleged UDFs.xlam
looks like
Option Explicit
Public Sub InitialisePrivelegedUDFsCallBack(ByRef control As IRibbonControl)
ThisWorkbook.InitialisePrivelegedUDFs
End Sub
Public Sub DeInitialisePrivelegedUDFsCallBack(ByRef control As IRibbonControl)
ThisWorkbook.DeInitialisePrivelegedUDFs
End Sub
Different elements have a different callback sub-routine signature. For buttons, the required sub-routine parameter is ByRef control As IRibbonControl
. If you don't conform to the required callback signature, you will receive an error while compiling your VBA project/projects. Part 3 of the Microsoft guide defines all the callback signatures.
Here's what my finished example looks like
Some closing tips
idQ
and xlmns:
keyword. In my example, the Chart Tools.xlam
and Priveleged UDFs.xlam
both have access to the elements with idQ
's equal to x:chartToolsTab
and x:privelgedUDFsTab
. For this to work, the x:
is required, and, I've defined its namespace in the first line of my customUI.xml
file, <customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" xmlns:x="sao">
. The section Two Ways to Customize the Fluent UI in the Microsoft guide gives some more details.isMSO
keyword. The section Two Ways to Customize the Fluent UI in the Microsoft guide gives some more details.There are very good answers with detailed explanation to this post. I just would like to refer that there is another explanation with visual representation for the meaning of Frame, Bounds, Center, Transform, Bounds Origin in WWDC 2011 video Understanding UIKit Rendering starting from @4:22 till 20:10
If you want to split a string into words, you can use explode() or str_word_count().
Working in GIT 1.7.2.2
For example you have a remote some_remote with branches branch1, branch32
so to checkout a specific file you call this commands:
git checkout remote/branch path/to/file
as an example it will be something like this
git checkout some_remote/branch32 conf/en/myscript.conf
git checkout some_remote/branch1 conf/fr/load.wav
This checkout command will copy the whole file structure conf/en and conf/fr into the current directory where you call these commands (of course I assume you ran git init at some point before)
The issue I had was also with serialization. The cause was some of my DTO/business classes and properties were renamed or deleted without updating the service reference. I'm surprised I didn't get a contract filter mismatch error
instead. But updating the service ref fixed the error for me (same error as OP).
// Copied from MSDN, the second point of non-clustered index is not clearly mentioned in the other answers.
Clustered
Nonclustered
If you have a pd.Series
object x
with index named 'Gene', you can use reset_index
and supply the name
argument:
df = x.reset_index(name='count')
Here's a demo:
x = pd.Series([2, 7, 1], index=['Ezh2', 'Hmgb', 'Irf1'])
x.index.name = 'Gene'
df = x.reset_index(name='count')
print(df)
Gene count
0 Ezh2 2
1 Hmgb 7
2 Irf1 1
My solution on using ObjectId
// usermodel.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const ObjectId = Schema.Types.ObjectId
let UserSchema = new Schema({
username: {
type: String
},
events: [{
type: ObjectId,
ref: 'Event' // Reference to some EventSchema
}]
})
UserSchema.set('autoIndex', true)
module.exports = mongoose.model('User', UserSchema)
Using mongoose's populate method
// controller.js
const mongoose = require('mongoose')
const User = require('./usermodel.js')
let query = User.findOne({ name: "Person" })
query.exec((err, user) => {
if (err) {
console.log(err)
}
user.events = events
// user.events is now an array of events
})
As shown below, range
only supports integers:
>>> range(15.0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: range() integer end argument expected, got float.
>>> range(15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>>
However, c/10
is a float because /
always returns a float.
Before you put it in range
, you need to make c/10
an integer. This can be done by putting it in int
:
range(int(c/10))
or by using //
, which returns an integer:
range(c//10)
EDIT: Although the original answer below works and is easy to set up, refer to this post by an Android Developer Advocate at Google if you want / need a more efficient implementation. Also note that the android:foreground
attribute is coming to all Views, including ImageView, by default in Android M.
The problem with using a selector for an ImageView is that you can only set it as the view's background - as long as your image is opaque, you will not see the selector's effect behind it.
The trick is to wrap your ImageView in a FrameLayout with the attribute android:foreground
which allows us to define an overlay for its content. If we set android:foreground
to a selector (e.g.?android:attr/selectableItemBackground
for API level 11+) and attach the OnClickListener
to the FrameLayout instead of the ImageView, the image will be overlaid with our selector's drawable - the click effect we desire!
Behold:
<FrameLayout
android:id="@+id/imageButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:foreground="?android:attr/selectableItemBackground" >
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/yourImageFile" />
</FrameLayout>
(Note this should be placed within your parent layout.)
final View imageButton = findViewById(R.id.imageButton);
imageButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View view) {
// do whatever we wish!
}
});
Erm, can you not just use Settings.Default.Reset() to restore your default settings?
// How about the following:
public int CountBits(int value)
{
int count = 0;
while (value > 0)
{
if (value & 1)
count++;
value <<= 1;
}
return count;
}
Changing my header to the following solve the problem:
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
We use a lot of DLL's (> 100) in our project. These DLL's have dependencies on each other and therefore we chose the setup of dynamic linking. However it has the following disadvantages:
Maybe a better setup was to make everything a static library (and therefore you just have one executable). This works only if no code duplication takes place. A test seems to support this assumption, but i couldn't find an official MSDN quote. So for example make 1 exe with:
The code and variables of shared_lib2 should be present in the final merged executable only once. Can anyone support this question?
You can find out occurrence of '_' in source string by using string functions. find() function takes 2 arguments , first - string whose occurrences we want to find out and second argument takes starting position.While loop is use to find out occurrence till the end of source string.
example:
string str2 = "_";
string strData = "bla_bla_blabla_bla_";
size_t pos = 0,pos2;
while ((pos = strData.find(str2, pos)) < strData.length())
{
printf("\n%d", pos);
pos += str2.length();
}
A different approach, i.e: You could just do it 'the Angular way' and use ngModel
and skip document.getElementById('loginInput').value = '123';
altogether. Instead:
<input type="text" [(ngModel)]="username"/>
<input type="text" [(ngModel)]="password"/>
and in your component you give these values:
username: 'whatever'
password: 'whatever'
this will preset the username and password upon navigating to page.
Download it from here:
http://sourceforge.net/projects/win32svn/
and run the setup program. The executables are in:
\Program Files (x86)\Subversion\bin
for the default installation.
I didn't know what I was doing when I started changing the Apache configuration. I picked up bits and pieces thought it was working until I ran into the same problem you encountered, specifically Chrome having this error.
What I did was comment out all the site-specific directives that are used to configure SSL verification, confirmed that Chrome let me in, reviewed the documentation before directive before re-enabling one, and restarted Apache. By carefully going through these you ought to be able to figure out which one(s) are causing your problem.
In my case, I went from this:
SSLVerifyClient optional
SSLVerifyDepth 1
SSLOptions +StdEnvVars +StrictRequire
SSLRequireSSL On
to this
<Location /sessions>
SSLRequireSSL
SSLVerifyClient require
</Location>
As you can see I had a fair number of changes to get there.
I also ran into this error when I was using Dapper and forgot to input a parameterized value.
To fix I had to ensure that the object passed in as a parameter had properties matching the parameterised values in the SQL string.
Simply using sort, use coloumn number based on which you want to sort.
a = np.array([1,1], [1,-1], [-1,1], [-1,-1]])
print (a)
a=a.tolist()
a = np.array(sorted(a, key=lambda a_entry: a_entry[0]))
print (a)
UPDATE: My original answer doesn't cover iPad in desktop mode (the default changes to desktop mode in upcoming iPadOS 13 and higher).
That's fine for my usecases, if it's not for you, use this update:
// iPhone and iPad including iPadOS 13+ regardless of desktop mode settings
iOSiPadOS = /^iP/.test(navigator.platform) ||
/^Mac/.test(navigator.platform) && navigator.maxTouchPoints > 4;
^
first checks the starting position of the platform string and stops if there is no "iP" (faster than searching the long UA string until the end anyway)navigator.userAgent
check as navigator.platform
is much less likely fakedThis one is IMHO fast, save, and working well:
iOS = /^iP/.test(navigator.platform);
// or, if you prefer it verbose:
iOS = /^(iPhone|iPad|iPod)/.test(navigator.platform);
You can do this using PHP:
$txt1 = "the color is";
$txt2 = " red!";
echo $txt1.$txt2;
This will combine two strings and the putput will be: "the color is red!".
atoi can do that for you
Example:
char string[] = "1234";
int sum = atoi( string );
printf("Sum = %d\n", sum ); // Outputs: Sum = 1234
I've had a look in date_pipe.ts and it has two bits of info which are of interest. near the top are the following two lines:
// TODO: move to a global configurable location along with other i18n components.
var defaultLocale: string = 'en-US';
Near the bottom is this line:
return DateFormatter.format(value, defaultLocale, pattern);
This suggests to me that the date pipe is currently hard-coded to be 'en-US'.
Please enlighten me if I am wrong.
This solution worked for me :)
Please add below line in the script and check.
Ngnix / Apache etc level settings might not be required.
header("Server:");
You cannot change the manifest or the resource in the signed-and-sealed APK, except through a software upgrade.
string myString = "abcdxxx";
if (myString.Length<3)
return;
string newString=myString.Remove(myString.Length - 3, 3);
2020 UPDATE:
Converting HTML to PDF is very simple to do now. All you have to do is use NuGet to install itext7 and itext7.pdfhtml. You can do this in Visual Studio by going to "Project" > "Manage NuGet Packages..."
Make sure to include this dependency:
using iText.Html2pdf;
Now literally just paste this one liner and you're done:
HtmlConverter.ConvertToPdf(new FileInfo(@"temp.html"), new FileInfo(@"report.pdf"));
If you're running this example in visual studio, your html file should be in the /bin/Debug
directory.
If you're interested, here's a good resource. Also, note that itext7 is licensed under AGPL.
I'd use minlog, personally. It's extremely simple, as the logging class is a few hundred lines of code.
You may want to wrap that functionality up into a filter, this way you don't have to put the mySplit function in all of your controllers. For example
angular.module('myModule', [])
.filter('split', function() {
return function(input, splitChar, splitIndex) {
// do some bounds checking here to ensure it has that index
return input.split(splitChar)[splitIndex];
}
});
From here, you can use a filter as you originally intended
{{test | split:',':0}}
{{test | split:',':0}}
More info at http://docs.angularjs.org/guide/filter (thanks ross)
Plunkr @ http://plnkr.co/edit/NA4UeL
I don't think you can (not without reflection), you should provide a type to your function as well:
void MyMethod(Object obj, Type t)
{
var convertedObject = Convert.ChangeType(obj, t);
...
}
UPD:
This may work for you:
void MyMethod(Object obj)
{
if (obj is A)
{
A a = obj as A;
...
}
else if (obj is B)
{
B b = obj as B;
...
}
}
In new page-plugin you can do multiple tabs in your website. The Page plugin lets you easily embed and promote any Facebook Page on your website. Just like on Facebook, your visitors can like and share the Page without leaving your site.
<body>
tag. <div id="fb-root"></div>_x000D_
<script>(function(d, s, id) {_x000D_
var js, fjs = d.getElementsByTagName(s)[0];_x000D_
if (d.getElementById(id)) return;_x000D_
js = d.createElement(s); js.id = id;_x000D_
js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.5&appId={APP_ID}";_x000D_
fjs.parentNode.insertBefore(js, fjs);_x000D_
}(document, 'script', 'facebook-jssdk'));</script>
_x000D_
<div class="fb-page" _x000D_
data-href="https://www.facebook.com/YourPageName" _x000D_
data-tabs="timeline" _x000D_
data-small-header="false" _x000D_
data-adapt-container-width="true" _x000D_
data-hide-cover="false" _x000D_
data-show-facepile="true">_x000D_
<div class="fb-xfbml-parse-ignore">_x000D_
<blockquote cite="https://www.facebook.com/facebook">_x000D_
<a href="https://www.facebook.com/facebook">Facebook</a>_x000D_
</blockquote>_x000D_
</div>_x000D_
</div>
_x000D_
You can also change the following settings:
Also You can now have timeline, events and messages tabs with the new page plugin:
<div class="fb-page" _x000D_
data-tabs="timeline,events,messages"_x000D_
data-href="https://www.facebook.com/YourPageName"_x000D_
data-width="380" _x000D_
data-hide-cover="false">_x000D_
</div>
_x000D_
Building on the answer of JMax, use this formula for the dynamic named range to make the solution work for multiple rows:
=OFFSET(Sheet2!$A$1,MATCH(INDIRECT("Sheet1!"&ADDRESS(ROW(),COLUMN(),4))&"*",Sheet2!$A$1:$A$300,0)-1,0,COUNTA(Sheet2!$A:$A))
Downgrading Node to 0.10.36 should do it per this thread on the node-sass github page: https://github.com/sass/node-sass/issues/490#issuecomment-70388754
If you have NVM you can just:
nvm install 0.10
If you don't, you can find NVM and instructions here: https://www.npmjs.com/package/nvm
private function upload_files($path, $title, $files)
{
$config = array(
'upload_path' => $path,
'allowed_types' => 'jpg|gif|png',
'overwrite' => 1,
);
$this->load->library('upload', $config);
$images = array();
foreach ($files['name'] as $key => $image) {
$_FILES['images[]']['name']= $files['name'][$key];
$_FILES['images[]']['type']= $files['type'][$key];
$_FILES['images[]']['tmp_name']= $files['tmp_name'][$key];
$_FILES['images[]']['error']= $files['error'][$key];
$_FILES['images[]']['size']= $files['size'][$key];
$fileName = $title .'_'. $image;
$images[] = $fileName;
$config['file_name'] = $fileName;
$this->upload->initialize($config);
if ($this->upload->do_upload('images[]')) {
$this->upload->data();
} else {
return false;
}
}
return true;
}
_x000D_
table tbody_x000D_
{_x000D_
border:1px solid red;_x000D_
}_x000D_
table td_x000D_
{_x000D_
background:yellow;_x000D_
_x000D_
border-bottom:1px solid green;_x000D_
_x000D_
_x000D_
}_x000D_
.tr0{_x000D_
line-height:0;_x000D_
}_x000D_
.tr0 td{_x000D_
background:red;_x000D_
}
_x000D_
<table>_x000D_
<tbody>_x000D_
<tr><td>test</td></tr>_x000D_
<tr><td>test</td></tr> _x000D_
<tr class="tr0"><td></td></tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
The example bellow explains how to remove bullets using a css style class. You can use , similar to css class, by identifier (#id), by parent tag, etc. The same way you can use to define a css to remove bullets from the page footer.
I've used this site as a starting point.
<html>
<head>
<style type="text/css">
div.ui-menu li {
list-style:none;
background-image:none;
background-repeat:none;
background-position:0;
}
ul
{
list-style-type:none;
padding:0px;
margin:0px;
}
li
{
background-image:url(sqpurple.gif);
background-repeat:no-repeat;
background-position:0px 5px;
padding-left:14px;
}
</style>
</head>
<body>
<div class="ui-menu">
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ul>
</div>
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ul>
</body>
</html>
I resolved this issue by using ojdbc8.jar. Oracle 12c is compatible with ojdbc8.jar
DELIMITER //
CREATE TRIGGER contacts_after_insert
AFTER INSERT
ON contacts FOR EACH ROW
BEGIN
DECLARE vUser varchar(50);
-- Find username of person performing the INSERT into table
SELECT USER() INTO vUser;
-- Insert record into audit table
INSERT INTO contacts_audit
( contact_id,
deleted_date,
deleted_by)
VALUES
( NEW.contact_id,
SYSDATE(),
vUser );
END; //
DELIMITER ;
Found out what was wrong. I never installed the setuptools for python, so it was missing some vital files, like the egg ones.
If you find yourself having my issue above, download this file and then in powershell or command prompt, navigate to ez_setup’s directory and execute the command and this will run the file for you:
$ [sudo] python ez_setup.py
If you still need to install pip at this point, run:
$ [sudo] easy_install pip
easy_install was part of the setuptools, and therefore wouldn't work for installing pip.
Then, pip will successfully install django with the command:
$ [sudo] pip install django
Hope I saved someone the headache I gave myself!
~Zorpix
Try this when your application still demands $parse
, $eval
, $watch
like behavior in Angular
In my case, creating canvas every time worked for me, even though it's not memory-friendly
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.image);
imageBitmap = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), bm.getConfig());
canvas = new Canvas(imageBitmap);
canvas.drawBitmap(bm, 0, 0, null);
Let us say your jsfunctions.js file has a function "display" and this file is stored in C:/Scripts/Jsfunctions.js
jsfunctions.js
var display = function(name) {
print("Hello, I am a Javascript display function",name);
return "display function return"
}
Now, in your java code, I would recommend you to use Java8 Nashorn. In your java class,
import java.io.FileNotFoundException;
import java.io.FileReader;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
class Test {
public void runDisplay() {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
try {
engine.eval(new FileReader("C:/Scripts/Jsfunctions.js"));
Invocable invocable = (Invocable) engine;
Object result;
result = invocable.invokeFunction("display", helloWorld);
System.out.println(result);
System.out.println(result.getClass());
} catch (FileNotFoundException | NoSuchMethodException | ScriptException e) {
e.printStackTrace();
}
}
}
Note: Get the absolute path of your javascript file and replace in FileReader() and run the java code. It should work.
Why do you want to use Firebug if Safari already comes with great Developer tools? :)
As Matt said, you can enable them from the preferences menu.
Here you will find an overview, summarized, of the Safari's Web inspector, and how to use it:
jsoup supports java 1.5
https://github.com/tburch/jsoup/commit/d8ea84f46e009a7f144ee414a9fa73ea187019a3
looks like that stack was a bug, and has been fixed
A more concise example might be as follows:
#/usr/bin/env python3
from functools import wraps
def wrapper(method):
@wraps(method)
def _impl(self, *method_args, **method_kwargs):
method_output = method(self, *method_args, **method_kwargs)
return method_output + "!"
return _impl
class Foo:
@wrapper
def bar(self, word):
return word
f = Foo()
result = f.bar("kitty")
print(result)
Which will print:
kitty!
open command prompt
python pip install <package-name>
This should complete the process
This problem happens because you are calling fun.cpp
instead of fun.hpp
. So c++ compiler finds func.cpp definition twice and throws this error.
Change line 3 of your main.cpp
file, from #include "fun.cpp"
to #include "fun.hpp"
.
As far as I know, there's a good library called localeplanet
for Localization and Internationalization in JavaScript. Furthermore, I think it's native and has no dependencies to other libraries (e.g. jQuery)
Here's the website of library: http://www.localeplanet.com/
Also look at this article by Mozilla, you can find very good method and algorithms for client-side translation: http://blog.mozilla.org/webdev/2011/10/06/i18njs-internationalize-your-javascript-with-a-little-help-from-json-and-the-server/
The common part of all those articles/libraries is that they use a i18n
class and a get
method (in some ways also defining an smaller function name like _
) for retrieving/converting the key
to the value
. In my explaining the key
means that string you want to translate and the value
means translated string.
Then, you just need a JSON document to store key
's and value
's.
For example:
var _ = document.webL10n.get;
alert(_('test'));
And here the JSON:
{ test: "blah blah" }
I believe using current popular libraries solutions is a good approach.
Alternatively to calling plt.show()
at the end of the script, you can also control each figure separately doing:
f = plt.figure(1)
plt.hist........
............
f.show()
g = plt.figure(2)
plt.hist(........
................
g.show()
raw_input()
In this case you must call raw_input
to keep the figures alive.
This way you can select dynamically which figures you want to show
Note: raw_input()
was renamed to input()
in Python 3
I faced the same issue and it's fixed now:) Just follow the below steps and the error could be for anything, but the below steps makes the process smoother. I spend lot of time to find the fix.
1.Try restart the Eclipse (if you are using Eclipse to built JAR file) --> Actually this helped my issue in exporting the JAR file properly.
2.After eclipse restart, try to see if your eclipse is able to recognize the main class/method by your Java project --> right click --> Run as --> Run configurations --> Main --> click Search button to see if your eclipse is able to lookup for your main class in the JAR file. --> This is for the validation that JAR file will have the entry point to the main class.
After this, export your Java Dynamic project as "Runnable JAR" file and not JAR file.
In Java launch configuration, choose your main class.
Once export the jar file, use the below command to execute. java -cp [Your JAR].jar [complete package].MainClass eg: java -cp AppleTCRuleAudit.jar com.apple.tcruleaudit.classes.TCRuleAudit
You might face the unsupported java version error. the fix is to change the java_home in your shell bash profile to match the java version used to compile the project in eclipse.
Hope this helps! Kindly let me know if you still have any issues.
The complete example for Express.js, API calling case and sending JSON content is the following:
...
app.get('/api/myApi', (req, res) => {
MongoClient.connect('mongodb://user:[email protected]:port/dbname',
{ useNewUrlParser: true }, (err, db) => {
if (err) throw err
const dbo = db.db('dbname')
dbo.collection('myCollection')
.find({}, { _id: 0 })
.sort({ _id: -1 })
.toArray(
(errFind, result) => {
if (errFind) throw errFind
const resultJson = JSON.stringify(result)
console.log('find:', resultJson)
res.send(resultJson)
db.close()
},
)
})
}
I know you asked to Rebase, but I'd Cherry-Pick the commits I wanted to move from Branch2 to Branch1 instead. That way, I wouldn't need to care about when which branch was created from master, and I'd have more control over the merging.
a -- b -- c <-- Master
\ \
\ d -- e -- f -- g <-- Branch1 (Cherry-Pick f & g)
\
f -- g <-- Branch2
My opinion is C# and ASP.NET would be the best of the three for development that is web biased.
I doubt anyone writes new web apps in C or C++ anymore. It was done 10 years ago, and there's likely a lot of legacy code still in use, but they're not particularly well suited, there doesn't appear to be as much (ongoing) tool support, and they probably have a small active community that does web development (except perhaps for web server development). I wrote many website C++ COM objects back in the day, but C# is far more productive that there's no compelling reason to code C or C++ (in this context) unless you need to.
I do still write C++ if necessary, but it's typically for a small problem domain. e.g. communicating from C# via P/Invoke to old C-style dll's - doing some things that are downright clumsy in C# were a breeze to create a C++ COM object as a bridge.
The nice thing with C# is that you can also easily transfer into writing Windows and Console apps and stay in C#. With Mono you're also not limited to Windows (although you may be limited to which libraries you use).
Anyways this is all from a web-biased perspective. If you asked about embedded devices I'd say C or C++. You could argue none of these are suited for web development, but C#/ASP.NET is pretty slick, it works well, there are heaps of online resources, a huge community, and free dev tools.
So from a real-world perspective, picking only one of C#, C++ and C as requested, as a general rule, you're better to stick with C#.
If you want to include the column that is the current identity, you can still do that but you have to explicitly list the columns and cast the current identity to an int (assuming it is one now), like so:
select cast (CurrentID as int) as CurrentID, SomeOtherField, identity(int) as TempID
into #temp
from myserver.dbo.mytable
JLS clearly says
An array initializer creates an array and provides initial values for all its components.
and this is irrespective of whether the array is an instance variable or local variable or class variable.
Default values for primitive types : docs
For objects default values is null
.
Recursion is a method that call itself. In this case it is a recursion. However it will be overloading until you put a restriction inside the method to stop the loop (if-condition).
You must sort your data according your needs (es. in reverse order) and use select top query