<?php echo date("Y"); ?>
I recommend php-ffmpeg library.
Extracting image
You can extract a frame at any timecode using the
FFMpeg\Media\Video::frame
method.This code returns a
FFMpeg\Media\Frame
instance corresponding to the second 42. You can pass anyFFMpeg\Coordinate\TimeCode
as argument, see dedicated documentation below for more information.
$frame = $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(42));
$frame->save('image.jpg');
If you want to extract multiple images from the video, you can use the following filter:
$video
->filters()
->extractMultipleFrames(FFMpeg\Filters\Video\ExtractMultipleFramesFilter::FRAMERATE_EVERY_10SEC, '/path/to/destination/folder/')
->synchronize();
$video
->save(new FFMpeg\Format\Video\X264(), '/path/to/new/file');
By default, this will save the frames as jpg images.
You are able to override this using setFrameFileType
to save the frames in another format:
$frameFileType = 'jpg'; // either 'jpg', 'jpeg' or 'png'
$filter = new ExtractMultipleFramesFilter($frameRate, $destinationFolder);
$filter->setFrameFileType($frameFileType);
$video->addFilter($filter);
import numpy as np
>>> np.shape(a)
(2,2)
Also works if the input is not a numpy array but a list of lists
>>> a = [[1,2],[1,2]]
>>> np.shape(a)
(2,2)
Or a tuple of tuples
>>> a = ((1,2),(1,2))
>>> np.shape(a)
(2,2)
It can also be useful to use String.Format
, e.g.
String.Format("{0}\t{1}", FirstName,Count);
I think the most safest downgrade path from PHP7 to PHP5 in Xampp is:
Download a self-packaged version of Xampp with PHP5 from here (as of today this is xampp-win32-5.6.37-0-VC11.zip
).
Rename the php
folder to php7
in Xampp.
Now copy the php
folder from xampp-win32-5.6.37-0-VC11.zip
into your Xampp install folder.
Make a backup from .\xampp\apache\conf\extra\httpd-xampp.conf
file.
Replace this file from xampp-win32-5.6.37-0-VC11.zip
as well.
This way the config files (including php.ini
) has settings from the Xampp team.
Before any changes, to verify changed Apache configs, you can compare both Xampp release folder at .\xampp\apache\conf
with tools like Meld.
I should note that please download PHP 5 and 7 Xampp packages released at the same time.
Notify me if I miss something.
I think assembly plugin puts the file on class path. The location will be different in in the JAR than you see on disk. Unpack the resulting JAR and look where the file is located there.
Related to your question, you may want to consider limiting the amount of RAM SQL Server has access to if you are using it in a shared environment, i.e., on a server that hosts more than just SQL Server:
This will help alleviate SQL Server from consuming all the server's RAM.
No, you cannot do that with CSS. That is the reason Microsoft initially introduced another, and maybe more practical box model. The box model that eventually won, makes it inpractical to mix percentages and units.
I don't think it is OK with you to express padding and border widths in percentage of the parent too.
This error appears in my android project with multiple kind of gfx files. At the end no change in the manifest file was accepted.
Because my lack of knowledge about the android devices I forget that my test device has a second User. This User also has an installed version of my app so I also have to delete the app for this user account and it works.
Not sure whether it would help you or not but it works to me:
l = ["a", "b", "c", "d", "e"]
outRes = dict((l[i], l[i+1]) if i+1 < len(l) else (l[i], '') for i in xrange(len(l)))
This is the solution I came up with:
import time
from threading import Thread
from threading import Lock
def myfunc(i, mutex):
mutex.acquire(1)
time.sleep(1)
print "Thread: %d" %i
mutex.release()
mutex = Lock()
for i in range(0,10):
t = Thread(target=myfunc, args=(i,mutex))
t.start()
print "main loop %d" %i
Output:
main loop 0
main loop 1
main loop 2
main loop 3
main loop 4
main loop 5
main loop 6
main loop 7
main loop 8
main loop 9
Thread: 0
Thread: 1
Thread: 2
Thread: 3
Thread: 4
Thread: 5
Thread: 6
Thread: 7
Thread: 8
Thread: 9
You can switch to manual build so can control when this is done. Just make sure that Project > Build Automatically
from the main menu is unchecked.
FileOutputStream fos = openFileOutput("/*file name like --> one.txt*/", MODE_PRIVATE);
FileWriter fw = new FileWriter(fos.getFD());
fw.write("");
Your port 80 is being used by the system.
And from "Overview>>CPU" just Right click on that process and click "End Process Tree". If that process is system that might be a critical issue.
All these suggestions work unless you put the anchors inside an UL list.
<ul>
<li>
<a>click me</a>>
</li>
</ul>
Then any cascade style sheet rules are overridden in the Chrome browser. The width becomes auto. Then you must use inline CSS rules directly on the anchor itself.
Use Max-Age=-1 rather than "Expires". It is shorter, less picky about the syntax, and Max-Age takes precedence over Expires anyway.
Good answers. Just to get an image representation of container vs VM, have a look at the one below.
I'd like to write explicitly two methods which allow accomplishing this in pure JavaScript:
document.getElementsByClassName('realClasssName').length
Note 1: Argument of this method needs a string with the real class name, without the dot at the begin of this string.
document.querySelectorAll('.realClasssName').length
Note 2: Argument of this method needs a string with the real class name but with the dot at the begin of this string.
Note 3: This method works also with any other CSS selectors, not only with class selector. So it's more universal.
I also write one method, but using two name conventions to solve this problem using jQuery:
jQuery('.realClasssName').length
or
$('.realClasssName').length
Note 4: Here we also have to remember about the dot, before the class name, and we can also use other CSS selectors.
Just use dynamic
as the argument:
var list = new List<dynamic>();
Yaur: Although what you have copied and pasted is good advice, this does not mean that it is impossible to change the source element of an HTML5 video element elegantly, even in IE9 (or IE8 for that matter).(This solution does NOT involve replacing the entire video element, as it is bad coding practice).
A complete solution to changing/switching videos in HTML5 video tags via javascript can be found here and is tested in all HTML5 browser (Firefox, Chrome, Safari, IE9, etc).
If this helps, or if you're having trouble, please let me know.
In the new Jenkins 2.0 pipeline (previously named the Workflow Plugin), this is done differently for:
Here I am specifically referring to the Multibranch Pipeline version 2.9.
Main repository
This is the repository that contains your Jenkinsfile
.
In the Configure screen for your pipeline project, enter your repository name, etc.
Do not use Additional Behaviors > Check out to a sub-directory. This will put your Jenkinsfile
in the sub-directory where Jenkins cannot find it.
In Jenkinsfile
, check out the main repository in the subdirectory using dir()
:
dir('subDir') {
checkout scm
}
Additional repositories
If you want to check out more repositories, use the Pipeline Syntax generator to automatically generate a Groovy code snippet.
In the Configure screen for your pipeline project:
env.BRANCH_NAME
contains the branch name of the main repository.Jenkinsfile
.For Rails 4
The generator accepts column type as references (also available as belongs_to
).
This migration will create a user_id
column and appropriate index:
$ rails g migration AddUserRefToProducts user:references
generates:
class AddUserRefToProducts < ActiveRecord::Migration
def change
add_reference :products, :user, index: true
end
end
http://guides.rubyonrails.org/active_record_migrations.html#creating-a-standalone-migration
For Rails 3
Helper is called references (also available as belongs_to
).
This migration will create a category_id
column of the appropriate type. Note that you pass the model name, not the column name. Active Record adds the _id
for you.
change_table :products do |t|
t.references :category
end
If you have polymorphic belongs_to
associations then references will add both of the columns required:
change_table :products do |t|
t.references :attachment, :polymorphic => {:default => 'Photo'}
end
Will add an attachment_id column and a string attachment_type
column with a default value of Photo
.
http://guides.rubyonrails.org/v3.2.21/migrations.html#creating-a-standalone-migration
Elasticsearch settings are in $ES_HOME/config/elasticsearch.yml
. There, if the cluster.name
setting is commented out, it means ES would take just about any cluster name. So, in your code, the cluster.name
as "elastictest"
might be the problem. Try this:
Client client = new TransportClient()
.addTransportAddress(new InetSocketTransportAddress(
"143.79.236.xxx",
9300));
What kind of document library information do you want in the view? How do you want the user to filter the view?
In general the most powerful way of creating views in sharepoint is with the data view web part. http://office.microsoft.com/en-us/sharepointdesigner/HA100948041033.aspx
You will need Microsoft Office SharePoint Designer.
You can present different views of you folders using the data view filter and sorting controls.
You can use web part connections to filter a dataview. You can use any datasource linked to say a drop down to filter a dataview. How to tie a dropdown list to a gridview in Sharepoint 2007?
The route engine uses the same sequence as you add rules into it. Once it gets the first matched rule, it will stop checking other rules and take this to search for controller and action.
So, you should:
Put your specific rules ahead of your general rules(like default), which means use RouteTable.Routes.MapHttpRoute
to map "WithActionApi" first, then "DefaultApi".
Remove the defaults: new { id = System.Web.Http.RouteParameter.Optional }
parameter of your "WithActionApi" rule because once id is optional, url like "/api/{part1}/{part2}" will never goes into "DefaultApi".
Add an named action to your "DefaultApi" to tell the route engine which action to enter. Otherwise once you have more than one actions in your controller, the engine won't know which one to use and throws "Multiple actions were found that match the request: ...". Then to make it matches your Get method, use an ActionNameAttribute.
So your route should like this:
// Map this rule first
RouteTable.Routes.MapRoute(
"WithActionApi",
"api/{controller}/{action}/{id}"
);
RouteTable.Routes.MapRoute(
"DefaultApi",
"api/{controller}/{id}",
new { action="DefaultAction", id = System.Web.Http.RouteParameter.Optional }
);
And your controller:
[ActionName("DefaultAction")] //Map Action and you can name your method with any text
public string Get(int id)
{
return "object of id id";
}
[HttpGet]
public IEnumerable<string> ByCategoryId(int id)
{
return new string[] { "byCategory1", "byCategory2" };
}
Tried almost all of the above. Ended up doing
chmod 666 .env
which worked. This problem seems to keep cropping up on the app I inherited however, this most recent time was after adding a .env.testing. Running Laravel 5.8
It occurred to me that you may have actually be asking how to implement the +
operator for dictionaries, the following seems to work:
>>> class Dict(dict):
... def __add__(self, other):
... copy = self.copy()
... copy.update(other)
... return copy
... def __radd__(self, other):
... copy = other.copy()
... copy.update(self)
... return copy
...
>>> default_data = Dict({'item1': 1, 'item2': 2})
>>> default_data + {'item3': 3}
{'item2': 2, 'item3': 3, 'item1': 1}
>>> {'test1': 1} + Dict(test2=2)
{'test1': 1, 'test2': 2}
Note that this is more overhead then using dict[key] = value
or dict.update()
, so I would recommend against using this solution unless you intend to create a new dictionary anyway.
If the value type is already double, then update the value with $set command can not change the value type double to int when using NumberInt() or NumberLong() function. So, to Change the value type, it must update the whole record.
var re = db.data.find({"name": "zero"})
re['value']=NumberInt(0)
db.data.update({"name": "zero"}, re)
There is no way to do that as the author of the HTML that a browser renders. At least not yet that I know of. Its pretty much up to the browser and its settings / preferences that are set by users themselves.
Also, you shouldn't impose this upon any user. A browser is the user's property. If a user wants to open all links in tabs or in new windows, then let the user do exactly that.
It's good that we can't do certain things. target=_blank
is still abused and popups have been done to death.
You can use this example to handle your problem:
System.out.printf( "%-15s %15s %n", "name", "lastname");
System.out.printf( "%-15s %15s %n", "Bill", "Smith");
You can play with the "%" until you find the right alignment to satisfy your needs
To perform this operation see the next images:
and next step is add *.mdf file,
very important, the .mdf file must be located in C:......\MSSQL12.SQLEXPRESS\MSSQL\DATA
Now remove the log file
What directory is file.txt in? cron runs jobs in your home directory, so unless your script cd
s somewhere else, that's where it's going to look for/create file.txt.
EDIT: When you refer to a file without specifying its full path (e.g. file.txt
, as opposed to the full path /home/myUser/scripts/file.txt
) in shell, it's taken that you're referring to a file in your current working directory. When you run a script (whether interactively or via crontab), the script's working directory has nothing at all to do with the location of the script itself; instead, it's inherited from whatever ran the script.
Thus, if you cd
(change working directory) to the directory the script's in and then run it, file.txt
will refer to a file in the same directory as the script. But if you don't cd
there first, file.txt
will refer to a file in whatever directory you happen to be in when you ran the script. For instance, if your home directory is /home/myUser, and you open a new shell and immediately run the script (as scripts/test.sh
or /home/myUser/scripts/test.sh
; ./test.sh
won't work), it'll touch the file /home/myUser/file.txt because /home/myUser is your current working directory (and therefore the script's).
When you run a script from cron
, it does essentially the same thing: it runs it with the working directory set to your home directory. Thus all file references in the script are taken relative to your home directory, unless the script cd
s somewhere else or specifies an absolute path to the file.
Differences in SOAP versions
Both SOAP Version 1.1 and SOAP Version 1.2 are World Wide Web Consortium (W3C) standards. Web services can be deployed that support not only SOAP 1.1 but also support SOAP 1.2. Some changes from SOAP 1.1 that were made to the SOAP 1.2 specification are significant, while other changes are minor.
The SOAP 1.2 specification introduces several changes to SOAP 1.1. This information is not intended to be an in-depth description of all the new or changed features for SOAP 1.1 and SOAP 1.2. Instead, this information highlights some of the more important differences between the current versions of SOAP.
The changes to the SOAP 1.2 specification that are significant include the following updates: SOAP 1.1 is based on XML 1.0. SOAP 1.2 is based on XML Information Set (XML Infoset). The XML information set (infoset) provides a way to describe the XML document with XSD schema. However, the infoset does not necessarily serialize the document with XML 1.0 serialization on which SOAP 1.1 is based.. This new way to describe the XML document helps reveal other serialization formats, such as a binary protocol format. You can use the binary protocol format to compact the message into a compact format, where some of the verbose tagging information might not be required.
In SOAP 1.2 , you can use the specification of a binding to an underlying protocol to determine which XML serialization is used in the underlying protocol data units. The HTTP binding that is specified in SOAP 1.2 - Part 2 uses XML 1.0 as the serialization of the SOAP message infoset.
SOAP 1.2 provides the ability to officially define transport protocols, other than using HTTP, as long as the vendor conforms to the binding framework that is defined in SOAP 1.2. While HTTP is ubiquitous, it is not as reliable as other transports including TCP/IP and MQ. SOAP 1.2 provides a more specific definition of the SOAP processing model that removes many of the ambiguities that might lead to interoperability errors in the absence of the Web Services-Interoperability (WS-I) profiles. The goal is to significantly reduce the chances of interoperability issues between different vendors that use SOAP 1.2 implementations. SOAP with Attachments API for Java (SAAJ) can also stand alone as a simple mechanism to issue SOAP requests. A major change to the SAAJ specification is the ability to represent SOAP 1.1 messages and the additional SOAP 1.2 formatted messages. For example, SAAJ Version 1.3 introduces a new set of constants and methods that are more conducive to SOAP 1.2 (such as getRole(), getRelay()) on SOAP header elements. There are also additional methods on the factories for SAAJ to create appropriate SOAP 1.1 or SOAP 1.2 messages. The XML namespaces for the envelope and encoding schemas have changed for SOAP 1.2. These changes distinguish SOAP processors from SOAP 1.1 and SOAP 1.2 messages and supports changes in the SOAP schema, without affecting existing implementations. Java Architecture for XML Web Services (JAX-WS) introduces the ability to support both SOAP 1.1 and SOAP 1.2. Because JAX-RPC introduced a requirement to manipulate a SOAP message as it traversed through the run time, there became a need to represent this message in its appropriate SOAP context. In JAX-WS, a number of additional enhancements result from the support for SAAJ 1.3.
There is not difine POST AND GET method for particular android....but all here is differance
GET The GET method appends name/value pairs to the URL, allowing you to retrieve a resource representation. The big issue with this is that the length of a URL is limited (roughly 3000 char) resulting in data loss should you have to much stuff in the form on your page, so this method only works if there is a small number parameters.
What does this mean for me? Basically this renders the GET method worthless to most developers in most situations. Here is another way of looking at it: the URL could be truncated (and most likely will be give today's data-centric sites) if the form uses a large number of parameters, or if the parameters contain large amounts of data. Also, parameters passed on the URL are visible in the address field of the browser (YIKES!!!) not the best place for any kind of sensitive (or even non-sensitive) data to be shown because you are just begging the curious user to mess with it.
POST The alternative to the GET method is the POST method. This method packages the name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the forms output, basically its a no-brainer on which one to use. POST is also more secure but certainly not safe. Although HTTP fully supports CRUD, HTML 4 only supports issuing GET and POST requests through its various elements. This limitation has held Web applications back from making full use of HTTP, and to work around it, most applications overload POST to take care of everything but resource retrieval.
Lodash.js (superset of Underscore.js)
It's good not to add a framework for every simple piece of logic, but relying on well tested utility frameworks can speed up development and reduce the amount of bugs.
Lodash produces very clean code and promotes a more functional programming style. In one glimpse it becomes clear what the intent of the code is.
OP's issue can simply be solved as:
const sortedObjs = _.sortBy(objs, 'last_nom');
More info? E.g. we have following nested object:
const users = [
{ 'user': {'name':'fred', 'age': 48}},
{ 'user': {'name':'barney', 'age': 36 }},
{ 'user': {'name':'wilma'}},
{ 'user': {'name':'betty', 'age': 32}}
];
We now can use the _.property shorthand user.age
to specify the path to the property that should be matched. We will sort the user objects by the nested age property. Yes, it allows for nested property matching!
const sortedObjs = _.sortBy(users, ['user.age']);
Want it reversed? No problem. Use _.reverse.
const sortedObjs = _.reverse(_.sortBy(users, ['user.age']));
Want to combine both using chain?
const { chain } = require('lodash');
const sortedObjs = chain(users).sortBy('user.age').reverse().value();
Or when do you prefer flow over chain
const { flow, reverse, sortBy } = require('lodash/fp');
const sortedObjs = flow([sortBy('user.age'), reverse])(users);
You should try this.
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Sakla Test');", true);
The same problem arrised for me when I installed Kaliko CMS Nuget Package. When I removed it, it started working fine again. So, your problem could be because of a recently installed Nuget Package. Uninstall it and your solution will work just fine.
in the new actionmailer, "razorengine" is a dependency. The latest version of Razorengine installs the dependency to System.Web.Razor 3.0.0.
If you use an earlier version in your application (i suppose you are using actionmailer in another project and that you reference the mail functionality from another project) than you get this issue of course.
In an earlier application, i had a webapplication MVC that uses system.web.Razor version 2.0.0. Of course, i got the issue to. How to fix? => Simple!
Install-Package RazorEngine -Version 3.3.0 (because version 3.3.0 will reference system.web.razor 2.0.0)
Also from Java doc:
java.lang
Class Process
Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.
Fail to clear the buffer of input stream (which pipes to the output stream of subprocess) from Process may lead to a subprocess blocking.
Try this:
Process process = Runtime.getRuntime().exec("tasklist");
BufferedReader reader =
new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((reader.readLine()) != null) {}
process.waitFor();
What if you have your data in CSV format and convert it to HTML for display on the web page? You may use the http://code.google.com/p/js-tables/ plugin. Check this example http://code.google.com/p/js-tables/wiki/Table As you are already using jQuery library I have assumed you are able to add other javascript toolkit libraries.
If the data is in CSV format, you should be able to use the generic 'application/octetstream' mime type. All the 3 mime types you have tried are dependent on the software installed on the clients computer.
Me, I'd do it something like this:
HTML:
onclick="myfunction({path:'/myController/myAction', ok:myfunctionOnOk, okArgs:['/myController2/myAction2','myParameter2'], cancel:myfunctionOnCancel, cancelArgs:['/myController3/myAction3','myParameter3']);"
JS:
function myfunction(params)
{
var path = params.path;
/* do stuff */
// on ok condition
params.ok(params.okArgs);
// on cancel condition
params.cancel(params.cancelArgs);
}
But then I'd also probable be binding a closure to a custom subscribed event. You need to add some detail to the question really, but being first-class functions are easily passable and getting params to them can be done any number of ways. I would avoid passing them as string labels though, the indirection is error prone.
You can use the dplyr
package to easily remove those particular rows.
library(dplyr)
df <- filter(df, C != "Foo")
As explained in Python's super() considered super, one way is to have class eat the arguments it requires, and pass the rest on. Thus, when the call-chain reaches object
, all arguments have been eaten, and object.__init__
will be called without arguments (as it expects). So your code should look like this:
class A(object):
def __init__(self, *args, **kwargs):
print "A"
super(A, self).__init__(*args, **kwargs)
class B(object):
def __init__(self, *args, **kwargs):
print "B"
super(B, self).__init__(*args, **kwargs)
class C(A):
def __init__(self, arg, *args, **kwargs):
print "C","arg=",arg
super(C, self).__init__(*args, **kwargs)
class D(B):
def __init__(self, arg, *args, **kwargs):
print "D", "arg=",arg
super(D, self).__init__(*args, **kwargs)
class E(C,D):
def __init__(self, arg, *args, **kwargs):
print "E", "arg=",arg
super(E, self).__init__(*args, **kwargs)
print "MRO:", [x.__name__ for x in E.__mro__]
E(10, 20, 30)
$('.ui-datepicker').css('font-size', $('.ui-datepicker').width() / 20 + 'px');
@Dmitri Novikov, FLAG_ACTIVITY_CLEAR_TOP
clears any active instance on top of the new one. So, it may end the old instance before it completes the process.
I had removed files from Compile Sources in Build Phases in Targets. I added main.m
and it worked.
Use Css Selector for this, or learn more about Css Selector just go here
https://www.w3schools.com/cssref/css_selectors.asp
#main_text > .title {
/* Style goes here */
}
#main_text .title {
/* Style goes here */
}
Your constructor's access modifier would be package-private(default). As you have declared the class public, it will be visible everywhere, but the constructor will not. Your constructor will be visible only in its package.
package flight.booking;
public class FlightLog // Public access modifier
{
private SpecificFlight flight;
FlightLog(SpecificFlight flight) // Default access modifier
{
this.flight = flight;
}
}
When you do not write any constructor in your class then the compiler generates a default constructor with the same access modifier of the class. For the following example, the compiler will generate a default constructor with the public access modifier (same as class).
package flight.booking;
public class FlightLog // Public access modifier
{
private SpecificFlight flight;
}
maybe this help :
declare
@statement AS NVARCHAR(MAX)
,@text1 varchar(50)='hello'
,@text2 varchar(50)='world'
set @statement = '
select '''+@text1+''' + '' beautifull '' + ''' + @text2 + '''
'
exec sp_executesql @statement;
this is same as below :
select @text1 + ' beautifull ' + @text2
The keyword you're looking for is list comprehensions:
>>> x = [1, 2, 3, 4, 5]
>>> y = [2*a for a in x if a % 2 == 1]
>>> print(y)
[2, 6, 10]
For Ubuntu users: First You need to install mailutils
sudo apt-get install mailutils
Setup an email server, if you are using gmail or smtp. follow this link. then use this command to send email.
echo "this is a test mail" | mail -s "Subject of mail" [email protected]
In case you are using gmail and still you are getting some authentication error then you need to change setting of gmail:
Turn on Access for less secure apps from here
This is nuts! How does Oracle provide an installer that doesn't install anything!?
Anyways for me it was:
sudo rm /usr/bin/java
sudo ln -s /Library/Java/JavaVirtualMachines/jdk1.8.0_31.jdk/Contents/Home/jre/bin/java /usr/bin/java
where 1.8.0_31 is your installed java version...
Quoting the official docs at https://docs.python.org/2.0/ref/strings.html:
In plain English: String literals can be enclosed in matching single quotes (') or double quotes (").
So there is no difference. Instead, people will tell you to choose whichever style that matches the context, and to be consistent. And I would agree - adding that it is pointless to try to come up with "conventions" for this sort of thing because you'll only end up confusing any newcomers.
If you use gulp with yargs, notice the following:
If you have a task 'customer' and wan't to use yargs build in Parameter checking for required commands:
.command("customer <place> [language]","Create a customer directory")
call it with:
gulp customer --customer Bob --place Chicago --language english
yargs will allway throw an error, that there are not enough commands was assigned to the call, even if you have!! —
Give it a try and add only a digit to the command (to make it not equal to the gulp-task name)... and it will work:
.command("customer1 <place> [language]","Create a customer directory")
This is cause of gulp seems to trigger the task, before yargs is able to check for this required Parameter. It cost me surveral hours to figure this out.
Hope this helps you..
"There are no safe means of assigning multiple recipients to a single mailto: link via HTML. There are safe, non-HTML, ways of assigning multiple recipients from a mailto: link."
http://www.sightspecific.com/~mosh/www_faq/multrec.html
For a quick fix to your problem, change your ;
to a comma ,
and eliminate the spaces between email addresses
<a href='mailto:[email protected],[email protected]'>Email Us</a>
This works for me ...
public class ShadowImage extends Drawable {
Bitmap bm;
@Override
public void draw(Canvas canvas) {
Paint mShadow = new Paint();
Rect rect = new Rect(0,0,bm.getWidth(), bm.getHeight());
mShadow.setAntiAlias(true);
mShadow.setShadowLayer(5.5f, 4.0f, 4.0f, Color.BLACK);
canvas.drawRect(rect, mShadow);
canvas.drawBitmap(bm, 0.0f, 0.0f, null);
}
public ShadowImage(Bitmap bitmap) {
super();
this.bm = bitmap;
} ... }
If UserGroups has a one to many relationship with UserGroupPrices table, then in EF, once the relationship is defined in code like:
//In UserGroups Model
public List<UserGroupPrices> UserGrpPriceList {get;set;}
//In UserGroupPrices model
public UserGroups UserGrps {get;set;}
You can pull the left joined result set by simply this:
var list = db.UserGroupDbSet.ToList();
assuming your DbSet for the left table is UserGroupDbSet, which will include the UserGrpPriceList, which is a list of all associated records from the right table.
Try this.
Single:
SELECT * FROM (VALUES ('Hello world')) t1 (col1) WHERE 1 = 1
Multi:
SELECT * FROM (VALUES ('Hello world'),('Hello world'),('Hello world')) t1 (col1) WHERE 1 = 1
more detail here : http://modern-sql.com/use-case/select-without-from
I think this is the problem
A little background
Traceview is a graphical viewer for execution logs that you create by using the Debug class to log tracing information in your code. Traceview can help you debug your application and profile its performance. Enabling it creates a .trace
file in the sdcard root folder which can then be extracted by ADB and processed by traceview bat file for processing. It also can get added by the DDMS.
It is a system used internally by the logger. In general unless you are using traceview to extract the trace file this error shouldnt bother you. You should look at error/logs directly related to your application
How do I enable it:
There are two ways to generate trace logs:
Include the Debug class in your code and call its methods such as
startMethodTracing()
andstopMethodTracing()
, to start and stop logging of trace information to disk. This option is very precise because you can specify exactly where to start and stop logging trace data in your code.Use the method profiling feature of DDMS to generate trace logs. This option is less precise because you do not modify code, but rather specify when to start and stop logging with DDMS. Although you have less control on exactly where logging starts and stops, this option is useful if you don't have access to the application's code, or if you do not need precise log timing.
But the following restrictions exist for the above
If you are using the Debug class, your application must have permission to write to external storage (
WRITE_EXTERNAL_STORAGE
).If you are using DDMS: Android 2.1 and earlier devices must have an SD card present and your application must have permission to write to the SD card. Android 2.2 and later devices do not need an SD card. The trace log files are streamed directly to your development machine.
So in essence the traceFile access requires two things
1.) Permission to write a trace log file i.e.
WRITE_EXTERNAL_STORAGE
andREAD_EXTERNAL_STORAGE
for good measure2.) An emulator with an SDCard attached with sufficient space. The doc doesnt say if this is only for DDMS but also for debug, so I am assuming this is also true for debugging via the application.
What do I do with this error:
Now the error is essentially a fall out of either not having the sdcard path to create a tracefile or not having permission to access it. This is an old thread, but the dev behind the bounty, check if are meeting the two prerequisites. You can then go search for the .trace
file in the sdcard folder in your emulator. If it exists it shouldn't be giving you this problem, if it doesnt try creating it by adding the startMethodTracing
to your app.
I'm not sure why it automatically looks for this file when the logger kicks in. I think when an error/log event occurs , the logger internally tries to write to trace file and does not find it, in which case it throws the error.Having scoured through the docs, I don't find too many references to why this is automatically on.
But in general this doesn't affect you directly, you should check direct application logs/errors.
Also as an aside Android 2.2 and later devices do not need an SD card for DDMS trace logging. The trace log files are streamed directly to your development machine.
Additional information on Traceview:
Copying Trace Files to a Host Machine
After your application has run and the system has created your trace files .trace on a device or emulator, you must copy those files to your development computer. You can use adb pull to copy the files. Here's an example that shows how to copy an example file, calc.trace, from the default location on the emulator to the /tmp directory on the emulator host machine:
adb pull /sdcard/calc.trace /tmp Viewing Trace Files in Traceview To run Traceview and view the trace files, enter traceview . For example, to run Traceview on the example files copied in the previous section, use:
traceview /tmp/calc Note: If you are trying to view the trace logs of an application that is built with ProGuard enabled (release mode build), some method and member names might be obfuscated. You can use the Proguard mapping.txt file to figure out the original unobfuscated names. For more information on this file, see the Proguard documentation.
I think any other answer regarding positioning of oncreate
statements or removing uses-sdk
are not related, but this is Android and I could be wrong. Would be useful to redirect this question to an android engineer or post it as a bug
More in the docs
As Matt said, the curly braces are for concatenation. The extra curly braces around 16{a[15]}
are the replication operator. They are described in the IEEE Standard for Verilog document (Std 1364-2005), section "5.1.14 Concatenations".
{16{a[15]}}
is the same as
{
a[15], a[15], a[15], a[15], a[15], a[15], a[15], a[15],
a[15], a[15], a[15], a[15], a[15], a[15], a[15], a[15]
}
In bit-blasted form,
assign result = {{16{a[15]}}, {a[15:0]}};
is the same as:
assign result[ 0] = a[ 0];
assign result[ 1] = a[ 1];
assign result[ 2] = a[ 2];
assign result[ 3] = a[ 3];
assign result[ 4] = a[ 4];
assign result[ 5] = a[ 5];
assign result[ 6] = a[ 6];
assign result[ 7] = a[ 7];
assign result[ 8] = a[ 8];
assign result[ 9] = a[ 9];
assign result[10] = a[10];
assign result[11] = a[11];
assign result[12] = a[12];
assign result[13] = a[13];
assign result[14] = a[14];
assign result[15] = a[15];
assign result[16] = a[15];
assign result[17] = a[15];
assign result[18] = a[15];
assign result[19] = a[15];
assign result[20] = a[15];
assign result[21] = a[15];
assign result[22] = a[15];
assign result[23] = a[15];
assign result[24] = a[15];
assign result[25] = a[15];
assign result[26] = a[15];
assign result[27] = a[15];
assign result[28] = a[15];
assign result[29] = a[15];
assign result[30] = a[15];
assign result[31] = a[15];
There is foreach loop in php. You have to traverse the array.
foreach($array as $key => $value)
{
echo $key." has the value". $value;
}
If you simply want to add commas between values, consider using implode
$string=implode(",",$array);
echo $string;
I tried this on the command.it is working for me.
if "$(OutDir)"=="bin\Debug\" goto Visual
:TFSBuild
goto exit
:Visual
xcopy /y "$(TargetPath)$(TargetName).dll" "$(ProjectDir)..\Demo"
xcopy /y "$(TargetDir)$(TargetName).pdb" "$(ProjectDir)..\Demo"
goto exit
:exit
Graphs are tough, because most non-trivial graph problems tend to require a decent amount of actual code to implement, if more than a sketch of an algorithm is required. A lot of it tends to come down to whether or not the candidate knows the shortest path and graph traversal algorithms, is familiar with cycle types and detection, and whether they know the complexity bounds. I think a lot of questions about this stuff comes down to trivia more than on the spot creative thinking ability.
I think problems related to trees tend to cover most of the difficulties of graph questions, but without as much code complexity.
I like the Project Euler problem that asks to find the most expensive path down a tree (16/67); common ancestor is a good warm up, but a lot of people have seen it. Asking somebody to design a tree class, perform traversals, and then figure out from which traversals they could rebuild a tree also gives some insight into data structure and algorithm implementation. The Stern-Brocot programming challenge is also interesting and quick to develop on a board (http://online-judge.uva.es/p/v100/10077.html).
If you want this for unit testing I just use the hasNoNullFieldsOrProperties()
method from assertj
assertThat(myObj).hasNoNullFieldsOrProperties();
Solution: Manifest merger failed Attribute application@ppComponentFactory ...
If you are using any latest & greatest Firebase libraries or any other libraries, those are actually using AndroidX instead of android.support then you might have the issue as Manifest merger failed!! So, in this case, your project needs to migrate to AndroidX. So follow the link: https://firebase.google.com/support/release-notes/android#update_-_june_17_2019
Or watch this video. https://youtu.be/RgveQ4AY1L8 Thank you.
There are two ways to SELECT a BLOB with TSQL:
SELECT * FROM OPENROWSET (BULK 'C:\Test\Test1.pdf', SINGLE_BLOB) a
As well as:
SELECT BulkColumn FROM OPENROWSET (BULK 'C:\Test\Test1.pdf', SINGLE_BLOB) a
Note the correlation name after the FROM clause, which is mandatory.
You can then this to INSERT by doing an INSERT SELECT.
You can also use the second version to do an UPDATE as I described in How To Update A BLOB In SQL SERVER Using TSQL .
mysqli is the enhanced version of mysql.
PDO extension defines a lightweight, consistent interface for accessing databases in PHP. Each database driver that implements the PDO interface can expose database-specific features as regular extension functions.
You have to calculate the total of grades If it is SQL 2005 you can use CTE
WITH Tot(Total) (
SELECT COUNT(*) FROM table
)
SELECT Grade, COUNT(*) / Total * 100
--, CONVERT(VARCHAR, COUNT(*) / Total * 100) + '%' -- With percentage sign
--, CONVERT(VARCHAR, ROUND(COUNT(*) / Total * 100, -2)) + '%' -- With Round
FROM table
GROUP BY Grade
Anything related with the size of text and appearance must use sp
or pt
. Whereas, anything related to the size of the controls, the layouts, etc. must be used with dp
.
You can use both dp
and dip
at its places.
I would do it this way if you needed an instance variable of the object to work with:
if @business = Business.where(:user_id => current_user.id).first
#Do stuff
else
#Do stuff
end
To avoid update names that contain .com
like [email protected]
to [email protected]
, you can do this:
UPDATE Yourtable
SET Email = LEFT(@Email, LEN(@Email) - 4) + REPLACE(RIGHT(@Email, 4), '.com', '.org')
In the first two cases, you simply forgot to actually call the member function (!, it's not a value) std::vector<int>::size
like this:
#include <vector>
int main () {
std::vector<int> v;
auto size = v.size();
}
Your third call
int size = v.size();
triggers a warning, as not every return value of that function (usually a 64 bit unsigned int) can be represented as a 32 bit signed int.
int size = static_cast<int>(v.size());
would always compile cleanly and also explicitly states that your conversion from std::vector::size_type
to int
was intended.
Note that if the size of the vector
is greater than the biggest number an int
can represent, size
will contain an implementation defined (de facto garbage) value.
The solution is fairly straight forward. To ensure that we don't impact the width of the cells in the table, we'll turn off white-space. To ensure we get a horizontal scroll bar, we'll turn on overflow-x. And that's pretty much it:
.container {
width: 30em;
overflow-x: auto;
white-space: nowrap;
}
You can see the end-result here, or in the animation below. If the table determines the height of your container, you should not need to explicitly set overflow-y
to hidden
. But understand that is also an option.
If you have added your own helper and you want its methods to be available in console, do:
include YourHelperName
method_name(args)
in the console.Example: say you have MyHelper (with a method my_method
) in 'app/helpers/my_helper.rb`, then in the console do:
include MyHelper
my_helper.my_method
Console applications will exit when the main function has finished running. A "return" will achieve this.
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("I'm running!");
return; //This will exit the console application's running thread
}
}
If you're returning an error code you can do it this way, which is accessible from functions outside of the initial thread:
System.Environment.Exit(-1);
Add these lines to your web.config file:
<system.data>
<DbProviderFactories>
<add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory,MySql.Data, Version=6.6.4.0, Culture=neutral, PublicKeyToken=C5687FC88969C44D"/>
</DbProviderFactories>
</system.data>
Change your provider from MySQL to SQL Server or whatever database provider you are connecting to.
It looks like you forgot to include the ngRoute module in your dependency for myApp.
In Angular 1.2, they've made ngRoute optional (so you can use third-party route providers, etc.) and you have to explicitly depend on it in modules, along with including the separate file.
'use strict';
angular.module('myApp', ['ngRoute']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/home'});
}]);
It look like the class Algebra5FirstViewController is compile multiple time.
Can you make sure that the .m and .mm is only included once in your project sources in Xcode? You can also confirm this by checking in the compile log (last icon at the right, next to the breakpoints icon) and see that confirm that it is only compiled once.
Also, if this class is part of a library that you link against and you have a class with the same name, you could have the same error.
Finally, you can try a clean and rebuild, just in case the old object files are still present and there is some junk in the compiled files. Just in case...
EDIT
I also note that the second reference is made in the file for ExercisesViewController. Maybe there is something in this file. Either you #imported the Algebra5FirstViewController file instead of the .h, or the ExercisesViewController has @implementation (Algebra5FirstViewController) instead of @implementation (ExercisesViewController), or there was some junk with this file that will cleaned with a Clean an Rebuild.
If you install Node using the windows installer, there is nothing you have to do. It adds path to node and npm.
You can also use Windows setx command for changing system environment variables. No reboot is required. Just logout/login. Or just open a new cmd window, if you want to see the changing there.
setx PATH "%PATH%;C:\Program Files\nodejs"
I'm not familiar with PHP, but I think String.split is Java equivalent to PHP explode
. As for implode
, standart library does not provide such functionality. You just iterate over your array and build string using StringBuilder/StringBuffer. Or you can try excellent Google Guava Splitter and Joiner or split/join
methods from Apache Commons StringUtils.
I know this is not the OPs issue, but I had this happen on a project. The solution had multiple MVC projects and the wrong project was set as startup.
I had also set the configuration of the project(s) to just start process/debugger and not open a new browser window.
So on the surface it looks as if the debugger is starting up, but it does so for the wrong process. So check that and keep in mind that you can attach to multiple processes also.
Silly mistake that left me scratching my head for about 30 minutes.
Here is a better and elegant solution for your problem statement.
int mynumbercheck = 1000;
// Your number to be checked
var myswitch = new Dictionary <Func<int,bool>, Action>
{
{ x => x < 10 , () => //Do this!... },
{ x => x < 100 , () => //Do this!... },
{ x => x < 1000 , () => //Do this!... },
{ x => x < 10000 , () => //Do this!... } ,
{ x => x < 100000 , () => //Do this!... },
{ x => x < 1000000 , () => //Do this!... }
};
Now to call our conditional switch
myswitch.First(sw => sw.Key(mynumbercheck)).Value();
Here you have another solution based on the one provided by @tarheel
function onEdit() {
var sheetWithNestedSelectsName = "Sitemap";
var columnWithNestedSelectsRoot = 1;
var sheetWithOptionPossibleValuesSuffix = "TabSections";
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var activeSheet = SpreadsheetApp.getActiveSheet();
// If we're not in the sheet with nested selects, exit!
if ( activeSheet.getName() != sheetWithNestedSelectsName ) {
return;
}
var activeCell = SpreadsheetApp.getActiveRange();
// If we're not in the root column or a content row, exit!
if ( activeCell.getColumn() != columnWithNestedSelectsRoot || activeCell.getRow() < 2 ) {
return;
}
var sheetWithActiveOptionPossibleValues = activeSpreadsheet.getSheetByName( activeCell.getValue() + sheetWithOptionPossibleValuesSuffix );
// Get all possible values
var activeOptionPossibleValues = sheetWithActiveOptionPossibleValues.getSheetValues( 1, 1, -1, 1 );
var possibleValuesValidation = SpreadsheetApp.newDataValidation();
possibleValuesValidation.setAllowInvalid( false );
possibleValuesValidation.requireValueInList( activeOptionPossibleValues, true );
activeSheet.getRange( activeCell.getRow(), activeCell.getColumn() + 1 ).setDataValidation( possibleValuesValidation.build() );
}
It has some benefits over the other approach:
So, how to use it:
Enjoy!
You have to use the equal sign in the formula box
=GOOGLEFINANCE("GOOG", "price", DATE(2014,1,1), DATE(2014,12,31), "DAILY")
Do I have to add an encapsulating <div> or <span>?
I think you do. The only thing that comes to mind is padding, but for that you would have to know the image's dimensions beforehand.
Without Using ANY Drop down Using your Drop Down ICON
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<layer-list>
<item>
<shape>
<gradient android:angle="90" android:endColor="#ffffff" android:startColor="#ffffff" android:type="linear" /><!--For gradient background-->
<stroke android:width="1dp" android:color="#FFF" /><!--For Border background-->
<corners android:radius="0dp" /><!--For background corner-->
<padding android:bottom="3dp" android:left="3dp" android:right="6dp" android:top="3dp" /><!--For padding for all sides-->
</shape>
</item>
<item>
<bitmap android:gravity="center|right" android:src="@drawable/ic_down_arrow" /> // Replace with your Icon
</item>
</layer-list>
</item>
also if you are running SharePoint and encounter this error, don't forget to run
Enable-SPSessionStateService -DefaultProvision
or you will continue to receive the above error message.
<SafeAreaView style={{flex:1}}>
<View style={{alignItems:'center'}}>
<Text style={{ textAlign:'center' }}>
This code will make your text centered even when there is a line-break
</Text>
</View>
</SafeAreaView>
This is easily done by replacing the frame's content pane with a JPanel which draws your image:
try {
final Image backgroundImage = javax.imageio.ImageIO.read(new File(...));
setContentPane(new JPanel(new BorderLayout()) {
@Override public void paintComponent(Graphics g) {
g.drawImage(backgroundImage, 0, 0, null);
}
});
} catch (IOException e) {
throw new RuntimeException(e);
}
This example also sets the panel's layout to BorderLayout to match the default content pane layout.
(If you have any trouble seeing the image, you might need to call setOpaque(false)
on some other components so that you can see through to the background.)
I advise you to go with Scanner
instead of DataInputStream
. Scanner
is specifically designed for this purpose and introduced in Java 5. See the following links to know how to use Scanner
.
Example
Scanner s = new Scanner(System.in);
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
All major browsers now include native JSON encoding/decoding.
// To encode an object (This produces a string)
var json_str = JSON.stringify(myobject);
// To decode (This produces an object)
var obj = JSON.parse(json_str);
Note that only valid JSON data will be encoded. For example:
var obj = {'foo': 1, 'bar': (function (x) { return x; })}
JSON.stringify(obj) // --> "{\"foo\":1}"
Valid JSON types are: objects, strings, numbers, arrays, true
, false
, and null
.
Some JSON resources:
Use angular.copy when assigning value of object or array to another variable and that object
value should not be changed.
Without deep copy or using angular.copy, changing value of property or adding any new property update all object referencing that same object.
var app = angular.module('copyExample', []);_x000D_
app.controller('ExampleController', ['$scope',_x000D_
function($scope) {_x000D_
$scope.printToConsole = function() {_x000D_
$scope.main = {_x000D_
first: 'first',_x000D_
second: 'second'_x000D_
};_x000D_
_x000D_
$scope.child = angular.copy($scope.main);_x000D_
console.log('Main object :');_x000D_
console.log($scope.main);_x000D_
console.log('Child object with angular.copy :');_x000D_
console.log($scope.child);_x000D_
_x000D_
$scope.child.first = 'last';_x000D_
console.log('New Child object :')_x000D_
console.log($scope.child);_x000D_
console.log('Main object after child change and using angular.copy :');_x000D_
console.log($scope.main);_x000D_
console.log('Assing main object without copy and updating child');_x000D_
_x000D_
$scope.child = $scope.main;_x000D_
$scope.child.first = 'last';_x000D_
console.log('Main object after update:');_x000D_
console.log($scope.main);_x000D_
console.log('Child object after update:');_x000D_
console.log($scope.child);_x000D_
}_x000D_
}_x000D_
]);_x000D_
_x000D_
// Basic object assigning example_x000D_
_x000D_
var main = {_x000D_
first: 'first',_x000D_
second: 'second'_x000D_
};_x000D_
var one = main; // same as main_x000D_
var two = main; // same as main_x000D_
_x000D_
console.log('main :' + JSON.stringify(main)); // All object are same_x000D_
console.log('one :' + JSON.stringify(one)); // All object are same_x000D_
console.log('two :' + JSON.stringify(two)); // All object are same_x000D_
_x000D_
two = {_x000D_
three: 'three'_x000D_
}; // two changed but one and main remains same_x000D_
console.log('main :' + JSON.stringify(main)); // one and main are same_x000D_
console.log('one :' + JSON.stringify(one)); // one and main are same_x000D_
console.log('two :' + JSON.stringify(two)); // two is changed_x000D_
_x000D_
two = main; // same as main_x000D_
_x000D_
two.first = 'last'; // change value of object's property so changed value of all object property _x000D_
_x000D_
console.log('main :' + JSON.stringify(main)); // All object are same with new value_x000D_
console.log('one :' + JSON.stringify(one)); // All object are same with new value_x000D_
console.log('two :' + JSON.stringify(two)); // All object are same with new value
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="copyExample" ng-controller="ExampleController">_x000D_
<button ng-click='printToConsole()'>Explain</button>_x000D_
</div>
_x000D_
You don't have to manipulate $PATH
anymore!
From [email protected], npm ships with npx
package which lets you run commands from a local node_modules/.bin
or from a central cache.
Simply run:
$ npx [options] <command>[@version] [command-arg]...
By default, npx
will check whether <command>
exists in $PATH
, or in the local project binaries, and execute that.
Calling npx <command>
when <command>
isn't already in your $PATH
will automatically install a package with that name from the NPM registry for you, and invoke it. When it's done, the installed package won’t be anywhere in your globals, so you won’t have to worry about pollution in the long-term. You can prevent this behaviour by providing --no-install
option.
For npm < 5.2.0
, you can install npx
package manually by running the following command:
$ npm install -g npx
If you accept itertools but not numpy, here is an adaptation of rwh_primes2 for Python 3 that runs about twice as fast on my machine. The only substantial change is using a bytearray instead of a list for the boolean, and using compress instead of a list comprehension to build the final list. (I'd add this as a comment like moarningsun if I were able.)
import itertools
izip = itertools.zip_longest
chain = itertools.chain.from_iterable
compress = itertools.compress
def rwh_primes2_python3(n):
""" Input n>=6, Returns a list of primes, 2 <= p < n """
zero = bytearray([False])
size = n//3 + (n % 6 == 2)
sieve = bytearray([True]) * size
sieve[0] = False
for i in range(int(n**0.5)//3+1):
if sieve[i]:
k=3*i+1|1
start = (k*k+4*k-2*k*(i&1))//3
sieve[(k*k)//3::2*k]=zero*((size - (k*k)//3 - 1) // (2 * k) + 1)
sieve[ start ::2*k]=zero*((size - start - 1) // (2 * k) + 1)
ans = [2,3]
poss = chain(izip(*[range(i, n, 6) for i in (1,5)]))
ans.extend(compress(poss, sieve))
return ans
Comparisons:
>>> timeit.timeit('primes.rwh_primes2(10**6)', setup='import primes', number=1)
0.0652179726976101
>>> timeit.timeit('primes.rwh_primes2_python3(10**6)', setup='import primes', number=1)
0.03267321276325674
and
>>> timeit.timeit('primes.rwh_primes2(10**8)', setup='import primes', number=1)
6.394284538007014
>>> timeit.timeit('primes.rwh_primes2_python3(10**8)', setup='import primes', number=1)
3.833829450302801
Assuming these are text files (since you are using notepad++) and that you are on Windows, you could fashion a simple batch script to concatenate them together.
For example, in the directory with all the text files, execute the following:
for %f in (*.txt) do type "%f" >> combined.txt
This will merge all files matching *.txt into one file called combined.txt.
For more information:
Natural versus artificial keys to me is a matter of how much of the business logic you want in your database. Social Security number (SSN) is a great example.
"Each client in my database will, and must, have an SSN." Bam, done, make it the primary key and be done with it. Just remember when your business rule changes you're burned.
I don't like natural keys myself, due to my experience with changing business rules. But if your sure it won't change, it might prevent a few critical joins.
DataRow[] dtr=dtPerson.select("name=Joe");
foreach(var drow in dtr)
{
drow.delete();
}
dtperson.AcceptChanges();
I hope it will help you
replaceChildren()
API!Replacing all children can now be done with the (cross-browser supported) replaceChildren() API:
container.replaceChildren(...arrayOfNewChildren);
This will do both: a) remove all existing children, and b) append all of the given new children, in one operation.
You can also use this same API to just remove existing children, without replacing them:
container.replaceChildren();
This is fully supported in Chrome/Edge 86+, Firefox 78+, and Safari 14+. (Note that the MDN data is currently incorrect for Safari.) It is fully specified behavior. This is likely to be faster than any other proposed method here, since the removal of old children and addition of new children is done a) without requiring innerHTML
, and b) in one step instead of multiple.
Your code has some conceptual issues:
First,
@Html.DropDownListFor(n => n.OrderTemplates, new SelectList(Model.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1), "Please select an order template")
When using DropDownListFor, the first parameter is the property where your selected value is stored once you submit the form. So, in your case, you should have a SelectedOrderId
as part of your model or something like that, in order to use it in this way:
@Html.DropDownListFor(n => n.SelectedOrderId, new SelectList(Model.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1), "Please select an order template")
Second,
Aside from using ViewBag, that is not wrong but there are better ways (put that information in the ViewModel instead), there is a "little bug" (or an unspected behavior) when your ViewBag property, where you are holding the SelectList, is the same name of the property where you put the selected value. To avoid this, just use another name when naming the property holding the list of items.
Some code I would use if I were you to avoid this issues and write better MVC code:
Viewmodel:
public class MyViewModel{
public int SelectedOrderId {get; set;}
public SelectList OrderTemplates {get; set;}
// Other properties you need in your view
}
Controller:
public ActionResult MyAction(){
var model = new MyViewModel();
model.OrderTemplates = new SelectList(db.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1);
//Other initialization code
return View(model);
}
In your View:
@Html.DropDownListFor(n => n.SelectedOrderId, Model.OrderTemplates, "Please select an order template")
If you need to have jquery use !important for more than one item, this is how you would do it.
e.g. set an img
tags max-width and max-height to 500px each
$('img').css('cssText', "max-width: 500px !important;' + "max-height: 500px !important;');
You could create a dict comprehension of just the elements whose values are None, and then update back into the original:
tmp = dict((k,"") for k,v in mydict.iteritems() if v is None)
mydict.update(tmp)
Update - did some performance tests
Well, after trying dicts of from 100 to 10,000 items, with varying percentage of None values, the performance of Alex's solution is across-the-board about twice as fast as this solution.
By writing your client code in terms of iterators you abstract away the container completely.
Consider this code:
class ExpressionParser // some generic arbitrary expression parser
{
public:
template<typename It>
void parse(It begin, const It end)
{
using namespace std;
using namespace std::placeholders;
for_each(begin, end,
bind(&ExpressionParser::process_next, this, _1);
}
// process next char in a stream (defined elsewhere)
void process_next(char c);
};
client code:
ExpressionParser p;
std::string expression("SUM(A) FOR A in [1, 2, 3, 4]");
p.parse(expression.begin(), expression.end());
std::istringstream file("expression.txt");
p.parse(std::istringstream<char>(file), std::istringstream<char>());
char expr[] = "[12a^2 + 13a - 5] with a=108";
p.parse(std::begin(expr), std::end(expr));
Edit: Consider your original code example, implemented with :
using namespace std;
vector<int> myIntVector;
// Add some elements to myIntVector
myIntVector.push_back(1);
myIntVector.push_back(4);
myIntVector.push_back(8);
copy(myIntVector.begin(), myIntVector.end(),
std::ostream_iterator<int>(cout, " "));
Python prefers English keywords to punctuation. Use not x
, i.e. not os.path.exists(...)
. The same thing goes for &&
and ||
which are and
and or
in Python.
So many ways to do it.
From Workbench: File > Run SQL Script -- then follow prompts
From Windows Command Line:
Option 1: mysql -u usr -p
mysql> source file_path.sql
Option 2: mysql -u usr -p '-e source file_path.sql'
Option 3: mysql -u usr -p < file_path.sql
Option 4: put multiple 'source' statements inside of file_path.sql (I do this to drop and recreate schemas/databases which requires multiple files to be run)
mysql -u usr -p < file_path.sql
If you get errors from the command line, make sure you have previously run
cd {!!>>mysqld.exe home directory here<<!!}
mysqld.exe --initialize
This must be run from within the mysqld.exe directory, hence the CD.
Hope this is helpful and not just redundant.
Add the DLL as an existing item to one of the projects and it should be sorted
<?php
header("Location: your url");
exit;
?>
Note: I found this question (varchar(255) v tinyblob v tinytext), which says that VARCHAR(n) requires n+1 bytes of storage for n<=255, n+2 bytes of storage for n>255. Is this the only reason? That seems kind of arbitrary, since you would only be saving two bytes compared to VARCHAR(256), and you could just as easily save another two bytes by declaring it VARCHAR(253).
No. you don't save two bytes by declaring 253. The implementation of the varchar is most likely a length counter and a variable length, nonterminated array. This means that if you store "hello" in a varchar(255) you will occupy 6 bytes: one byte for the length (the number 5) and 5 bytes for the five letters.
Everyone is correct. However, if you're also busy testing your code your own application might still "own" the socket if it starts and stops relatively quickly. Try SO_REUSEADDR as a socket option:
What exactly does SO_REUSEADDR do?
This socket option tells the kernel that even if this port is busy (in the TIME_WAIT state), go ahead and reuse it anyway. If it is busy, but with another state, you will still get an address already in use error. It is useful if your server has been shut down, and then restarted right away while sockets are still active on its port. You should be aware that if any unexpected data comes in, it may confuse your server, but while this is possible, it is not likely.
It has been pointed out that "A socket is a 5 tuple (proto, local addr, local port, remote addr, remote port). SO_REUSEADDR just says that you can reuse local addresses. The 5 tuple still must be unique!" by Michael Hunter ([email protected]). This is true, and this is why it is very unlikely that unexpected data will ever be seen by your server. The danger is that such a 5 tuple is still floating around on the net, and while it is bouncing around, a new connection from the same client, on the same system, happens to get the same remote port. This is explained by Richard Stevens in ``2.7 Please explain the TIME_WAIT state.''.
The problem is with the following CSS line on .nav_button
:
margin: 0 auto;
That would only work if you had one button, that's why they're off-centered when there are more than one nav_button
divs.
If you want all your buttons centered nest the nav_buttons
in another div:
<div class="nav">
<div class="centerButtons">
<div class="nav_button">
<div class="b_left"></div>
<div class="b_middle">Home</div>
<div class="b_right"></div>
</div>
<div class="nav_button">
<div class="b_left"></div>
<div class="b_middle">Contact Us</div>
<div class="b_right"></div>
</div>
</div>
</div>
And style it this way:
.nav{
margin-top:167px;
width:1024px;
height:34px;
}
/* Centers the div that nests the nav_buttons */
.centerButtons {
margin: 0 auto;
float: left;
}
.nav_button{
height:34px;
margin-right:10px;
float: left;
}
I'm using Angular 8 and the answer of @franklin-pious solves the problem. In my case, get the previous url inside a subscribe cause some side effects if it's attached with some data in the view.
The workaround I used was to send the previous url as an optional parameter in the route navigation.
this.router.navigate(['/my-previous-route', {previousUrl: 'my-current-route'}])
And to get this value in the component:
this.route.snapshot.paramMap.get('previousUrl')
this.router and this.route are injected inside the constructor of each component and are imported as @angular/router members.
import { Router, ActivatedRoute } from '@angular/router';
While AngularJS allows you to get a hand on a click event (and thus a target of it) with the following syntax (note the $event
argument to the setMaster
function; documentation here: http://docs.angularjs.org/api/ng.directive:ngClick):
function AdminController($scope) {
$scope.setMaster = function(obj, $event){
console.log($event.target);
}
}
this is not very angular-way of solving this problem. With AngularJS the focus is on the model manipulation. One would mutate a model and let AngularJS figure out rendering.
The AngularJS-way of solving this problem (without using jQuery and without the need to pass the $event
argument) would be:
<div ng-controller="AdminController">
<ul class="list-holder">
<li ng-repeat="section in sections" ng-class="{active : isSelected(section)}">
<a ng-click="setMaster(section)">{{section.name}}</a>
</li>
</ul>
<hr>
{{selected | json}}
</div>
where methods in the controller would look like this:
$scope.setMaster = function(section) {
$scope.selected = section;
}
$scope.isSelected = function(section) {
return $scope.selected === section;
}
Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/WXJ3p/15/
Refer django docs on static files.
In settings.py:
import os
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__).decode('utf-8'))
MEDIA_ROOT = os.path.join(CURRENT_PATH, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = 'static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(CURRENT_PATH, 'static'),
)
Then place your js and css files static folder in your project. Not in media folder.
In views.py:
from django.shortcuts import render_to_response, RequestContext
def view_name(request):
#your stuff goes here
return render_to_response('template.html', locals(), context_instance = RequestContext(request))
In template.html:
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/style.css" />
<script type="text/javascript" src="{{ STATIC_URL }}js/jquery-1.8.3.min.js"></script>
In urls.py:
from django.conf import settings
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
)
Project file structure can be found here in imgbin.
Using Perl
$ cat rayne.txt
A1 123 456
B1 234 567
C1 345 678
A1 098 766
B1 987 6545
C1 876 5434
$ perl -lane ' /A1/ and $x=$F[2] ; END { print "$x" } ' rayne.txt
766
$
After 8 years the situation is changed a bit.
I'm unable to open a new session of Google Chrome without other parameters and allow 'file:' schema.
On macOS I do:
open -n -a "Google Chrome" --args \
--disable-web-security \ # This disable all CORS and other security checks
--user-data-dir=$HOME/fakeChromeDir # This let you to force open a new Google Chrome session
Without this arguments I'm unable to test the XSL stylesheet in local.
Open Notepad++. On the menu go to: Run -> Run.. (F5). Type in:
C:\Python26\python.exe "$(FULL_CURRENT_PATH)"
Now, instead of pressing run, press save to create a shortcut for it.
Notes
Python31
instead of Python26
-i
if you want the command line window to stay open after the script has finishedUse a batch script that runs the Python script and then create a shortcut to that from Notepad++.
As explained here: http://it-ride.blogspot.com/2009/08/notepad-and-python.html
The code opens “HKEY_CURRENT_USER\Software\Python\PythonCore”, if the key exists it will get the path from the first child key of this key.
Check if this key exists, and if does not, you could try creating it.
I also stumbled on this - although caused by yet another possibility: the event identifier (which was "obfuscated" in a #define
) was setting severity to error (the two high-order bits as stated in Event Identifiers). As Event Viewer displays the event identifier (the low-order 16 bits), there couldn't be a match...
For reference, I've put together a set of tips based in my own research while troubleshooting and fixing this:
If your log entry doesn't end with "the message resource is present but the message is not found in the string/message table" (as opposed to the original question):
If you need to add/edit registry information, remember to:
EventLog
service (or restart the system, as hinted by @BrunoBieri).If you don't wish to create a custom DLL resource, mind that commonly available event message files have some caveats:
EventLogMessages.dll
(as hinted by @Matt) goes up to 0xFFFF
EventCreate.exe
"only" goes up to 0x3E9
%1
ReportEvent
can still be inspected by looking into event details (select the desired event, go to Details tab and expand EventData)If you're still getting "cannot be found" in your logged events (original question):
In Winform App(C#):
static string strFilesLoc = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), @"..\..\")) + "Resources\\";
public static string[] GetFontFamily()
{
var result = File.ReadAllText(strFilesLoc + "FontFamily.txt").Trim();
string[] items = result.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
return items;
}
In-text file(FontFamily.txt):
Microsoft Sans Serif
9
true
Not too hard to explain... This is like typing hello worl
, hitting the left-arrow key twice, typing d
, and hitting the down-arrow key.
At least, that is how I infer your terminal is interpeting the \b
and \n
codes.
Redirect the output to a file and I bet you get something else entirely. Although you may have to look at the file's bytes to see the difference.
[edit]
To elaborate a bit, this printf
emits a sequence of bytes: hello worl^H^Hd^J
, where ^H
is ASCII character #8 and ^J
is ASCII character #10. What you see on your screen depends on how your terminal interprets those control codes.
The effects of the three different methods to remove an element from a list:
remove
removes the first matching value, not a specific index:
>>> a = [0, 2, 3, 2]
>>> a.remove(2)
>>> a
[0, 3, 2]
del
removes the item at a specific index:
>>> a = [9, 8, 7, 6]
>>> del a[1]
>>> a
[9, 7, 6]
and pop
removes the item at a specific index and returns it.
>>> a = [4, 3, 5]
>>> a.pop(1)
3
>>> a
[4, 5]
Their error modes are different too:
>>> a = [4, 5, 6]
>>> a.remove(7)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>> del a[7]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
>>> a.pop(7)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: pop index out of range
While creating the user like 'myuser'@'localhost', the user gets limited to be connected only from localhost. Create a user only for remote access and use your remote client IP address from where you will be connecting to the MySQL server. If you can bear the risk of allowing connections from all remote hosts (usually when using dynamic IP address), you can use 'myuser'@'%'. I did this, and also removed bind_address from /etc/mysql/mysql.cnf (Ubuntu) and now it connects flawlessly.
mysql> select host,user from mysql.user;
+-----------+-----------+
| host | user |
+-----------+-----------+
| % | myuser |
| localhost | mysql.sys |
| localhost | root |
+-----------+-----------+
3 rows in set (0.00 sec)
Although all other answers are technically correct, I would recommend you adding the custom path to the beginning of your PATH, not at the end. That way it would be the first place to look for instead of the last:
Add to bottom of ~/.bash_profile
:
export PATH="/cygdrive/C/Program Files/Java/jdk1.6.0_23/bin/":$PATH
That way if you have more than one java
or javac
it will use the one you provided first.
Do a query:
SELECT * FROM v$session s;
Find your user and do the next query (with appropriate parameters):
ALTER SYSTEM KILL SESSION '<SID>, <SERIAL>';
If this is for something that will be called a lot in an application instance, it's a lot faster to compile and cache dynamic code instead of using the activator or ConstructorInfo.Invoke()
. Two easy options for dynamic compilation are compiled Linq Expressions or some simple IL
opcodes and DynamicMethod
. Either way, the difference is huge when you start getting into tight loops or multiple calls.
For those that use coffeescript, I've put the code we use globally to disable the submit buttons on our most widely used form. An adaption of Adil's answer above.
$('#new_post button').prop 'disabled', true
$('#new_post #post_message').keyup ->
$('#new_post button').prop 'disabled', if @value == '' then true else false
return
All great answer guys. I know the question here is specific to enumeration but how about something like this, just another perspective
from itertools import izip, count
a = ["5", "6", "1", "2"]
tupleList = list( izip( count(), a ) )
print(tupleList)
It becomes more powerful, if one has to iterate multiple lists in parallel in terms of performance. Just a thought
a = ["5", "6", "1", "2"]
b = ["a", "b", "c", "d"]
tupleList = list( izip( count(), a, b ) )
print(tupleList)
Here's the nearly shortest possible solution to your question. The solution works in python 3.x. For python 2.x change the import
to Tkinter
rather than tkinter
(the difference being the capitalization):
import tkinter as tk
#import Tkinter as tk # for python 2
def create_window():
window = tk.Toplevel(root)
root = tk.Tk()
b = tk.Button(root, text="Create new window", command=create_window)
b.pack()
root.mainloop()
This is definitely not what I recommend as an example of good coding style, but it illustrates the basic concepts: a button with a command, and a function that creates a window.
Use this code to move items to the right.
<div class="collapse navbar-collapse justify-content-end">
Alternatively to hobodave's answer
SELECT * FROM table
WHERE YEAR(date_created) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
AND MONTH(date_created) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)
You could achieve the same with EXTRACT, using YEAR_MONTH as unit, thus you wouldn't need the AND, like so:
SELECT * FROM table
WHERE EXTRACT(YEAR_MONTH FROM date_created) = EXTRACT(YEAR_MONTH FROM CURDATE() - INTERVAL
1 MONTH)
This can be done using the shuffle method:
private List<Integer> getJumbledList() {
List<Integer> myArrayList2 = new ArrayList<Integer>();
myArrayList2.add(8);
myArrayList2.add(4);
myArrayList2.add(9);
Collections.shuffle(myArrayList2);
return myArrayList2;
Use CSS:
<html>
<head>
<style>
.Large
{
font-size: 16pt;
height: 50px;
}
</style>
<body>
<input type="text" class="Large">
</body>
</html>
composer dump-autoload
PATH vendor/composer/autoload_classmap.php
php artisan dump-autoload
var val = yyy.First().Value;
return yyy.All(x=>x.Value == val) ? val : otherValue;
Cleanest way I can think of. You can make it a one-liner by inlining val, but First() would be evaluated n times, doubling execution time.
To incorporate the "empty set" behavior specified in the comments, you simply add one more line before the two above:
if(yyy == null || !yyy.Any()) return otherValue;
I adapted a script originally written by Narayana Vyas Kondreddi in 2002. I changed the where clause to check text/ntext fields as well, by using patindex rather than like. I also changed the results table slightly. Unreasonably, I changed variable names, and aligned as I prefer (no disrespect to Mr. Kondretti). The user may want to change the data types searched. I used a global table to allow querying mid-processing, but a permanent table might be a smarter way to go.
/* original script by Narayana Vyas Kondreddi, 2002 */
/* adapted by Oliver Holloway, 2009 */
/* these lines can be replaced by use of input parameter for a proc */
declare @search_string varchar(1000);
set @search_string = 'what.you.are.searching.for';
/* create results table */
create table ##string_locations (
table_name varchar(1000),
field_name varchar(1000),
field_value varchar(8000)
)
;
/* special settings */
set nocount on
;
/* declare variables */
declare
@table_name varchar(1000),
@field_name varchar(1000)
;
/* variable settings */
set @table_name = ''
;
set @search_string = QUOTENAME('%' + @search_string + '%','''')
;
/* for each table */
while @table_name is not null
begin
set @field_name = ''
set @table_name = (
select MIN(QUOTENAME(table_schema) + '.' + QUOTENAME(table_name))
from INFORMATION_SCHEMA.TABLES
where
table_type = 'BASE TABLE' and
QUOTENAME(table_schema) + '.' + QUOTENAME(table_name) > @table_name and
OBJECTPROPERTY(OBJECT_ID(QUOTENAME(table_schema) + '.' + QUOTENAME(table_name)), 'IsMSShipped') = 0
)
/* for each string-ish field */
while (@table_name is not null) and (@field_name is not null)
begin
set @field_name = (
select MIN(QUOTENAME(column_name))
from INFORMATION_SCHEMA.COLUMNS
where
table_schema = PARSENAME(@table_name, 2) and
table_name = PARSENAME(@table_name, 1) and
data_type in ('char', 'varchar', 'nchar', 'nvarchar', 'text', 'ntext') and
QUOTENAME(column_name) > @field_name
)
/* search that field for the string supplied */
if @field_name is not null
begin
insert into ##string_locations
exec(
'select ''' + @table_name + ''',''' + @field_name + ''',' + @field_name +
'from ' + @table_name + ' (nolock) ' +
'where patindex(' + @search_string + ',' + @field_name + ') > 0' /* patindex works with char & text */
)
end
;
end
;
end
;
/* return results */
select table_name, field_name, field_value from ##string_locations (nolock)
;
/* drop temp table */
--drop table ##string_locations
;
You can also use inline-table
alongside table-cell
if you want to center your items vertically and horizontally. Below an example of using those display properties to make a menu:
.menu {_x000D_
background-color: lightgrey;_x000D_
height: 30px; /* calc(16px + 12px * 2) */_x000D_
}_x000D_
_x000D_
.menu-container {_x000D_
margin: 0px;_x000D_
padding: 0px;_x000D_
padding-left: 10px;_x000D_
padding-right: 10px;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.menu-item {_x000D_
list-style-type: none;_x000D_
display: inline-table;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.menu-item a {_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
padding-left: 2px;_x000D_
padding-right: 2px;_x000D_
text-decoration: none;_x000D_
color: initial;_x000D_
}_x000D_
_x000D_
.text-upper {_x000D_
text-transform: uppercase;_x000D_
}_x000D_
_x000D_
.text-bold {_x000D_
font-weight: bold;_x000D_
}
_x000D_
<header>_x000D_
<nav class="menu">_x000D_
<ul class="menu-container">_x000D_
<li class="menu-item text-upper text-bold"><a href="javascript:;">StackOverflow</a></li>_x000D_
<li class="menu-item"><a href="javascript:;">Getting started</a></li>_x000D_
<li class="menu-item"><a href="javascript:;">Tags</a></li>_x000D_
</ul>_x000D_
</nav>_x000D_
</header>
_x000D_
It works by setting display: inline-table;
to all the <li>
, and then applying display: table-cell;
and vertical-align: middle;
to the children <a>
. This gives us the power of <table>
tag without using it.
This solution is useful if you do not know the height of your element.
The compatibilty is very good (relative to caniuse.com), with Internet Explorer >= 8.
this.$router.go()
does exactly this; if no arguments are specified, the router navigates to current location, refreshing the page.
note: current implementation of router and its history components don't mark the param as optional, but IMVHO it's either a bug or an omission on Evan You's part, since the spec explicitly allows it. I've filed an issue report about it. If you're really concerned with current TS annotations, just use the equivalent this.$router.go(0)
As to 'why is it so': go
internally passes its arguments to window.history.go
, so its equal to windows.history.go()
- which, in turn, reloads the page, as per MDN doc.
note: since this executes a "soft" reload on regular desktop (non-portable) Firefox, a bunch of strange quirks may appear if you use it but in fact you require a true reload; using the window.location.reload(true);
(https://developer.mozilla.org/en-US/docs/Web/API/Location/reload) mentioned by OP instead may help - it certainly did solve my problems on FF.
No Tracking LINQ to Entities queries
Usage of AsNoTracking() is recommended when your query is meant for read operations. In these scenarios, you get back your entities but they are not tracked by your context.This ensures minimal memory usage and optimal performance
Pros
- Improved performance over regular LINQ queries.
- Fully materialized objects.
- Simplest to write with syntax built into the programming language.
Cons
- Not suitable for CUD operations.
- Certain technical restrictions, such as: Patterns using DefaultIfEmpty for OUTER JOIN queries result in more complex queries than simple OUTER JOIN statements in Entity SQL.
- You still can’t use LIKE with general pattern matching.
More info available here:
I suppose that you are using an array to create your select
form input.
In that case, use an array:
<?php
$selected = array( $_REQUEST['yesnofine'] => 'selected="selected"' );
$fields = array(1 => 'Yes', 2 => 'No', 3 => 'Fine');
?>
<select name=‘yesnofine'>
<?php foreach ($fields as $k => $v): ?>
<option value="<?php echo $k;?>" <?php @print($selected[$k]);?>><?php echo $v;?></options>
<?php endforeach; ?>
</select>
If not, you may just unroll the above loop, and still use an array.
<option value="1" <?php @print($selected[$k]);?>>Yes</options>
<option value="2" <?php @print($selected[$k]);?>>No</options>
<option value="3" <?php @print($selected[$k]);?>>Fine</options>
Notes that I don't know:
$_REQUEST
, You will have to adapt the code to match requirements of the framework you are using, if any.
Also, it is customary in many frameworks to use the alternative syntax in view dedicated scripts.
viewStyle : {
backgroundColor: '#F8F8F8',
justifyContent: 'center',
alignItems: 'center',
height: 60,
paddingTop: 15,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.2,
marginBottom: 10,
elevation: 2,
position: 'relative'
},
Use marginBottom: 10
Best and Simple solution, we can add more events as well!
swal({ title: "WOW!",
text: "Message!",
type: "success"}).then(okay => {
if (okay) {
window.location.href = "URL";
}
});
To set the PATH
variable, within the Makefile only, use something like:
PATH := $(PATH):/my/dir
test:
@echo my new PATH = $(PATH)
I just found this thread and wanted to add to the discussion if the person doesn't want to use a batch file to restart services. In Windows there is an option if you go to Services, service properties, then recovery. Here you can set parameters for the service. Like to restart the service if the service stops. Also, you can even have a second fail attempt do something different as in restart the computer.
If you can use PL/SQL, try (EDIT: Incorporates Neil's xlnt suggestion to start at next higher value):
SELECT 'CREATE SEQUENCE transaction_sequence MINVALUE 0 START WITH '||MAX(trans_seq_no)+1||' INCREMENT BY 1 CACHE 20'
INTO v_sql
FROM transaction_log;
EXECUTE IMMEDIATE v_sql;
Another point to consider: By setting the CACHE parameter to 20, you run the risk of losing up to 19 values in your sequence if the database goes down. CACHEd values are lost on database restarts. Unless you're hitting the sequence very often, or, you don't care that much about gaps, I'd set it to 1.
One final nit: the values you specified for CACHE and INCREMENT BY are the defaults. You can leave them off and get the same result.
The following expression should be unbiased if I am not mistaken:
std::floor( ( max - min + 1.0 ) * rand() ) + min;
I am assuming here that rand() gives you a random value in the range between 0.0 and 1.0 NOT including 1.0 and that max and min are integers with the condition that min < max.
PHP has its own inbuilt class that can be used to unzip or extracts contents from a zip file. The class is ZipArchive. Below is the simple and basic PHP code that will extract a zip file and place it in a specific directory:
<?php
$zip_obj = new ZipArchive;
$zip_obj->open('dummy.zip');
$zip_obj->extractTo('directory_name/sub_dir');
?>
If you want some advance features then below is the improved code that will check if the zip file exists or not:
<?php
$zip_obj = new ZipArchive;
if ($zip_obj->open('dummy.zip') === TRUE) {
$zip_obj->extractTo('directory/sub_dir');
echo "Zip exists and successfully extracted";
}
else {
echo "This zip file does not exists";
}
?>
If you don't care about data:
Best way would be to drop the database and run syncdb
again. Or you can run:
For Django >= 1.5
python manage.py flush
For Django < 1.5
python manage.py reset appname
(you can add --no-input
to the end of the command for it to skip the interactive prompt.)
If you do care about data:
From the docs:
syncdb will only create tables for models which have not yet been installed. It will never issue ALTER TABLE statements to match changes made to a model class after installation. Changes to model classes and database schemas often involve some form of ambiguity and, in those cases, Django would have to guess at the correct changes to make. There is a risk that critical data would be lost in the process.
If you have made changes to a model and wish to alter the database tables to match, use the sql command to display the new SQL structure and compare that to your existing table schema to work out the changes.
https://docs.djangoproject.com/en/dev/ref/django-admin/
Reference: FAQ - https://docs.djangoproject.com/en/dev/faq/models/#if-i-make-changes-to-a-model-how-do-i-update-the-database
People also recommend South ( http://south.aeracode.org/docs/about.html#key-features ), but I haven't tried it.
Depending on how many dynamic classes you need to add as your project grows it's probably worth checking out the classnames utility by JedWatson on GitHub. It allows you to represent your conditional classes as an object and returns those that evaluate to true.
So as an example from its React documentation:
render () {
var btnClass = classNames({
'btn': true,
'btn-pressed': this.state.isPressed,
'btn-over': !this.state.isPressed && this.state.isHovered
});
return <button className={btnClass}>I'm a button!</button>;
}
Since React triggers a re-render when there is a state change, your dynamic class names are handled naturally and kept up to date with the state of your component.
What version of SQL Server are you using? In SQL Server 2008 you can use Table Parameters and Table Types.
An alternative approach is to return a table variable from a user defined function but I am not a big fan of this method.
You can find an example here
I have built semi-long shell scripts (300-500 lines) and Python code which does similar functionality. When many external commands are being executed, I find the shell is easier to use. Perl is also a good option when there is lots of text manipulation.
For SQL Server 2012:
SELECT name, modify_date, create_date, type
FROM sys.procedures
WHERE name like '%XXX%'
ORDER BY modify_date desc
Python 3.4 includes the method statistics.mode
, so it is straightforward:
>>> from statistics import mode
>>> mode([1, 1, 2, 3, 3, 3, 3, 4])
3
You can have any type of elements in the list, not just numeric:
>>> mode(["red", "blue", "blue", "red", "green", "red", "red"])
'red'
try this:
select salesid,count (salesid) from AXDelNotesNoTracking group by salesid having count (salesid) >1
Try putting this into the view controller where you want to detect the press:
-(void) viewWillDisappear:(BOOL)animated {
if ([self.navigationController.viewControllers indexOfObject:self]==NSNotFound) {
// back button was pressed. We know this is true because self is no longer
// in the navigation stack.
}
[super viewWillDisappear:animated];
}
The below command is enough to get the path of the file from a dialog box -
my_FileName = Application.GetOpenFilename("Excel Files (*.tsv), *.txt")
Main difference between JPA and JDBC is level of abstraction.
JDBC is a low level standard for interaction with databases. JPA is higher level standard for the same purpose. JPA allows you to use an object model in your application which can make your life much easier. JDBC allows you to do more things with the Database directly, but it requires more attention. Some tasks can not be solved efficiently using JPA, but may be solved more efficiently with JDBC.
As per the django documentation 2.2 you can use:
To get all fields: Model._meta.get_fields()
To get an individual field: Model._meta.get_field('field name')
ex. Session._meta.get_field('expire_date')
Here's a table to help find the required flags for different permission combinations.
+-----------------------------------------------------------------------------------------------------------------------------------------------------------+ ¦ ¦ folder only ¦ folder, sub-folders and files ¦ folder and sub-folders ¦ folder and files ¦ sub-folders and files ¦ sub-folders ¦ files ¦ ¦-------------+-------------+-------------------------------+------------------------+------------------+-----------------------+-------------+-------------¦ ¦ Propagation ¦ none ¦ none ¦ none ¦ none ¦ InheritOnly ¦ InheritOnly ¦ InheritOnly ¦ ¦ Inheritance ¦ none ¦ Container|Object ¦ Container ¦ Object ¦ Container|Object ¦ Container ¦ Object ¦ +-----------------------------------------------------------------------------------------------------------------------------------------------------------+
So, as David said, you'll want
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit PropagationFlags.None
There are 2 steps you need to perform,
You can read more about this at http://devcenter.heroku.com/articles/custom-domains
At a guess you've missed out the first step perhaps?
UPDATE: Following the announcement of Bamboo's EOL proxy.heroku.com being retired (September 2014) for Bamboo applications so these should also now use the yourapp.herokuapp.com mapping now as well.
select a.empno,a.ename,a.job,a.mgr,B.empno,B.ename as MGR_name, B.job as MGR_JOB from
emp a, emp B where a.mgr=B.empno ;
What is the difference between char array vs char pointer in C?
C99 N1256 draft
There are two different uses of character string literals:
Initialize char[]
:
char c[] = "abc";
This is "more magic", and described at 6.7.8/14 "Initialization":
An array of character type may be initialized by a character string literal, optionally enclosed in braces. Successive characters of the character string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.
So this is just a shortcut for:
char c[] = {'a', 'b', 'c', '\0'};
Like any other regular array, c
can be modified.
Everywhere else: it generates an:
So when you write:
char *c = "abc";
This is similar to:
/* __unnamed is magic because modifying it gives UB. */
static char __unnamed[] = "abc";
char *c = __unnamed;
Note the implicit cast from char[]
to char *
, which is always legal.
Then if you modify c[0]
, you also modify __unnamed
, which is UB.
This is documented at 6.4.5 "String literals":
5 In translation phase 7, a byte or code of value zero is appended to each multibyte character sequence that results from a string literal or literals. The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. For character string literals, the array elements have type char, and are initialized with the individual bytes of the multibyte character sequence [...]
6 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.
6.7.8/32 "Initialization" gives a direct example:
EXAMPLE 8: The declaration
char s[] = "abc", t[3] = "abc";
defines "plain" char array objects
s
andt
whose elements are initialized with character string literals.This declaration is identical to
char s[] = { 'a', 'b', 'c', '\0' }, t[] = { 'a', 'b', 'c' };
The contents of the arrays are modifiable. On the other hand, the declaration
char *p = "abc";
defines
p
with type "pointer to char" and initializes it to point to an object with type "array of char" with length 4 whose elements are initialized with a character string literal. If an attempt is made to usep
to modify the contents of the array, the behavior is undefined.
GCC 4.8 x86-64 ELF implementation
Program:
#include <stdio.h>
int main(void) {
char *s = "abc";
printf("%s\n", s);
return 0;
}
Compile and decompile:
gcc -ggdb -std=c99 -c main.c
objdump -Sr main.o
Output contains:
char *s = "abc";
8: 48 c7 45 f8 00 00 00 movq $0x0,-0x8(%rbp)
f: 00
c: R_X86_64_32S .rodata
Conclusion: GCC stores char*
it in .rodata
section, not in .text
.
If we do the same for char[]
:
char s[] = "abc";
we obtain:
17: c7 45 f0 61 62 63 00 movl $0x636261,-0x10(%rbp)
so it gets stored in the stack (relative to %rbp
).
Note however that the default linker script puts .rodata
and .text
in the same segment, which has execute but no write permission. This can be observed with:
readelf -l a.out
which contains:
Section to Segment mapping:
Segment Sections...
02 .text .rodata
In such cases, you are better off re-adding the whitespace which makes the syntax error immediate apparent:
function(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
document.getElementById("content").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","data/"+id+".html",true);xmlhttp.send();
}
There's a } too many. Also, after the closing } of the function, you should add a ; before the xmlhttp.open()
And finally, I don't see what that anonymous function does up there. It's never executed or referenced. Are you sure you pasted the correct code?
hashCode()
is a function that takes an object and outputs a numeric value. The hashcode for an object is always the same if the object doesn't change.
Functions like HashMap
, HashTable
, HashSet
, etc. that need to store objects will use a hashCode
modulo the size of their internal array to choose in what "memory position" (i.e. array position) to store the object.
There are some cases where collisions may occur (two objects end up with the same hashcode), and that, of course, needs to be solved carefully.
When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object).
At most one parameter is allowed to read from the message body. So this will not work:
// Caution: Will not work!
public HttpResponseMessage Post([FromBody] int id, [FromBody] string name) { ... }
The reason for this rule is that the request body might be stored in a non-buffered stream that can only be read once.
Please go through the website for more details: https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
There are a number of possible ways to do this, but have a google for tkprof
There's no GUI... it's entirely command line and possibly a touch intimidating for Oracle beginners; but it's very powerful.
This link looks like a good start:
In C++, using the std::array class to declare an array, one can easily find the size of an array and also the last element.
#include<iostream>
#include<array>
int main()
{
std::array<int,3> arr;
//To find the size of the array
std::cout<<arr.size()<<std::endl;
//Accessing the last element
auto it=arr.end();
std::cout<<arr.back()<<"\t"<<arr[arr.size()-1]<<"\t"<<*(--it);
return 0;
}
In fact, array class has a whole lot of other functions which let us use array a standard container.
Reference 1 to C++ std::array class
Reference 2 to std::array class
The examples in the references are helpful.
This is the best way for me:
cat filename.tsv |
while read FILENAME
do
sudo find /PATH_FROM/ -name "$FILENAME" -maxdepth 4 -exec cp '{}' /PATH_TO/ \; ;
done
Answering your question as the examples also given previously:
items = []
items.append("apple")
items.append("orange")
items.append("banana")
print items.__len__()
Boost Test Library is a very good choice especially if you're already using Boost.
// TODO: Include your class to test here.
#define BOOST_TEST_MODULE MyTest
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_CASE(MyTestCase)
{
// To simplify this example test, let's suppose we'll test 'float'.
// Some test are stupid, but all should pass.
float x = 9.5f;
BOOST_CHECK(x != 0.0f);
BOOST_CHECK_EQUAL((int)x, 9);
BOOST_CHECK_CLOSE(x, 9.5f, 0.0001f); // Checks differ no more then 0.0001%
}
It supports:
PS: I wrote an article about it that may help you getting started: C++ Unit Testing Framework: A Boost Test Tutorial
For DEFAULT CURRENT_TIMESTAMP:
ALTER TABLE tablename
CHANGE COLUMN columnname1 columname1 DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
CHANGE COLUMN columnname2 columname2 DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;
Please note double columnname declaration
Removing DEFAULT CURRENT_TIMESTAMP:
ALTER TABLE tablename
ALTER COLUMN columnname1 DROP DEFAULT,
ALTER COLUMN columnname2 DROPT DEFAULT;
Adding onKeyPress will work onChange in Text Field.
<TextField
onKeyPress={(ev) => {
console.log(`Pressed keyCode ${ev.key}`);
if (ev.key === 'Enter') {
// Do code here
ev.preventDefault();
}
}}
/>
Try one of these:
Use column alias:
ORDER BY RadioServiceCodeId,RadioService
Use column position:
ORDER BY 1,2
You can only order by columns that actually appear in the result of the DISTINCT query - the underlying data isn't available for ordering on.
Your suggestion would work, but using a Do loop might be a little more readable.
This is actually an idiom in C - instead of using a goto, you can have a do { } while (0) loop with a break statement if you want to bail out of the construct early.
Dim i
For i = 0 To 10
Do
If i = 4 Then Exit Do
WScript.Echo i
Loop While False
Next
As crush suggests, it looks a little better if you remove the extra indentation level.
Dim i
For i = 0 To 10: Do
If i = 4 Then Exit Do
WScript.Echo i
Loop While False: Next
If you are using the GET request to actually SEND data...
check: http://techhelplist.com/index.php/tech-tutorials/37-windows-troubles/60-vbscript-sending-get-request
The problem with MSXML2.XMLHTTP is that there are several versions of it, with different names depending on the windows os version and patches.
this explains it: http://support.microsoft.com/kb/269238
i have had more luck using vbscript to call
set ID = CreateObject("InternetExplorer.Application")
IE.visible = 0
IE.navigate "http://example.com/parser.php?key=" & value & "key2=" & value2
do while IE.Busy....
....and more stuff but just to let the request go thru.
A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method.
Consider the following code:
void Foo(int i, float f)
{
// Do things
}
void Bar()
{
int anInt = 1;
Foo(anInt, 2.0);
}
Here i
and f
are the parameters, and anInt
and 2.0
are the arguments.
It works, but I wouldn't do it if I were you. You don't seem to be deleting that heap data when you're done, which means that you've created a memory leak. The C++ compiler takes care of ensuring that exception data is kept alive even as the stack is popped, so don't feel that you need to use the heap.
Incidentally, throwing a std::string
isn't the best approach to begin with. You'll have a lot more flexibility down the road if you use a simple wrapper object. It may just encapsulate a string
for now, but maybe in future you will want to include other information, like some data which caused the exception or maybe a line number (very common, that). You don't want to change all of your exception handling in every spot in your code-base, so take the high road now and don't throw raw objects.
For those using CloudFormation template. You can set AWS_DEFAULT_REGION
environment variable using UserData and AWS::Region
. For example,
MyInstance1:
Type: AWS::EC2::Instance
Properties:
ImageId: ami-04b9e92b5572fa0d1 #ubuntu
InstanceType: t2.micro
UserData:
Fn::Base64: !Sub |
#!/bin/bash -x
echo "export AWS_DEFAULT_REGION=${AWS::Region}" >> /etc/profile
brilliant example Jonathan Leffler, to make your code work on SLES, I needed to add an additional header to allow the pid_t object :)
#include <sys/types.h>
if the last element type is article too, last-of-type
will not work as expected.
maybe i not really understand how it work.
It is not possible with the default Link List web part, but there are resources describing how to extend Sharepoint server-side to add this functionality.
Share Point Links Open in New Window
Changing Link Lists in Sharepoint 2007
Follow the link below and configure it to what you need. Daterangepicker does it for you, very easily. :)
In case you want to train CNN's with the theano backend like the Keras mnist_cnn.py example:
You better use theano bleeding edge version. Otherwise there may occur assertion errors.
pip install --upgrade --no-deps git+git://github.com/Theano/Theano.git
pip install git+git://github.com/fchollet/keras.git
As for timezones. I have to store the UTC offset as seconds from UTC that way formulas in Excel/OpenOffice can eventually localize datetimes. I found this to be easier than storing any number that has a 0 in front of it. -0900 didn't parse well in any spreadsheet system and importing it was nearly impossible to train people to do.
This code detects left and right swipes, avoids deprecated API calls, and has other miscellaneous improvements over earlier answers.
/**
* Detects left and right swipes across a view.
*/
public class OnSwipeTouchListener implements OnTouchListener {
private final GestureDetector gestureDetector;
public OnSwipeTouchListener(Context context) {
gestureDetector = new GestureDetector(context, new GestureListener());
}
public void onSwipeLeft() {
}
public void onSwipeRight() {
}
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
private final class GestureListener extends SimpleOnGestureListener {
private static final int SWIPE_DISTANCE_THRESHOLD = 100;
private static final int SWIPE_VELOCITY_THRESHOLD = 100;
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
float distanceX = e2.getX() - e1.getX();
float distanceY = e2.getY() - e1.getY();
if (Math.abs(distanceX) > Math.abs(distanceY) && Math.abs(distanceX) > SWIPE_DISTANCE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (distanceX > 0)
onSwipeRight();
else
onSwipeLeft();
return true;
}
return false;
}
}
}
Use it like this:
view.setOnTouchListener(new OnSwipeTouchListener(context) {
@Override
public void onSwipeLeft() {
// Whatever
}
});
Search extension in
/etc/php5/apache2/php.ini
You can use this format as of 4/6/2017.
https://docs.google.com/viewerng/viewer?url=http://yourfile.pdf
Just replace http://yourfile.pdf with the link you use.
I wanted to cover a simple way of doing this with the front end too:
Controller:
public ActionResult Index(int page = 0)
{
const int PageSize = 3; // you can always do something more elegant to set this
var count = this.dataSource.Count();
var data = this.dataSource.Skip(page * PageSize).Take(PageSize).ToList();
this.ViewBag.MaxPage = (count / PageSize) - (count % PageSize == 0 ? 1 : 0);
this.ViewBag.Page = page;
return this.View(data);
}
View:
@* rest of file with view *@
@if (ViewBag.Page > 0)
{
<a href="@Url.Action("Index", new { page = ViewBag.Page - 1 })"
class="btn btn-default">
« Prev
</a>
}
@if (ViewBag.Page < ViewBag.MaxPage)
{
<a href="@Url.Action("Index", new { page = ViewBag.Page + 1 })"
class="btn btn-default">
Next »
</a>
}
Looks like you are using maven (src/main/java)
. In this case put the applicationContext.xml
file in the src/main/resources
directory. It will be copied in the classpath directory and you should be able to access it with
@ContextConfiguration("/applicationContext.xml")
From the Spring-Documentation: A plain path, for example "context.xml", will be treated as a classpath resource from the same package in which the test class is defined. A path starting with a slash is treated as a fully qualified classpath location, for example "/org/example/config.xml".
So it's important that you add the slash when referencing the file in the root directory of the classpath.
If you work with the absolute file path you have to use 'file:C:...' (if I understand the documentation correctly).
This will give DISTINCT values across all the columns:
SELECT DISTINCT value
FROM (
SELECT DISTINCT a AS value FROM my_table
UNION SELECT DISTINCT b AS value FROM my_table
UNION SELECT DISTINCT c AS value FROM my_table
) AS derived
multipart/form-data
Note. Please consult RFC2388 for additional information about file uploads, including backwards compatibility issues, the relationship between "multipart/form-data" and other content types, performance issues, etc.
Please consult the appendix for information about security issues for forms.
The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.
The content type "multipart/form-data" follows the rules of all multipart MIME data streams as outlined in RFC2045. The definition of "multipart/form-data" is available at the [IANA] registry.
A "multipart/form-data" message contains a series of parts, each representing a successful control. The parts are sent to the processing agent in the same order the corresponding controls appear in the document stream. Part boundaries should not occur in any of the data; how this is done lies outside the scope of this specification.
As with all multipart MIME types, each part has an optional "Content-Type" header that defaults to "text/plain". User agents should supply the "Content-Type" header, accompanied by a "charset" parameter.
application/x-www-form-urlencoded
This is the default content type. Forms submitted with this content type must be encoded as follows:
Control names and values are escaped. Space characters are replaced by +', and then reserved characters are escaped as described in [RFC1738], section 2.2: Non-alphanumeric characters are replaced by
%HH', a percent sign and two hexadecimal digits representing the ASCII code of the character. Line breaks are represented as "CR LF" pairs (i.e., %0D%0A').
The control names/values are listed in the order they appear in the document. The name is separated from the value by
=' and name/value pairs are separated from each other by `&'.
application/x-www-form-urlencoded
the body of the HTTP message sent to the server is essentially one giant query string -- name/value pairs are separated by the ampersand (&), and names are separated from values by the equals symbol (=). An example of this would be:
MyVariableOne=ValueOne&MyVariableTwo=ValueTwo
The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.
Swift 5 and 5.1. Create a separate file and put UIAlertController Customization code there
import Foundation
import UIKit
extension UIAlertController {
//Set background color of UIAlertController
func setBackgroudColor(color: UIColor) {
if let bgView = self.view.subviews.first,
let groupView = bgView.subviews.first,
let contentView = groupView.subviews.first {
contentView.backgroundColor = color
}
}
//Set title font and title color
func setTitle(font: UIFont?, color: UIColor?) {
guard let title = self.title else { return }
let attributeString = NSMutableAttributedString(string: title)//1
if let titleFont = font {
attributeString.addAttributes([NSAttributedString.Key.font : titleFont],//2
range: NSMakeRange(0, title.utf8.count))
}
if let titleColor = color {
attributeString.addAttributes([NSAttributedString.Key.foregroundColor : titleColor],//3
range: NSMakeRange(0, title.utf8.count))
}
self.setValue(attributeString, forKey: "attributedTitle")//4
}
//Set message font and message color
func setMessage(font: UIFont?, color: UIColor?) {
guard let title = self.message else {
return
}
let attributedString = NSMutableAttributedString(string: title)
if let titleFont = font {
attributedString.addAttributes([NSAttributedString.Key.font : titleFont], range: NSMakeRange(0, title.utf8.count))
}
if let titleColor = color {
attributedString.addAttributes([NSAttributedString.Key.foregroundColor : titleColor], range: NSMakeRange(0, title.utf8.count))
}
self.setValue(attributedString, forKey: "attributedMessage")//4
}
//Set tint color of UIAlertController
func setTint(color: UIColor) {
self.view.tintColor = color
}
}
Now On any action Show Alert
func tapShowAlert(sender: UIButton) {
let alertController = UIAlertController(title: "Alert!!", message: "This is custom alert message", preferredStyle: .alert)
// Change font and color of title
alertController.setTitle(font: UIFont.boldSystemFont(ofSize: 26), color: UIColor.yellow)
// Change font and color of message
alertController.setMessage(font: UIFont(name: "AvenirNextCondensed-HeavyItalic", size: 18), color: UIColor.red)
// Change background color of UIAlertController
alertController.setBackgroudColor(color: UIColor.black)
let actnOk = UIAlertAction(title: "Ok", style: .default, handler: nil)
let actnCancel = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alertController.addAction(actnOk)
alertController.addAction(actnCancel)
self.present(alertController, animated: true, completion: nil)
}
Result
You can check your g++
by command:
which g++
g++ --version
this will tell you which complier is currently it is pointing.
To switch to g++
4.7 (assuming that you have installed it in your machine),run:
sudo update-alternatives --config gcc
There are 2 choices for the alternative gcc (providing /usr/bin/gcc).
Selection Path Priority Status
------------------------------------------------------------
0 /usr/bin/gcc-4.6 60 auto mode
1 /usr/bin/gcc-4.6 60 manual mode
* 2 /usr/bin/gcc-4.7 40 manual mode
Then select 2
as selection(My machine already pointing to g++
4.7,so the *)
Once you switch the complier then again run g++ --version
to check the switching has happened correctly.
Now compile your program with
g++ -std=c++11 your_file.cpp -o main
I had the same problem and tried everything but it didn't worked. So I used following trick:
function do_stuff(e)
{
if(e){ alert(e); }
}
$("#delete").click(function() {
do_stuff("Clicked");
});
You check if that parameter isn't null than you do code. So when the function will triggered second time it will show what you want.
On a Windows machine, the .m2 folder is expected to be located under ${user.home}
. On Windows 7 and Vista this resolves to <root>\Users\<username>
and on XP it is <root>\Documents and Settings\<username>\.m2
. So you'd normally see it under c:\Users\Jonathan\.m2
.
If you want to create a folder with a .
prefix on Windows, you can simply do this on the command line.
Note that you don't actually need the .m2 location unless you want to create a distinct user settings file, which is optional (see the Settings reference for more details).
If you don't need a separate user settings file and don't really want the local repository under your user home you can simply set the location of your repository to a different folder by modifying the global settings file (located in \conf\settings.xml).
The following snippet would set the local repository to c:\Maven\repository
for example:
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository>c:\Maven\repository</localRepository>
...
if don't work above port id then change it.like 8082,8080 Restart xammp,Start apache server,Check it.It's now working.
It tends to be a bad idea to make non-const fields public because it then becomes hard to force error checking constraints and/or add side-effects to value changes in the future.
In your case, you have a const field, so the above issues are not a problem. The main downside of making it a public field is that you're locking down the underlying implementation. For example, if in the future you wanted to change the internal representation to a C-string or a Unicode string, or something else, then you'd break all the client code. With a getter, you could convert to the legacy representation for existing clients while providing the newer functionality to new users via a new getter.
I'd still suggest having a getter method like the one you have placed above. This will maximize your future flexibility.
In Layman terms, you need to include external js file in your HTML file & thereafter you could directly call your JS method written in an external js file from HTML page. Follow the code snippet for insight:-
caller.html
<script type="text/javascript" src="external.js"></script>
<input type="button" onclick="letMeCallYou()" value="run external javascript">
external.js
function letMeCallYou()
{
alert("Bazinga!!! you called letMeCallYou")
}
From the documentation:
If the pattern does not contain a slash /, git treats it as a shell glob pattern and checks for a match against the pathname relative to the location of the .gitignore file (relative to the toplevel of the work tree if not from a .gitignore file).
A leading slash matches the beginning of the pathname. For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
So you should add the following line to your root .gitignore
:
/config.php
You can also do this with createRange, which is more accurate, than the text cloning technique:
function getNodeTextWidth(nodeWithText) {
var textNode = $(nodeWithText).contents().filter(function () {
return this.nodeType == Node.TEXT_NODE;
})[0];
var range = document.createRange();
range.selectNode(textNode);
return range.getBoundingClientRect().width;
}
I faced the same problem and solved it by doing the following:
From the build menu select
1- clean Project.
2- Build APK.
Handle the form's submit in a function via onSubmit() and perform something like below to remove the form element:
Use getElementById()
of the DOM, then using [object].parentNode.removeChild([object])
suppose your field in question has an id attribute "my_removable_field" code:
var remEl = document.getElementById("my_removable_field");
if ( remEl.parentNode && remEl.parentNode.removeChild ) {
remEl.parentNode.removeChild(remEl);
}
This will get you exactly what you are looking for.
You can do this with GNU grep's perl mode:
echo "12 BBQ ,45 rofl, 89 lol"|grep -P '\d+ (?=rofl)' -o
-P
means Perl-style, and -o
means match only.
Normally yes, .gitignore
is useful for everyone who wants to work with the repository. On occasion you'll want to ignore more private things (maybe you often create LOG
or something. In those cases you probably don't want to force that on anyone else.