Use the 'EntireColumn' property, that's what it is there for. C# snippet, but should give you a good indication of how to do this:
string rangeQuery = "A1:A1";
Range range = workSheet.get_Range(rangeQuery, Type.Missing);
range = range.EntireColumn;
you can use something like this:
$(this).addClass('someClass');
$(Selector).trigger('ClassChanged')
$(otherSelector).bind('ClassChanged', data, function(){//stuff });
but otherwise, no, there's no predefined function to fire an event when a class changes.
Read more about triggers here
XAMPP for linux and mac comes with ProFTPD. Make sure to start the service from XAMPP control panel -> manage servers.
Further complete instructions can be found at localhost XAMPP dashboard -> How-to guides -> Configure FTP Access. I have pasted them below :
Open a new Linux terminal and ensure you are logged in as root.
Create a new group named ftp. This group will contain those user accounts allowed to upload files via FTP.
groupadd ftp
usermod -a -G ftp susan
cd /opt/lampp chown root.ftp htdocs chmod 775 htdocs
You can now transfer files to the XAMPP server using the steps below:
If you’re connecting to the server from the same system, use "127.0.0.1" as the host address. If you’re connecting from a different system, use the network hostname or IP address of the XAMPP server.
Use "21" as the port.
Enter your Linux username and password as your FTP credentials.
Your FTP client should now connect to the server and enter the /opt/lampp/htdocs/ directory, which is the default Web server document root.
Once the file is successfully transferred, you should be able to see it in action.
How about not using strings at all...
This should work for any number of digits...
int[] nums = {1, 0, 2, 2, 1};
int retval = 0;
for (int digit : nums)
{
retval *= 10;
retval += digit;
}
System.out.println("Return value is: " + retval);
step 1: Enter into the MongoDB shell.
mongo
step 2: for the display all the databases.
show dbs;
step 3: for a select database :
use 'databases_name'
step 4: for statistics of your database.
db.stats()
step 5: listing out all the collections(tables).
show collections
step 6:print the data from a particular collection.
db.'collection_name'.find().pretty()
If you want to open many batch files at once you can use the call command. However, the call command closes the current bat file and goes to another. If you want to open many at once, you may want to try this:
@echo off
start cmd "call ex1.bat&ex2.bat&ex3.bat"
And so on or repeat start cmd
"call
..." for however many files. This works for Windows 7, but I am not sure about other systems.
.border-blue.background { ... }
is for one item with multiple classes.
.border-blue, .background { ... }
is for multiple items each with their own class.
.border-blue .background { ... }
is for one item where '.background' is the child of '.border-blue'.
See Chris' answer for a more thorough explanation.
I haven't done time test with this but it was fun to try. Basically convert two columns to one column of tuples. Now convert that to a dataframe, do 'value_counts()' which finds the unique elements and counts them. Fiddle with zip again and put the columns in order you want. You can probably make the steps more elegant but working with tuples seems more natural to me for this problem
b = pd.DataFrame({'A':['yes','yes','yes','yes','no','no','yes','yes','yes','no'],'B':['yes','no','no','no','yes','yes','no','yes','yes','no']})
b['count'] = pd.Series(zip(*[b.A,b.B]))
df = pd.DataFrame(b['count'].value_counts().reset_index())
df['A'], df['B'] = zip(*df['index'])
df = df.drop(columns='index')[['A','B','count']]
<script type="text/javascript" language="javascript">
function createDiv()
{
var divTag = document.createElement("div");
divTag.innerHTML = "Div tag created using Javascript DOM dynamically";
document.body.appendChild(divTag);
}
</script>
I prefere this one:
private ResourceLoader resourceLoader = new DefaultResourceLoader();
@ResponseBody
@RequestMapping(value = "/{id}", produces = "image/bmp")
public Resource texture(@PathVariable("id") String id) {
return resourceLoader.getResource("classpath:images/" + id + ".bmp");
}
Change the media type to what ever image format you have.
And here's one to clear all cookies in all paths and all variants of the domain (www.mydomain.com, mydomain.com etc):
(function () {
var cookies = document.cookie.split("; ");
for (var c = 0; c < cookies.length; c++) {
var d = window.location.hostname.split(".");
while (d.length > 0) {
var cookieBase = encodeURIComponent(cookies[c].split(";")[0].split("=")[0]) + '=; expires=Thu, 01-Jan-1970 00:00:01 GMT; domain=' + d.join('.') + ' ;path=';
var p = location.pathname.split('/');
document.cookie = cookieBase + '/';
while (p.length > 0) {
document.cookie = cookieBase + p.join('/');
p.pop();
};
d.shift();
}
}
})();
The best source of information and updates on this issue I could find is in the TechNet Blogs » The Microsoft Excel Support Team Blog (as mentioned):
Form Controls stop working after December 2014 Updates (Updated March 10, 2015)
On March 2015 a hotfix was released in addition to the automated fix-it and manual instructions, and it's available on Windows Update as well.
The latest update and fix from Microsoft: 3025036 "Cannot insert object" error in an ActiveX custom Office solution after you install the MS14-082 security update
STATUS: Update March 10, 2015:
Hotfixes for this issue have been released in the March 2015 Updates for Office 2007, 2010 & 2013.
For some users, Form Controls (FM20.dll) are no longer working as expected after installing MS14-082 Microsoft Office Security Updates for December 2014. Issues are experienced at times such as when they open files with existing VBA projects using forms controls, try to insert a forms control in to a new worksheet or run third party software that may use these components.
https://technet.microsoft.com/en-us/library/security/ms14-082.aspx
You may receive errors such as: "Cannot insert object"; "Object library invalid or contains references to object definitions that could not be found"; "The program used to create this object is Forms. That program is either not installed on your computer or it is not responding. To edit this object, install Forms or ensure that any dialog boxes in Forms are closed." [...] Additionally, you may be unable to use or change properties of an ActiveX control on a worksheet or receive an error when trying to refer to an ActiveX control as a member of a worksheet via code.
Scripting solution:
Because this problem may affect more than one machine, it is also possible to create a scripting solution to delete the EXD files and run the script as part of the logon process using a policy. The script you would need should contain the following lines and would need to be run for each USER as the .exd files are USER specific.
del %temp%\vbe\*.exd
del %temp%\excel8.0\*.exd
del %appdata%\microsoft\forms\*.exd
del %appdata%\microsoft\local\*.exd
del %temp%\word8.0\*.exd
del %temp%\PPT11.0\*.exd
Additional step:
If the steps above do not resolve your issue, another step that can be tested (see warning below):
On a fully updated machine and after removing the .exd files, open the file in Excel with edit permissions.
Open Visual Basic for Applications > modify the project by adding a comment or edit of some kind to any code module > Debug > Compile VBAProject.
Save and reopen the file. Test for resolution.
If resolved, provide this updated project to additional users.
Warning: If this step resolves your issue, be aware that after deploying this updated project to the other users, these users will also need to have the updates applied on their systems and .exd files removed as well.
If you want to pass two values, you can use this approach
<asp:LinkButton ID="RemoveFroRole" Text="Remove From Role" runat="server"
CommandName='<%# Eval("UserName") %>' CommandArgument='<%# Eval("RoleName") %>'
OnClick="RemoveFromRole_Click" />
Basically I am treating {CommmandName,CommandArgument} as key value. Set both from database field. You will have to use OnClick event and use OnCommand
event in this case, which I think is more clean code.
I personally wouldn't try grabbing it inside of the view. I'm not amazing at Laravel, but I would imagine you'd need to send your route to a controller, and then within the controller, pass the variable (via an array) into your view, using something like $url = Request::url();
.
One way of doing it anyway.
EDIT: Actually look at the method above, probably a better way.
I stumbled upon this question, looking for another answer.
I wanted to prevent all children from triggering the parent.
JavaScript:
document.getElementById("parent").addEventListener("click", function (e) {
if (this !== event.target) return;
// Do something
});
jQuery:
$("#parent").click(function () {
// Do something
}).children().on("click", function (e) {
e.stopPropagation();
});
Use a QR library like ZXing... I had very good experience with it, QrDroid is much buggier. If you must rely on an external reader, rely on a standard one like Google Goggles!
The issue caused by the docker container which exits as soon as the "start" process finishes. i added a command that runs forever and it worked. This issue mentioned here
How about XStream? Not 1 class but 2 jars for many use cases including yours, very simple to use yet quite powerful.
Update your Android SDK via Android SDK Managager. It will probably work fine!
I've got a similar error when installing FCL that needs CCD lib(libccd) like this:
/usr/bin/ld: /usr/local/lib/libccd.a(ccd.o): relocation R_X86_64_32S against `a local symbol' can not be used when making a shared object; recompile with -fPIC
I find that there is two different files named "libccd.a" :
I solved the problem by removing the first file.
For me uninstalling the app from the device works. :)
INADDR_ANY is a constant, that contain 0 in value . this will used only when you want connect from all active ports you don't care about ip-add . so if you want connect any particular ip you should mention like as my_sockaddress.sin_addr.s_addr = inet_addr("192.168.78.2")
If you only have 1 set of radio buttons on 1 form, the jQuery code is as simple as this:
$( "input:checked" ).val()
No, you don't "inherit" non-default constructors, you need to define the one taking a String in your class. Typically you use super(message)
in your constructor to invoke your parent constructor. For example, like this:
public class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
first of all you shouldn't write for (int k = 0; k **<** data.length **- 1**; k++)
because the < is until the k is smaller the length -1 and then the loop will run until the last position in the array and won't get the last place in the array;
so you can fix it by two ways:
1: for (int k = 0; k <= data.length - 1; k++)
2: for (int k = 0; k < data.length; k++)
and then it will work fine!!!
and to swap you can use: to keep one of the int's in another place and then to replace
int x = data[k]
data[k] = data[data.length - 1]
data[data.length - 1] = x;
because you don't want to lose one of the int's!!
c:out
escapes HTML characters so that you can avoid cross-site scripting.
if person.name = <script>alert("Yo")</script>
the script will be executed in the second case, but not when using c:out
I found no other answer gives a border radius, you can simply do it like this, no nested Container
TextField(
decoration: InputDecoration(
border: OutlineInputBorder(
borderSide: BorderSide.none,
borderRadius: BorderRadius.circular(20),
),
),
);
You can use pattern for this:
<input id="numbers" pattern="[0-9.]+" type="number">
Here you can see the complete mobile website interface tips.
There are two ways to know the about Sybase version,
1) Using this System procedure to get the information about Sybase version
> sp_version
> go
2) Using this command to get Sybase version
> select @@version
> go
Here is a similiar thing that I would like to share,
while you're working on Visual Studio you could get an error like:
'scanf': function or variable may be unsafe. Consider using
scanf_s
instead. To disable deprecation, use_CRT_SECURE_NO_WARNINGS
To prevent this, you should write it in the following format
A single character may be read as follows:
char c;
scanf_s("%c", &c, 1);
When multiple characters for non-null terminated strings are read, integers are used as the width specification and the buffer size.
char c[4];
scanf_s("%4c", &c, _countof(c));
Library - Any set of classes or components that can be used as the client deems fit to accomplish a certain task.
Framework - mandates certain guidelines for you to "plug-in" into something bigger than you. You merely provide the pieces specific to your application/requirements in a published-required manner, so that 'the framwework can make your life easy'
In case it helps anyone setBackgroundImage
didn't work for me, but setImage
did
You don't have to export your VMs at all. You can move the VM and clone to a TAXI host in vCenter 1. Then add the host to vCenter 2, and vMotion away whatever VMs to other hosts previously managed by vCenter 2. When done, you can add the TAXI host back to vCenter 1.
It looks like you are executing that command from a DOS session (see this thread), and that means you need to create the .ssh
directory before said command.
Or you can execute it from the bash session (part of the msysgit distribution), and it should work.
If statement for images in jquery:
#html
<button id="chain">Chain</button>
<img src="bulb_on.jpg" alt="img" id="img"/>
#script
<script>
$(document).ready(function(){
$("#chain").click(function(){
if($("#img").attr('src')!='bulb_on.jpg'){
$("#img").attr('src', 'bulb_on.jpg');
}
else
{
$("#img").attr('src', 'bulb_onn.jpg');
}
});
});
</script>
If escaping doesn't work, you can try this:
$str += $("" | Out-String)
It just adds nothing, but as an Out-String
, which creates a new line.
<?php header("Access-Control-Allow-Origin: http://example.com"); ?>
This command disables only first console warning info
Result: console result
I don't like the accepted answer or @fivetwentysix's comment regarding how to solve this. It gets at one method for doing this, but doesn't give the full solution to using toArray. You need to use toArray and give it an argument that's an array of the correct type and size so that you don't end up with an Object array. While an object array will work, I don't think it's best practice in a strongly typed language.
String[] array = arrayList.toArray(new String[arrayList.size()]);
JComboBox comboBox = new JComboBox(array);
Alternatively, you can also maintain strong typing by just using a for loop.
String[] array = new String[arrayList.size()];
for(int i = 0; i < array.length; i++) {
array[i] = arrayList.get(i);
}
JComboBox comboBox = new JComboBox(array);
As far as I know this:
div[class=yourclass] table { your style here; }
or in your case even this:
div.yourclass table { your style here; }
(but this will work for elements with yourclass
that might not be div
s) will affect only tables inside yourclass
. And, as Ken says, the > is not supported everywhere (and div[class=yourclass]
too, so use the point notation for classes).
Vector was part of 1.0 -- the original implementation had two drawbacks:
1. Naming: vectors are really just lists which can be accessed as arrays, so it should have been called ArrayList
(which is the Java 1.2 Collections replacement for Vector
).
2. Concurrency: All of the get()
, set()
methods are synchronized
, so you can't have fine grained control over synchronization.
There is not much difference between ArrayList
and Vector
, but you should use ArrayList
.
From the API doc.
As of the Java 2 platform v1.2, this class was retrofitted to implement the List interface, making it a member of the Java Collections Framework. Unlike the new collection implementations, Vector is synchronized.
The text inside $type is substituted directly into the insert string, therefore MySQL gets this:
... VALUES(testing, 'john', 'whatever')
Notice that there are no quotes around testing, you need to put these in like so:
$type = 'testing';
mysql_query("INSERT INTO contents (type, reporter, description) VALUES('$type', 'john', 'whatever')");
I also recommend you read up on SQL injection, as this sort of parameter passing is prone to hacking attempts if you do not sanitize the data being used:
When you are using GET Method the contract must be this.
[WebGet(UriTemplate = "/", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
List<User> Get();
with this we have a json without the boot parameter
Aldo Flores @alduar http://alduar.blogspot.com
You could use the Any() extension method. The following seems to work for me.
XStreamingElement root = new XStreamingElement("Results",
from el in StreamProductItem(file)
where fieldsToSearch.Any(s => el.Element(s) != null && el.Element(s).Value.Contains(searchTerm))
select fieldsToReturn.Select(r => (r == "product") ? el : el.Element(r))
);
Console.WriteLine(root.ToString());
Where 'fieldsToSearch' and 'fieldsToReturn' are both List objects.
Something like this:
// interface implementation publisher
public delegate void eiSubjectEventHandler(eiSubject subject);
public interface eiSubject
{
event eiSubjectEventHandler OnUpdate;
void GenereteEventUpdate();
}
// class implementation publisher
class ecSubject : eiSubject
{
private event eiSubjectEventHandler _OnUpdate = null;
public event eiSubjectEventHandler OnUpdate
{
add
{
lock (this)
{
_OnUpdate -= value;
_OnUpdate += value;
}
}
remove { lock (this) { _OnUpdate -= value; } }
}
public void GenereteEventUpdate()
{
eiSubjectEventHandler handler = _OnUpdate;
if (handler != null)
{
handler(this);
}
}
}
// interface implementation subscriber
public interface eiObserver
{
void DoOnUpdate(eiSubject subject);
}
// class implementation subscriber
class ecObserver : eiObserver
{
public virtual void DoOnUpdate(eiSubject subject)
{
}
}
I agree with Bryan's answer
if I do
cell.isUserInteractionEnabled = false
then the subviews within the cell won't be user interacted.
On the other site, setting
cell.selectionStyle = .none
will trigger the didSelect method despite not updating the selection color.
Using willSelectRowAt is the way I solved my problem. Example:
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if indexPath.section == 0{
if indexPath.row == 0{
return nil
}
}
else if indexPath.section == 1{
if indexPath.row == 0{
return nil
}
}
return indexPath
}
The enumeration option is excellent however can be improved upon by multiplying the numbers as in:
enum ExitCodes : int
{
Success = 0,
SignToolNotInPath = 1,
AssemblyDirectoryBad = 2,
PFXFilePathBad = 4,
PasswordMissing = 8,
SignFailed = 16,
UnknownError = 32
}
In the case of multiple errors, adding the specific error numbers together will give you a unique number that will represent the combination of detected errors.
For example, an errorlevel of 6 can only consist of errors 4 and 2, 12 can only consist of errors 4 and 8, 14 can only consist of 2, 4 and 8 etc.
After 2017 Solution:
From the homepage, click My Apps, select your app.
Click the TestFlight tab.
In the sidebar, below Builds, click the platform (iOS or tvOS).
In the table on the right, in the Build column, click the app icon or build string for the build that is missing compliance information.
5.Click Expire Build.
Ta-da! Build expired at the App Store Connect.
See Role permissions.
For more information please visit.
Seems to work
$(".selector").change(function() {
var $value = $(this).val();
var $title = $(this).children('option[value='+$value+']').html();
$('#bacon').val($title);
});
Just check with your firebug. And don't put css on hidden input.
For windows you can use:
Running Windows command prompt commands in python.
import os
os.system('tzutil /s "Central Standard Time"')
In windows command prompt try:
This gives current timezone:
tzutil /g
This gives a list of timezones:
tzutil /l
This will set the timezone:
tzutil /s "Central America Standard Time"
For further reference: http://woshub.com/how-to-set-timezone-from-command-prompt-in-windows/
function truncate ($str, $length) {
if (strlen($str) > $length) {
$str = substr($str, 0, $length+1);
$pos = strrpos($str, ' ');
$str = substr($str, 0, ($pos > 0)? $pos : $length);
}
return $str;
}
Example:
print truncate('The first step to eternal life is you have to die.', 25);
string(25) "The first step to eternal"
print truncate('The first step to eternal life is you have to die.', 12);
string(9) "The first"
print truncate('FirstStepToEternalLife', 5);
string(5) "First"
I assume you're seeing this in a React component's render
method, like this (edit: your edited question does indeed show that):
class Example extends React.Component {_x000D_
render() {_x000D_
return <div>_x000D_
<div>Children ({this.props.children.length}):</div>_x000D_
{this.props.children}_x000D_
</div>;_x000D_
}_x000D_
}_x000D_
_x000D_
class Widget extends React.Component {_x000D_
render() {_x000D_
return <div>_x000D_
<div>First <code>Example</code>:</div>_x000D_
<Example>_x000D_
<div>1</div>_x000D_
<div>2</div>_x000D_
<div>3</div>_x000D_
</Example>_x000D_
<div>Second <code>Example</code> with different children:</div>_x000D_
<Example>_x000D_
<div>A</div>_x000D_
<div>B</div>_x000D_
</Example>_x000D_
</div>;_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
<Widget/>,_x000D_
document.getElementById("root")_x000D_
);
_x000D_
<div id="root"></div>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
_x000D_
children
is a special property of React components which contains any child elements defined within the component, e.g. the divs
inside Example
above. {this.props.children}
includes those children in the rendered result.
...what are the situations to use the same
You'd do it when you want to include the child elements in the rendered output directly, unchanged; and not if you didn't.
If you need the space for the purpose of later concatenating it with other strings, then you can use the string formatting approach of adding arguments to your string definition:
<string name="error_">Error: %s</string>
Then for format the string (eg if you have an error returned by the server, otherwise use getString(R.string.string_resource_example)
):
String message = context.getString(R.string.error_, "Server error message here")
Which results in:
Error: Server error message here
I've had this problem. See The Python "Connection Reset By Peer" Problem.
You have (most likely) run afoul of small timing issues based on the Python Global Interpreter Lock.
You can (sometimes) correct this with a time.sleep(0.01)
placed strategically.
"Where?" you ask. Beats me. The idea is to provide some better thread concurrency in and around the client requests. Try putting it just before you make the request so that the GIL is reset and the Python interpreter can clear out any pending threads.
You want to use %d
or %i
for integers. %@
is used for objects.
It's worth noting, though, that the following code will accomplish the same task and is much clearer.
label.intValue = count;
If you are using PHP, try adding the following code at the beginning of the php file:
If you are using localhost, try this:
header("Access-Control-Allow-Origin: *");
If you are using external domains such as server, try this:
header("Access-Control-Allow-Origin: http://www.website.com");
I don't know of a way to force Chrome to not clear the Network debugger, but this might accomplish what you're looking for:
window.addEventListener("beforeunload", function() { debugger; }, false)
This will pause chrome before loading the new page by hitting a breakpoint.
stdin.read(1)
will not return when you press one character - it will wait for '\n'. The problem is that the second character is buffered in standard input, and the moment you call another input - it will return immediately because it gets its input from buffer.
I ran into problems with just an FittedBox
so I wrapped my Image in an LayoutBuilder
:
LayoutBuilder(
builder: (_, constraints) => Image(
fit: BoxFit.fill,
width: constraints.maxWidth,
image: AssetImage(assets.example),
),
)
This worked like a charm and I suggest you give it a try.
Of course you can use height instead of width, this is just what I used.
If you have a copy of backup of SQL Server setup then you could add features (Management Tools Basic/Complete) as you requested.
Please use the below steps in Windows machine:
Managed code runs inside the environment of CLR i.e. .NET runtime.In short all IL are managed code.But if you are using some third party software example VB6 or VC++ component they are unmanaged code as .NET runtime (CLR) does not have control over the source code execution of the language.
In your specific case, you can set the containing a
element to be:
a {
display: block;
text-align: center;
}
See,
There are two ways to convert an RDD to DF in Spark.
toDF()
and createDataFrame(rdd, schema)
I will show you how you can do that dynamically.
The toDF()
command gives you the way to convert an RDD[Row]
to a Dataframe. The point is, the object Row()
can receive a **kwargs
argument. So, there is an easy way to do that.
from pyspark.sql.types import Row
#here you are going to create a function
def f(x):
d = {}
for i in range(len(x)):
d[str(i)] = x[i]
return d
#Now populate that
df = rdd.map(lambda x: Row(**f(x))).toDF()
This way you are going to be able to create a dataframe dynamically.
Other way to do that is creating a dynamic schema. How?
This way:
from pyspark.sql.types import StructType
from pyspark.sql.types import StructField
from pyspark.sql.types import StringType
schema = StructType([StructField(str(i), StringType(), True) for i in range(32)])
df = sqlContext.createDataFrame(rdd, schema)
This second way is cleaner to do that...
So this is how you can create dataframes dynamically.
One way would be to look for the "ProgramFiles(x86)" environment variable:
String x86folder = Environment.GetEnvironmentVariable("ProgramFiles(x86)");
On a fresh install on CENTOS7 I have tried the above methods (edit phpMyAdmin.conf and add Require all granted), it still does'nt work. Here is the solution : install the mod_php module :
$ sudo yum install php
then restart httpd :
$ sudo systemctl restart httpd
and voila !
If you happen to be using date in a MacOS environment, try this:
ST1:~ ejf$ date
Mon Feb 20 21:55:48 CST 2017
ST1:~ ejf$ date -v-1m +%m
01
ST1:~ ejf$ date -v+1m +%m
03
Also, I'd rather calculate the previous and next month on the first day of each month, this way you won't have issues with months ending the 30/31 or 28/29 (Feb/Feb leap year)
If you are using Angular 7 or a previous version and you dont' have access to the clear() method, there is a way to achieve that without doing any loop:
yourFormGroup.controls.youFormArrayName = new FormArray([]);
Authentication is done via a simple ldap_bind command that takes the users DN and the password. The user is authenticated when the bind is successfull. Usually you would get the users DN via an ldap_search based on the users uid or email-address.
Getting the users roles is something different as it is an ldap_search and depends on where and how the roles are stored in the ldap. But you might be able to retrieve the roles during the lap_search used to find the users DN.
You can solve the issue by adding below lines in web.config file.
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-8.0.0.0" newVersion="8.0.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
Can't you implement your own timeout system?
Keep a sorted list, or better yet a priority heap as Heath suggests, of timeout events. In your select or poll calls use the timeout value from the top of the timeout list. When that timeout arrives, do that action attached to that timeout.
That action could be closing a socket that hasn't connected yet.
In the future the format might need to be changed which could be a small head ache having date.dateFromISO8601 calls everywhere in an app. Use a class and protocol to wrap the implementation, changing the date time format call in one place will be simpler. Use RFC3339 if possible, its a more complete representation. DateFormatProtocol and DateFormat is great for dependency injection.
class AppDelegate: UIResponder, UIApplicationDelegate {
internal static let rfc3339DateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
internal static let localeEnUsPosix = "en_US_POSIX"
}
import Foundation
protocol DateFormatProtocol {
func format(date: NSDate) -> String
func parse(date: String) -> NSDate?
}
import Foundation
class DateFormat: DateFormatProtocol {
func format(date: NSDate) -> String {
return date.rfc3339
}
func parse(date: String) -> NSDate? {
return date.rfc3339
}
}
extension NSDate {
struct Formatter {
static let rfc3339: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601)
formatter.locale = NSLocale(localeIdentifier: AppDelegate.localeEnUsPosix)
formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
formatter.dateFormat = rfc3339DateFormat
return formatter
}()
}
var rfc3339: String { return Formatter.rfc3339.stringFromDate(self) }
}
extension String {
var rfc3339: NSDate? {
return NSDate.Formatter.rfc3339.dateFromString(self)
}
}
class DependencyService: DependencyServiceProtocol {
private var dateFormat: DateFormatProtocol?
func setDateFormat(dateFormat: DateFormatProtocol) {
self.dateFormat = dateFormat
}
func getDateFormat() -> DateFormatProtocol {
if let dateFormatObject = dateFormat {
return dateFormatObject
} else {
let dateFormatObject = DateFormat()
dateFormat = dateFormatObject
return dateFormatObject
}
}
}
I copied the code from rally25rs answer and added some tests for non-integer data. The results are undeniably in favor of the method posted by Jonas Klemming. The results for the Exception method that I originally posted are pretty good when you have integer data, but they're the worst when you don't, while the results for the RegEx solution (that I'll bet a lot of people use) were consistently bad. See Felipe's answer for a compiled regex example, which is much faster.
public void runTests()
{
String big_int = "1234567890";
String non_int = "1234XY7890";
long startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByException(big_int);
long endTime = System.currentTimeMillis();
System.out.print("ByException - integer data: ");
System.out.println(endTime - startTime);
startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByException(non_int);
endTime = System.currentTimeMillis();
System.out.print("ByException - non-integer data: ");
System.out.println(endTime - startTime);
startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByRegex(big_int);
endTime = System.currentTimeMillis();
System.out.print("\nByRegex - integer data: ");
System.out.println(endTime - startTime);
startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByRegex(non_int);
endTime = System.currentTimeMillis();
System.out.print("ByRegex - non-integer data: ");
System.out.println(endTime - startTime);
startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByJonas(big_int);
endTime = System.currentTimeMillis();
System.out.print("\nByJonas - integer data: ");
System.out.println(endTime - startTime);
startTime = System.currentTimeMillis();
for(int i = 0; i < 100000; i++)
IsInt_ByJonas(non_int);
endTime = System.currentTimeMillis();
System.out.print("ByJonas - non-integer data: ");
System.out.println(endTime - startTime);
}
private boolean IsInt_ByException(String str)
{
try
{
Integer.parseInt(str);
return true;
}
catch(NumberFormatException nfe)
{
return false;
}
}
private boolean IsInt_ByRegex(String str)
{
return str.matches("^-?\\d+$");
}
public boolean IsInt_ByJonas(String str)
{
if (str == null) {
return false;
}
int length = str.length();
if (length == 0) {
return false;
}
int i = 0;
if (str.charAt(0) == '-') {
if (length == 1) {
return false;
}
i = 1;
}
for (; i < length; i++) {
char c = str.charAt(i);
if (c <= '/' || c >= ':') {
return false;
}
}
return true;
}
Results:
ByException - integer data: 47
ByException - non-integer data: 547
ByRegex - integer data: 390
ByRegex - non-integer data: 313
ByJonas - integer data: 0
ByJonas - non-integer data: 16
The regex below will match both numbers from your example.
\b\d[\d,.]*\b
It will return 5000 and 99,999.99998713 - matching your requirements.
Add an annotation to the method using the keyword Obsolete
. Message argument is optional but a good idea to communicate why the item is now obsolete and/or what to use instead.
Example:
[System.Obsolete("use myMethodB instead")]
void myMethodA()
You can't do that. If you use a redirect (or any other server technique) you will never send the actual page to the browser, only redirection pages.
You have to either use a meta tag or JavaScript to do this, so that you can reload the page after it has been displayed for a while:
ScriptManager.RegisterStartupScript(this, GetType(), "refresh", "window.setTimeout('window.location.reload(true);',5000);", true);
I know this question asks about Phonegap 3.X specifically, but just for reference any Phonegap version above 4.0.0 uses Gradle instead of Ant to build by default. To use Ant instead of Gradle you can add this to your config.xml:
<preference name="android-build-tool" value="ant" />
When using Gradle the keystore signing information now needs to go into a new location (as outlined in this post). Create new file called 'release-signing.properties' in the same folder as "build.gradle" file and put inside the following content:
storeFile=..\\..\\some-keystore.keystore
storeType=jks
keyAlias=some-key
// if you don't want to enter the password at every build, you can store it with this
keyPassword=your-key-password
storePassword=your-store-password
Use this one :
onSelect: function(dateText) {
$("input#DateTo").datepicker('option', 'minDate', dateText);
}
This may be useful : http://jsfiddle.net/injulkarnilesh/xNeTe/
If you just want to check service existence:
if (Get-Service "My Service" -ErrorAction SilentlyContinue)
{
"service exists"
}
class Program
{
static void Main(string[] args)
{
int transactionDate = 20201010;
int? transactionTime = 210000;
var agreementDate = DateTime.Today;
var previousDate = agreementDate.AddDays(-1);
var agreementHour = 22;
var agreementMinute = 0;
var agreementSecond = 0;
var startDate = new DateTime(previousDate.Year, previousDate.Month, previousDate.Day, agreementHour, agreementMinute, agreementSecond);
var endDate = new DateTime(agreementDate.Year, agreementDate.Month, agreementDate.Day, agreementHour, agreementMinute, agreementSecond);
DateTime selectedDate = Convert.ToDateTime(transactionDate.ToString().Substring(6, 2) + "/" + transactionDate.ToString().Substring(4, 2) + "/" + transactionDate.ToString().Substring(0, 4) + " " + string.Format("{0:00:00:00}", transactionTime));
Console.WriteLine("Selected Date : " + selectedDate.ToString());
Console.WriteLine("Start Date : " + startDate.ToString());
Console.WriteLine("End Date : " + endDate.ToString());
if (selectedDate > startDate && selectedDate <= endDate)
Console.WriteLine("Between two dates..");
else if (selectedDate <= startDate)
Console.WriteLine("Less than or equal to the start date!");
else if (selectedDate > endDate)
Console.WriteLine("Greater than end date!");
else
Console.WriteLine("Out of date ranges!");
}
}
Assuming lengths of portfolio and index are the same:
matrix = []
for i in range(len(portfolio)):
matrix.append([portfolio[i], index[i]])
Or a one-liner using list comprehension:
matrix2 = [[portfolio[i], index[i]] for i in range(len(portfolio))]
You can use NumberFormat Class object to accomplish the task.
// Creating number format object to set 2 places after decimal point
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
nf.setGroupingUsed(false);
System.out.println(nf.format(precision));// Assuming precision is a double type variable
Use floats to float the image, the text should wrap beside
Use the formula by tigeravatar:
=COUNTIF($B$2:$B$5,A2)>0 – tigeravatar Aug 28 '13 at 14:50
as conditional formatting. Highlight column A. Choose conditional formatting by forumula. Enter the formula (above) - this finds values in col B that are also in A. Choose a format (I like to use FILL and a bold color).
To find all of those values, highlight col A. Data > Filter and choose Filter by color.
Check https://github.com/mmin18/FlexLayout which you can use percent or java expression directly in layout xml.
<EditText
app:layout_left="0%"
app:layout_right="60%"
app:layout_height="wrap_content"/>
<EditText
app:layout_left="prev.right+10dp"
app:layout_right="100%"
app:layout_height="wrap_content"/>
That particular package does not include assemblies for dotnet core, at least not at present. You may be able to build it for core yourself with a few tweaks to the project file, but I can't say for sure without diving into the source myself.
Use Range("A1").Text
instead of .Value
post comment edit:
Why?
Because the .Text
property of Range object returns what is literally visible in the spreadsheet, so if you cell displays for example i100l:25he*_92
then <- Text
will return exactly what it in the cell including any formatting.
The .Value
and .Value2
properties return what's stored in the cell under the hood excluding formatting. Specially .Value2
for date types, it will return the decimal representation.
If you want to dig deeper into the meaning and performance, I just found this article
which seems like a good guide
another edit
Here you go @Santosh
type in (MANUALLY) the values from the DEFAULT (col A) to other columns
Do not format column A at all
Format column B as Text
Format column C as Date[dd/mm/yyyy]
Format column D as Percentage
now,
paste this code in a module
Sub main()
Dim ws As Worksheet, i&, j&
Set ws = Sheets(1)
For i = 3 To 7
For j = 1 To 4
Debug.Print _
"row " & i & vbTab & vbTab & _
Cells(i, j).Text & vbTab & _
Cells(i, j).Value & vbTab & _
Cells(i, j).Value2
Next j
Next i
End Sub
and Analyse
the output! Its really easy and there isn't much more i can do to help :)
.TEXT .VALUE .VALUE2
row 3 hello hello hello
row 3 hello hello hello
row 3 hello hello hello
row 3 hello hello hello
row 4 1 1 1
row 4 1 1 1
row 4 01/01/1900 31/12/1899 1
row 4 1.00% 0.01 0.01
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 6 63 63 63
row 6 =7*9 =7*9 =7*9
row 6 03/03/1900 03/03/1900 63
row 6 6300.00% 63 63
row 7 29/05/2013 29/05/2013 41423
row 7 29/05/2013 29/05/2013 29/05/2013
row 7 29/05/2013 29/05/2013 41423
row 7 29/05/2013% 29/05/2013% 29/05/2013%
The std::mbstowcs
function is what you are looking for:
char text[] = "something";
wchar_t wtext[20];
mbstowcs(wtext, text, strlen(text)+1);//Plus null
LPWSTR ptr = wtext;
for string
s,
string text = "something";
wchar_t wtext[20];
mbstowcs(wtext, text.c_str(), text.length());//includes null
LPWSTR ptr = wtext;
--> ED: The "L" prefix only works on string literals, not variables. <--
Ahah! Cade is on the money.
An artifact in TOAD prints \r\n
as two placeholder 'blob' characters, but prints a single \r
also as two placeholders. The 1st step toward a solution is to use ..
REPLACE( col_name, CHR(13) || CHR(10) )
.. but I opted for the slightly more robust ..
REPLACE(REPLACE( col_name, CHR(10) ), CHR(13) )
.. which catches offending characters in any order. My many thanks to Cade.
M.
Going back to absolute basics here. The answers on this page and a little googling have brought me to the following resolution to my issue. Steps to restart the apache service with Xampp installed:-
cd C:\xampp\apache\bin
(the default installation path for Xampp)httpd -k restart
I hope that this is of use to others just starting out with running a local Apache server.
You can design a lowpass Butterworth filter in runtime, using butter()
function, and then apply that to the signal.
fc = 300; % Cut off frequency
fs = 1000; % Sampling rate
[b,a] = butter(6,fc/(fs/2)); % Butterworth filter of order 6
x = filter(b,a,signal); % Will be the filtered signal
Highpass and bandpass filters are also possible with this method. See https://www.mathworks.com/help/signal/ref/butter.html
Alternatively, you could set the .AcceptButton property of your form. Enter will automcatically create a click event.
this.AcceptButton = this.buttonSearch;
This article clarifies the question for me and discusses other types of load balancer persistence.
Dave's Thoughts: Load balancer persistence (sticky sessions)
With Git 2.23 (August 2019), that would be, using git switch -f
:
git switch -f master
That avoids the confusion with git checkout
(which deals with files or branches).
And that will proceeds, even if the index or the working tree differs from HEAD.
Both the index and working tree are restored to match the switching target.
If --recurse-submodules
is specified, submodule content is also restored to match the switching target.
This is used to throw away local changes.
Environment.NewLine will give "\r\n" when run on Windows. If you are generating strings for Unix based environments, you don't want the "\r".
I made this into a jQuery function:
jQuery.fn.sortDivs = function sortDivs() {
$("> div", this[0]).sort(dec_sort).appendTo(this[0]);
function dec_sort(a, b){ return ($(b).data("sort")) < ($(a).data("sort")) ? 1 : -1; }
}
So you have a big div like "#boo" and all your little divs inside of there:
$("#boo").sortDivs();
You need the "? 1 : -1" because of a bug in Chrome, without this it won't sort more than 10 divs! http://blog.rodneyrehm.de/archives/14-Sorting-Were-Doing-It-Wrong.html
Original (And Correct) Answer:
You can use is()
and check for the selector :hover
.
var isHovered = $('#elem').is(":hover"); // returns true or false
Example: http://jsfiddle.net/Meligy/2kyaJ/3/
(This only works when the selector matches ONE element max. See Edit 3 for more)
.
Edit 1 (June 29, 2013): (Applicable to jQuery 1.9.x only, as it works with 1.10+, see next Edit 2)
This answer was the best solution at the time the question was answered. This ':hover' selector was removed with the .hover()
method removal in jQuery 1.9.x.
Interestingly a recent answer by "allicarn" shows it's possible to use :hover
as CSS selector (vs. Sizzle) when you prefix it with a selector $($(this).selector + ":hover").length > 0
, and it seems to work!
Also, hoverIntent plugin mentioned in a another answer looks very nice as well.
Edit 2 (September 21, 2013): .is(":hover")
works
Based on another comment I have noticed that the original way I posted, .is(":hover")
, actually still works in jQuery, so.
It worked in jQuery 1.7.x.
It stopped working in 1.9.1, when someone reported it to me, and we all thought it was related to jQuery removing the hover
alias for event handling in that version.
It worked again in jQuery 1.10.1 and 2.0.2 (maybe 2.0.x), which suggests that the failure in 1.9.x was a bug or so not an intentional behaviour as we thought in the previous point.
If you want to test this in a particular jQuery version, just open the JSFidlle example at the beginning of this answer, change to the desired jQuery version and click "Run". If the colour changes on hover, it works.
.
As shown by @Wilmer in the comments, he has a fiddle which doesn't even work against jQuery versions I and others here tested it against. When I tried to find what's special about his case I noticed that he was trying to check multiple elements at a time. This was throwing Uncaught Error: Syntax error, unrecognized expression: unsupported pseudo: hover
.
So, working with his fiddle, this does NOT work:
var isHovered = !!$('#up, #down').filter(":hover").length;
While this DOES work:
var isHovered = !!$('#up,#down').
filter(function() { return $(this).is(":hover"); }).length;
It also works with jQuery sequences that contain a single element, like if the original selector matched only one element, or if you called .first()
on the results, etc.
This is also referenced at my JavaScript + Web Dev Tips & Resources Newsletter.
do you want to try the below code I found on the internet somewhere many moons ago and used.
It uses the Export function of the Chart object along with the CopyPicture method of the Range object.
References:
MSDN - CopyPicture method as it applies to the Range object to copy the range as a picture
dim sSheetName as string
dim oRangeToCopy as range
Dim oCht As Chart
sSheetName ="Sheet1" ' worksheet to work on
set oRangeToCopy =Range("B2:H8") ' range to be copied
Worksheets(sSheetName).Range(oRangeToCopy).CopyPicture xlScreen, xlBitmap
set oCht =charts.add
with oCht
.paste
.Export FileName:="C:\SavedRange.jpg", Filtername:="JPG"
end with
Within the package there is a class called JwtSecurityTokenHandler
which derives from System.IdentityModel.Tokens.SecurityTokenHandler
. In WIF this is the core class for deserialising and serialising security tokens.
The class has a ReadToken(String)
method that will take your base64 encoded JWT string and returns a SecurityToken
which represents the JWT.
The SecurityTokenHandler
also has a ValidateToken(SecurityToken)
method which takes your SecurityToken
and creates a ReadOnlyCollection<ClaimsIdentity>
. Usually for JWT, this will contain a single ClaimsIdentity
object that has a set of claims representing the properties of the original JWT.
JwtSecurityTokenHandler
defines some additional overloads for ValidateToken
, in particular, it has a ClaimsPrincipal ValidateToken(JwtSecurityToken, TokenValidationParameters)
overload. The TokenValidationParameters
argument allows you to specify the token signing certificate (as a list of X509SecurityTokens
). It also has an overload that takes the JWT as a string
rather than a SecurityToken
.
The code to do this is rather complicated, but can be found in the Global.asax.cx code (TokenValidationHandler
class) in the developer sample called "ADAL - Native App to REST service - Authentication with ACS via Browser Dialog", located at
http://code.msdn.microsoft.com/AAL-Native-App-to-REST-de57f2cc
Alternatively, the JwtSecurityToken
class has additional methods that are not on the base SecurityToken
class, such as a Claims
property that gets the contained claims without going via the ClaimsIdentity
collection. It also has a Payload
property that returns a JwtPayload
object that lets you get at the raw JSON of the token. It depends on your scenario which approach it most appropriate.
The general (i.e. non JWT specific) documentation for the SecurityTokenHandler
class is at
http://msdn.microsoft.com/en-us/library/system.identitymodel.tokens.securitytokenhandler.aspx
Depending on your application, you can configure the JWT handler into the WIF pipeline exactly like any other handler.
There are 3 samples of it in use in different types of application at
Probably, one will suite your needs or at least be adaptable to them.
It is supported by Chrome. It's not supposed to be used for validation, but for type hinting the OS. If you have an accept="image/jpeg"
attribute in a file upload the OS can only show files of the suggested type.
I have made it from fastboot mode (Phone - Xiomi Mi5 Android 6.0.1)
Here is steps:
# check if device available
fastboot devices
# remove user data
fastboot erase userdata
# remove cache
fastboot erase cache
# reboot device
fastboot reboot
Like this:
import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);
Or adding from an Array/ or multiple literals; wrap to a list, first.
Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b)); // from an array variable
b.addAll( Arrays.asList( 8, 9, 10)); // from literals
To get the intersection:
// copies all from A; then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print; r.toString() implied.
System.out.println("A intersect B="+r);
Hope this answer helps. Vote for it!
Use the FormBorderStyle
property of your Form
:
this.FormBorderStyle = FormBorderStyle.FixedDialog;
In Symfony 4, you can use the ParameterBagInterface
:
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
class MessageGenerator
{
private $params;
public function __construct(ParameterBagInterface $params)
{
$this->params = $params;
}
public function someMethod()
{
$parameterValue = $this->params->get('parameter_name');
// ...
}
}
and in app/config/services.yaml
:
parameters:
locale: 'en'
dir: '%kernel.project_dir%'
It works for me in both controller and form classes. More details can be found in the Symfony blog.
find, ls, and perl tested against 40,000 files has the same speed (though I didn't try to clear the cache):
[user@server logs]$ time find . | wc -l
42917
real 0m0.054s
user 0m0.018s
sys 0m0.040s
[user@server logs]$ time /bin/ls -f | wc -l
42918
real 0m0.059s
user 0m0.027s
sys 0m0.037s
And with Perl's opendir and readdir, the same time:
[user@server logs]$ time perl -e 'opendir D, "."; @files = readdir D; closedir D; print scalar(@files)."\n"'
42918
real 0m0.057s
user 0m0.024s
sys 0m0.033s
Note: I used /bin/ls -f to make sure to bypass the alias option which might slow a little bit and -f
to avoid file ordering.
ls
without -f
is twice slower than find
/perl
except if ls
is used with -f
, it seems to be the same time:
[user@server logs]$ time /bin/ls . | wc -l
42916
real 0m0.109s
user 0m0.070s
sys 0m0.044s
I also would like to have some script to ask the file system directly without all the unnecessary information.
The tests were based on the answers of Peter van der Heijden, glenn jackman, and mark4o.
In my experience, don't use ffmpeg for splitting/join.
MP4Box, is faster and light than ffmpeg. Please tryit.
Eg if you want to split a 1400mb MP4 file into two parts a 700mb you can use the following cmdl:
MP4Box -splits 716800 input.mp4
eg for concatenating two files you can use:
MP4Box -cat file1.mp4 -cat file2.mp4 output.mp4
Or if you need split by time, use -splitx StartTime:EndTime
:
MP4Box -add input.mp4 -splitx 0:15 -new split.mp4
Where the range is multiple cells:
Excel.Worksheet sheet = workbook.ActiveSheet;
Excel.Range rng = (Excel.Range) sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[3,3]);
Where range is one cell:
Excel.Worksheet sheet = workbook.ActiveSheet;
Excel.Range rng = (Excel.Range) sheet.Cells[1, 1];
You can convert the int
back to an enumeration member with a simple cast, and then call ToString()
:
int value = GetValueFromDb();
var enumDisplayStatus = (EnumDisplayStatus)value;
string stringValue = enumDisplayStatus.ToString();
Using a UINavigationController
and setting its navigation bar's barStyle
to .Black
. past this line in your AppDelegate.m
file.
navigationController.navigationBar.barStyle = UIBarStyleBlack;
If you are not using UINavigationController
then add following code in your ViewController.m
file.
- (UIStatusBarStyle)preferredStatusBarStyle
{
return UIStatusBarStyleLightContent;
}
And call the method to this line :
[self setNeedsStatusBarAppearanceUpdate];
Try this:
SCRIPT:
function winOpen()
{
window.open("yourpage.jsp");
}
HTML:
<a href="javascript:;" onclick="winOpen()">Pop Up</a>
Read https://developer.mozilla.org/en/docs/DOM/window.open for window.open
"Allocation Failure" is cause of GC to kick is not correct. It is an outcome of GC operation.
GC kicks in when there is no space to allocate( depending on region minor or major GC is performed). Once GC is performed if space is freed good enough, but if there is not enough size it fails. Allocation Failure is one such failure. Below document have good explanation https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/g1_gc.html
Use a NavigableMap
implementation, like TreeMap
.
/* Setup */
NavigableMap<Integer, Optional<String>> messages = new TreeMap<>();
messages.put(Integer.MIN_VALUE, Optional.empty());
messages.put(1, Optional.of("testing case 1 to 5"));
messages.put(6, Optional.of("testing case 6 to 10"));
messages.put(11, Optional.empty());
/* Use */
messages.floorEntry(3).getValue().ifPresent(System.out::println);
Try this.
$string = 'my domain name is website3.com';
foreach ($owned_urls as $url) {
//if (strstr($string, $url)) { // mine version
if (strpos($string, $url) !== FALSE) { // Yoshi version
echo "Match found";
return true;
}
}
echo "Not found!";
return false;
Use stristr() or stripos() if you want to check case-insensitive.
With C# 4.0, reflection isn't necessary as the DLR can call it using runtime types. Since using the DLR library is kind of a pain dynamically (instead of the C# compiler generating code for you), the open source framework Dynamitey (.net standard 1.5) gives you easy cached run-time access to the same calls the compiler would generate for you.
var name = InvokeMemberName.Create;
Dynamic.InvokeMemberAction(this, name("GenericMethod", new[]{myType}));
var staticContext = InvokeContext.CreateStatic;
Dynamic.InvokeMemberAction(staticContext(typeof(Sample)), name("StaticMethod", new[]{myType}));
You must run fastboot as root. Try sudo fastboot
For statements, use exec(string)
(Python 2/3) or exec string
(Python 2):
>>> mycode = 'print "hello world"'
>>> exec(mycode)
Hello world
When you need the value of an expression, use eval(string)
:
>>> x = eval("2+2")
>>> x
4
However, the first step should be to ask yourself if you really need to. Executing code should generally be the position of last resort: It's slow, ugly and dangerous if it can contain user-entered code. You should always look at alternatives first, such as higher order functions, to see if these can better meet your needs.
Giving write permissions to all IIS_USRS group is a bad idea from the security point of view. You dont need to do that and you can go with giving permissions only to system user running the application pool.
If you are using II7 (and I guess you do) do the following.
Note #1: if you see ApplicationPoolIdentity in #3 you need to reference this system user like this IIS AppPool{application_pool_name} . For example IIS AppPool\DefaultAppPool
Note #2: when adding this user make sure to set correct locations in the Select Users or Groups dialog. This needs to be set to local machine because this is local account.
With Java 8, Steve's answer can become
public void testMyFunction() throws Exception {
Application mock = mock(Application.class);
when(mock.myFunction(anyString())).thenAnswer(
invocation -> {
Object[] args = invocation.getArguments();
return args[0];
});
assertEquals("someString", mock.myFunction("someString"));
assertEquals("anotherString", mock.myFunction("anotherString"));
}
EDIT: Even shorter:
public void testMyFunction() throws Exception {
Application mock = mock(Application.class);
when(mock.myFunction(anyString())).thenAnswer(
invocation -> invocation.getArgument(0));
assertEquals("someString", mock.myFunction("someString"));
assertEquals("anotherString", mock.myFunction("anotherString"));
}
The reason you are getting the unexpected result is that hist(...)
calculates the distribution from a numeric vector. In your code, table(animalFactor)
behaves like a numeric vector with three elements: 1, 3, 7. So hist(...)
plots the number of 1's (1), the number of 3's (1), and the number of 7's (1). @Roland's solution is the simplest.
Here's a way to do this using ggplot
:
library(ggplot2)
ggp <- ggplot(data.frame(animals),aes(x=animals))
# counts
ggp + geom_histogram(fill="lightgreen")
# proportion
ggp + geom_histogram(fill="lightblue",aes(y=..count../sum(..count..)))
You would get precisely the same result using animalFactor
instead of animals
in the code above.
Excel Interop:
This method prevents Dates getting flipped from dd-mm-yyyy to mm-dd-yyyy
public bool DataTableToExcelFile(DataTable dt, string targetFile)
{
const bool dontSave = false;
bool success = true;
//Exit if there is no rows to export
if (dt.Rows.Count == 0) return false;
object misValue = System.Reflection.Missing.Value;
List<int> dateColIndex = new List<int>();
Excel.Application excelApp = new Excel.Application();
Excel.Workbook excelWorkBook = excelApp.Workbooks.Add(misValue);
Excel.Worksheet excelWorkSheet = excelWorkBook.Sheets("sheet1");
//Iterate through the DataTable and populate the Excel work sheet
try {
for (int i = -1; i <= dt.Rows.Count - 1; i++) {
for (int j = 0; j <= dt.Columns.Count - 1; j++) {
if (i < 0) {
//Take special care with Date columns
if (dt.Columns(j).DataType is typeof(DateTime)) {
excelWorkSheet.Cells(1, j + 1).EntireColumn.NumberFormat = "d-MMM-yyyy;@";
dateColIndex.Add(j);
}
//else if ... Feel free to add more Formats
else {
//Otherwise Format the column as text
excelWorkSheet.Cells(1, j + 1).EntireColumn.NumberFormat = "@";
}
excelWorkSheet.Cells(1, j + 1) = dt.Columns(j).Caption;
}
else if (dateColIndex.IndexOf(j) > -1) {
excelWorkSheet.Cells(i + 2, j + 1) = Convert.ToDateTime(dt.Rows(i).ItemArray(j)).ToString("d-MMM-yyyy");
}
else {
excelWorkSheet.Cells(i + 2, j + 1) = dt.Rows(i).ItemArray(j).ToString();
}
}
}
//Add Autofilters to the Excel work sheet
excelWorkSheet.Cells.AutoFilter(1, Type.Missing, Excel.XlAutoFilterOperator.xlAnd, Type.Missing, true);
//Autofit columns for neatness
excelWorkSheet.Columns.AutoFit();
if (File.Exists(exportFile)) File.Delete(exportFile);
excelWorkSheet.SaveAs(exportFile);
} catch {
success = false;
} finally {
//Do this irrespective of whether there was an exception or not.
excelWorkBook.Close(dontSave);
excelApp.Quit();
releaseObject(excelWorkSheet);
releaseObject(excelWorkBook);
releaseObject(excelApp);
}
return success;
}
If you dont care about Dates being flipped, then use see link that shows how to populate all the cells in the Excel spreadsheet in one line of code:
Excel Interop - Efficiency and performance
CSV:
public string DataTableToCSV(DataTable dt, bool includeHeader, string rowFilter, string sortFilter, bool useCommaDelimiter = false, bool truncateTimesFromDates = false)
{
dt.DefaultView.RowFilter = rowFilter;
dt.DefaultView.Sort = sortFilter;
DataView dv = dt.DefaultView;
string csv = DataTableToCSV(dv.ToTable, includeHeader, useCommaDelimiter, truncateTimesFromDates);
//reset the Filtering
dt.DefaultView.RowFilter = string.Empty;
return csv;
}
public string DataTableToCsv(DataTable dt, bool includeHeader, bool useCommaDelimiter = false, bool truncateTimesFromDates = false)
{
StringBuilder sb = new StringBuilder();
string delimter = Constants.vbTab;
if (useCommaDelimiter)
delimter = ",";
if (includeHeader) {
foreach (DataColumn dc in dt.Columns) {
sb.AppendFormat("{0}" + Constants.vbTab, dc.ColumnName);
}
//remove the last Tab
sb.Remove(sb.ToString.Length - 1, 1);
sb.Append(Environment.NewLine);
}
foreach (DataRow dr in dt.Rows) {
foreach (DataColumn dc in dt.Columns) {
if (Information.IsDate(dr(dc.ColumnName).ToString()) & dr(dc.ColumnName).ToString().Contains(".") == false & truncateTimesFromDates) {
sb.AppendFormat("{0}" + delimter, Convert.ToDateTime(dr(dc.ColumnName).ToString()).Date.ToShortDateString());
} else {
sb.AppendFormat("{0}" + delimter, CheckDBNull(dr(dc.ColumnName).ToString().Replace(",", "")));
}
}
//remove the last Tab
sb.Remove(sb.ToString.Length - 1, 1);
sb.Append(Environment.NewLine);
}
return sb.ToString;
}
public enum enumObjectType
{
StrType = 0,
IntType = 1,
DblType = 2
}
public object CheckDBNull(object obj, enumObjectType ObjectType = enumObjectType.StrType)
{
object objReturn = null;
objReturn = obj;
if (ObjectType == enumObjectType.StrType & Information.IsDBNull(obj)) {
objReturn = "";
} else if (ObjectType == enumObjectType.IntType & Information.IsDBNull(obj)) {
objReturn = 0;
} else if (ObjectType == enumObjectType.DblType & Information.IsDBNull(obj)) {
objReturn = 0.0;
}
return objReturn;
}
If you are using django app to deploy on heroku
make sure to put request library in the requirements.txt file.
Using:
SELECT t.ctn_no
FROM YOUR_TABLE t
GROUP BY t.ctn_no
HAVING COUNT(t.ctn_no) > 1
...will show you the ctn_no
value(s) that have duplicates in your table. Adding criteria to the WHERE will allow you to further tune what duplicates there are:
SELECT t.ctn_no
FROM YOUR_TABLE t
WHERE t.s_ind = 'Y'
GROUP BY t.ctn_no
HAVING COUNT(t.ctn_no) > 1
If you want to see the other column values associated with the duplicate, you'll want to use a self join:
SELECT x.*
FROM YOUR_TABLE x
JOIN (SELECT t.ctn_no
FROM YOUR_TABLE t
GROUP BY t.ctn_no
HAVING COUNT(t.ctn_no) > 1) y ON y.ctn_no = x.ctn_no
I know the answer is already given but I want give a bit brief answer how to update value of a form so that other new comers can get a clear idea.
your form structure is so perfect to use it as an example. so, throughout my answer I will denote it as the form.
this.form = this.fb.group({
'name': ['', Validators.required],
'dept': ['', Validators.required],
'description': ['', Validators.required]
});
so our form is a FormGroup type of object that has three FormControl.
There are two ways to update the model value:
Use the setValue() method to set a new value for an individual control. The setValue() method strictly adheres to the structure of the form group and replaces the entire value for the control.
Use the patchValue() method to replace any properties defined in the object that have changed in the form model.
The strict checks of the setValue() method help catch nesting errors in complex forms, while patchValue() fails silently on those errors.
From Angular official documentation here
so, When updating the value for a form group instance that contains multiple controls, but you may only want to update parts of the model. patchValue() is the one you are looking for.
lets see example. When you use patchValue()
this.form.patchValue({
dept: 1
});
//here we are just updating only dept field and it will work.
but when you use setValue() you need to update the full model as it strictly adheres the structure of the form group. so, if we write
this.form.setValue({
dept: 1
});
// it will throw error.
We must pass all the properties of the form group model. like this
this.form.setValue({
name: 'Mr. Bean'
dept: 1,
description: 'spome description'
});
but I don't use this style frequently. I prefer using the following approach that helps to keep my code cleaner and more understandable.
What I do is, I declare all the controls as a seperate variable and use setValue() to update that specific control.
for the above form, I will do something like this.
get companyIdentifier(): FormControl {
return this.form.get('name') as FormControl;
}
get dept(): FormControl {
return this.form.get('dept') as FormControl;
}
get description(): FormControl {
return this.form.get('description') as FormControl;
}
when you need to update the form control just use that property to update it. In the example the questioner tried to update the dept form control when user select an item from the drop down list.
deptSelected(selected: { id: string; text: string }) {
console.log(selected) // Shows proper selection!
// instead of using this.form.controls['dept'].setValue(selected.id), I prefer the following.
this.dept.setValue(selected.id); // this.dept is the property that returns the 'dept' FormControl of the form.
}
I suggest to have a look FormGroup API to get know how of all the properties and methods of FormGroup.
Additional: to know about getter see here
This worked for me in chrome, jquery.fileupload.js version is 5.42.3
add: function(e, data) {
var uploadErrors = [];
var ext = data.originalFiles[0].name.split('.').pop().toLowerCase();
if($.inArray(ext, ['odt','docx']) == -1) {
uploadErrors.push('Not an accepted file type');
}
if(data.originalFiles[0].size > (2*1024*1024)) {//2 MB
uploadErrors.push('Filesize is too big');
}
if(uploadErrors.length > 0) {
alert(uploadErrors.join("\n"));
} else {
data.submit();
}
},
One of the best examples of Hadoop-like MapReduce implementation.
Keep in mind though that they are limited to key-value based implementations of the MapReduce idea (so they are limiting in applicability).
I was trying to also sort by a DateTime field descending and this seems to do the trick:
var ud = (from d in env
orderby -d.ReportDate.Ticks
select d.ReportDate.ToString("yyyy-MMM") ).Distinct();
SELECT * FROM `permlog` as one
RIGHT JOIN (SELECT MAX(id) as max_id FROM `permlog`) as two
ON one.id = two.max_id
Enable "Show All Files" for the specific project (you might need to hit "Refresh" to see them)**.
The folders/files that are not part of your project appear slightly "lighter" in the project tree.
Right click the folders/files you want to add and click "Include In Project". It will recursively add folders/files to the project.
** These buttons are located on the mini Solution Explorer toolbar.
** Make sure you are NOT in debug mode.
I saw it's solved, but I still want to share a solution which worked for me.
.env file:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=[your database name]
DB_USERNAME=[your MySQL username]
DB_PASSWORD=[your MySQL password]
MySQL admin:
SELECT user, host FROM mysql.user
Console:
php artisan cache:clear
php artisan config:cache
Now it works for me.
You can maintain a Map
(for fast lookup) and List
(for order) but a LinkedHashMap
may be the simplest. You can also try a SortedMap
e.g. TreeMap
, which an have any order you specify.
Currently my build is working. Here you are the steps I tried until it finally worked:
And If you don't have that Pod, maybe you can try by making the same steps with some old Pod that you may encounter in your project.
Added information: also If you have some code error inside a Pod, first you need to solve that code problem and then try to compile again the project.
I'm going to copy the changes made in my project.pbxproj. I know it's not very helpful but it's the only thing that have changed in the git difference commit:
Removed: BDC9821B1E9BD1B600ADE0EF /* (null) in Sources */ = {isa = PBXBuildFile; };
Added: BDC9821B1E9BD1B600ADE0EF /* BuildFile in Sources */ = {isa = PBXBuildFile; };
I hope this can help,
Regards.
As per Atmocreation's solution, except you don't need to re-checkout the whole project, which is useful if you have existing work in progress.
Let's say you have a working copy:
/foo/
which contains directories:
/foo/bar/baz
and you're getting the error message on commit:
svn: File already exists: filesystem '/foo/bar'
Backup the contents of bar somewhere:
mkdir -p ~/tmp/code_backup
cp -r /foo/bar ~/tmp/code_backup
Delete the .svn control directories from the backup. Make sure you get this command right, or you can do pretty serious damage!! Delete them manually if you're unsure.
find ~/tmp/code_backup/bar -name .svn -type d -exec rm -rf {} \;
Double check that the copy is identical:
diff -r -x .svn dist ~/tmp/code_backup/dist
Remove the offending directory from the working copy: cd /foo rm -rf bar
And then restore it from the repository:
cd /foo
svn update bar
Copy back the modified files from backup:
cp -r ~/tmp/code_backup/bar /foo/
You should now be able to commit without the error.
for (NSString* key in xyz) {
id value = xyz[key];
// do stuff
}
This works for every class that conforms to the NSFastEnumeration protocol (available on 10.5+ and iOS), though NSDictionary
is one of the few collections which lets you enumerate keys instead of values. I suggest you read about fast enumeration in the Collections Programming Topic.
Oh, I should add however that you should NEVER modify a collection while enumerating through it.
A cleaner approach would be to create a Person
object that contains contactName
, contactPhone
, etc. Then, use an ArrayList
rather then an array to add the new objects. Create a loop that accepts all the fields for each `Person:
while (!done) {
Person person = new Person();
String name = input.nextLine();
person.setContactName(name);
...
myPersonList.add(person);
}
Using the list will remove the need for array bounds checking.
If anyone else that finds this question and needs a dynamic solution for this where you have an undefined number of columns to transpose to and not exactly 3, you can find a nice solution here: https://github.com/jumpstarter-io/colpivot
var defaults = {_x000D_
_x000D_
"background-color": "#000",_x000D_
color: "#fff",_x000D_
weekdays: [_x000D_
{0: 'sun'},_x000D_
{1: 'mon'},_x000D_
{2: 'tue'},_x000D_
{3: 'wed'},_x000D_
{4: 'thu'},_x000D_
{5: 'fri'},_x000D_
{6: 'sat'}_x000D_
]_x000D_
_x000D_
};_x000D_
_x000D_
console.log(defaults.weekdays[3]);
_x000D_
I think in your private key definition, You should replace:
X509EncodedKeySpec spec = new X509EncodedKeySpec(decoded);
with:
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded);
Look your openssl
command:
$openssl **pkcs8** -topk8 -inform PEM -outform PEM -in mykey.pem \ -out private_key.pem -nocrypt
And the java Exception:
Only PCKS8 codification
There is css&html style guide by google, which recommends to always use a hyphen: https://google.github.io/styleguide/htmlcssguide.html#ID_and_Class_Name_Delimiters .
If you want a true validator that does not rely on jquery and handles server side validation as well ( and you should. server side validation is the most important part) then here is a control
public class RequiredCheckBoxValidator : System.Web.UI.WebControls.BaseValidator
{
private System.Web.UI.WebControls.CheckBox _ctrlToValidate = null;
protected System.Web.UI.WebControls.CheckBox CheckBoxToValidate
{
get
{
if (_ctrlToValidate == null)
_ctrlToValidate = FindControl(this.ControlToValidate) as System.Web.UI.WebControls.CheckBox;
return _ctrlToValidate;
}
}
protected override bool ControlPropertiesValid()
{
if (this.ControlToValidate.Length == 0)
throw new System.Web.HttpException(string.Format("The ControlToValidate property of '{0}' is required.", this.ID));
if (this.CheckBoxToValidate == null)
throw new System.Web.HttpException(string.Format("This control can only validate CheckBox."));
return true;
}
protected override bool EvaluateIsValid()
{
return CheckBoxToValidate.Checked;
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (this.Visible && this.Enabled)
{
System.Web.UI.ClientScriptManager cs = this.Page.ClientScript;
if (this.DetermineRenderUplevel() && this.EnableClientScript)
{
cs.RegisterExpandoAttribute(this.ClientID, "evaluationfunction", "cb_verify", false);
}
if (!this.Page.ClientScript.IsClientScriptBlockRegistered(this.GetType().FullName))
{
cs.RegisterClientScriptBlock(this.GetType(), this.GetType().FullName, GetClientSideScript());
}
}
}
private string GetClientSideScript()
{
return @"<script language=""javascript"">function cb_verify(sender) {var cntrl = document.getElementById(sender.controltovalidate);return cntrl.checked;}</script>";
}
}
You can use negated character classes to exclude certain characters: for example [^abcde]
will match anything but a,b,c,d,e characters.
Instead of specifying all the characters literally, you can use shorthands inside character classes: [\w]
(lowercase) will match any "word character" (letter, numbers and underscore), [\W]
(uppercase) will match anything but word characters; similarly, [\d]
will match the 0-9 digits while [\D]
matches anything but the 0-9 digits, and so on.
If you use PHP you can take a look at the regex character classes documentation.
new Integer(i).toString();
This statement creates the object of the Integer and then call its methods toString(i)
to return the String representation of Integer's value.
Integer.toString(i);
It returns the String object representing the specific int (integer), but here toString(int)
is a static
method.
Summary is in first case it returns the objects string representation, where as in second case it returns the string representation of integer.
The simple solution is to just remap coordinates from the original to the final image, copying pixels from one coordinate space to the other, rounding off as necessary -- which may result in some pixels being copied several times adjacent to each other, and other pixels being skipped, depending on whether you're stretching or shrinking (or both) in either dimension. Make sure your copying iterates through the destination space, so all pixels are covered there even if they're painted more than once, rather than thru the source which may skip pixels in the output.
The better solution involves calculating the corresponding source coordinate without rounding, and then using its fractional position between pixels to compute an appropriate average of the (typically) four pixels surrounding that location. This is essentially a filtering operation, so you lose some resolution -- but the result looks a LOT better to the human eye; it does a much better job of retaining small details and avoids creating straight-line artifacts which humans find objectionable.
Note that the same basic approach can be used to remap flat images onto any other shape, including 3D surface mapping.
If you just need to search for one string within another, use the index
function (or rindex
if you want to start scanning from the end of the string):
if (index($string, $substring) != -1) {
print "'$string' contains '$substring'\n";
}
To search a string for a pattern match, use the match operator m//
:
if ($string =~ m/pattern/) {
print "'$string' matches the pattern\n";
}
/* Design Pattern "table-data gateway" */
class Gateway
{
protected $connection = null;
public function __construct()
{
$this->connection = new PDO("mysql:host=localhost; dbname=db_users", 'root', '');
}
public function loadAll()
{
$sql = 'SELECT * FROM users';
$rows = $this->connection->query($sql);
return $rows;
}
public function loadById($id)
{
$sql = 'SELECT * FROM users WHERE user_id = ' . (int) $id;
$result = $this->connection->query($sql);
return $result->fetch(PDO::FETCH_ASSOC);
// http://php.net/manual/en/pdostatement.fetch.php //
}
}
/* Print all row with column 'user_id' only */
$gateway = new Gateway();
$users = $gateway->loadAll();
$no = 1;
foreach ($users as $key => $value) {
echo $no . '. ' . $key . ' => ' . $value['user_id'] . '<br />';
$no++;
}
/* Print user_id = 1 with all column */
$user = $gateway->loadById(1);
$no = 1;
foreach ($user as $key => $value) {
echo $no . '. ' . $key . ' => ' . $value . '<br />';
$no++;
}
/* Print user_id = 1 with column 'email and password' */
$user = $gateway->loadById(1);
echo $user['email'];
echo $user['password'];
I just found some issues on FAB and I want to enhance another answer.
So, the issue will come once you set the ripple color (FAB color on pressed) programmatically through setRippleColor
. But, we still have an alternative way to set it, i.e. by calling:
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
ColorStateList rippleColor = ContextCompat.getColorStateList(context, R.color.fab_ripple_color);
fab.setBackgroundTintList(rippleColor);
Your project need to has this structure:
/res/color/fab_ripple_color.xml
And the code from fab_ripple_color.xml
is:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="@color/fab_color_pressed" />
<item android:state_focused="true" android:color="@color/fab_color_pressed" />
<item android:color="@color/fab_color_normal"/>
</selector>
Finally, alter your FAB slightly:
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_action_add"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
app:fabSize="normal"
app:borderWidth="0dp"
app:elevation="6dp"
app:pressedTranslationZ="12dp"
app:rippleColor="@android:color/transparent"/> <!-- set to transparent color -->
For API level 21 and higher, set margin right and bottom to 24dp:
...
android:layout_marginRight="24dp"
android:layout_marginBottom="24dp" />
As you can see on my FAB xml code above, I set:
...
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
app:elevation="6dp"
app:pressedTranslationZ="12dp"
...
By setting these attributes, you don't need to set layout_marginTop
and layout_marginRight
again (only on pre-Lollipop). Android will place it automatically on the right corned side of the screen, which the same as normal FAB in Android Lollipop.
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
Or, you can use this in CoordinatorLayout
:
android:layout_gravity="end|bottom"
elevation
and 12dp pressedTranslationZ
, according to this guide from Google.After PushAsync
use PopAsync
(with this
) to remove current page.
await Navigation.PushAsync(new YourSecondPage());
this.Navigation.PopAsync(this);
^([^\s]+) use this it correctly matches only the first word you can test this using this link https://regex101.com/
fileprivate class BundleTargetingClass {}
func loadJSON<T>(name: String) -> T? {
guard let filePath = Bundle(for: BundleTargetingClass.self).url(forResource: name, withExtension: "json") else {
return nil
}
guard let jsonData = try? Data(contentsOf: filePath, options: .mappedIfSafe) else {
return nil
}
guard let json = try? JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) else {
return nil
}
return json as? T
}
copy-paste ready, 3rd party framework independent solution.
usage
let json:[[String : AnyObject]] = loadJSON(name: "Stations")!
public async void Decompile(string DllName)
{
string destinationfilename = "";
if (System.IO.File.Exists(DllName))
{
destinationfilename = (@helperRoot + System.IO.Path.GetFileName(medRuleBook.Schemapath)).ToLower();
if (System.IO.File.Exists(destinationfilename))
{
System.IO.File.Delete(destinationfilename);
}
System.IO.File.Copy(DllName, @destinationfilename);
}
// use dll-> XSD
var returnVal = await DoProcess(
@helperRoot + "xsd.exe", "\"" + @destinationfilename + "\"");
destinationfilename = destinationfilename.Replace(".dll", ".xsd");
if (System.IO.File.Exists(@destinationfilename))
{
// now use XSD
returnVal =
await DoProcess(
@helperRoot + "xsd.exe", "/c /namespace:RuleBook /language:CS " + "\"" + @destinationfilename + "\"");
if (System.IO.File.Exists(@destinationfilename.Replace(".xsd", ".cs")))
{
string getXSD = System.IO.File.ReadAllText(@destinationfilename.Replace(".xsd", ".cs"));
}
}
}
There is the potential for a subtle bug in your code.
[UPDATE: Since he's using map.remove() this description isn't totally valid. I missed that fact the first time thru. :( Thanks to the question's author for pointing that out. I'm leaving the rest as is, but changed the lead statement to say there is potentially a bug.]
In doWork() you get the List value from the Map in a thread-safe way. Afterward, however, you are accessing that list in an unsafe matter. For instance, one thread may be using the list in doWork() while another thread invokes synchronizedMap.get(key).add(value) in addToMap(). Those two access are not synchronized. The rule of thumb is that a collection's thread-safe guarantees don't extend to the keys or values they store.
You could fix this by inserting a synchronized list into the map like
List<String> valuesList = new ArrayList<String>();
valuesList.add(value);
synchronizedMap.put(key, Collections.synchronizedList(valuesList)); // sync'd list
Alternatively you could synchronize on the map while you access the list in doWork():
public void doWork(String key) {
List<String> values = null;
while ((values = synchronizedMap.remove(key)) != null) {
synchronized (synchronizedMap) {
//do something with values
}
}
}
The last option will limit concurrency a bit, but is somewhat clearer IMO.
Also, a quick note about ConcurrentHashMap. This is a really useful class, but is not always an appropriate replacement for synchronized HashMaps. Quoting from its Javadocs,
This class is fully interoperable with Hashtable in programs that rely on its thread safety but not on its synchronization details.
In other words, putIfAbsent() is great for atomic inserts but does not guarantee other parts of the map won't change during that call; it guarantees only atomicity. In your sample program, you are relying on the synchronization details of (a synchronized) HashMap for things other than put()s.
Last thing. :) This great quote from Java Concurrency in Practice always helps me in designing an debugging multi-threaded programs.
For each mutable state variable that may be accessed by more than one thread, all accesses to that variable must be performed with the same lock held.
You need to go into your SDK installation directory, and make sure that the /build-tools sub-directory matches the buildToolsVersion
in your app's build.gradle file:
Simply add a class that tells the interval not to do anything. For example: on hover.
var i = 0;_x000D_
this.setInterval(function() {_x000D_
if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'_x000D_
console.log('Counting...');_x000D_
$('#counter').html(i++); //just for explaining and showing_x000D_
} else {_x000D_
console.log('Stopped counting');_x000D_
}_x000D_
}, 500);_x000D_
_x000D_
/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */_x000D_
$('#counter').hover(function() { //mouse enter_x000D_
$(this).addClass('pauseInterval');_x000D_
},function() { //mouse leave_x000D_
$(this).removeClass('pauseInterval');_x000D_
}_x000D_
);_x000D_
_x000D_
/* Other example */_x000D_
$('#pauseInterval').click(function() {_x000D_
$('#counter').toggleClass('pauseInterval');_x000D_
});
_x000D_
body {_x000D_
background-color: #eee;_x000D_
font-family: Calibri, Arial, sans-serif;_x000D_
}_x000D_
#counter {_x000D_
width: 50%;_x000D_
background: #ddd;_x000D_
border: 2px solid #009afd;_x000D_
border-radius: 5px;_x000D_
padding: 5px;_x000D_
text-align: center;_x000D_
transition: .3s;_x000D_
margin: 0 auto;_x000D_
}_x000D_
#counter.pauseInterval {_x000D_
border-color: red; _x000D_
}
_x000D_
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<p id="counter"> </p>_x000D_
<button id="pauseInterval">Pause</button></p>
_x000D_
I've been looking for this fast and easy approach for ages, so I'm posting several versions to introduce as many people to it as possible.
Repository managers with support for private npm registries:
With VSCode 1.43 (Q1 2020), those Alt+? / Alt+?, or Ctrl+- / Ctrl+Shift+- will also... preserve selection.
See issue 89699:
Benjamin Pasero (bpasero
) adds:
going back/forward restores selections as they were.
Note that in order to get a history entry there needs to be at least 10 lines between the positions to consider the entry as new entry.
I had the same problem when called another javascript file from a file without putting javascript "physical" address. I solved it by calling it same way from the html, example: "JS / archivo.js" instead of "archivo.js"
In case anyone arrives looking for how to generate a relative path from the rails console
ActionView::Helpers::AssetTagHelper
image_path('my_image.png')
=> "/images/my_image.png"
Or the controller
include ActionView::Helpers::AssetTagHelper
image_path('my_image.png')
=> "/images/my_image.png"
You could put the async calls in a separate method and call that method in the constructor. Although, this may lead to a situation where some variable values not being available at the time you expect them.
public NewTravelPageVM(){
GetVenues();
}
async void GetVenues(){
var locator = CrossGeolocator.Current;
var position = await locator.GetPositionAsync();
Venues = await Venue.GetVenues(position.Latitude, position.Longitude);
}
In Python 2.7 and 3 you can use this:
import string
string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
As @Zaz says:
string.lowercase
is deprecated and no longer works in Python 3 but string.ascii_lowercase
works in both
You could try different colors for brackets, maybe some green or red would help ? I think your compiler can't rcognize black ink :P
Assign value to a hidden field in the code-behind file. Access this value in your javascript like a normal HTML control.
You need to search for OWNER_NAME.
cat -v dumpfile.dmp | grep -o '<OWNER_NAME>.*</OWNER_NAME>' | uniq -u
cat -v turn the dumpfile into visible text.
grep -o shows only the match so we don't see really long lines
uniq -u removes duplicate lines so you see less output.
This works pretty well, even on large dump files, and could be tweaked for usage in a script.
You can also get it from Chocolatey:
It will focus with mouse point
$("#TextBox").focus();
This is now natively in VS2017:
//#region fold this up
//#endregion
Whitespace between the // and # does not matter.
I do not know what version this was added in, as I cannot find any mention of it in the changelogs. I am able to use it in v15.7.3.
Please try this... This works for me..
In adapter,take a sparse boolean array.
SparseBooleanArray sparseBooleanArray;
In constructor initialise this,
sparseBooleanArray=new SparseBooleanArray();
In bind holder add,
@Override
public void onBindViewHolder(DispositionViewHolder holder, final int position) {
holder.tv_disposition.setText(dispList.get(position).getName());
if(sparseBooleanArray.get(position,false))
{
holder.rd_disp.setChecked(true);
}
else
{
holder.rd_disp.setChecked(false);
}
setClickListner(holder,position);
}
private void setClickListner(final DispositionViewHolder holder, final int position) {
holder.rd_disp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sparseBooleanArray.clear();
sparseBooleanArray.put(position, true);
notifyDataSetChanged();
}
});
}
rd_disp is radio button in xml file.
So when the recycler view load the items,in bindView Holder it check whether the sparseBooleanArray contain the value "true" correspnding to its position.
If the value returned is true then we set the radio button selection true.Else we set the selection false. In onclickHolder I have cleared the sparseArray and set the value true corresponding to that position. When I call notify datasetChange it again call the onBindViewHolder and the condition are checked again. This makes our selection to only select particular radio.
I had an almost identical error:
Error while connecting to MySQL: Authentication plugin 'caching_sha2_password' is not supported
The solution for me was simple:
My db username/password creds were incorrect. The error was not descriptive of the problem, so I thought I would share this in case someone else runs into this.
Setting your provisioning profile moved. It confounded me for a while until I found it also.
Exercise 16 from Zed Shaw's book? You can use escape characters as follows:
paragraph1 = "%s \n %s \n %s \n" % (line1, line2, line3)
target.write(paragraph1)
target.close()
I just installed conda 4.7.11 in Windows 10. OpenCV can be easily installed in Anaconda Navigator. After launching Navigator, click on Environments on the left panel. In the top drop-down, select Not installed. Then search for py-opencv, tick on the left checkbox to install it. It will install the dependent package libopencv. I use import cv2
in Spyder to access it.
Why not just use setBackgroundColor(getResources().getColor(R.color.holo_light_green))
?
Edit: If you want to have something which looks more like an Android button you are going to want to create a gradient and set it as the background. For an example of this, you can check out this question.
I have solved this issue by storing images on internal storage and then using .setImageURI() rather than .setBitmap().
The problem is with navbar-fixed-top, which will overlay your content unless specify body-padding. No solution provided here works in 100% cases. The JQuery solution blink/shift the page after the page is loaded, which looks weird.
The real solution for me is not to use navbar-fixed-top, but navbar-static-top.
.navbar { margin-bottom:0px;} //for jumtron support, see http://stackoverflow.com/questions/23911242/gap-between-navbar-and-jumbotron
<nav class="navbar navbar-inverse navbar-static-top">
...
</nav>
I'm writtinga phonegap app, and checkboxes vary in size, look, etc. So I made my own simple checkbox:
First the HTML code:
<span role="checkbox"/>
Then the CSS:
[role=checkbox]{
background-image: url(../img/checkbox_nc.png);
height: 15px;
width: 15px;
display: inline-block;
margin: 0 5px 0 5px;
cursor: pointer;
}
.checked[role=checkbox]{
background-image: url(../img/checkbox_c.png);
}
To toggle checkbox state, I used JQuery:
CLICKEVENT='touchend';
function createCheckboxes()
{
$('[role=checkbox]').bind(CLICKEVENT,function()
{
$(this).toggleClass('checked');
});
}
But It can easily be done without it...
Hope it can help!
You can only use await
in an async
method, and Main
cannot be async
.
You'll have to use your own async
-compatible context, call Wait
on the returned Task
in the Main
method, or just ignore the returned Task
and just block on the call to Read
. Note that Wait
will wrap any exceptions in an AggregateException
.
If you want a good intro, see my async
/await
intro post.
I always use this code... Use this code
String clientScriptName = "ButtonClickScript";
Type clientScriptType = this.GetType ();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager clientScript = Page.ClientScript;
// Check to see if the client script is already registered.
if (!clientScript.IsClientScriptBlockRegistered (clientScriptType, clientScriptName))
{
StringBuilder sb = new StringBuilder ();
sb.Append ("<script type='text/javascript'>");
sb.Append ("window.open(' " + url + "')"); //URL = where you want to redirect.
sb.Append ("</script>");
clientScript.RegisterClientScriptBlock (clientScriptType, clientScriptName, sb.ToString ());
}
Add path of your PHP to Windows System Path. The path should contain php.exe
.
After adding the path open a new command prompt and make sure php.exe
is in path by typing
C:\>php --help
Once you see proper help message from above, enable the php_ldap.dll
extension in php.ini
Also copy php_ldap.dll
from php/ext
directory to apache/bin
folder
Restart wamp and phpinfo()
will now show ldap enabled.
The main()
method is the entry point for a Java application. run()
is typically used for new threads or tasks.
Where have you been writing a run()
method, what kind of application are you writing (e.g. Swing, AWT, console etc) and what's your development environment?
char *
and const unsigned char *
are considered unrelated types. So you want to use reinterpret_cast
.
But if you were going from const unsigned char*
to a non const
type you'd need to use const_cast
first. reinterpret_cast
cannot cast away a const
or volatile
qualification.
You should not rely on a hard coded build dir name in your script, so the line with ../Compile
must be changed.
It's because it should be up to user where to compile.
Instead of that use one of predefined variables:
http://www.cmake.org/Wiki/CMake_Useful_Variables
(look for CMAKE_BINARY_DIR
and CMAKE_CURRENT_BINARY_DIR
)
var test = {'red':'#FF0000', 'blue':'#0000FF'};_x000D_
delete test.blue; // or use => delete test['blue'];_x000D_
console.log(test);
_x000D_
this deletes test.blue
Recent sdk-manager's download does not contain android-support-v7-appcompat.jar But the following dir contains aar file C:\Users\madan\android-sdks\extras\android\m2repository\com\ android\support\appcompat-v7\24.2.1\appcompat-v7-24.2.1.aar This file can be imported by right-click project, import, select general, select archieve and finally select aar file. Even this does not solve the problem. Later remove 'import android.R' and add 'import android.support.v7.appcompat.*;' Follow this tutorial for other details: http://www.srccodes.com/p/article/22/android-hello-world-example-using-eclipse-ide-and-android-development-tools-adt-plugin
My answer is too late, but it can help others.
I had the same problem, even when I used a form tag.
I solved it by declaring Meta Charset in the header of the page:
<meta charset = "UTF-8" />
_x000D_
In a more general case:
N( A union B) = N(A) + N(B) - N(A intersect B)
= COUNTIFS(A1:A196,"Yes",J1:J196,"Agree")+COUNTIFS(A1:A196,"No",J1:J196,"Agree")-A1:A196,"Yes",A1:A196,"No")
Allocate memory to hold chars.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct PString {
char *chars;
int (*length)(PString *self);
} PString;
int length(PString *self) {
return strlen(self->chars);
}
PString *initializeString(int n) {
PString *str = malloc(sizeof(PString));
str->chars = malloc(sizeof(char) * n);
str->length = length;
str->chars[0] = '\0'; //add a null terminator in case the string is used before any other initialization.
return str;
}
int main() {
PString *p = initializeString(30);
strcpy(p->chars, "Hello");
printf("\n%d", p->length(p));
return 0;
}
Have a look at these pages. They contain many open source CSV parsers. JSaPar is one of them.
**add the icon top button like this **
#copy_btn{_x000D_
align-items: center;_x000D_
position: absolute;_x000D_
width: 30px;_x000D_
height: 30px;_x000D_
background-color: Transparent;_x000D_
background-repeat:no-repeat;_x000D_
border: none;_x000D_
cursor:pointer;_x000D_
overflow: hidden;_x000D_
outline:none;_x000D_
}_x000D_
.icon_copy{_x000D_
position: absolute;_x000D_
padding: 0px;_x000D_
top:0;_x000D_
left: 0;_x000D_
width: 25px;_x000D_
height: 35px;_x000D_
_x000D_
}
_x000D_
<button id="copy_btn">_x000D_
_x000D_
<img class="icon_copy" src="./assest/copy.svg" alt="Copy Text">_x000D_
</button>
_x000D_
I had the same issue and I resolved this by making some changes in my web.config.js file. FYI I am using the latest version of webpack and webpack-cli. This trick just saved my day. I have attached the example of mine web.config.js file before and after version.
Before:
module.exports = {
resolve: {
extensions: ['.js', '.jsx']
},
entry: './index.js',
output: {
filename: 'bundle.js'
},
module: {
loaders : [
{ test: /\.js?/, loader: 'bable-loader', exclude: /node_modules/ }
]
}
}
After: I Just replaced loaders to rules in module object as you can see in my code snippet.
module.exports = {
resolve: {
extensions: ['.js', '.jsx']
},
entry: './index.js',
output: {
filename: 'bundle.js'
},
module: {
rules : [
{ test: /\.js?/, loader: 'bable-loader', exclude: /node_modules/ }
]
}
}
Hopefully, This will help someone to get rid out of this issue.
Strings are immutable, meaning their contents cannot change. When you call replace(this,that)
you end up with a totally new String. If you want to keep this new copy, you need to assign it to a variable. You can overwrite the old reference (a la sentence = sentence.replace(this,that)
or a new reference as seen below:
public class Test{
public static void main(String[] args) {
String sentence = "Define, Measure, Analyze, Design and Verify";
String replaced = sentence.replace("and", "");
System.out.println(replaced);
}
}
As an aside, note that I've removed the contains()
check, as it is an unnecessary call here. If it didn't contain it, the replace will just fail to make any replacements. You'd only want that contains method if what you're replacing was different than the actual condition you're checking.
I used the code below and tried to show the sitemap.xml file
router.get('/sitemap.xml', function (req, res) {
res.sendFile('sitemap.xml', { root: '.' });
});
You can wrap your query in another SELECT
:
select count(*)
from
(
select count(SID) tot -- add alias
from Test
where Date = '2012-12-10'
group by SID
) src; -- add alias
In order for it to work, the count(SID)
need a column alias and you have to provide an alias to the subquery itself.
You don't have a Date
, you have a String
representation of a date. You should convert the String
into a Date
and then obtain the milliseconds. To convert a String
into a Date
and vice versa you should use SimpleDateFormat
class.
Here's an example of what you want/need to do (assuming time zone is not involved here):
String myDate = "2014/10/29 18:10:45";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = sdf.parse(myDate);
long millis = date.getTime();
Still, be careful because in Java the milliseconds obtained are the milliseconds between the desired epoch and 1970-01-01 00:00:00.
Using the new Date/Time API available since Java 8:
String myDate = "2014/10/29 18:10:45";
LocalDateTime localDateTime = LocalDateTime.parse(myDate,
DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss") );
/*
With this new Date/Time API, when using a date, you need to
specify the Zone where the date/time will be used. For your case,
seems that you want/need to use the default zone of your system.
Check which zone you need to use for specific behaviour e.g.
CET or America/Lima
*/
long millis = localDateTime
.atZone(ZoneId.systemDefault())
.toInstant().toEpochMilli();
Use sonar.coverage.exclusions property.
mvn clean install -Dsonar.coverage.exclusions=**/*ToBeExcluded.java
This should exclude the classes from coverage calculation.
On macs chrome browser:
cmd-ctrl-f
Just repeat to undo or hover above top
cmd-shift-f
cmd-shift-f
undo hide cmd-ctrl-f
undo full screen For user check, just post get the access token as accessToken and post it and get the response
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=accessToken
you can try in address bar in browsers too, use httppost and response in java also
response will be like
{
"issued_to": "xxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
"audience": "xxxxxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
"user_id": "xxxxxxxxxxxxxxxxxxxxxxx",
"scope": "https://www.googleapis.com/auth/userinfo.profile https://gdata.youtube.com",
"expires_in": 3340,
"access_type": "offline"
}
The scope is the given permission of the accessToken. you can check the scope ids in this link
Update: New API post as below
https://oauth2.googleapis.com/tokeninfo?id_token=XYZ123
Response will be as
{
// These six fields are included in all Google ID Tokens.
"iss": "https://accounts.google.com",
"sub": "110169484474386276334",
"azp": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
"aud": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
"iat": "1433978353",
"exp": "1433981953",
// These seven fields are only included when the user has granted the "profile" and
// "email" OAuth scopes to the application.
"email": "[email protected]",
"email_verified": "true",
"name" : "Test User",
"picture": "https://lh4.googleusercontent.com/-kYgzyAWpZzJ/ABCDEFGHI/AAAJKLMNOP/tIXL9Ir44LE/s99-c/photo.jpg",
"given_name": "Test",
"family_name": "User",
"locale": "en"
}
For more info, https://developers.google.com/identity/sign-in/android/backend-auth
Although this question has over 35 answers at the time of writing, there is a better solution to this problem.
@flamingLogos provided an answer which is based on Mathematics and doesn't contain any loops. That solution provides a time complexity of T(1)
. However, the math behind it is pretty complex especially the leap year handling.
@Glavic provided a good solution that is minimal and elegant. But it doesn't preform the calculation in a constant time, so it could produce a denial of service (DOS) attack or at least timeout if used with large periods like 10 or 100 of years since it loops on 1 day interval.
So I propose a mathematical approach that have constant time and yet very readable.
The idea is to count how many days to have complete weeks.
<?php
function getWorkingHours($start_date, $end_date) {
// validate input
if(!validateDate($start_date) || !validateDate($end_date)) return ['error' => 'Invalid Date'];
if($end_date < $start_date) return ['error' => 'End date must be greater than or equal Start date'];
//We save timezone and switch to UTC to prevent issues
$old_timezone = date_default_timezone_get();
date_default_timezone_set("UTC");
$startDate = strtotime($start_date);
$endDate = strtotime($end_date);
//The total number of days between the two dates. We compute the no. of seconds and divide it to 60*60*24
//We add one to include both dates in the interval.
$days = ($endDate - $startDate) / 86400 + 1;
$no_full_weeks = ceil($days / 7);
//we get only missing days count to complete full weeks
//we take modulo 7 in case it was already full weeks
$no_of_missing_days = (7 - ($days % 7)) % 7;
$workingDays = $no_full_weeks * 5;
//Next we remove the working days we added, this loop will have max of 6 iterations.
for ($i = 1; $i <= $no_of_missing_days; $i++){
if(date('N', $endDate + $i * 86400) < 6) $workingDays--;
}
$holidays = getHolidays(date('Y', $startDate), date('Y', $endDate));
//We subtract the holidays
foreach($holidays as $holiday){
$time_stamp=strtotime($holiday);
//If the holiday doesn't fall in weekend
if ($startDate <= $time_stamp && $time_stamp <= $endDate && date("N",$time_stamp) != 6 && date("N",$time_stamp) != 7)
$workingDays--;
}
date_default_timezone_set($old_timezone);
return ['days' => $workingDays];
}
The input to the function are in the format of Y-m-d
in php or yyyy-mm-dd
in general date format.
The get holiday function will return an array of holiday dates starting from start year and until end year.
This is a very old post, but I recently encountered the problem and for me the following solved the issue by formatting the SQL as follows,
SELECT CONVERT (varchar, getdate(), 120) AS Date
If you copy the result from SQL Server and paste in Excel then Excel holds the proper formatting.
A naive, CPU-intensive method to block execution for a number of milliseconds:
/**
* Delay for a number of milliseconds
*/
function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() < start + delay);
}
In pgAdmin you can also use
SET search_path TO your_db_name;