The key to all of this is understanding map projections. As others have pointed out, the cause of the distortion is the fact that the spherical (or more accurately ellipsoidal) earth is projected onto a plane.
In order to achieve your goal, you first must know two things about your data:
I'm assuming your data is in these coordinate systems.
The spherical Mercator projection defines a coordinate pair in meters, for the surface of the earth. This means, for every lat/long coordinate there is a matching meter/meter coordinate. This enables you to do the conversion using the following procedure:
In order to go from a WGS84 point to a pixel on the image, the procedure is now:
You can use the proj4js library like this:
// include the library
<script src="lib/proj4js-combined.js"></script> //adjust the path for your server
//or else use the compressed version
// creating source and destination Proj4js objects
// once initialized, these may be re-used as often as needed
var source = new Proj4js.Proj('EPSG:4326'); //source coordinates will be in Longitude/Latitude, WGS84
var dest = new Proj4js.Proj('EPSG:3785'); //destination coordinates in meters, global spherical mercators projection, see http://spatialreference.org/ref/epsg/3785/
// transforming point coordinates
var p = new Proj4js.Point(-76.0,45.0); //any object will do as long as it has 'x' and 'y' properties
Proj4js.transform(source, dest, p); //do the transformation. x and y are modified in place
//p.x and p.y are now EPSG:3785 in meters
int iInt = 10;
Integer iInteger = new Integer(iInt);
I found the way to fix this problem was to rename the project. If you give it a name with strange characters (in my case, :), it will have trouble locating your class. I don't know if this rule applies to numbers, but try renaming the project or making a new one and copying the files. Name it without any numbers or special characters.
I've not played around with all possibilities, but at least I had the impression that this could be a python version related issue. No idea why, I just trusted my gut.
Thus I just changed the pythonPath to python3 (default: python):
"python.pythonPath": "python3"
I reinstalled the dependencies (including pylint!!!) with
pip3 install <package> --user
... and after restarting vs code, everything looked fine.
HTH Kai
One can easily use
CONVERT_TZ(your_timestamp_column_name, 'UTC', 'your_desired_timezone_name')
For example:
CONVERT_TZ(timeperiod, 'UTC', 'Asia/Karachi')
Plus this can also be used in WHERE statement and to compare timestamp i would use the following in Where clause:
WHERE CONVERT_TZ(timeperiod, 'UTC', '{$this->timezone}') NOT BETWEEN {$timeperiods['today_start']} AND {$timeperiods['today_end']}
This is what I've used for my latest app.
# redirect the main page to landing
##RedirectMatch 302 ^/$ /landing
# remove php ext from url
# https://stackoverflow.com/questions/4026021/remove-php-extension-with-htaccess
RewriteEngine on
# File exists but has a trailing slash
# https://stackoverflow.com/questions/21417263/htaccess-add-remove-trailing-slash-from-url
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?(.*)/+$ /$1 [R=302,L,QSA]
# ok. It will still find the file but relative assets won't load
# e.g. page: /landing/ -> assets/js/main.js/main
# that's we have the rules above.
RewriteCond %{REQUEST_FILENAME} !\.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^/?(.*?)/?$ $1.php
The text color can be changed using,
<span style='color:green'> message/text </span>
l.insert(index, obj)
doesn't actually return anything. It just updates the list.
As ATO said, you can do b = a[:index] + [obj] + a[index:]
.
However, another way is:
a = [1, 2, 4]
b = a[:]
b.insert(2, 3)
ncftp -u <user> -p <pass> <server>
ncftp> mget directory
Use the open function to open the file. The open function returns a file object, which you can use the read and write to files:
file_input = open('input.txt') #opens a file in reading mode
file_output = open('output.txt') #opens a file in writing mode
data = file_input.read(1024) #read 1024 bytes from the input file
file_output.write(data) #write the data to the output file
I got the same issue, and I changed to IP and it working well
Go to System References --> Network --> Advanced --> Open TCP/IP tabs --> copy the IPv4 Address.
change that IP instead localhost
Hope this can help
I think this is very nice and short
<img src="imagenotfound.gif" alt="Image not found" onerror="this.src='imagefound.gif';" />
But, be careful. The user's browser will be stuck in an endless loop if the onerror image itself generates an error.
EDIT
To avoid endless loop, remove the onerror
from it at once.
<img src="imagenotfound.gif" alt="Image not found" onerror="this.onerror=null;this.src='imagefound.gif';" />
By calling this.onerror=null
it will remove the onerror then try to get the alternate image.
NEW I would like to add a jQuery way, if this can help anyone.
<script>
$(document).ready(function()
{
$(".backup_picture").on("error", function(){
$(this).attr('src', './images/nopicture.png');
});
});
</script>
<img class='backup_picture' src='./images/nonexistent_image_file.png' />
You simply need to add class='backup_picture' to any img tag that you want a backup picture to load if it tries to show a bad image.
Adding "-EA Stop" solved this for me.
I think, this is you exactly needed.
Here drawable(xml) file that creates rounded rectangle. round_rect_shape.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<solid android:color="#ffffff" />
<corners
android:bottomLeftRadius="8dp"
android:bottomRightRadius="8dp"
android:topLeftRadius="8dp"
android:topRightRadius="8dp" />
</shape>
Here layout file: my_layout.xml
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/round_rect_shape"
android:orientation="vertical"
android:padding="5dp" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Something text"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ff0000" />
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<requestFocus />
</EditText>
</LinearLayout>
-> In the above code, LinearLayout having the background(That is the key role to place to create rounded rectangle). So you can place any view like TextView, EditText... in that LinearLayout to see background as round rectangle for all.
Another reason, Check your Developer account is connected with xCode
You are trying to link objects compiled by different versions of the compiler. That's not supported in modern versions of VS, at least not if you are using the C++ standard library. Different versions of the standard library are binary incompatible and so you need all the inputs to the linker to be compiled with the same version. Make sure you re-compile all the objects that are to be linked.
The compiler error names the objects involved so the information the the question already has the answer you are looking for. Specifically it seems that the static library that you are linking needs to be re-compiled.
So the solution is to recompile Projectname1.lib with VS2012.
__file__
is absolute since Python 3.4, except when executing a script directly using a relative path:
Module
__file__
attributes (and related values) should now always contain absolute paths by default, with the sole exception of__main__.__file__
when a script has been executed directly using a relative path. (Contributed by Brett Cannon in bpo-18416.)
Not sure if it resolves symlinks though.
Example of passing a relative path:
$ python script.py
Try this:
import java.net.HttpURLConnection;
URL url = new URL("http://www.myurl.com/sample.xml");
HttpURLConnection huc = (HttpURLConnection) url.openConnection();
HttpURLConnection.setFollowRedirects(false);
huc.setConnectTimeout(15 * 1000);
huc.setRequestMethod("GET");
huc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");
huc.connect();
InputStream input = huc.getInputStream();
import org.jsoup.nodes.Document;
Document doc = null;
try {
doc = Jsoup.connect("http://www.myurl.com/sample.xml").get();
} catch (Exception e) {
//log error
}
And take look on how to use Jsoup: http://jsoup.org/cookbook/input/load-document-from-url
This behavior is related to Zone that is set - Internet/Intranet/etc and corresponding Security Level
You can change this by setting less secure Security Level (not recommended) or by customizing Display Mixed Content property
You can do that by following steps:
Modified @dsamblas function to work when parameters are date strings like this '2019-01-01' and when there is array passed using IN like
$qb->expr()->in('ps.code', ':activeCodes'),
. So do everything what dsamblas wrote, but replace startQuery with this one or see the differences and add my code. (in case he modified something in his function and my version does not have modifications).
public function startQuery($sql, array $params = null, array $types = null)
{
if($this->isLoggable($sql)){
if(!empty($params)){
foreach ($params as $key=>$param) {
try {
$type=Type::getType($types[$key]);
$value=$type->convertToDatabaseValue($param,$this->dbPlatform);
} catch (Exception $e) {
if (is_array($param)) {
// connect arrays like ("A", "R", "C") for SQL IN
$value = '"' . implode('","', $param) . '"';
} else {
$value = $param; // case when there are date strings
}
}
$sql = join(var_export($value, true), explode('?', $sql, 2));
}
}
echo $sql . " ;".PHP_EOL;
}
}
Did not test much.
This is the simplest example of function pointers and function pointer arrays that I wrote as an exercise.
typedef double (*pf)(double x); /*this defines a type pf */
double f1(double x) { return(x+x);}
double f2(double x) { return(x*x);}
pf pa[] = {f1, f2};
main()
{
pf p;
p = pa[0];
printf("%f\n", p(3.0));
p = pa[1];
printf("%f\n", p(3.0));
}
The following shows an example of a shared class library shared.[h,cpp] and a main.cpp module using the library. It's a very simple example and the makefile could be made much better. But it works and may help you:
shared.h defines the class:
class myclass {
int myx;
public:
myclass() { myx=0; }
void setx(int newx);
int getx();
};
shared.cpp defines the getx/setx functions:
#include "shared.h"
void myclass::setx(int newx) { myx = newx; }
int myclass::getx() { return myx; }
main.cpp uses the class,
#include <iostream>
#include "shared.h"
using namespace std;
int main(int argc, char *argv[])
{
myclass m;
cout << m.getx() << endl;
m.setx(10);
cout << m.getx() << endl;
}
and the makefile that generates libshared.so and links main with the shared library:
main: libshared.so main.o
$(CXX) -o main main.o -L. -lshared
libshared.so: shared.cpp
$(CXX) -fPIC -c shared.cpp -o shared.o
$(CXX) -shared -Wl,-soname,libshared.so -o libshared.so shared.o
clean:
$rm *.o *.so
To actual run 'main' and link with libshared.so you will probably need to specify the load path (or put it in /usr/local/lib or similar).
The following specifies the current directory as the search path for libraries and runs main (bash syntax):
export LD_LIBRARY_PATH=.
./main
To see that the program is linked with libshared.so you can try ldd:
LD_LIBRARY_PATH=. ldd main
Prints on my machine:
~/prj/test/shared$ LD_LIBRARY_PATH=. ldd main
linux-gate.so.1 => (0xb7f88000)
libshared.so => ./libshared.so (0xb7f85000)
libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0xb7e74000)
libm.so.6 => /lib/libm.so.6 (0xb7e4e000)
libgcc_s.so.1 => /usr/lib/libgcc_s.so.1 (0xb7e41000)
libc.so.6 => /lib/libc.so.6 (0xb7cfa000)
/lib/ld-linux.so.2 (0xb7f89000)
It worked for me after adding the following dependency in pom,
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.0.Final</version>
</dependency>
Finally got it: The way Eclipse picks up the JRE is using the system's PATH.
I did not have C:\home\SFTWR\jdk1.6.0_21\bin
in the path at all before and I did have C:\Program Files (x86)\Java\jre6\bin
. I had both JRE_HOME
and JAVA_HOME
set to C:\home\SFTWR\jdk1.6.0_21
but neither of those two mattered. I guess Eclipse did (something to the effect of) where java (or which on UNIX/Linux) to see where Java is in the path and took the JRE to which that java.exe
belonged. In my case, despite all the configuration tweaks I had done (including eclipse.ini
-vm option as suggested above), it remained stuck to what was in the path.
I removed the old JRE bin from the path, put the new one in, and it works for all workspaces.
Make the member private and add a setter/getter pair. In your setter, if null, then set default value instead. Additionally, I have shown the snippet with the getter also returning a default when internal value is null.
class JavaObject {
private static final String DEFAULT="Default Value";
public JavaObject() {
}
@NotNull
private String notNullMember;
public void setNotNullMember(String value){
if (value==null) { notNullMember=DEFAULT; return; }
notNullMember=value;
return;
}
public String getNotNullMember(){
if (notNullMember==null) { return DEFAULT;}
return notNullMember;
}
public String optionalMember;
}
I accepted trebleCode's answer, but I wanted to provide a bit more detail regarding the steps I took to install the nupkg of interest pswindowsupdate.2.0.0.4.nupkg
on my unconnected Win 7 machine by way of following trebleCode's answer.
First: after digging around a bit, I think I found the MS docs that trebleCode refers to:
Bootstrap the NuGet provider and NuGet.exe
To continue, as trebleCode stated, I did the following
Install NuGet provider on my connected machine
On a connected machine (Win 10 machine), from the PS command line, I ran Install-PackageProvider -Name NuGet -RequiredVersion 2.8.5.201 -Force
. The Nuget software was obtained from the 'Net and installed on my local connected machine.
After the install I found the NuGet provider software at C:\Program Files\PackageManagement\ProviderAssemblies
(Note: the folder name \ProviderAssemblies
as opposed to \ReferenceAssemblies
was the one minor difference relative to trebleCode's answer.
The provider software is in a folder structure like this:
C:\Program Files\PackageManagement\ProviderAssemblies
\NuGet
\2.8.5.208
\Microsoft.PackageManagement.NuGetProvider.dll
Install NuGet provider on my unconnected machine
I copied the \NuGet folder (and all its children) from the connected machine onto a thumb drive and copied it to C:\Program Files\PackageManagement\ProviderAssemblies
on my unconnected (Win 7) machine
I started PS (v5) on my unconnected (Win 7) machine and ran Import-PackageProvider -Name NuGet -RequiredVersion 2.8.5.201
to import the provider to the current PowerShell
session.
I ran Get-PackageProvider -ListAvailable
and saw this (NuGet appears where it was not present before):
Name Version DynamicOptions
---- ------- --------------
msi 3.0.0.0 AdditionalArguments
msu 3.0.0.0
NuGet 2.8.5.208 Destination, ExcludeVersion, Scope, SkipDependencies, Headers, FilterOnTag, Contains, AllowPrereleaseVersions, ConfigFile, SkipValidate
PowerShellGet 1.0.0.1 PackageManagementProvider, Type, Scope, AllowClobber, SkipPublisherCheck, InstallUpdate, NoPathUpdate, Filter, Tag, Includes, DscResource, RoleCapability, Command, PublishLocati...
Programs 3.0.0.0 IncludeWindowsInstaller, IncludeSystemComponent
Create local repository on my unconnected machine
On unconnected (Win 7) machine, I created a folder to serve as my PS repository (say, c:\users\foo\Documents\PSRepository
)
I registered the repo: Register-PSRepository -Name fooPsRepository -SourceLocation c:\users\foo\Documents\PSRepository -InstallationPolicy Trusted
Install the NuGet package
I obtained and copied the nupkg pswindowsupdate.2.0.0.4.nupkg
to c:\users\foo\Documents\PSRepository
on my unconnected Win7 machine
I learned the name of the module by executing Find-Module -Repository fooPsRepository
Version Name Repository Description
------- ---- ---------- -----------
2.0.0.4 PSWindowsUpdate fooPsRepository This module contain functions to manage Windows Update Client.
I installed the module by executing Install-Module -Name pswindowsupdate
I verified the module installed by executing Get-Command –module PSWindowsUpdate
CommandType Name Version Source
----------- ---- ------- ------
Alias Download-WindowsUpdate 2.0.0.4 PSWindowsUpdate
Alias Get-WUInstall 2.0.0.4 PSWindowsUpdate
Alias Get-WUList 2.0.0.4 PSWindowsUpdate
Alias Hide-WindowsUpdate 2.0.0.4 PSWindowsUpdate
Alias Install-WindowsUpdate 2.0.0.4 PSWindowsUpdate
Alias Show-WindowsUpdate 2.0.0.4 PSWindowsUpdate
Alias UnHide-WindowsUpdate 2.0.0.4 PSWindowsUpdate
Alias Uninstall-WindowsUpdate 2.0.0.4 PSWindowsUpdate
Cmdlet Add-WUServiceManager 2.0.0.4 PSWindowsUpdate
Cmdlet Enable-WURemoting 2.0.0.4 PSWindowsUpdate
Cmdlet Get-WindowsUpdate 2.0.0.4 PSWindowsUpdate
Cmdlet Get-WUApiVersion 2.0.0.4 PSWindowsUpdate
Cmdlet Get-WUHistory 2.0.0.4 PSWindowsUpdate
Cmdlet Get-WUInstallerStatus 2.0.0.4 PSWindowsUpdate
Cmdlet Get-WUJob 2.0.0.4 PSWindowsUpdate
Cmdlet Get-WULastResults 2.0.0.4 PSWindowsUpdate
Cmdlet Get-WURebootStatus 2.0.0.4 PSWindowsUpdate
Cmdlet Get-WUServiceManager 2.0.0.4 PSWindowsUpdate
Cmdlet Get-WUSettings 2.0.0.4 PSWindowsUpdate
Cmdlet Get-WUTest 2.0.0.4 PSWindowsUpdate
Cmdlet Invoke-WUJob 2.0.0.4 PSWindowsUpdate
Cmdlet Remove-WindowsUpdate 2.0.0.4 PSWindowsUpdate
Cmdlet Remove-WUServiceManager 2.0.0.4 PSWindowsUpdate
Cmdlet Set-WUSettings 2.0.0.4 PSWindowsUpdate
Cmdlet Update-WUModule 2.0.0.4 PSWindowsUpdate
I think I'm good to go
Using Java 8, you can simply use ncopies
of Collections
class:
Object[] arrays = Collections.nCopies(size, object).stream().toArray();
In your case it will be:
Integer[] arrays = Collections.nCopies(10, Integer.valueOf(1)).stream().toArray(Integer[]::new);
.
Here is a detailed answer of a similar case of yours.
(I presume you are aware that using UDP(User Datagram Protocol) does not guarantee delivery, checks for duplicates and congestion control and will just answer your question).
In your server this line:
var data = udpServer.Receive(ref groupEP);
re-assigns groupEP
from what you had to a the address you receive something on.
This line:
udpServer.Send(new byte[] { 1 }, 1);
Will not work since you have not specified who to send the data to. (It works on your client because you called connect which means send will always be sent to the end point you connected to, of course we don't want that on the server as we could have many clients). I would:
UdpClient udpServer = new UdpClient(UDP_LISTEN_PORT);
while (true)
{
var remoteEP = new IPEndPoint(IPAddress.Any, 11000);
var data = udpServer.Receive(ref remoteEP);
udpServer.Send(new byte[] { 1 }, 1, remoteEP); // if data is received reply letting the client know that we got his data
}
Also if you have server and client on the same machine you should have them on different ports.
Official documentation says, click on a link in a WebView will launch application that handles URLs. You need to override this default behavior
myWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
});
or if there is no conditional logic in the method simply do this
myWebView.setWebViewClient(new WebViewClient());
nobody has mentioned yet, in ASP.NET 4.0 there's new syntax to do this. instead of
<%= HttpUtility.HtmlEncode(unencoded) %>
you can simply do
<%: unencoded %>
read more here: http://weblogs.asp.net/scottgu/archive/2010/04/06/new-lt-gt-syntax-for-html-encoding-output-in-asp-net-4-and-asp-net-mvc-2.aspx
If you want to present the image, add a method as a helper class or to the model itself and allow the method to convert the byte array image to a image format like PNG or JPG then convert to Base64 string. Once you have that, bind the base64 value on your view in the format
"data:image/[image file type extension];base64,[your base64 string goes here]"
The above is assigned to the img
tag's src
attribute.
The only issue I have with this is the base64 string being too long. So, I would not recommend it for multiple models being shown in a view.
Short (un-precise) definition:
Compiled language: Entire program is translated to machine code at once, then the machine code is run by the CPU.
Interpreted language: Program is read line-by-line and as soon as a line is read the machine instructions for that line are executed by the CPU.
But really, few languages these days are purely compiled or purely interpreted, it often is a mix. For a more detailed description with pictures, see this thread:
What is the difference between compilation and interpretation?
Or my later blog post:
https://orangejuiceliberationfront.com/the-difference-between-compiler-and-interpreter/
As you can see i am binding to Password, but maybe its bind it to the static class..
It is an attached property. This kind of property can be applied to any kind of DependencyObject
, not just the type in which it is declared. So even though it is declared in the PasswordHelper
static class, it is applied to the PasswordBox
on which you use it.
To use this attached property, you just need to bind it to the Password
property in your ViewModel :
<PasswordBox w:PasswordHelper.Attach="True"
w:PasswordHelper.Password="{Binding Password}"/>
I tried Test Mail Server Tool and while it worked great, you still need to open the email on some client.
I found Papercut: https://papercut.codeplex.com/
For configuration it's easy as Test Mail Server Tool (pratically zero-conf), and it also serves as an email client, with views for the Message (great for HTML emails), Headers, Body (to inspect the HTML) and Raw (full unparsed email).
It also has a Sections view, to split up the different media types found in the email.
It has a super clean and friendly UI, a good log viewer and gives you notifications when you receive an email.
I find it perfect, so I just wanted to give my 2c and maybe help someone.
When you upload your build from Application loader or directly from your xcode to App Store and it is not showing even on multiple uploads with different build version then
Note: This permission string is mandatory from iOS 10.
UPDATE 2018: C++20 will come with templated and conceptualized lambdas. The feature has already been integrated into the standard draft.
UPDATE 2014: C++14 has been released this year and now provides Polymorphic lambdas with the same syntax as in this example. Some major compilers already implement it.
At it stands (in C++11), sadly no. Polymorphic lambdas would be excellent in terms of flexibility and power.
The original reason they ended up being monomorphic was because of concepts. Concepts made this code situation difficult:
template <Constraint T>
void foo(T x)
{
auto bar = [](auto x){}; // imaginary syntax
}
In a constrained template you can only call other constrained templates. (Otherwise the constraints couldn't be checked.) Can foo
invoke bar(x)
? What constraints does the lambda have (the parameter for it is just a template, after all)?
Concepts weren't ready to tackle this sort of thing; it'd require more stuff like late_check
(where the concept wasn't checked until invoked) and stuff. Simpler was just to drop it all and stick to monomorphic lambdas.
However, with the removal of concepts from C++0x, polymorphic lambdas become a simple proposition again. However, I can't find any proposals for it. :(
I add double backslash to the dot to make it work. Cheer.
var st = "okay.this.is.a.string";
var Re = new RegExp("\\.","g");
st = st.replace(Re," ");
alert(st);
I have had another issue giving me a 504. It's pretty far out but I'll write it up here for googlers and posterity...
I have a client calling an IIS hosted webservice hosted in another domain (Active Directory). There is not full trust between the client domain and the domain where the web services is hosted. One of the many challenges with the selective trust between these two domains is that Kerberos does not work when calling from one to the other.
In my case I was trying to call a service in another domain where I found out that a SPN was registered. Like this : http/myurl.test.local (just an example)
This forces the call to use Kerberos instead of letting it fall back to NTLM and this gave me a 405 back from the calling server.
After removing the spn and allowing the call to fall back to NTLM, it works fine.
As I said ... this is not something you are likely to run into, as most organizations do not venture into having such a selective trusts between two domains ... But it gives a 504 and caused me a few (more) gray hairs.
Just develop a normal app and then add a couple of lines to the app's manifest file.
First you need to add the following attribute to your activity:
android:launchMode="singleTask"
Then add two categories to the intent filter :
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.HOME" />
The result could look something like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dummy.app"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.dummy.app.MainActivity"
android:launchMode="singleTask"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</activity>
</application>
</manifest>
It's that simple!
Why :not just use two :not
:
input:not([type="radio"]):not([type="checkbox"])
Yes, it is intentional
I'd go for purchase-rest-service
. Reasons:
What is "pur chase rests ervice"? Long, concatenated words are hard to understand. I know, I'm German. "Donaudampfschifffahrtskapitänspatentausfüllungsassistentenausschreibungsstellenbewerbung."
"_" is harder to type than "-"
Things change. The escape/unescape methods have been deprecated.
You can URI encode the string before you Base64-encode it. Note that this does't produce Base64-encoded UTF8, but rather Base64-encoded URL-encoded data. Both sides must agree on the same encoding.
See working example here: http://codepen.io/anon/pen/PZgbPW
// encode string
var base64 = window.btoa(encodeURIComponent('€ ?? æøåÆØÅ'));
// decode string
var str = decodeURIComponent(window.atob(tmp));
// str is now === '€ ?? æøåÆØÅ'
For OP's problem a third party library such as js-base64 should solve the problem.
When you did:
(function (msg){alert(msg)});
('SO');
You ended the function before ('SO')
because of the semicolon. If you just write:
(function (msg){alert(msg)})
('SO');
It will work.
Working example: http://jsfiddle.net/oliverni/dbVjg/
And to add multiple library files you can write as below:
INCLUDEPATH *= E:/DebugLibrary/VTK E:/DebugLibrary/VTK/Common E:/DebugLibrary/VTK/Filtering E:/DebugLibrary/VTK/GenericFiltering E:/DebugLibrary/VTK/Graphics E:/DebugLibrary/VTK/GUISupport/Qt E:/DebugLibrary/VTK/Hybrid E:/DebugLibrary/VTK/Imaging E:/DebugLibrary/VTK/IO E:/DebugLibrary/VTK/Parallel E:/DebugLibrary/VTK/Rendering E:/DebugLibrary/VTK/Utilities E:/DebugLibrary/VTK/VolumeRendering E:/DebugLibrary/VTK/Widgets E:/DebugLibrary/VTK/Wrapping
LIBS *= -LE:/DebugLibrary/VTKBin/bin/release -lvtkCommon -lvtksys -lQVTK -lvtkWidgets -lvtkRendering -lvtkGraphics -lvtkImaging -lvtkIO -lvtkFiltering -lvtkDICOMParser -lvtkpng -lvtktiff -lvtkzlib -lvtkjpeg -lvtkexpat -lvtkNetCDF -lvtkexoIIc -lvtkftgl -lvtkfreetype -lvtkHybrid -lvtkVolumeRendering -lQVTKWidgetPlugin -lvtkGenericFiltering
if your column contain any value that you want to neglect. it will help you
## da is data frame & Ozone is column name
##for single column
mean(da$Ozone, na.rm = TRUE)
##for all columns
colMeans(x=da, na.rm = TRUE)
In my case of picking date from JXDatePicker (java calender) and getting it stored in database as SQL Date type, below works fine ..
java.sql.Date date = new java.sql.Date(pickedDate.getDate().getTime());
where pickedDate is object of JXDatePicker
type(dict())
says "make a new dict, and then find out what its type is". It's quicker to say just dict
.
But if you want to just check type, a more idiomatic way is isinstance(x, dict)
.
Note, that isinstance
also includes subclasses (thanks Dustin):
class D(dict):
pass
d = D()
print("type(d) is dict", type(d) is dict) # -> False
print("isinstance (d, dict)", isinstance(d, dict)) # -> True
I was running on Win7, Tomcat7 with maven-pom setup on Eclipse Mars with maven project enabled. On a NOT running server I only had to change from 3.1 to 3.0 on this screen:
For me it was important to have Dynamic Web Module disabled! Then change the version and then enable Dynamic Web Module again.
You want to put code in the master page code behind that inserts HTML into the contents of a page that is using that master page?
I would not search for the control via FindControl as this is a fragile solution that could easily be broken if the name of the control changed.
Your best bet is to declare an event in the master page that any child page could handle. The event could pass the HTML as an EventArg.
Another solutions are assign RangeIndex
or range
:
df.index = pd.RangeIndex(len(df.index))
df.index = range(len(df.index))
It is faster:
df = pd.DataFrame({'a':[8,7], 'c':[2,4]}, index=[7,8])
df = pd.concat([df]*10000)
print (df.head())
In [298]: %timeit df1 = df.reset_index(drop=True)
The slowest run took 7.26 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 105 µs per loop
In [299]: %timeit df.index = pd.RangeIndex(len(df.index))
The slowest run took 15.05 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 7.84 µs per loop
In [300]: %timeit df.index = range(len(df.index))
The slowest run took 7.10 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 14.2 µs per loop
test -e
will test whether a file exists or not. The test command returns a zero value if the test succeeds or 1 otherwise.
Test can be written either as test -e
or using []
[ -e "$file_name" ] && grep "poet" $file_name
Unless you actually need the output of grep you can test the return value as grep will return 1 if there are no matches and zero if there are any.
In general terms you can test if a string is non-empty using [ "string" ]
which will return 0 if non-empty and 1 if empty
It can take time for the network close to be observed - the total time is nominally about 2 minutes (yes, minutes!) after a close before the packets destined for the port are all assumed to be dead. The error condition is detected at some point. With a small write, you are inside the MTU of the system, so the message is queued for sending. With a big write, you are bigger than the MTU and the system spots the problem quicker. If you ignore the SIGPIPE signal, then the functions will return EPIPE error on a broken pipe - at some point when the broken-ness of the connection is detected.
Another great example of when static attributes and operations are used when you want to apply the Singleton design pattern. In a nutshell, the Singleton design pattern ensures that one and only one object of a particular class is ever constructeed during the lifetime of your system. to ensure that only one object is ever constructed, typical implemenations of the Singleton pattern keep an internal static reference to the single allowed object instance, and access to that instance is controlled using a static
operation
I did not find the -q1
option on my netcat. Instead I used the -w1
option. Below is the bash script I did to send an udp packet to any host and port:
#!/bin/bash
def_host=localhost
def_port=43211
HOST=${2:-$def_host}
PORT=${3:-$def_port}
echo -n "$1" | nc -4u -w1 $HOST $PORT
patterns[1]="1\.2\.3\.4.*Has exploded"
patterns[2]="5\.6\.7\.8.*Has died"
patterns[3]="\!9\.10\.11\.12.*Has exploded"
for i in {1..3}
do
grep "${patterns[$i]}" logfile.log
done
should be the the same as
egrep "(1\.2\.3\.4.*Has exploded|5\.6\.7\.8.*Has died)" logfile.log | egrep -v "9\.10\.11\.12.*Has exploded"
You can use Linq in case you are using .NET 3.5 or later:
test = test.Where(x => !string.IsNullOrEmpty(x)).ToArray();
If you can't use Linq then you can do it like this:
var temp = new List<string>();
foreach (var s in test)
{
if (!string.IsNullOrEmpty(s))
temp.Add(s);
}
test = temp.ToArray();
When it shows the red writing - the error , don't close the emulator - leave it as is and run the application again.
It is possible the other branch you try to pull from is out of synch; so before adding and removing remote try to (if you are trying to pull from master)
git pull origin master
for me that simple call solved those error messages:
pep8 was recently added to PyPi.
It is now super easy to check your code against pep8.
In Windows Forms, you have the app.config
file, which is very similar to the web.config
file. But since what I see you need it for are custom values, I suggest using Settings.
To do that, open your project properties, and then go to settings. If a settings file does not exist you will have a link to create one. Then, you can add the settings to the table you see there, which would generate both the appropriate XML, and a Settings class that can be used to load and save the settings.
The settings class will be named something like DefaultNamespace.Properties.Settings
. Then, you can use code similar to:
using DefaultNamespace.Properties;
namespace DefaultNamespace {
class Class {
public int LoadMySettingValue() {
return Settings.Default.MySettingValue;
}
public void SaveMySettingValue(int value) {
Settings.Default.MySettingValue = value;
}
}
}
I had this issue when I was trying to make my Docker container smaller. It was because I'd installed Python 2.7 with:
apt-get install -y --no-install-recommends python
And I should not have included the --no-install-recommends
flag:
apt-get install -y python
Debian 9
I just did the following and everything else needed got automatically installed as well.
sudo apt-get -y -f install php-imagick
sudo /etc/init.d/apache2 restart
Turn on less secure app from this link and boom...
As @gaurang171 mentioned, we can use .closest() which will return the first ancestor, or the closest to our delete button, and use .remove() to remove it.
This is how we can implement it using jQuery click event instead of using JavaScript onclick.
HTML:
<table id="myTable">
<tr>
<th width="30%" style="color:red;">ID</th>
<th width="25%" style="color:red;">Name</th>
<th width="25%" style="color:red;">Age</th>
<th width="1%"></th>
</tr>
<tr>
<td width="30%" style="color:red;">SSS-001</td>
<td width="25%" style="color:red;">Ben</td>
<td width="25%" style="color:red;">25</td>
<td><button type='button' class='btnDelete'>x</button></td>
</tr>
<tr>
<td width="30%" style="color:red;">SSS-002</td>
<td width="25%" style="color:red;">Anderson</td>
<td width="25%" style="color:red;">47</td>
<td><button type='button' class='btnDelete'>x</button></td>
</tr>
<tr>
<td width="30%" style="color:red;">SSS-003</td>
<td width="25%" style="color:red;">Rocky</td>
<td width="25%" style="color:red;">32</td>
<td><button type='button' class='btnDelete'>x</button></td>
</tr>
<tr>
<td width="30%" style="color:red;">SSS-004</td>
<td width="25%" style="color:red;">Lee</td>
<td width="25%" style="color:red;">15</td>
<td><button type='button' class='btnDelete'>x</button></td>
</tr>
jQuery
$(document).ready(function(){
$("#myTable").on('click','.btnDelete',function(){
$(this).closest('tr').remove();
});
});
Try in JSFiddle: click here.
To use cache-control in HTML, you use the meta tag, e.g.
<meta http-equiv="Cache-control" content="public">
The value in the content field is defined as one of the four values below.
Some information on the Cache-Control
header is as follows
HTTP 1.1. Allowed values = PUBLIC | PRIVATE | NO-CACHE | NO-STORE.
Public - may be cached in public shared caches.
Private - may only be cached in private cache.
No-Cache - may not be cached.
No-Store - may be cached but not archived.The directive CACHE-CONTROL:NO-CACHE indicates cached information should not be used and instead requests should be forwarded to the origin server. This directive has the same semantics as the PRAGMA:NO-CACHE.
Clients SHOULD include both PRAGMA: NO-CACHE and CACHE-CONTROL: NO-CACHE when a no-cache request is sent to a server not known to be HTTP/1.1 compliant. Also see EXPIRES.
Note: It may be better to specify cache commands in HTTP than in META statements, where they can influence more than the browser, but proxies and other intermediaries that may cache information.
You're using share folders, so you need to install VirtualBox Guest Additions inside your virtual machine to support that feature.
If you're using Vagrant (OS X: brew cask install vagrant
), run:
vagrant plugin install vagrant-vbguest
vagrant vbguest
In case it fails, check the logs, e.g.
vagrant ssh -c "cat /var/log/vboxadd-install.log"
Maybe you're just missing the kernel header files.
Inside VM, you should install Guest Additions, kernel headers and start the service and double check if kernel extension is running.
This depends on the guest operating system, so here are brief steps:
Install kernel include headers (required by VBoxLinuxAdditions).
sudo apt-get update && sudo apt-get install kernel-devel
sudo yum update && sudo yum -y install kernel-headers kernel-devel
Install Guest Additions (this depends on the operating system).
Ubuntu: sudo apt-get -y install dkms build-essential linux-headers-$(uname -r) virtualbox-guest-additions-iso
If you can't find it, check by aptitude search virtualbox
.
Debian: sudo apt-get -y install build-essential module-assistant virtualbox-ose-guest-utils
If you can't find it, check by dpkg -l | grep virtualbox
.
manually by downloading the iso file inside VM (e.g. wget
) and installing it, e.g.
wget http://download.virtualbox.org/virtualbox/5.0.16/VBoxGuestAdditions_5.0.16.iso -P /tmp
sudo mount -o loop /tmp/VBoxGuestAdditions_5.0.16.iso /mnt
sudo sh -x /mnt/VBoxLinuxAdditions.run # --keep
Extra debug: cd ~/install && sh -x ./install.sh /mnt/VBoxLinuxAdditions.run
Double check that kernel extensions are up and running:
sudo modprobe vboxsf
Start/restart the service:
sudo /opt/VBoxGuestAdditions*/init/vboxadd setup
(add sudo sh -x
to debug)sudo /etc/init.d/vboxadd-service start
sudo /etc/init.d/vboxdrv setup
sudo service VBoxService start
If above didn't work, here are more sophisticated steps to fix it. This assumes that you've already VBoxGuestAdditions installed (as shown above).
The most common reason why mounting shared folder doesn't work may related to building Guest Additions module which failed. If in /var/log/vboxadd-install.log
you've the following error:
The headers for the current running kernel were not found.
this means either you didn't install kernel sources, or they cannot be found.
If you installed them already as instructed above, run this command:
$ sudo sh -x /opt/VBoxGuestAdditions-5.0.16/init/vboxadd setup 2>&1 | grep KERN
+ KERN_VER=2.6.32-573.18.1.el6.x86_64
+ KERN_DIR=/lib/modules/2.6.32-573.18.1.el6.x86_64/build
So basically vboxadd
script is expecting your kernel sources to be available at the following dir:
ls -la /lib/modules/$(uname -r)/build
Check if the kernel dir exists (symbolic link points to the existing folder). If it's not, please install them to the right folder (e.g. in /usr/src/kernels
).
So vboxadd
script can enter your kernel source directory and run make kernelrelease
, get the value and compare with your current kernel version.
Here is the logic:
KERN_VER=`uname -r`
KERN_DIR="/lib/modules/$KERN_VER/build"
if [ -d "$KERN_DIR" ]; then
KERN_REL=`make -sC $KERN_DIR --no-print-directory kernelrelease 2>/dev/null || true`
if [ -z "$KERN_REL" -o "x$KERN_REL" = "x$KERN_VER" ]; then
return 0
fi
fi
If the kernel version doesn't match with the sources, maybe you've to upgrade your Linux kernel (in case the sources are newer than your kernel).
Try:
vagrant plugin install vagrant-vbguest vagrant vbgues
If won't work, try the following manual steps for CentOS:
$ sudo yum update
$ sudo yum install kernel-$(uname -r) kernel-devel kernel-headers # or: reinstall
$ rpm -qf /lib/modules/$(uname -r)/build
kernel-2.6.32-573.18.1.el6.x86_64
$ ls -la /lib/modules/$(uname -r)/build
$ sudo reboot # and re-login
$ sudo ln -sv /usr/src/kernels/$(uname -r) /lib/modules/$(uname -r)/build
$ sudo /opt/VBoxGuestAdditions-*/init/vboxadd setup
You need to add to your PYTHONPATH variable instead of Windows PATH variable.
Here's a bit of an improvement on the excellent answer provided by Mathew Wolf. This one appends the main container as a style tag to the head element and appends each new class to that style tag. a little more concise and I find it works well.
function changeCss(className, classValue) {
var cssMainContainer = $('#css-modifier-container');
if (cssMainContainer.length == 0) {
var cssMainContainer = $('<style id="css-modifier-container"></style>');
cssMainContainer.appendTo($('head'));
}
cssMainContainer.append(className + " {" + classValue + "}\n");
}
2007 is more powerful with ribbon..:=) To add new series in chart do: Select Chart, then click Design in Chart Tools on the ribbon, On the Design ribbon, select "Select Data" in Data Group, Then you will see the button for Add to add new series.
Hope that will help.
No need to create a GD resource, as someone else suggested.
$input = 'http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com';
$output = 'google.com.jpg';
file_put_contents($output, file_get_contents($input));
Note: this solution only works if you're setup to allow fopen access to URLs. If the solution above doesn't work, you'll have to use cURL.
I use this simple way
docker exec -it <container id or name> hostname -i
e.g
ubuntu@myhost:~$ docker exec -it 3d618ac670fe hostname -i
10.0.1.5
You can have as many classes as you wish like this
public class Fun {
Fun() {
System.out.println("Fun constructor");
}
void fun() {
System.out.println("Fun mathod");
}
public static void main(String[] args) {
Fun fu = new Fun();
fu.fun();
Fen fe = new Fen();
fe.fen();
Fin fi = new Fin();
fi.fin();
Fon fo = new Fon();
fo.fon();
Fan fa = new Fan();
fa.fan();
fa.run();
}
}
class Fen {
Fen() {
System.out.println("fen construuctor");
}
void fen() {
System.out.println("Fen method");
}
}
class Fin {
void fin() {
System.out.println("Fin method");
}
}
class Fon {
void fon() {
System.out.println("Fon method");
}
}
class Fan {
void fan() {
System.out.println("Fan method");
}
public void run() {
System.out.println("run");
}
}
Assuming that you have access to Prototype, this could work. I wrote this code for myself just a few minutes ago; I only needed a single key at a time, so this isn't time efficient for big lists of key:value pairs or for spitting out multiple key names.
function key(int) {
var j = -1;
for(var i in this) {
j++;
if(j==int) {
return i;
} else {
continue;
}
}
}
Object.prototype.key = key;
This is numbered to work the same way that arrays do, to save headaches. In the case of your code:
buttons.key(0) // Should result in "button1"
is a concept that languages like Perl have had for quite a while, and now we’ll get this ability in C# as well. In String Interpolation, we simply prefix the string with a $ (much like we use the @ for verbatim strings). Then, we simply surround the expressions we want to interpolate with curly braces (i.e. { and }):
It looks a lot like the String.Format() placeholders, but instead of an index, it is the expression itself inside the curly braces. In fact, it shouldn’t be a surprise that it looks like String.Format() because that’s really all it is – syntactical sugar that the compiler treats like String.Format() behind the scenes.
A great part is, the compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.
C# string interpolation is a method of concatenating,formatting and manipulating strings. This feature was introduced in C# 6.0. Using string interpolation, we can use objects and expressions as a part of the string interpolation operation.
Syntax of string interpolation starts with a ‘$’ symbol and expressions are defined within a bracket {} using the following syntax.
{<interpolatedExpression>[,<alignment>][:<formatString>]}
Where:
The following code example concatenates a string where an object, author as a part of the string interpolation.
string author = "Mohit";
string hello = $"Hello {author} !";
Console.WriteLine(hello); // Hello Mohit !
Read more on C#/.NET Little Wonders: String Interpolation in C# 6
Dim P As String = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)
P = New Uri(P).LocalPath
int main()
{
int days[] = {1,2,3,4,5};
int *ptr = days;
printf("%u\n", sizeof(days));
printf("%u\n", sizeof(ptr));
return 0;
}
Size of days[] is 20 which is no of elements * size of it's data type. While the size of pointer is 4 no matter what it is pointing to. Because a pointer points to other element by storing it's address.
A little improved and wrapped into a manager solution.
Things to keep in mind. FragmentManager is not a singleton, it manages only Fragments within Activity, so in every activity it will be new. Also, this solution so far doesn't take ViewPager into account that calls setUserVisibleHint() method helping to control visiblity of Fragments.
Feel free to use following classes when dealing with this issue (uses Dagger2 injection). Call in Activity:
//inject FragmentBackstackStateManager instance to myFragmentBackstackStateManager
FragmentManager fragmentManager = getSupportFragmentManager();
myFragmentBackstackStateManager.apply(fragmentManager);
FragmentBackstackStateManager.java:
@Singleton
public class FragmentBackstackStateManager {
private FragmentManager fragmentManager;
@Inject
public FragmentBackstackStateManager() {
}
private BackstackCallback backstackCallbackImpl = new BackstackCallback() {
@Override
public void onFragmentPushed(Fragment parentFragment) {
parentFragment.onPause();
}
@Override
public void onFragmentPopped(Fragment parentFragment) {
parentFragment.onResume();
}
};
public FragmentBackstackChangeListenerImpl getListener() {
return new FragmentBackstackChangeListenerImpl(fragmentManager, backstackCallbackImpl);
}
public void apply(FragmentManager fragmentManager) {
this.fragmentManager = fragmentManager;
fragmentManager.addOnBackStackChangedListener(getListener());
}
}
FragmentBackstackChangeListenerImpl.java:
public class FragmentBackstackChangeListenerImpl implements FragmentManager.OnBackStackChangedListener {
private int lastBackStackEntryCount = 0;
private final FragmentManager fragmentManager;
private final BackstackCallback backstackChangeListener;
public FragmentBackstackChangeListenerImpl(FragmentManager fragmentManager, BackstackCallback backstackChangeListener) {
this.fragmentManager = fragmentManager;
this.backstackChangeListener = backstackChangeListener;
lastBackStackEntryCount = fragmentManager.getBackStackEntryCount();
}
private boolean wasPushed(int backStackEntryCount) {
return lastBackStackEntryCount < backStackEntryCount;
}
private boolean wasPopped(int backStackEntryCount) {
return lastBackStackEntryCount > backStackEntryCount;
}
private boolean haveFragments() {
List<Fragment> fragmentList = fragmentManager.getFragments();
return fragmentList != null && !fragmentList.isEmpty();
}
/**
* If we push a fragment to backstack then parent would be the one before => size - 2
* If we pop a fragment from backstack logically it should be the last fragment in the list, but in Android popping a fragment just makes list entry null keeping list size intact, thus it's also size - 2
*
* @return fragment that is parent to the one that is pushed to or popped from back stack
*/
private Fragment getParentFragment() {
List<Fragment> fragmentList = fragmentManager.getFragments();
return fragmentList.get(Math.max(0, fragmentList.size() - 2));
}
@Override
public void onBackStackChanged() {
int currentBackStackEntryCount = fragmentManager.getBackStackEntryCount();
if (haveFragments()) {
Fragment parentFragment = getParentFragment();
//will be null if was just popped and was last in the stack
if (parentFragment != null) {
if (wasPushed(currentBackStackEntryCount)) {
backstackChangeListener.onFragmentPushed(parentFragment);
} else if (wasPopped(currentBackStackEntryCount)) {
backstackChangeListener.onFragmentPopped(parentFragment);
}
}
}
lastBackStackEntryCount = currentBackStackEntryCount;
}
}
BackstackCallback.java:
public interface BackstackCallback {
void onFragmentPushed(Fragment parentFragment);
void onFragmentPopped(Fragment parentFragment);
}
var css_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: "yourcustomaddress/bundles/andreistatistics/css/like.css"
});
css_link.appendTo('head');
There is no equivalent to $scope.emit()
or $scope.broadcast()
from AngularJS.
EventEmitter inside of a component comes close, but as you mentioned, it will only emit an event to the immediate parent component.
In Angular, there are other alternatives which I'll try to explain below.
@Input() bindings allows the application model to be connected in a directed object graph (root to leaves). The default behavior of a component's change detector strategy is to propagate all changes to an application model for all bindings from any connected component.
Aside: There are two types of models: View Models and Application Models. An application model is connected through @Input() bindings. A view model is a just a component property (not decorated with @Input()) which is bound in the component's template.
To answer your questions:
What if I need to communicate between sibling components?
Shared Application Model: Siblings can communicate through a shared application model (just like angular 1). For example, when one sibling makes a change to a model, the other sibling that has bindings to the same model is automatically updated.
Component Events: Child components can emit an event to the parent component using @Output() bindings. The parent component can handle the event, and manipulate the application model or it's own view model. Changes to the Application Model are automatically propagated to all components that directly or indirectly bind to the same model.
Service Events: Components can subscribe to service events. For example, two sibling components can subscribe to the same service event and respond by modifying their respective models. More on this below.
How can I communicate between a Root component and a component nested several levels deep?
$scope.broadcast()
from Angular 1. The next section describes this idea in more detail.Example of an Observable Service that uses Service Events to Propagate Changes
Here is an example of an observable service that uses service events to propagate changes. When a TodoItem is added, the service emits an event notifying its component subscribers.
export class TodoItem {
constructor(public name: string, public done: boolean) {
}
}
export class TodoService {
public itemAdded$: EventEmitter<TodoItem>;
private todoList: TodoItem[] = [];
constructor() {
this.itemAdded$ = new EventEmitter();
}
public list(): TodoItem[] {
return this.todoList;
}
public add(item: TodoItem): void {
this.todoList.push(item);
this.itemAdded$.emit(item);
}
}
Here is how a root component would subscribe to the event:
export class RootComponent {
private addedItem: TodoItem;
constructor(todoService: TodoService) {
todoService.itemAdded$.subscribe(item => this.onItemAdded(item));
}
private onItemAdded(item: TodoItem): void {
// do something with added item
this.addedItem = item;
}
}
A child component nested several levels deep would subscribe to the event in the same way:
export class GrandChildComponent {
private addedItem: TodoItem;
constructor(todoService: TodoService) {
todoService.itemAdded$.subscribe(item => this.onItemAdded(item));
}
private onItemAdded(item: TodoItem): void {
// do something with added item
this.addedItem = item;
}
}
Here is the component that calls the service to trigger the event (it can reside anywhere in the component tree):
@Component({
selector: 'todo-list',
template: `
<ul>
<li *ngFor="#item of model"> {{ item.name }}
</li>
</ul>
<br />
Add Item <input type="text" #txt /> <button (click)="add(txt.value); txt.value='';">Add</button>
`
})
export class TriggeringComponent{
private model: TodoItem[];
constructor(private todoService: TodoService) {
this.model = todoService.list();
}
add(value: string) {
this.todoService.add(new TodoItem(value, false));
}
}
Reference: Change Detection in Angular
It is because there is a DLL that your program is missing or can't find.
In your case I believe you are missing the openCV dlls. You can find these under the "build" directory that comes with open CV. If you are using VS2010 and building to an x86 program you can locate your dlls here under "opencv\build\x86\vc10\bin". Simply copy all these files to your Debug and Release folders and it should resolve your issues.
Generally you can resolve this issue using the following procedure:
Remember that you will need to have these DLLs in the same directory as your .exe. If you copy the .exe from the Release folder to somewhere else then you will need those DLLs copied with the .exe as well. For portability I tend to try and have a test Virtual Machine with a clean install of Windows (no updates or programs installed), and I walk through the Dependencies using the Dependency Walker one by one until the program is running happily.
This is a common problem. Also see these questions:
Can't run a vc++, error code 0xc0150002
The application was unable to start (0xc0150002) with libcurl C++ Windows 7 VS 2010
0xc0150002 Error when trying to run VC++ libcurl
The application was unable to start correctly 0xc150002
The application was unable to start correctly (0*0150002) - OpenCv
Good Luck!
One of the biggest causes of this issue is the active .NET Framework version. The .NET framework runtime version affects which security protocols are enabled by default.
There doesn't seem to be any authoritative documentation on how it specifically works in different versions, but it seems the defaults are determined more or less as follows:
(For the older versions, your mileage may vary somewhat based on which .NET runtimes are installed on the system. For example, there could be a situation where you are using a very old framework and TLS 1.0 is not supported, or using 4.6.x and TLS 1.3 is not supported)
Microsoft's documentation strongly advises using 4.7+ and the system defaults:
We recommend that you:
- Target .NET Framework 4.7 or later versions on your apps. Target .NET Framework 4.7.1 or later versions on your WCF apps.
- Do not specify the TLS version. Configure your code to let the OS decide on the TLS version.
- Perform a thorough code audit to verify you're not specifying a TLS or SSL version.
For ASP.NET sites: check the targetFramework
version in your <httpRuntime>
element, as this (when present) determines which runtime is actually used by your site:
<httpRuntime targetFramework="4.5" />
Better:
<httpRuntime targetFramework="4.7" />
UPDATE 9 July 2012 - Looks like this is fixed in RTM.
^
and $
so you don't need to add them. (It doesn't appear to be a problem to include them, but you don't need them)View source shows the following:
data-val-regex-pattern="([a-zA-Z0-9 .&'-]+)" <-- MVC 3
data-val-regex-pattern="([a-zA-Z0-9 .&amp;&#39;-]+)" <-- MVC 4/Beta
It looks like we're double encoding.
I had the same issue. I had accidentally deleted the .classpath and .project file in my workspace. Luckily it was in Recycle bin, as soon as it was restored, there were no issues.
You should be able to do the following:
MyFragmentClass test = (MyFragmentClass) getSupportFragmentManager().findFragmentByTag("testID");
if (test != null && test.isVisible()) {
//DO STUFF
}
else {
//Whatever
}
I would like to elaborate on the accepted answer to highlight the nuance between setting a variable to None
versus removing it with del
:
Given the variable foo = 'bar'
, and the following function definition:
def test_var(var):
if var:
print('variable tested true')
else:
print('variable tested false')
Once initially declared, test_var(foo)
yields variable tested true
as expected.
Now try:
foo = None
test_var(foo)
which yields variable tested false
.
Contrast this behavior with:
del foo
test_var(foo)
which now raises NameError: name 'foo' is not defined
.
var args = [ 'p0', 'p1', 'p2' ];
function call_me (param0, param1, param2 ) {
// ...
}
// Calling the function using the array with apply()
call_me.apply(this, args);
And here a link to the original post that I personally liked for its readability
if you are using html agility pack use getattributeValue:
$doc2.DocumentNode.SelectNodes("//div[@class='className']/div[@class='InternalClass']/a[@class='InternalClass']").GetAttributeValue("href","")
For future readers, "Still Reachable" might mean you forgot to close something like a file. While it doesn't seem that way in the original question, you should always make sure you've done that.
Note that if you're using Sublime as your commit editor, you need the -n -w
flags, otherwise git keeps thinking your commit message is empty and aborting.
Building on ideas expressed above, This is effective for changing a month name to its appropriate month number:
from time import strptime
monthWord = 'september'
newWord = monthWord [0].upper() + monthWord [1:3].lower()
# converted to "Sep"
print(strptime(newWord,'%b').tm_mon)
# "Sep" converted to "9" by strptime
In C++11 you could also create an alias for convenience:
template<class T> using min_heap = priority_queue<T, std::vector<T>, std::greater<T>>;
And use it like this:
min_heap<int> my_heap;
Try os.chdir
os.chdir(path)
Change the current working directory to path. Availability: Unix, Windows.
In this case, it doesn't matter as there is no content between the two div
s.
Either one will get the browser to scroll down to it.
The a
element will look like:
<a href="mypageName.html#buttonOne">buttonOne</a>
Or:
<a href="mypageName.html#linkedinB">linkedinB</a>
If you set Vim to use the system clipboard (:set clipboard=unnamed
), then any text you copy in Vim can be pasted using Shift + Insert. Shift + Insert is simply an OS-wide paste key-combination (Ctrl + Insert is the corresponding 'copy').
A tridend based approach would be better. Here is a quick function for checking IE 8.
<?php
function is_IE8(){
if(strpos(str_replace(' ', '', $_SERVER['HTTP_USER_AGENT']),'Trident/4.0')!== FALSE){
return TRUE;
};
return FALSE;
}
?>
Set the html and body tags height
to 100%
and remove the margin around the body:
html, body {
height: 100%;
margin: 0px; /* Remove the margin around the body */
}
Now set the position
of your div to fixed
:
#dimScreen
{
width: 100%;
height: 100%;
background:rgba(255,255,255,0.5);
position: fixed;
top: 0px;
left: 0px;
z-index: 1000; /* Now the div will be on top */
}
document.ontouchmove = function(e){
e.preventDefault();
}
is actually the best choice i found out it allows you to still be able to tap on input fields as well as drag things using jQuery UI draggable but it stops the page from scrolling.
You can do this using Input.setSelectionRange
, part of the Range API for interacting with text selections and the text cursor:
var searchInput = $('#Search');
// Multiply by 2 to ensure the cursor always ends up at the end;
// Opera sometimes sees a carriage return as 2 characters.
var strLength = searchInput.val().length * 2;
searchInput.focus();
searchInput[0].setSelectionRange(strLength, strLength);
Demo: Fiddle
Here is a list of python packages that implement Trie:
http://pinvoke.net/default.aspx/user32.EnumDesktopWindows
There is an example of using user.dll's EnumWindow in C# to list all open windows.
yes, supposing your variable is in the global namespace:
<button onclick="myVar += 1;alert('myVar now equals ' + myVar)">Increment!!</button>
SELECT md.*, DATEDIFF(md.end_date, md.start_date) AS days FROM membership_dates md
output::
id entity_id start_date end_date days
1 1236 2018-01-16 00:00:00 2018-08-31 00:00:00 227
2 2876 2015-06-26 00:00:00 2019-06-30 00:00:00 1465
3 3880 1990-06-05 00:00:00 2018-07-04 00:00:00 10256
4 3882 1993-07-05 00:00:00 2018-07-04 00:00:00 9130
hope it helps someone in future
Another way to create an absolute URL to an action:
var relativeUrl = Url.Action("MyAction"); //..or one of the other .Action() overloads
var currentUrl = Request.Url;
var absoluteUrl = new System.Uri(currentUrl, relativeUrl);
if (HttpContext.Current.Session["emp_num"] != null)
{
// code if session is not null
}
Use:
SELECT t1.Notes,
t2.Name
FROM Table1 t1
JOIN Table2 t2 ON t1.Notes LIKE CONCAT('%', t2.Name ,'%')
Well, the "last five rows" are actually the last five rows depending on your clustered index. Your clustered index, by definition, is the way that he rows are ordered. So you really can't get the "last five rows" without some order. You can, however, get the last five rows as it pertains to the clustered index.
SELECT TOP 5 * FROM MyTable
ORDER BY MyCLusteredIndexColumn1, MyCLusteredIndexColumnq, ..., MyCLusteredIndexColumnN DESC
More simply:
city_name=city_name.replace(/ /gi,'_');
Replaces all spaces with '_'!
Use the following code to Hide the softkeyboard first time when you start the Activity
getActivity().getWindow().setSoftInputMode(WindowManager.
LayoutParams.SOFT_INPUT_STATE_HIDDEN);
Paul H's answer is right that you will have to make a second groupby
object, but you can calculate the percentage in a simpler way -- just groupby
the state_office
and divide the sales
column by its sum. Copying the beginning of Paul H's answer:
# From Paul H
import numpy as np
import pandas as pd
np.random.seed(0)
df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3,
'office_id': list(range(1, 7)) * 2,
'sales': [np.random.randint(100000, 999999)
for _ in range(12)]})
state_office = df.groupby(['state', 'office_id']).agg({'sales': 'sum'})
# Change: groupby state_office and divide by sum
state_pcts = state_office.groupby(level=0).apply(lambda x:
100 * x / float(x.sum()))
Returns:
sales
state office_id
AZ 2 16.981365
4 19.250033
6 63.768601
CA 1 19.331879
3 33.858747
5 46.809373
CO 1 36.851857
3 19.874290
5 43.273852
WA 2 34.707233
4 35.511259
6 29.781508
Did you forget to add the init.py in your package?
You can also try Altair or ggpot which are focused on declarative visualisations.
import numpy as np
import pandas as pd
np.random.seed(1974)
# Generate Data
num = 20
x, y = np.random.random((2, num))
labels = np.random.choice(['a', 'b', 'c'], num)
df = pd.DataFrame(dict(x=x, y=y, label=labels))
from altair import Chart
c = Chart(df)
c.mark_circle().encode(x='x', y='y', color='label')
from ggplot import *
ggplot(aes(x='x', y='y', color='label'), data=df) +\
geom_point(size=50) +\
theme_bw()
Capturing group (pattern)
creates a group that has capturing property.
A related one that you might often see (and use) is (?:pattern)
, which creates a group without capturing property, hence named non-capturing group.
A group is usually used when you need to repeat a sequence of patterns, e.g. (\.\w+)+
, or to specify where alternation should take effect, e.g. ^(0*1|1*0)$
(^
, then 0*1
or 1*0
, then $
) versus ^0*1|1*0$
(^0*1
or 1*0$
).
A capturing group, apart from grouping, will also record the text matched by the pattern inside the capturing group (pattern)
. Using your example, (.*):
, .*
matches ABC
and :
matches :
, and since .*
is inside capturing group (.*)
, the text ABC
is recorded for the capturing group 1.
The whole pattern is defined to be group number 0.
Any capturing group in the pattern start indexing from 1. The indices are defined by the order of the opening parentheses of the capturing groups. As an example, here are all 5 capturing groups in the below pattern:
(group)(?:non-capturing-group)(g(?:ro|u)p( (nested)inside)(another)group)(?=assertion)
| | | | | | || | |
1-----1 | | 4------4 |5-------5 |
| 3---------------3 |
2-----------------------------------------2
The group numbers are used in back-reference \n
in pattern and $n
in replacement string.
In other regex flavors (PCRE, Perl), they can also be used in sub-routine calls.
You can access the text matched by certain group with Matcher.group(int group)
. The group numbers can be identified with the rule stated above.
In some regex flavors (PCRE, Perl), there is a branch reset feature which allows you to use the same number for capturing groups in different branches of alternation.
From Java 7, you can define a named capturing group (?<name>pattern)
, and you can access the content matched with Matcher.group(String name)
. The regex is longer, but the code is more meaningful, since it indicates what you are trying to match or extract with the regex.
The group names are used in back-reference \k<name>
in pattern and ${name}
in replacement string.
Named capturing groups are still numbered with the same numbering scheme, so they can also be accessed via Matcher.group(int group)
.
Internally, Java's implementation just maps from the name to the group number. Therefore, you cannot use the same name for 2 different capturing groups.
Please Check below code that using that You can find all Music Files from sdcard :
public class MainActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_animations);
getAllSongsFromSDCARD();
}
public void getAllSongsFromSDCARD() {
String[] STAR = { "*" };
Cursor cursor;
Uri allsongsuri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
cursor = managedQuery(allsongsuri, STAR, selection, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String song_name = cursor
.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
int song_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media._ID));
String fullpath = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DATA));
String album_name = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.ALBUM));
int album_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
String artist_name = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.ARTIST));
int artist_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
System.out.println("sonng name"+fullpath);
} while (cursor.moveToNext());
}
cursor.close();
}
}
}
I have also added following line in the AndroidManifest.xml file as below:
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
A one-line solution with data.table
could be
library(data.table)
setDT(x)[,.N,by=Believe]
Believe N
1: FALSE 1
2: TRUE 3
Use position:absolute; and width:xxx%; on the td-Element.
If you used managed wordpress or caching plugins, you have to CLEAR YOUR CACHE before the facebook debugger tool can fetch new info!
I've been pulling my hair out for weeks figuring out why changes I made wouldn't show up in facebook debugger for 24 hours!!!! The fix is I have to go into my wordpress dashboard, click the godaddy icon on the top, and click "flush cache." I think many managed wordpress hosters have a cache to figure out how to clear it and you'll be golden.
I know it's been a long time since the question was asked, but I found the check to be clearer like this :
if ($("#A").is('[myattr]')) {
// attribute exists
} else {
// attribute does not exist
}
(As found on this site here)
Documentation about is can be found here
If you use a static key, encrypt and decrypt always give the same result;
public static final String CRYPTOR_KEY = "your static key here";
byte[] keyByte = Base64.getDecoder().decode(CRYPTOR_KEY);
key = new SecretKeySpec(keyByte, "AES");
Taking a guess at the results you want so maybe this is the query you want then
SELECT DISTINCT a FROM my_table
UNION
SELECT DISTINCT b FROM my_table
UNION
SELECT DISTINCT c FROM my_table
UNION
SELECT DISTINCT d FROM my_table
Precision is the total number of digits, can be between 1 and 38.
Scale is the number of digits after the decimal point, may also be set as negative for rounding.
Example:
NUMBER(7,5): 12.12345
NUMBER(5,0): 12345
More details on the ORACLE website:
https://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT1832
I realize this question is over a year old, but I just stumbled across it in dealing with a similar problem and thought I would share another potential solution in case it might help a future traveler (or myself, when I forget this later and find myself flopping around on StackOverflow between screams and throwings of the nearest object on my desk).
In my case I was able to get the effect I wanted by using a DataGridTemplateColumn instead of a DataGridComboBoxColumn, a la the following snippet. [caveat: I'm using .NET 4.0, and what I've been reading leads me to believe the DataGrid has done a lot of evolving, so YMMV if using earlier version]
<DataGridTemplateColumn Header="Identifier_TEMPLATED">
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox IsEditable="False"
Text="{Binding ComponentIdentifier,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
ItemsSource="{Binding Path=ApplicableIdentifiers, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding ComponentIdentifier}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
All the 'use UDP' answers assume an open network and 'stuff it as much as you can' approach. Good for old-style closed-garden dedicated audio/video networks, which are a vanishing sort.
In the actual world, your transmission will go through firewalls (that will drop multicast and sometimes udp), the network is shared with others more important ($$$) apps, so you want to punish abusers with window scaling.
I was getting an additional warning
The compiler compliance specified is 1.6 but a JRE 1.8 is used
Resolving this warning make the error also go away. The steps are as follows:
I right-clicked on it, then clicked on Quick Fix
. From the dialog that opened I selected Open the Compiler Compliance property page
, and clicked the Finish
button.
(This is same as Java Compiler
section.)
In this dialog I found the Compiler compliance level
drop down and changed 1.6
to 1.8
, and clicked on Apply and close
.
I got a message box Compiler Settings Changed
which asked if I wanted to Build the project now?
. I clicked on Yes
.
The build path error went away.
The links in Dave's post are great. Just to put a few technical details about the google links into an answer here on SO:
Google Calendar Link
<a href="http://www.google.com/calendar/event?action=TEMPLATE&text=Example%20Event&dates=20131124T010000Z/20131124T020000Z&details=Event%20Details%20Here&location=123%20Main%20St%2C%20Example%2C%20NY">Add to gCal</a>
the parameters being:
Here's a new link structure that seems to support the new google version of google calendar w/o requiring API interaction:
https://calendar.google.com/calendar/r/eventedit?text=My+Custom+Event&dates=20180512T230000Z/20180513T030000Z&details=For+details,+link+here:+https://example.com/tickets-43251101208&location=Garage+Boston+-+20+Linden+Street+-+Allston,+MA+02134
New base url: https://calendar.google.com/calendar/r/eventedit
New parameters:
Notes:
+
for space in addition to %20
(urlencode
vs rawurlencode
in php - both work)From the PHP manual:
<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
?>
For those looking for OBJC solution, to be added in App Delegate didFinishLaunchingWithOptions method:
[[UINavigationBar appearance] setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
[UINavigationBar appearance].shadowImage = [UIImage new];
[UINavigationBar appearance].backgroundColor = [UIColor clearColor];
[UINavigationBar appearance].translucent = YES;
There is not any safe way to include php
file into js
.
One thing you can do as define
your php file data as javascript global variable
in php file. for example i have three variable which i want to use as js.
abc.php
<?php
$abc = "Abc";
$number = 052;
$mydata = array("val1","val2","val3");
?>
<script type="text/javascript">
var abc = '<?php echo $abc?>';
var number = '<?php echo $number ?>';
var mydata = <?php echo json_encode($mydata); ?>;
</script>
After use
it directly in your js file
wherever you want to use.
abc.js
function test(){
alert('Print php variable : '+ abc +', '+number);
}
function printArrVar(){
alert('print php array variable : '+ JSON.stringify(mydata));
}
Beside If you have any critical data which you don't want to show publicly then you can encrypt data with js. and also get original value of it's from js so no one can get it's original value. if they show into publicly.
this is the standard way you can call php script data into js file without including js into php code or php script into js.
SWIFT 3.0 solution based roughly on the one above using extensions.
extension CMTime {
var durationText:String {
let totalSeconds = CMTimeGetSeconds(self)
let hours:Int = Int(totalSeconds.truncatingRemainder(dividingBy: 86400) / 3600)
let minutes:Int = Int(totalSeconds.truncatingRemainder(dividingBy: 3600) / 60)
let seconds:Int = Int(totalSeconds.truncatingRemainder(dividingBy: 60))
if hours > 0 {
return String(format: "%i:%02i:%02i", hours, minutes, seconds)
} else {
return String(format: "%02i:%02i", minutes, seconds)
}
}
}
Use it with AVPlayer calling it like this?
let dTotalSeconds = self.player.currentTime()
playingCurrentTime = dTotalSeconds.durationText
It means that the field is (part of) a non-unique index. You can issue
show create table <table>;
To see more information about the table structure.
Attach an event handler to the submit event of the form. Make sure it cancels the default action.
Quirks Mode has a guide to event handlers, but you would probably be better off using a library to simplify the code and iron out the differences between browsers. All the major ones (such as YUI and jQuery) include event handling features, and there is a large collection of tiny event libraries.
Here is how you would do it in YUI 3:
<script src="http://yui.yahooapis.com/3.4.1/build/yui/yui-min.js"></script>
<script>
YUI().use('event', function (Y) {
Y.one('form').on('submit', function (e) {
// Whatever else you want to do goes here
e.preventDefault();
});
});
</script>
Make sure that the server will pick up the slack if the JavaScript fails for any reason.
I'm adding an answer here in case someone else finds this on Google. Same symptoms; different problem. For me, the type caches had become corrupt.
From http://mschrag.blogspot.co.nz/2009/01/open-type-cant-find-your-class.html
If you wanted to search some elements based on a regex, you can use the filter
function. For example, say you wanted to make sure that in all the input boxes, the user has only entered numbers, so let's find all the inputs which don't match and highlight them.
$("input:text")
.filter(function() {
return this.value.match(/[^\d]/);
})
.addClass("inputError")
;
Of course if it was just something like this, you could use the form validation plugin, but this method could be applied to any sort of elements you like. Another example to show what I mean: Find all the elements whose id
matches /[a-z]+_\d+/
$("[id]").filter(function() {
return this.id.match(/[a-z]+_\d+/);
});
Most of the answers show how to best handle HttpContext
from the documentation, which is also what I went with.
I did want to mention that you'll want to check you project settings when debugging, the default is Enable Anonymous Authentication = true
.
In case you use jQuery on the client side, you may be interested in this blog post that provides code how to globally extend jQuery's $.parseJSON()
function to automatically convert dates for you.
You don't have to change existing code in case of adding this code. It doesn't affect existing calls to $.parseJSON()
, but if you start using $.parseJSON(data, true)
, dates in data
string will be automatically converted to Javascript dates.
It supports Asp.net date strings: /Date(2934612301)/
as well as ISO strings 2010-01-01T12_34_56-789Z
. The first one is most common for most used back-end web platform, the second one is used by native browser JSON support (as well as other JSON client side libraries like json2.js).
Anyway. Head over to blog post to get the code. http://erraticdev.blogspot.com/2010/12/converting-dates-in-json-strings-using.html
I think you should have a look at the Pathogen plugin. After you have this installed, you can keep all of your plugins in separate folders in ~/.vim/bundle/, and Pathogen will take care of loading them.
Or, alternatively, perhaps you would prefer Vundle, which provides similar functionality (with the added bonus of automatic updates from plugins in github).
You would use an MvcHtmlString
if you want to pass raw HTML to an MVC helper method and you don't want the helper method to encode the HTML.
This works for me:
;
(function ($) {
$(document).ready(function (event) {
$(document).on('click input', 'input[type="date"], input[type="text"].date-picker', function (e) {
var $this = $(this);
$this.prop('type', 'text').datepicker({
showOtherMonths: true,
selectOtherMonths: true,
showButtonPanel: true,
changeMonth: true,
changeYear: true,
dateFormat: 'yy-mm-dd',
showWeek: true,
firstDay: 1
});
setTimeout(function() {
$this.datepicker('show');
}, 1);
});
});
})(jQuery, jQuery.ui);
See also:
How can I disable the new Chrome HTML5 date input?
http://zizhujy.com/blog/post/2014/09/18/Add-date-picker-to-dynamically-generated-input-elements.aspx
You can use the values()
method of a queryset
, which returns a dictionary. Further, this method accepts a list of fields to subset on. The values()
method will not work with get()
, so you must use filter()
(refer to the QuerySet API).
In view
...
def show(request, object_id):
object = Foo.objects.filter(id=object_id).values()[0]
return render_to_response('detail.html', {'object': object})
In detail.html
...
<ul>
{% for key, value in object.items %}
<li><b>{{ key }}:</b> {{ value }}</li>
{% endfor %}
</ul>
For a collection of instances returned by filter:
object = Foo.objects.filter(id=object_id).values() # no [0]
In detail.html...
{% for instance in object %}
<h1>{{ instance.id }}</h1>
<ul>
{% for key, value in instance.items %}
<li><b>{{ key }}:</b> {{ value }}</li>
{% endfor %}
</ul>
{% endfor %}
you can try this curl -sS "http://www.example.com/backup.php" by putting your URL into "" that worked for me I don't know the exact reason but I suppose that putting the url into "" completes the request to the server or just completes the header request.
The following script reads from a file named "testonthis" line by line and then compares each line with a simple string, a string with special characters and a regular expression. If it doesn't match, then the script will print the line, otherwise not.
Space in Bash is so much important. So the following will work:
[ "$LINE" != "table_name" ]
But the following won't:
["$LINE" != "table_name"]
So please use as is:
cat testonthis | while read LINE
do
if [ "$LINE" != "table_name" ] && [ "$LINE" != "--------------------------------" ] && [[ "$LINE" =~ [^[:space:]] ]] && [[ "$LINE" != SQL* ]]; then
echo $LINE
fi
done
Just go to cmd and install pip install pywin32
pythoncom is part of pywin32 for API window extension.... good luck
If you need the transition to run infinitely, try the below example:
#box {_x000D_
position: relative;_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background-color: gray;_x000D_
border: 5px solid black;_x000D_
display: block;_x000D_
}_x000D_
_x000D_
#box:hover {_x000D_
border-color: red;_x000D_
animation-name: flash_border;_x000D_
animation-duration: 2s;_x000D_
animation-timing-function: linear;_x000D_
animation-iteration-count: infinite;_x000D_
-webkit-animation-name: flash_border;_x000D_
-webkit-animation-duration: 2s;_x000D_
-webkit-animation-timing-function: linear;_x000D_
-webkit-animation-iteration-count: infinite;_x000D_
-moz-animation-name: flash_border;_x000D_
-moz-animation-duration: 2s;_x000D_
-moz-animation-timing-function: linear;_x000D_
-moz-animation-iteration-count: infinite;_x000D_
}_x000D_
_x000D_
@keyframes flash_border {_x000D_
0% {_x000D_
border-color: red;_x000D_
}_x000D_
50% {_x000D_
border-color: black;_x000D_
}_x000D_
100% {_x000D_
border-color: red;_x000D_
}_x000D_
}_x000D_
_x000D_
@-webkit-keyframes flash_border {_x000D_
0% {_x000D_
border-color: red;_x000D_
}_x000D_
50% {_x000D_
border-color: black;_x000D_
}_x000D_
100% {_x000D_
border-color: red;_x000D_
}_x000D_
}_x000D_
_x000D_
@-moz-keyframes flash_border {_x000D_
0% {_x000D_
border-color: red;_x000D_
}_x000D_
50% {_x000D_
border-color: black;_x000D_
}_x000D_
100% {_x000D_
border-color: red;_x000D_
}_x000D_
}
_x000D_
<div id="box">roll over me</div>
_x000D_
Here is a function I wrote to solve this issue (assuming tag has no attributes). This function will keep HTML formatting in the node:
function getAsXMLContent($xmlElement)
{
$content=$xmlElement->asXML();
$end=strpos($content,'>');
if ($end!==false)
{
$tag=substr($content, 1, $end-1);
return str_replace(array('<'.$tag.'>', '</'.$tag.'>'), '', $content);
}
else
return '';
}
$string = "<element><child>Hello World</child></element>";
$xml = new SimpleXMLElement($string);
echo getAsXMLContent($xml->child); // prints Hello World
My issue was that I left the "mex" onto the end of my web service link.
Instead of "http://yeagertech.com/yeagerte/YeagerTechWcfService.YeagerTechWcfService.svc/mex"
Use "http://yeagertech.com/yeagerte/YeagerTechWcfService.YeagerTechWcfService.svc"
You can use some thing like this
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div ng-app="" ng-init="btn1=false" ng-init="btn2=false">_x000D_
<p>_x000D_
<input type="submit" ng-disabled="btn1||btn2" ng-click="btn1=true" ng-model="btn1" />_x000D_
</p>_x000D_
<p>_x000D_
<button ng-disabled="btn1||btn2" ng-model="btn2" ng-click="btn2=true">Click Me!</button>_x000D_
</p>_x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
I am using rails 6 and Model.all(:order 'columnName DESC') is not working. I have found the correct answer in OrderInRails
This is very simple.
@variable=Model.order('columnName DESC')
Sometimes, XCode does not forget the line which had an "Editor Placeholder" even if you have replaced it with a value. Cut the portion of the code where XCode is complaining and paste the code back to the same place to make the error message go away. This worked for me.
Assembly.GetExecutingAssembly().Location
You can not use ORDER BY as part of the UPDATE statement (you can use in sub-selects that are part of the update).
UPDATE Test
SET Number = rowNumber
FROM Test
INNER JOIN
(SELECT ID, row_number() OVER (ORDER BY ID DESC) as rowNumber
FROM Test) drRowNumbers ON drRowNumbers.ID = Test.ID
I was trying to do this but having problems with Kjetil Watnedal's solution because I don't use the inline linq syntax - I prefer method-style syntax. My specific problem was in trying to do dynamic sorting using a custom IComparer
.
My solution ended up like this:
Given an IQueryable query like so:
List<DATA__Security__Team> teams = TeamManager.GetTeams();
var query = teams.Where(team => team.ID < 10).AsQueryable();
And given a run-time sort field argument:
string SortField; // Set at run-time to "Name"
The dynamic OrderBy looks like so:
query = query.OrderBy(item => item.GetReflectedPropertyValue(SortField));
And that's using a little helper method called GetReflectedPropertyValue():
public static string GetReflectedPropertyValue(this object subject, string field)
{
object reflectedValue = subject.GetType().GetProperty(field).GetValue(subject, null);
return reflectedValue != null ? reflectedValue.ToString() : "";
}
One last thing - I mentioned that I wanted the OrderBy
to use custom IComparer
- because I wanted to do Natural sorting.
To do that, I just alter the OrderBy
to:
query = query.OrderBy(item => item.GetReflectedPropertyValue(SortField), new NaturalSortComparer<string>());
See this post for the code for NaturalSortComparer()
.
Use proper escaping: string.split("\\|")
Or, in Java 5+, use the helper Pattern.quote()
which has been created for exactly this purpose:
string.split(Pattern.quote("|"))
which works with arbitrary input strings. Very useful when you need to quote / escape user input.
Highlight everything you want to run and run as a script. You can do that by clicking the icon on the menu bar that looks like a text file with a lightning bolt on it. That is the same as hitting F5. So if F5 doesn't work you probably have an error in your script.
Do you have semicolons after each statement?
You need a main()
function so the program knows where to start.
I've implemented and tested this one; it should cover most bases:
public static <T> List<T> safeSubList(List<T> list, int fromIndex, int toIndex) {
int size = list.size();
if (fromIndex >= size || toIndex <= 0 || fromIndex >= toIndex) {
return Collections.emptyList();
}
fromIndex = Math.max(0, fromIndex);
toIndex = Math.min(size, toIndex);
return list.subList(fromIndex, toIndex);
}
Here's a script that will use the Google API to acquire the users postal code and populate an input field.
function postalCodeLookup(input) {
var head= document.getElementsByTagName('head')[0],
script= document.createElement('script');
script.src= '//maps.googleapis.com/maps/api/js?sensor=false';
head.appendChild(script);
script.onload = function() {
if (navigator.geolocation) {
var a = input,
fallback = setTimeout(function () {
fail('10 seconds expired');
}, 10000);
navigator.geolocation.getCurrentPosition(function (pos) {
clearTimeout(fallback);
var point = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
new google.maps.Geocoder().geocode({'latLng': point}, function (res, status) {
if (status == google.maps.GeocoderStatus.OK && typeof res[0] !== 'undefined') {
var zip = res[0].formatted_address.match(/,\s\w{2}\s(\d{5})/);
if (zip) {
a.value = zip[1];
} else fail('Unable to look-up postal code');
} else {
fail('Unable to look-up geolocation');
}
});
}, function (err) {
fail(err.message);
});
} else {
alert('Unable to find your location.');
}
function fail(err) {
console.log('err', err);
a.value('Try Again.');
}
};
}
You can adjust accordingly to acquire different information. For more info, check out the Google Maps API documentation.
This happened to me too! But I accidentally found out that execute the 'mysqld' command can solve your problem.
My SQL version is 5.7. Hope this works for you.
Sharing on Facebook: How to Improve Your Results by Customizing the Image, Title, and Text
From the link above. For the best possible share, you'll want to suggest 3 pieces of data in your HTML:
This accomplished by the following, placed inside the 'head' tag of your HTML:
<title>INSERT POST TITLE</title>
<meta property=og:image content="http://site.com/YOUR_IMAGE.jpg"/>
<meta name=description content="INSERT YOUR SUMMARY TEXT"/>
If you website is static HTML, you'll have to do this for every page using your HTML editor.
If you're using a CMS like Drupal, you can automate a lot of it (see above link). If you use wordpress, you can probably implement something similar using the Drupal example as a guideline. I hope you found these useful.
Finally, you can always manually edit your share posts. See this example with illustrations.
I have solve this problem in my program using:
number_input = float("{:.1f}".format(float(input())))
list.append(number_input)
The answer by Nick Mitchinson is for Bootstrap version 2.
If you are using Bootstrap version 3, then forms have changed a bit. For bootstrap 3, use the following instead:
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-6">
<textarea class="form-control" rows="3" placeholder="What's up?" required></textarea>
</div>
</div>
</div>
Where, col-md-6 will target medium sized devices. You can add col-xs-6 etc to target smaller devices.
In Jenkins 2.60.3 there is a way to delete build artifacts (not the archived artifacts) in order to save hard drive space on the build machine. In the General section, check "Discard old builds" with strategy "Log Rotation" and then go into its Advanced options. Two more options will appear related to keeping build artifacts for the job based on number of days or builds.
The settings that work for me are to enter 1 for "Max # of builds to keep with artifacts" and then to have a post-build action to archive the artifacts. This way, all artifacts from all builds will be archived, all information from builds will be saved, but only the last build will keep its own artifacts.
I need to do 2 things to connect with instance name
1. Enable SQL Server Browser (in SQL server config manager)
2. Enable UDP, port 1434 trong file wall (if you using amazon EC2 or other service you need open port in their setting too)
Restart sql and done
This answer is taken from TuxRadar:
When running PHP through your web server, there are two distinct options: running it using PHP's CGI SAPI, or running it as a module for the web server. Each have their own benefits, but, overall, the module is generally preferred.
Running PHP as a CGI means that you basically tell your web server the location of the PHP executable file, and the server runs that executable, giving it the script you called, each time you visit a page. That means each time you load a page, PHP needs to read php.ini and set its settings, it needs to load all its extensions, and then it needs to start work parsing the script - there is a lot of repeated work.
When you run PHP as a module, PHP literally sits inside your web server - it starts only once, loads its settings and extensions only once, and can also store information across sessions. For example, PHP accelerators rely on PHP being able to save cached data across requests, which is impossible using the CGI version.
The obvious advantage of using PHP as a module is speed - you will see a big speed boost if you convert from CGI to a module. Many people, particularly Windows users, do not realise this, and carry on using the php.exe CGI SAPI, which is a shame - the module is usually three to five times faster.
There is one key advantage to using the CGI version, though, and that is that PHP reads its settings every time you load a page. With PHP running as a module, any changes you make in the php.ini file do not kick in until you restart your web server, which makes the CGI version preferable if you are testing a lot of new settings and want to see instant responses.
In OpenCV header "types_c.h" there are a set of defines which generate these, the format is CV_bits{U|S|F}C<number_of_channels>
So for example CV_8UC3
means 8 bit unsigned chars, 3 colour channels - each of these names map onto an arbitrary integer with the macros in that file.
Edit: See "types_c.h" for example:
#define CV_8UC3 CV_MAKETYPE(CV_8U,3)
#define CV_MAKETYPE(depth,cn) (CV_MAT_DEPTH(depth) + (((cn)-1) << CV_CN_SHIFT))
eg.
depth = CV_8U = 0
cn = 3
CV_CN_SHIFT = 3
CV_MAT_DEPTH(0) = 0
(((cn)-1) << CV_CN_SHIFT) = (3-1) << 3 = 2<<3 = 16
So CV_8UC3 = 16
but you aren't supposed to use this number, just check type() == CV_8UC3
if you need to know what type an internal OpenCV array is.
Remember OpenCV will convert the jpeg into BGR (or grey scale if you pass '0' to imread
) - so it doesn't tell you anything about the original file.
Internally, string::operator==()
is using string::compare()
. Please refer to: CPlusPlus - string::operator==()
I wrote a small application to compare the performance, and apparently if you compile and run your code on debug environment the string::compare()
is slightly faster than string::operator==()
. However if you compile and run your code in Release environment, both are pretty much the same.
FYI, I ran 1,000,000 iteration in order to come up with such conclusion.
In order to prove why in debug environment the string::compare is faster, I went to the assembly and here is the code:
DEBUG BUILD
string::operator==()
if (str1 == str2)
00D42A34 lea eax,[str2]
00D42A37 push eax
00D42A38 lea ecx,[str1]
00D42A3B push ecx
00D42A3C call std::operator==<char,std::char_traits<char>,std::allocator<char> > (0D23EECh)
00D42A41 add esp,8
00D42A44 movzx edx,al
00D42A47 test edx,edx
00D42A49 je Algorithm::PerformanceTest::stringComparison_usingEqualOperator1+0C4h (0D42A54h)
string::compare()
if (str1.compare(str2) == 0)
00D424D4 lea eax,[str2]
00D424D7 push eax
00D424D8 lea ecx,[str1]
00D424DB call std::basic_string<char,std::char_traits<char>,std::allocator<char> >::compare (0D23582h)
00D424E0 test eax,eax
00D424E2 jne Algorithm::PerformanceTest::stringComparison_usingCompare1+0BDh (0D424EDh)
You can see that in string::operator==(), it has to perform extra operations (add esp, 8 and movzx edx,al)
RELEASE BUILD
string::operator==()
if (str1 == str2)
008533F0 cmp dword ptr [ebp-14h],10h
008533F4 lea eax,[str2]
008533F7 push dword ptr [ebp-18h]
008533FA cmovae eax,dword ptr [str2]
008533FE push eax
008533FF push dword ptr [ebp-30h]
00853402 push ecx
00853403 lea ecx,[str1]
00853406 call std::basic_string<char,std::char_traits<char>,std::allocator<char> >::compare (0853B80h)
string::compare()
if (str1.compare(str2) == 0)
00853830 cmp dword ptr [ebp-14h],10h
00853834 lea eax,[str2]
00853837 push dword ptr [ebp-18h]
0085383A cmovae eax,dword ptr [str2]
0085383E push eax
0085383F push dword ptr [ebp-30h]
00853842 push ecx
00853843 lea ecx,[str1]
00853846 call std::basic_string<char,std::char_traits<char>,std::allocator<char> >::compare (0853B80h)
Both assembly code are very similar as the compiler perform optimization.
Finally, in my opinion, the performance gain is negligible, hence I would really leave it to the developer to decide on which one is the preferred one as both achieve the same outcome (especially when it is release build).
Here is one that works better for me (LINQPad version):
DateTime d;
DateTime.TryParseExact(
"2010-08-20T15:00:00Z",
@"yyyy-MM-dd\THH:mm:ss\Z",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal,
out d);
d.ToString()
produces
true
8/20/2010 8:00:00 AM
Here's a complete (yet simple) example of redirecting after X seconds, while updating a counter div:
<html>_x000D_
<body>_x000D_
<div id="counter">5</div>_x000D_
<script>_x000D_
setInterval(function() {_x000D_
var div = document.querySelector("#counter");_x000D_
var count = div.textContent * 1 - 1;_x000D_
div.textContent = count;_x000D_
if (count <= 0) {_x000D_
window.location.replace("https://example.com");_x000D_
}_x000D_
}, 1000);_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
The initial content of the counter
div is the number of seconds to wait.
From this question -- add the following styles to a print-only stylesheet. This solution will work in IE and Firefox, but not in Chrome (as of version 21):
#header {
display: table-header-group;
}
#main {
display: table-row-group;
}
#footer {
display: table-footer-group;
}
Due to the way that strings are stored in Perl, getting the length of a string is optimized.
if (length $str)
is a good way of checking that a string is non-empty.
If you're in a situation where you haven't already guarded against undef
, then the catch-all for "non-empty" that won't warn is if (defined $str and length $str)
.
That's simple. It's explained in man bash
:
/bin/bash
The bash executable
/etc/profile
The systemwide initialization file, executed for login shells
~/.bash_profile
The personal initialization file, executed for login shells
~/.bashrc
The individual per-interactive-shell startup file
~/.bash_logout
The individual login shell cleanup file, executed when a login shell exits
~/.inputrc
Individual readline initialization file
Login shells are the ones that are read one you login (so, they are not executed when merely starting up xterm, for example). There are other ways to login. For example using an X display manager. Those have other ways to read and export environment variables at login time.
Also read the INVOCATION
chapter in the manual. It says "The following paragraphs describe how bash executes its startup files.", i think that's a spot-on :) It explains what an "interactive" shell is too.
Bash does not know about .environment
. I suspect that's a file of your distribution, to set environment variables independent of the shell that you drive.
I just got done doing this exact thing in a project. The HTML side looked a bit like this:
<a href="[fullsize]" class="gallerypic" title="">
<img src="[thumbnail pic]" height="90" width="140" alt="[Gallery Photo]" class="pic" />
<span class="zoom-icon">
<img src="/images/misc/zoom.gif" width="32" height="32" alt="Zoom">
</span>
</a>
Then using CSS:
a.gallerypic{
width:140px;
text-decoration:none;
position:relative;
display:block;
border:1px solid #666;
padding:3px;
margin-right:5px;
float:left;
}
a.gallerypic span.zoom-icon{
visibility:hidden;
position:absolute;
left:40%;
top:35%;
filter:alpha(opacity=50);
-moz-opacity:0.5;
-khtml-opacity: 0.5;
opacity: 0.5;
}
a.gallerypic:hover span.zoom-icon{
visibility:visible;
}
I left a lot of the sample in there on the CSS so you can see how I decided to do the style. Note I lowered the opacity so you could see through the magnifying glass.
Hope this helps.
EDIT: To clarify for your example - you could ignore the visibility:hidden;
and kill the :hover
execution if you wanted, this was just the way I did it.
when i write import StringIO it says there is no such module.
From What’s New In Python 3.0:
The
StringIO
andcStringIO
modules are gone. Instead, import theio
module and useio.StringIO
orio.BytesIO
for text and data respectively.
.
A possibly useful method of fixing some Python 2 code to also work in Python 3 (caveat emptor):
try:
from StringIO import StringIO ## for Python 2
except ImportError:
from io import StringIO ## for Python 3
Note: This example may be tangential to the main issue of the question and is included only as something to consider when generically addressing the missing
StringIO
module. For a more direct solution the messageTypeError: Can't convert 'bytes' object to str implicitly
, see this answer.
I'm on Ubuntu. I used apt-get to install node. Npm was not included in that package, so it had to be installed separately. I assumed that would work, but apparently the npm version in the Ubuntu distribution was outdated.
The node wiki has this instruction:
Obtaining a recent version of Node or installing on older Ubuntu and other apt-based distributions may require a few extra steps. Example install:
sudo apt-get update
sudo apt-get install -y python-software-properties python g++ make
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs
After that, npm was already included and worked perfectly.
Read all the answers.
There is another user case where final
keyword can be used i.e. in a method argument:
public void showCaseFinalArgumentVariable(final int someFinalInt){
someFinalInt = 9; // won't compile as the argument is final
}
Can be used for variable which should not be changed.
struct var e2 address pushed as arg to callee stack and values gets assigned there. In fact, get() returns e2's address in eax reg. This works like call by reference.
For a system-agnostic solution that works on both Windows and Linux, no matter what the input path, one could use os.path.join(os.sep, rootdir + os.sep, targetdir)
On WIndows:
>>> os.path.join(os.sep, "C:" + os.sep, "Windows")
'C:\\Windows'
On Linux:
>>> os.path.join(os.sep, "usr" + os.sep, "lib")
'/usr/lib'
A possible very simple fix that worked for me. After deleting any database references and connections you find in server/serverobject explorer, right click the App_Data folder (didn't show any objects within the application for me) and select open. Once open put all the database/etc. files in a backup folder or if you have the guts just delete them. Run your application and it should recreate everything from scratch.
Here is another solution using Lodash:
var _ = require('lodash');
var result1 = [
{id:1, name:'Sandra', type:'user', username:'sandra'},
{id:2, name:'John', type:'admin', username:'johnny2'},
{id:3, name:'Peter', type:'user', username:'pete'},
{id:4, name:'Bobby', type:'user', username:'be_bob'}
];
var result2 = [
{id:2, name:'John', email:'[email protected]'},
{id:4, name:'Bobby', email:'[email protected]'}
];
// filter all those that do not match
var result = types1.filter(function(o1){
// if match found return false
return _.findIndex(types2, {'id': o1.id, 'name': o1.name}) !== -1 ? false : true;
});
console.log(result);
It seems that for Jackson 1.9.12 there is no such possibility by default, because of:
public final static class DateTimeSerializer
extends JodaSerializer<DateTime>
{
public DateTimeSerializer() { super(DateTime.class); }
@Override
public void serialize(DateTime value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonGenerationException
{
if (provider.isEnabled(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS)) {
jgen.writeNumber(value.getMillis());
} else {
jgen.writeString(value.toString());
}
}
@Override
public JsonNode getSchema(SerializerProvider provider, java.lang.reflect.Type typeHint)
{
return createSchemaNode(provider.isEnabled(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS)
? "number" : "string", true);
}
}
This class serializes data using toString() method of Joda DateTime.
Approach proposed by Rusty Kuntz works perfect for my case.
Try this:
public static void main(String[] args)
{
Pattern p = Pattern.compile("^\\d+$");
Scanner kb = new Scanner(System.in);
int num1;
int num2 = 0;
String temp;
Matcher numberMatcher;
System.out.print("Enter number 1: ");
try
{
num1 = kb.nextInt();
}
catch (java.util.InputMismatchException e)
{
System.out.println("Invalid Input");
//
return;
}
while(num2<num1)
{
System.out.print("Enter number 2: ");
temp = kb.next();
numberMatcher = p.matcher(temp);
if (numberMatcher.matches())
{
num2 = Integer.parseInt(temp);
}
else
{
System.out.println("Invalid Number");
}
}
}
You could try to parse the string into an int
as well, but usually people try to avoid throwing exceptions.
What I have done is that I have defined a regular expression that defines a number, \d
means a numeric digit. The +
sign means that there has to be one or more numeric digits. The extra \
in front of the \d
is because in java, the \
is a special character, so it has to be escaped.
Try this: Adding users to MySQL
You need grant privileges to the user if you want external acess to database(ie. web pages).
.icon {
width: 48px;
height: 48px;
display: inline-block;
background: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/18515/heart.svg) no-repeat 50% 50%;
background-size: cover;
}
.icon-orange {
-webkit-filter: hue-rotate(40deg) saturate(0.5) brightness(390%) saturate(4);
filter: hue-rotate(40deg) saturate(0.5) brightness(390%) saturate(4);
}
.icon-yellow {
-webkit-filter: hue-rotate(70deg) saturate(100);
filter: hue-rotate(70deg) saturate(100);
}
You can loop through the keys:
foo = {one:1, two:2, three:3};
for (key in foo){
console.log("foo["+ key +"]="+ foo[key]);
}
will output:
foo[one]=1
foo[two]=2
foo[three]=3
I was face same problem ..... And I got solution by using typeof()
if (typeof(value) !== 'undefined' && value != null) {
console.log('Not Undefined and Not Null')
} else {
console.log('Undefined or Null')
}
You must have to use typeof()
to identified undefined
I ended up using BackgroundWorker, it is definitely asynchronous unlike some of the above solutions, it handles returning to the GUI thread for you, and it is very easy to understand.
It is also very easy to handle exceptions, as they end up in the RunWorkerCompleted method, but make sure you read this: Unhandled exceptions in BackgroundWorker
I used WebClient but obviously you could use HttpWebRequest.GetResponse if you wanted.
var worker = new BackgroundWorker();
worker.DoWork += (sender, args) => {
args.Result = new WebClient().DownloadString(settings.test_url);
};
worker.RunWorkerCompleted += (sender, e) => {
if (e.Error != null) {
connectivityLabel.Text = "Error: " + e.Error.Message;
} else {
connectivityLabel.Text = "Connectivity OK";
Log.d("result:" + e.Result);
}
};
connectivityLabel.Text = "Testing Connectivity";
worker.RunWorkerAsync();
Similarly, I needed to create an rpm with just a few files. Since these files were source controlled, and because it seemed silly, I didn't want to go through taring them up just to have rpm untar them. I came up with the following:
Set up your environment:
mkdir -p ~/rpm/{BUILD,RPMS}
echo '%_topdir %(echo "$HOME")/rpm' > ~/.rpmmacros
Create your spec file, foobar.spec, with the following contents:
Summary: Foo to the Bar
Name: foobar
Version: 0.1
Release: 1
Group: Foo/Bar
License: FooBarPL
Source: %{expand:%%(pwd)}
BuildRoot: %{_topdir}/BUILD/%{name}-%{version}-%{release}
%description
%{summary}
%prep
rm -rf $RPM_BUILD_ROOT
mkdir -p $RPM_BUILD_ROOT/usr/bin
mkdir -p $RPM_BUILD_ROOT/etc
cd $RPM_BUILD_ROOT
cp %{SOURCEURL0}/foobar ./usr/bin/
cp %{SOURCEURL0}/foobar.conf ./etc/
%clean
rm -r -f "$RPM_BUILD_ROOT"
%files
%defattr(644,root,root)
%config(noreplace) %{_sysconfdir}/foobar.conf
%defattr(755,root,root)
%{_bindir}/foobar
Build your rpm:
rpmbuild -bb foobar.spec
There's a little hackery there specifying the 'source' as your current directory, but it seemed far more elegant then the alternative, which was to, in my case, write a separate script to create a tarball, etc, etc.
Note: In my particular situation, my files were arranged in folders according to where they needed to go, like this:
./etc/foobar.conf
./usr/bin/foobar
and so the prep section became:
%prep
rm -rf $RPM_BUILD_ROOT
mkdir -p $RPM_BUILD_ROOT
cd $RPM_BUILD_ROOT
tar -cC %{SOURCEURL0} --exclude 'foobar.spec' -f - ./ | tar xf -
Which is a little cleaner.
Also, I happen to be on a RHEL5.6 with rpm versions 4.4.2.3, so your mileage may vary.
EDIT: There is now a queuecomplete
event that you can use for exactly that purpose.
Previous answer:
Paul B.'s answer works, but an easier way to do so, is by checking if there are still files in the queue or uploading whenever a file completes. This way you don't have to keep track of the files yourself:
Dropzone.options.filedrop = {
init: function () {
this.on("complete", function (file) {
if (this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
doSomething();
}
});
}
};
In the spectrum of kernel designs the two extreme points are monolithic kernels and microkernels.
The (classical) Linux kernel for instance is a monolithic kernel (and so is every commercial OS to date as well - though they might claim otherwise);
In that its code is a
single C file giving rise to a single process that implements all of the above
services.
To exemplify the encapsulation of the Linux kernel we remark that
the Linux kernel does not even have access to any of the standard C libraries.
Indeed the Linux kernel cannot use rudimentary C library functions such as
printf. Instead it implements its own printing function (called prints).
This seclusion of the Linux kernel and self-containment provide Linux kernel
with its main advantage: the kernel resides in a single address space1
enabling
all features to communicate in the fastest way possible without resorting to
any type of message passing.
In particular, a monolithic kernel implements all of the device drivers
of the system.
This however is the main drawback of a monolithic kernel:
introduction of any new unsupported hardware requires a rewrite of the
kernel (in the relevant parts), recompilation of it, and re-installing the entire
OS.
More importantly, if any device driver crashes the entire kernel suffers
as a result.
This un-modular approach to hardware additions and hardware crashes
is the main argument for supporting the other extreme design approach
for kernels. A microkernel is in a sense a minimalistic kernel that houses
only the very basic of OS services (like process management and file system
management). In a microkernel the device drivers lie outside of the kernel
allowing for addition and removal of device drivers while the OS is running
and require no alternations of the kernel.
I tested what @Samy Dindane suggested in the comment on the OP.
I believe it works, try
git fetch <remote_name> <remote_branch>:<local_branch>
git checkout <local_branch>
Here's an example for a fictitious remote repository named foo
with a branch named bar
where I create a local branch bar
tracking the remote:
git fetch foo bar:bar
git checkout bar
I would suggest you try the html tag <br>
, in case your marketing application will recognize it.
I use %0D%0A
. This should work as long as the email is HTML formatted.
<a href="mailto:[email protected]?subject=Subscribe&body=Lastame%20%3A%0D%0AFirstname%20%3A"><img alt="Subscribe" class="center" height="50" src="subscribe.png" style="width: 137px; height: 50px; color: #4da6f7; font-size: 20px; display: block;" width="137"></a>
You will likely want to take out the %20 before Firstname, otherwise you will have a space as the first character on the next line.
A note, when I tested this with your code, it worked (along with some extra spacing). Are you using a mail client that doesn't allow HTML formatting?
This worked for me:
PL SQL Developer -> Tools -> Export User Objects
Select checkboxes: Include privilege and Include storage
Select your file name. Hit export.
You can later use generated export file to create table in another schema.
You could also make life easier using a wrapper, e.g. with ADODb:
$myarray=$db->GetCol("SELECT type FROM cars ".
"WHERE owner=? and selling=0",
array($_SESSION['username']));
A good wrapper will do all your escaping for you too, making things easier to read.
0755
= User:rwx
Group:r-x
World:r-x
0750
= User:rwx
Group:r-x
World:---
(i.e. World: no access)
r = read
w = write
x = execute (traverse for directories)
You probably want to use an ArrayList for this -- for a dynamically sized array like structure.
I've separated this answer into two(2) methods. The first method will separate your fullname field into first, middle, and last names. The middle name will show as NULL if there is no middle name.
SELECT
SUBSTRING_INDEX(SUBSTRING_INDEX(fullname, ' ', 1), ' ', -1) AS first_name,
If( length(fullname) - length(replace(fullname, ' ', ''))>1,
SUBSTRING_INDEX(SUBSTRING_INDEX(fullname, ' ', 2), ' ', -1) ,NULL)
as middle_name,
SUBSTRING_INDEX(SUBSTRING_INDEX(fullname, ' ', 3), ' ', -1) AS last_name
FROM registeredusers
This second method considers the middle name as part of the lastname. We will only select a firstname and lastname column from your fullname field.
SELECT
SUBSTRING_INDEX(SUBSTRING_INDEX(fullname, ' ', 1), ' ', -1) AS first_name,
TRIM( SUBSTR(fullname, LOCATE(' ', fullname)) ) AS last_name
FROM registeredusers
There's a bunch of cool things you can do with substr, locate, substring_index, etc. Check the manual for some real confusion. http://dev.mysql.com/doc/refman/5.0/en/string-functions.html
You have to check your quotes
properly,
$sql = $wpdb->prepare(
"INSERT INTO `wp_submitted_form`
(`name`,`email`,`phone`,`country`,`course`,`message`,`datesent`)
values ($name, $email, $phone, $country, $course, $message, $datesent)");
$wpdb->query($sql);
OR you can use like,
$sql = "INSERT INTO `wp_submitted_form`
(`name`,`email`,`phone`,`country`,`course`,`message`,`datesent`)
values ($name, $email, $phone, $country, $course, $message, $datesent)";
$wpdb->query($sql);
On pure JS:
let select = document.getElementById("select_id")
let to_hide = select[select.selectedIndex];
to_hide.setAttribute('hidden', 'hidden');
to unhide just
to_hide.removeAttr('hidden');
or
to_hide.hidden = true; // to hide
to_hide.hidden = false; // to unhide
I implemented it in the following way. I wanted a generic MakeRequest
method that could call my API and receive content for the body of the request - and also deserialise the response into the desired type. I create a Dictionary<string, string>
object to house the content to be submitted, and then set the HttpRequestMessage
Content
property with it:
Generic method to call the API:
private static T MakeRequest<T>(string httpMethod, string route, Dictionary<string, string> postParams = null)
{
using (var client = new HttpClient())
{
HttpRequestMessage requestMessage = new HttpRequestMessage(new HttpMethod(httpMethod), $"{_apiBaseUri}/{route}");
if (postParams != null)
requestMessage.Content = new FormUrlEncodedContent(postParams); // This is where your content gets added to the request body
HttpResponseMessage response = client.SendAsync(requestMessage).Result;
string apiResponse = response.Content.ReadAsStringAsync().Result;
try
{
// Attempt to deserialise the reponse to the desired type, otherwise throw an expetion with the response from the api.
if (apiResponse != "")
return JsonConvert.DeserializeObject<T>(apiResponse);
else
throw new Exception();
}
catch (Exception ex)
{
throw new Exception($"An error ocurred while calling the API. It responded with the following message: {response.StatusCode} {response.ReasonPhrase}");
}
}
}
Call the method:
public static CardInformation ValidateCard(string cardNumber, string country = "CAN")
{
// Here you create your parameters to be added to the request content
var postParams = new Dictionary<string, string> { { "cardNumber", cardNumber }, { "country", country } };
// make a POST request to the "cards" endpoint and pass in the parameters
return MakeRequest<CardInformation>("POST", "cards", postParams);
}
Moreover, mousemove
events are not triggered if you perform drag'n'drop over a browser window.
To track mouse coordinates during drag'n'drop you should attach handler for document.ondragover
event and use it's originalEvent property.
Example:
var globalDragOver = function (e)
{
var original = e.originalEvent;
if (original)
{
window.x = original.pageX;
window.y = original.pageY;
}
}
An awesome repository here .
api : masfufa.js
sample : masfufa.html
Two Examples will be enough to understand this library :
/* | 1 , 2 , 3 |
* MX= | 4 , 5 , 6 | Dimensions= 3 x 3
* | 7 , 8 , 9 |
*/
jsdk.getAPI('my');
var A=[1, 2, 3, 4, 5, 6, 7, 8, 9];
var MX=myAPI.getInstance('masfufa',{data:A,dim:'3x3'});
then :
MX.get[0][0] // -> 1 (first)
MX.get[2][2] // ->9 (last)
/* | 1 , 9 , 3 , 4 |
* MXB= | 4 , 5 , 6 , 2 | Dimensions= 2 x 4
*
*/
var B=[1 , 9 , 3 , 4 , 4 , 5 , 6 , 2];
var MXB=myAPI.getInstance('masfufa',{data:B,dim:'2x4'});
then :
MXB.get[0][0] // -> 1 (first)
MXB.get[1][3] // -> 2 (last)
MXB.get[1][2] // -> 6 (before last)
I had a same issue recently (visual studio 2017 & Windows 10), and solved it using the following method:
Control Panel --> Credential Manager --> Manage Windows Credentials --> Choose the entry of the git repository, and Edit the user and password.
Done.