k-a-f's answer works for selecting one column, if selecting multiple column, we can.
DECLARE a BIGINT DEFAULT 1;
DECLARE b BIGINT DEFAULT "name";
SELECT id, name from table into a,b;
Then we just need to check a,b for values.
Swift Version of Lithu T.V's answer:
webView.loadHTMLString(htmlString, baseURL: NSBundle.mainBundle().bundleURL)
You need to give privileges to the particular user by giving the command mysql> GRANT ALL PRIVILEGES . To 'username'@'localhost'; and then give FLUSH PRIVILEGES; command. Then it won't give this error.., hope it helps thank you..!
String accountID = request.getParameter("accountID");
I am not sure if this is relevant in today's world, but double quotes used to be used for content that needed to have control characters processed and single quotes for strings that didn't.
The compiler will run string manipulation on a double quoted string while leaving a single quoted string literally untouched. This used to lead to 'good' developers choosing to use single quotes for strings that didn't contain control characters like \n
or \0
(not processed within single quotes) and double quotes when they needed the string parsed (at a slight cost in CPU cycles for processing the string).
Use IS
instead of =
This will solve your problem
example syntax:
UPDATE studentdetails
SET contactnumber = 9098979690
WHERE contactnumber IS NULL;
I read all of the responses here and finally came up with a usable solution that is simple. The performance issues arise from the BETWEEN statement, not the generation of the row numbers themselves. So I used an algorithm to do dynamic paging by passing the page number and the number of records.
The passes are not start row and number of rows, but rather "rows per page (500)" and "page number (4)" which would be rows 1501 - 2000. These values can be replaced by stored procedure variables so you are not locked into using a specific paging amount.
select * from (
select
(((ROW_NUMBER() OVER(ORDER BY MyField) - 1) / 500) + 1) AS PageNum
, *
from MyTable
) as PagedTable
where PageNum = 4;
If you are looking for a way to make this work without recompiling your Any CPU application, here is another potential workaround:
I take no credit for the solution, but it worked for us. Check the source link for more information and other comments.
Source: https://techtalk.gfi.com/32bit-object-64bit-environment/
Hopefully it helps someone: I ran into this error and the cause was wrong permission on the log folder for phpfpm, after changing it so phpfpm could write to it, everything was fine.
another.obj = [obj copyWithZone: zone];
I think, that this line causes memory leak, because you access to obj
through property which is (I assume) declared as retain
. So, retain count will be increased by property and copyWithZone
.
I believe it should be:
another.obj = [[obj copyWithZone: zone] autorelease];
or:
SomeOtherObject *temp = [obj copyWithZone: zone];
another.obj = temp;
[temp release];
In some cases for some security reasons the unit would be marked as masked. This state is much stronger than being disabled in which you cannot even start the service manually.
to check this, run the following command:
systemctl list-unit-files | grep mongod
if you find out something like this:
mongod.service masked
then you can unmask the unit by:
sudo systemctl unmask mongod
then you may want to start the service:
sudo systemctl start mongod
and to enable auto-start during system boot:
sudo systemctl enable mongod
However if mongodb did not start again or was not masked at all, you have the option to reinstall it this way:
sudo apt-get --purge mongo*
sudo apt-get install mongodb-org
thanks to @jehanzeb-malik
SELECT train, dest, time FROM (
SELECT train, dest, time,
RANK() OVER (PARTITION BY train ORDER BY time DESC) dest_rank
FROM traintable
) where dest_rank = 1
Not sure what you are trying to do, but you have two select clauses. Do this instead:
SELECT *
FROM ( SELECT *
FROM orders_products
INNER JOIN orders ON orders_products.orders_id = orders.orders_id
WHERE products_id = 181) AS A
JOIN ( SELECT *
FROM orders_products
INNER JOIN orders ON orders_products.orders_id = orders.orders_id
WHERE products_id = 180) AS B
ON A.orders_id=B.orders_id
Update:
You could probably reduce it to something like this:
SELECT o.orders_id,
op1.products_id,
op1.quantity,
op2.products_id,
op2.quantity
FROM orders o
INNER JOIN orders_products op1 on o.orders_id = op1.orders_id
INNER JOIN orders_products op2 on o.orders_id = op2.orders_id
WHERE op1.products_id = 180
AND op2.products_id = 181
If, one day, someone else have to deal with this code as "legacy code", then that person will be grateful if you write a less exoteric code, such as
grep -q -F 'include "/configs/projectname.conf"' lighttpd.conf
if [ $? -ne 0 ]; then
echo 'include "/configs/projectname.conf"' >> lighttpd.conf
fi
The Pythonic way to create a static class is simply to declare those methods outside of a class (Java uses classes both for objects and for grouping related functions, but Python modules are sufficient for grouping related functions that do not require any object instance). However, if you insist on making a method at the class level that doesn't require an instance (rather than simply making it a free-standing function in your module), you can do so by using the "@staticmethod" decorator.
That is, the Pythonic way would be:
# My module
elements = []
def add_element(x):
elements.append(x)
But if you want to mirror the structure of Java, you can do:
# My module
class World(object):
elements = []
@staticmethod
def add_element(x):
World.elements.append(x)
You can also do this with @classmethod
if you care to know the specific class (which can be handy if you want to allow the static method to be inherited by a class inheriting from this class):
# My module
class World(object):
elements = []
@classmethod
def add_element(cls, x):
cls.elements.append(x)
That can be done by using some/every methods of Array and RegEx.
To check whether ALL of words from list(array) are present in the string:
const multiSearchAnd = (text, searchWords) => (
searchWords.every((el) => {
return text.match(new RegExp(el,"i"))
})
)
multiSearchAnd("Chelsey Dietrich Engineer 2018-12-11 Hire", ["cle", "hire"]) //returns false
multiSearchAnd("Chelsey Dietrich Engineer 2018-12-11 Hire", ["che", "hire"]) //returns true
To check whether ANY of words from list(array) are present in the string:
const multiSearchOr = (text, searchWords) => (
searchWords.some((el) => {
return text.match(new RegExp(el,"i"))
})
)
multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["che", "hire"]) //returns true
multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["aaa", "hire"]) //returns true
multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["che", "zzzz"]) //returns true
multiSearchOr("Chelsey Dietrich Engineer 2018-12-11 Hire", ["aaa", "1111"]) //returns false
Try this:
table {
border-spacing: 0;
border-collapse: collapse;
}
There are many ways to do this. My favorite way is:
Add a mod_user
field to your source table (the one you want to log).
Create a log table that contains the fields you want to log, plus a log_datetime
and seq_num
field. seq_num
is the primary key.
Build a trigger on the source table that inserts the current record into the log table whenever any monitored field is changed.
Now you've got a record of every change and who made it.
After little investigation I concluded the followings: You have 2 options:
go with transformations. Very usefull package for this: https://bundletransformer.codeplex.com/ you need following transformation for every problematic bundle:
BundleResolver.Current = new CustomBundleResolver();
var cssTransformer = new StyleTransformer();
standardCssBundle.Transforms.Add(cssTransformer);
bundles.Add(standardCssBundle);
Advantages: of this solution, you can name your bundle whatever you want => you can combine css files into one bundle from different directories. Disadvantages: You need to transform every problematic bundle
According to the Javadoc of Scanner, it closes the stream when you call it's close method. Generally speaking, the code that creates a resource is also responsible for closing it. System.in was not instantiated by by your code, but by the VM. So in this case it's safe to not close the Scanner, ignore the warning and add a comment why you ignore it. The VM will take care of closing it if needed.
(Offtopic: instead of "amount", the word "number" would be more appropriate to use for a number of players. English is not my native language (I'm Dutch) and I used to make exactly the same mistake.)
If there is a Relation R(ABC)
-----------
|A | B | C |
-----------
|a | 1 | x |
|b | 1 | x |
|c | 1 | x |
|d | 2 | y |
|e | 2 | y |
|f | 3 | z |
|g | 3 | z |
----------
Given,
F1: A --> B
F2: B --> C
The Primary Key and Candidate Key is: A
As the closure of A+ = {ABC} or R --- So only attribute A is sufficient to find Relation R.
DEF-1: From Some Definitions (unknown source) - A partial dependency is a dependency when prime attribute (i.e., an attribute that is a part(or proper subset) of Candidate Key) determines non-prime attribute (i.e., an attribute that is not the part (or subset) of Candidate Key).
Hence, A is a prime(P) attribute and B, C are non-prime(NP) attributes.
So, from the above DEF-1,
CONSIDERATION-1:: F1: A --> B (P determines NP) --- It must be Partial Dependency.
CONSIDERATION-2:: F2: B --> C (NP determines NP) --- Transitive Dependency.
What I understood from @philipxy answer (https://stackoverflow.com/a/25827210/6009502) is...
CONSIDERATION-1:: F1: A --> B; Should be fully functional dependency because B is completely dependent on A and If we Remove A then there is no proper subset of (for complete clarification consider L.H.S. as X NOT BY SINGLE ATTRIBUTE) that could determine B.
For Example: If I consider F1: X --> Y where X = {A} and Y = {B} then if we remove A from X; i.e., X - {A} = {}; and an empty set is not considered generally (or not at all) to define functional dependency. So, there is no proper subset of X that could hold the dependency F1: X --> Y; Hence, it is fully functional dependency.
F1: A --> B If we remove A then there is no attribute that could hold functional dependency F1. Hence, F1 is fully functional dependency not partial dependency.
If F1 were, F1: AC --> B;
and F2 were, F2: C --> B;
then on the removal of A;
C --> B that means B is still dependent on C;
we can say F1 is partial dependecy.
So, @philipxy answer contradicts DEF-1 and CONSIDERATION-1 that is true and crystal clear.
Hence, F1: A --> B is Fully Functional Dependency not partial dependency.
I have considered X to show left hand side of functional dependency because single attribute couldn't have a proper subset of attributes. Here, I am considering X as a set of attributes and in current scenario X is {A}
-- For the source of DEF-1, please search on google you may be able to hit similar definitions. (Consider that DEF-1 is incorrect or do not work in the above-mentioned example).
If you are using Docker 1.12 or newer, just use SHELL
!
general:
SHELL ["/bin/bash", "-c"]
for python vituralenv:
SHELL ["/bin/bash", "-c", "source /usr/local/bin/virtualenvwrapper.sh"]
from https://docs.docker.com/engine/reference/builder/#shell
SHELL ["executable", "parameters"]
The SHELL instruction allows the default shell used for the shell form of commands to be overridden. The default shell on Linux is ["/bin/sh", "-c"], and on Windows is ["cmd", "/S", "/C"]. The SHELL instruction must be written in JSON form in a Dockerfile.
The SHELL instruction is particularly useful on Windows where there are two commonly used and quite different native shells: cmd and powershell, as well as alternate shells available including sh.
The SHELL instruction can appear multiple times. Each SHELL instruction overrides all previous SHELL instructions, and affects all subsequent instructions. For example:
FROM microsoft/windowsservercore # Executed as cmd /S /C echo default RUN echo default # Executed as cmd /S /C powershell -command Write-Host default RUN powershell -command Write-Host default # Executed as powershell -command Write-Host hello SHELL ["powershell", "-command"] RUN Write-Host hello # Executed as cmd /S /C echo hello SHELL ["cmd", "/S"", "/C"] RUN echo hello
The following instructions can be affected by the SHELL instruction when the shell form of them is used in a Dockerfile: RUN, CMD and ENTRYPOINT.
The following example is a common pattern found on Windows which can be streamlined by using the SHELL instruction:
... RUN powershell -command Execute-MyCmdlet -param1 "c:\foo.txt" ...
The command invoked by docker will be:
cmd /S /C powershell -command Execute-MyCmdlet -param1 "c:\foo.txt"
This is inefficient for two reasons. First, there is an un-necessary cmd.exe command processor (aka shell) being invoked. Second, each RUN instruction in the shell form requires an extra powershell -command prefixing the command.
To make this more efficient, one of two mechanisms can be employed. One is to use the JSON form of the RUN command such as:
... RUN ["powershell", "-command", "Execute-MyCmdlet", "-param1 \"c:\\foo.txt\""] ...
While the JSON form is unambiguous and does not use the un-necessary cmd.exe, it does require more verbosity through double-quoting and escaping. The alternate mechanism is to use the SHELL instruction and the shell form, making a more natural syntax for Windows users, especially when combined with the escape parser directive:
# escape=` FROM microsoft/nanoserver SHELL ["powershell","-command"] RUN New-Item -ItemType Directory C:\Example ADD Execute-MyCmdlet.ps1 c:\example\ RUN c:\example\Execute-MyCmdlet -sample 'hello world'
Resulting in:
PS E:\docker\build\shell> docker build -t shell . Sending build context to Docker daemon 4.096 kB Step 1/5 : FROM microsoft/nanoserver ---> 22738ff49c6d Step 2/5 : SHELL powershell -command ---> Running in 6fcdb6855ae2 ---> 6331462d4300 Removing intermediate container 6fcdb6855ae2 Step 3/5 : RUN New-Item -ItemType Directory C:\Example ---> Running in d0eef8386e97 Directory: C:\ Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 10/28/2016 11:26 AM Example ---> 3f2fbf1395d9 Removing intermediate container d0eef8386e97 Step 4/5 : ADD Execute-MyCmdlet.ps1 c:\example\ ---> a955b2621c31 Removing intermediate container b825593d39fc Step 5/5 : RUN c:\example\Execute-MyCmdlet 'hello world' ---> Running in be6d8e63fe75 hello world ---> 8e559e9bf424 Removing intermediate container be6d8e63fe75 Successfully built 8e559e9bf424 PS E:\docker\build\shell>
The SHELL instruction could also be used to modify the way in which a shell operates. For example, using SHELL cmd /S /C /V:ON|OFF on Windows, delayed environment variable expansion semantics could be modified.
The SHELL instruction can also be used on Linux should an alternate shell be required such as zsh, csh, tcsh and others.
The SHELL feature was added in Docker 1.12.
For more info on this click here.
Example
<div id="header_id" class="header_class">Text</div>
#header_id {font-color:#fff}
.header_class {font-color:#000}
(Note that CSS uses the prefix # for IDs and . for Classes.)
However color
was an HTML 4.01 <font>
tag attribute deprecated in HTML 5.
In CSS there is no "font-color", the style is color
so the above should read:
Example
<div id="header_id" class="header_class">Text</div>
#header_id {color:#fff}
.header_class {color:#000}
The text would be white.
Factory pattern: The factory produces IProduct-implementations
Abstract Factory Pattern: A factory-factory produces IFactories, which in turn produces IProducts :)
[Update according to the comments]
What I wrote earlier is not correct according to Wikipedia at least. An abstract factory is simply a factory interface. With it, you can switch your factories at runtime, to allow different factories in different contexts. Examples could be different factories for different OS'es, SQL providers, middleware-drivers etc..
Try this:
<TextBlock Text="{Binding PropertyPath, StringFormat=d}" />
which is culture sensitive and requires .NET 3.5 SP1 or above.
NOTE: This is case sensitive. "d" is the short date format specifier while "D" is the long date format specifier.
There's a full list of string format on the MSDN page on Standard Date and Time Format Strings and a fuller explanation of all the options on this MSDN blog post
However, there is one gotcha with this - it always outputs the date in US format unless you set the culture to the correct value yourself.
If you do not set this property, the binding engine uses the Language property of the binding target object. In XAML this defaults to "en-US" or inherits the value from the root element (or any element) of the page, if one has been explicitly set.
One way to do this is in the code behind (assuming you've set the culture of the thread to the correct value):
this.Language = XmlLanguage.GetLanguage(Thread.CurrentThread.CurrentCulture.Name);
The other way is to set the converter culture in the binding:
<TextBlock Text="{Binding PropertyPath, StringFormat=d, ConverterCulture=en-GB}" />
Though this doesn't allow you to localise the output.
In Swift
To trim space & newline from both side of the String:
var url: String = "\n http://example.com/xyz.mp4 "
var trimmedUrl: String = url.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
check pyplot
docs. For completeness,
import numpy as np
import matplotlib.pyplot as plt
#evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)
# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()
Inline elements can't be transformed, and pseudo elements are inline by default, so you must apply display: block
or display: inline-block
to transform them:
#whatever:after {
content: "\24B6";
display: inline-block;
transform: rotate(30deg);
}
_x000D_
<div id="whatever">Some text </div>
_x000D_
x86 refers to the Intel processor architecture that was used in PCs. Model numbers were 8088 (8 bit bus version of 8086 and used in the first IBM PC), 8086, 286, 386, 486. After which they switched to names instead of numbers to stop AMD from copying the processor names. Pentium etc, never a Hexium :).
x64 is the architecture name for the extensions to the x86 instruction set that enable 64-bit code. Invented by AMD and later copied by Intel when they couldn't get their own 64-bit arch to be competitive, Itanium didn't fare well. Other names for it are x86_64, AMD's original name and commonly used in open source tools. And amd64, AMD's next name and commonly used in Microsoft tools. Intel's own names for it (EM64T and "Intel 64") never caught on.
x32 is a fuzzy term that's not associated with hardware. It tends to be used to mean "32-bit" or "32-bit pointer architecture", Linux has an ABI by that name.
Image Viewer with ViewPager Implementation, check this project https://github.com/chiuki/android-swipe-image-viewer
Refer this discussion also Swiping images (not layouts) with viewpager
Yes. You can have a span
within a span
. Your problem stems from something else.
From http://en.wikipedia.org/wiki/CDATA:
Since it is useful to be able to use less-than signs (<) and ampersands (&) in web page scripts, and to a lesser extent styles, without having to remember to escape them, it is common to use CDATA markers around the text of inline and elements in XHTML documents. But so that the document can also be parsed by HTML parsers, which do not recognise the CDATA markers, the CDATA markers are usually commented-out, as in this JavaScript example:
<script type="text/javascript">
//<![CDATA[
document.write("<");
//]]>
</script>
.delegate is the only one that is working to me with jQuery JavaScript Library v2.1.1
$(document).delegate('#textareaID','change', function() {
console.log("change!");
});
You could use LastIndexOf and Substring combined to get all characters to the left of the last index of the comma within the sting.
string var = var.Substring(0, var.LastIndexOf(','));
As mscdex said NPM comes with the nodejs msi installed file. I happened to just install the node js installer (standalone). To separately add NPM I followed following step
Donal had the right solution for me. However, the updated plist
name for 2017 is
com.oracle.oss.mysql.mysqld.plist.
Ok I have used the last week to massively rewrite my code to precisely fit your test. You can now copy this 1:1 and it will immediately work - including setSingleLine()
. Please remember to adjust MIN_TEXT_SIZE
and MAX_TEXT_SIZE
if you're going for extreme values.
Converging algorithm looks like this:
for (float testSize; (upperTextSize - lowerTextSize) > mThreshold;) {
// Go to the mean value...
testSize = (upperTextSize + lowerTextSize) / 2;
// ... inflate the dummy TextView by setting a scaled textSize and the text...
mTestView.setTextSize(TypedValue.COMPLEX_UNIT_SP, testSize / mScaledDensityFactor);
mTestView.setText(text);
// ... call measure to find the current values that the text WANTS to occupy
mTestView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
int tempHeight = mTestView.getMeasuredHeight();
// ... decide whether those values are appropriate.
if (tempHeight >= targetFieldHeight) {
upperTextSize = testSize; // Font is too big, decrease upperSize
}
else {
lowerTextSize = testSize; // Font is too small, increase lowerSize
}
}
And the whole class can be found here.
The result is very flexible now. This works the same declared in xml like so:
<com.example.myProject.AutoFitText
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="4"
android:text="@string/LoremIpsum" />
... as well as built programmatically like in your test.
I really hope you can use this now. You can call setText(CharSequence text)
now to use it by the way. The class takes care of stupendously rare exceptions and should be rock-solid. The only thing that the algorithm does not support yet is:
setMaxLines(x)
where x >= 2
But I have added extensive comments to help you build this if you wish to!
Please note:
If you just use this normally without limiting it to a single line then there might be word-breaking as you mentioned before. This is an Android feature, not the fault of the AutoFitText
. Android will always break words that are too long for a TextView and it's actually quite a convenience. If you want to intervene here than please see my comments and code starting at line 203. I have already written an adequate split and the recognition for you, all you'd need to do henceforth is to devide the words and then modify as you wish.
In conclusion: You should highly consider rewriting your test to also support space chars, like so:
final Random _random = new Random();
final String ALLOWED_CHARACTERS = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
final int textLength = _random.nextInt(80) + 20;
final StringBuilder builder = new StringBuilder();
for (int i = 0; i < textLength; ++i) {
if (i % 7 == 0 && i != 0) {
builder.append(" ");
}
builder.append(ALLOWED_CHARACTERS.charAt(_random.nextInt(ALLOWED_CHARACTERS.length())));
}
((AutoFitText) findViewById(R.id.textViewMessage)).setText(builder.toString());
This will produce very beutiful (and more realistic) results.
You will find commenting to get you started in this matter as well.
Good luck and best regards
You can use the minus operator or Math.abs. These work for all negative integers EXCEPT for Integer.MIN_VALUE! If you do 0 - MIN_VALUE the answer is still MIN_VALUE.
First of all, there are two possible 'versions' that you might be interested in:
Windows filesystem file version, applicable to all executable files
Assembly build version, which is embedded in a .NET assembly by the compiler (obviously only applicable to .NET assembly dll and exe files)
In the former case, you should use Ben Anderson's answer; in the latter case, use AssemblyName.GetAssemblyName(@"c:\path\to\file.dll").Version
, or Tataro's answer, in case the assembly is referenced by your code.
Note that you can ignore all the answers that use .Load()
/.LoadFrom()
methods, since these actually load the assembly in the current AppDomain - which is analogous to cutting down a tree to see how old it is.
This issue is because you are not adding any LayoutManager
for your RecyclerView
.
Another reason is because you are calling this code in a NonUIThread. Make sure to call this call in the UIThread.
The solution is only you have to add a LayoutManager
for the RecyclerView
before you setAdapter
in the UI Thread.
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
I think that it is better (for my expirience) to use: :first-of-type
, :nth-of-type()
, :last-of-type
. It can be done whit a little changing of rules, but I was able to do much more than whit *-of-type
, than *-child
selectors.
Does your DLL project have any actual exports? If there are no exports, the linker will not generate an import library .lib file.
In the non-Express version of VS, the import libray name is specfied in the project settings here:
Configuration Properties/Linker/Advanced/Import Library
I assume it's the same in Express (if it even provides the ability to configure the name).
This question is the top Google result for "Java String Right".
Surprisingly, no-one has yet mentioned Apache Commons StringUtils.right():
String numbers = org.apache.commons.lang.StringUtils.right( text, 7 );
This also handles the case where text
is null, where many of the other answers would throw a NullPointerException.
You are missing either the inclusion of the route package, or including the router module in your main app module.
Make sure your package.json has this:
"@angular/router": "^3.3.1"
Then in your app.module import the router and configure the routes:
import { RouterModule } from '@angular/router';
imports: [
RouterModule.forRoot([
{path: '', component: DashboardComponent},
{path: 'dashboard', component: DashboardComponent}
])
],
Update:
Move the AppRoutingModule to be first in the imports:
imports: [
AppRoutingModule.
BrowserModule,
FormsModule,
HttpModule,
AlertModule.forRoot(), // What is this?
LayoutModule,
UsersModule
],
FOR UNINSTALLING AND THEN BEING ABLE TO REINSTALL XCODE 9 CORRECTLY
I followed the topmost answer for deleting Xcode 7 and found a major error, deleting ~/Library/Developer
will delete an important folder called PrivateFrameworks
, which will actually crash Xcode everytime you reinstall and force you to have to get your friends to send you the PrivateFrameworks folder again, a complete waste of time seeing if you needed to uninstall and reinstall Xcode urgently for immediate work purposes.
I have tried editing the topmost answer but see no changes so below is the modified steps you should take for Xcode 9:
Delete
/Applications/Xcode.app
~/Library/Preferences/com.apple.dt.*
(Generally anything with com.apple.dt. as prefix is removable in the Preferences folder)
~/Library/Caches/com.apple.dt.Xcode
~/Library/Application Support/Xcode
Everything in
/Library/Developer
directory except for
/Library/Developer/PrivateFrameworks
int[,] arr = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for(int i = 0; i < arr.GetLength(0); i++){
for (int j = 0; j < arr.GetLength(1); j++)
Console.Write( "{0}\t",arr[i, j]);
Console.WriteLine();
}
output: 1 2 3
4 5 6
7 8 9
How to write a compound statement with if?
You can write a compound statement in an if block using parenthesis. The first parenthesis must come on the line with the if and the second on a line by itself.
if %ERRORLEVEL% == 0 (
echo ErrorLevel is zero
echo A second statement
) else if %ERRORLEVEL% == 1 (
echo ErrorLevel is one
echo A second statement
) else (
echo ErrorLevel is > 1
echo A second statement
)
For ASP.NET 1.1, this is still due to someone posting more than 1000 form fields, but the setting must be changed in the registry rather than a config file. It should be added as a DWORD named MaxHttpCollectionKeys in the registry under
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ASP.NET\1.1.4322.0
for 32-bit editions of Windows, and
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\ASP.NET\1.1.4322.0
for 64-bit editions of Windows.
The shortest date format of mm/dd/yy can be obtained with:
Select Convert(varchar(8),getdate(),1)
Do you want to know if a type is the same type as int64_t or do you want to know if something is 64 bits? Based on your proposed solution, I think you're asking about the latter. In that case, I would do something like
template<typename T>
bool is_64bits() { return sizeof(T) * CHAR_BIT == 64; } // or >= 64
SSL certificates are bound to a 'common name', which is usually a fully qualified domain name but can be a wildcard name (eg. *.domain.com) or even an IP address, but it usually isn't.
In your case, you are accessing your LDAP server by a hostname and it sounds like your two LDAP servers have different SSL certificates installed. Are you able to view (or download and view) the details of the SSL certificate? Each SSL certificate will have a unique serial numbers and fingerprint which will need to match. I assume the certificate is being rejected as these details don't match with what's in your certificate store.
Your solution will be to ensure that both LDAP servers have the same SSL certificate installed.
BTW - you can normally override DNS entries on your workstation by editing a local 'hosts' file, but I wouldn't recommend this.
You can Do this
var array = [];
// assigning values to corresponding keys
array[0] = "Main page";
array[1] = "Guide page";
array[2] = "Articles page";
array[3] = "Forum board";
array.forEach(value => {
console.log(value)
})
The thing to watch out for when writing C++ dlls is name mangling. If you want interoperability between C and C++, you'd be better off by exporting non-mangled C-style functions from within the dll.
You have two options to use a dll
LoadLibrary()
or some suitable function to load the library, retrieve a function pointer (GetProcAddress
) and call it -- runtime dynamic linkingExporting classes will not work if you follow the second method though.
Since you are iterating over an indexable collection (lists, etc.), I presume that you can then just iterate with the indices of the elements:
IntStream.range(0, params.size())
.forEach(idx ->
query.bind(
idx,
params.get(idx)
)
)
;
The resulting code is similar to iterating a list with the classic i++-style for loop, except with easier parallelizability (assuming, of course, that concurrent read-only access to params is safe).
See ReceivedTime
Property
http://msdn.microsoft.com/en-us/library/office/aa171873(v=office.11).aspx
You added another \
to the end of C:\Temp\
in the SaveAs File line. Could be a problem. Do a test first before adding a path separator.
dateFormat = Format(itm.ReceivedTime, "yyyy-mm-dd H-mm")
saveFolder = "C:\Temp"
You have not set objAtt
so there is no need for "Set objAtt = Nothing
". If there was it would be just before End Sub
not in the loop.
Public Sub saveAttachtoDisk (itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim saveFolder As String Dim dateFormat
dateFormat = Format(itm.ReceivedTime, "yyyy-mm-dd H-mm") saveFolder = "C:\Temp"
For Each objAtt In itm.Attachments
objAtt.SaveAsFile saveFolder & "\" & dateFormat & objAtt.DisplayName
Next
End Sub
Re: It worked the first day I started tinkering but after that it stopped saving files.
This is usually due to Security settings. It is a "trap" set for first time users to allow macros then take it away. http://www.slipstick.com/outlook-developer/how-to-use-outlooks-vba-editor/
To actually do it in HTML with inline CSS (not with an external CSS style sheet)
<input type="text" style="font-size: 44pt">
A lot of people would consider putting the style right into the html like this to be poor form. However, I frequently make extreeemly simple web pages for my own use that don't even have a <html>
or <body>
tag, and such is appropriate there.
If you don't really need the button element, just move the classes to a regular link:
<div class="btn-group">
<a href="/save/1" class="btn btn-primary active">
<i class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></i> Save
</a>
<a href="/cancel/1" class="btn btn-default">Cancel</a>
</div>
Conversely, you can also change a button to appear like a link:
<button type="button" class="btn btn-link">Link</button>
I use AJAX to do this. You have your partial with your typical twitter modal template html:
<div class="container">
<!-- Modal -->
<div class="modal fade" id="LocationNumberModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
×
</button>
<h4 class="modal-title">
Serial Numbers
</h4>
</div>
<div class="modal-body">
<span id="test"></span>
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">
Close
</button>
</div>
</div>
</div>
</div>
</div>
Then you have your controller method, I use JSON and have a custom class that rendors the view to a string. I do this so I can perform multiple ajax updates on the screen with one ajax call. Reference here: Example but you can use an PartialViewResult/ActionResult on return if you are just doing the one call. I will show it using JSON..
And the JSON Method in Controller:
public JsonResult LocationNumberModal(string partNumber = "")
{
//Business Layer/DAL to get information
return Json(new {
LocationModal = ViewUtility.RenderRazorViewToString(this.ControllerContext, "LocationNumberModal.cshtml", new SomeModelObject())
},
JsonRequestBehavior.AllowGet
);
}
And then, in the view using your modal: You can package the AJAX in your partial and call @{Html.RenderPartial... Or you can have a placeholder with a div:
<div id="LocationNumberModalContainer"></div>
then your ajax:
function LocationNumberModal() {
var partNumber = "1234";
var src = '@Url.Action("LocationNumberModal", "Home", new { area = "Part" })'
+ '?partNumber='' + partNumber;
$.ajax({
type: "GET",
url: src,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
$("#LocationNumberModalContainer").html(data.LocationModal);
$('#LocationNumberModal').modal('show');
}
});
};
Then the button to your modal:
<button type="button" id="GetLocBtn" class="btn btn-default" onclick="LocationNumberModal()">Get</button>
If you are creating an array whose main feature is it's length, rather than the value of each index, defining an array as var a=Array(length);
is appropriate.
eg-
String.prototype.repeat= function(n){
n= n || 1;
return Array(n+1).join(this);
}
Embed code example:
<object type="application/pdf" data="example.pdf" width="100%" height="100%" id="examplePDF" name="examplePDF"><param name='src' value='example.pdf'/></object>
<script>
examplePDF.printWithDialog();
</script>
May have to fool around with the ids/names. Using adobe reader...
Your comparator is not transitive.
Let A
be the parent of B
, and B
be the parent of C
. Since A > B
and B > C
, then it must be the case that A > C
. However, if your comparator is invoked on A
and C
, it would return zero, meaning A == C
. This violates the contract and hence throws the exception.
It's rather nice of the library to detect this and let you know, rather than behave erratically.
One way to satisfy the transitivity requirement in compareParents()
is to traverse the getParent()
chain instead of only looking at the immediate ancestor.
CSS will skip over style declarations it doesn't understand. Mozilla-based browsers will not understand -webkit
-prefixed declarations, and WebKit-based browsers will not understand -moz
-prefixed declarations.
Because of this, we can simply declare width
twice:
elem {
width: 100%;
width: -moz-available; /* WebKit-based browsers will ignore this. */
width: -webkit-fill-available; /* Mozilla-based browsers will ignore this. */
width: fill-available;
}
The width: 100%
declared at the start will be used by browsers which ignore both the -moz
and -webkit
-prefixed declarations or do not support -moz-available
or -webkit-fill-available
.
Since Java 11 you may use that:
public FileReader(String fileName, Charset charset) throws IOException;
You should consider creating a timestamp from that date witk mktime()
eg:
$date = explode('/', $_POST['date']);
$time = mktime(0,0,0,$date[0],$date[1],$date[2]);
$mysqldate = date( 'Y-m-d H:i:s', $time );
More information than you would want to know:
http://wiki.secondlife.com/wiki/Message_Queue_Evaluation_Notes
Just elaborating what Paul added in comment. The page mentioned above is dead after 2010, so read with a pinch of salt. Lot of stuff has been been changed in 3 years.
This worked for me: Top Menu -> File -> Invalidate Caches/Restart
Even if both work, I would use the latter.
location
is an object, and assigning a string to an object doesn't bode well for readability or maintenance.
Depends on what you know about your url and exactly what you're tryinh to do. If you know that it will always end in '.com' (or '.net' or '.org') then
url=url[:-4]
is the quickest solution. If it's a more general URLs then you're probably better of looking into the urlparse library that comes with python.
If you on the other hand you simply want to remove everything after the final '.' in a string then
url.rsplit('.',1)[0]
will work. Or if you want just want everything up to the first '.' then try
url.split('.',1)[0]
You can use the following method inside the catch block:
response.sendError(HttpStatus.UNAUTHORIZED.value(), "Invalid token")
Notice that you can use any HttpStatus code and a custom message.
With empty set, which is part of all the subsets, you could use:
def subsets(iterable):
for n in range(len(iterable) + 1):
yield from combinations(iterable, n)
MY PREFERRED METHOD is using fopen,fwrite and fclose [it will cost less CPU]
$f=fopen('myfile.txt','w');
fwrite($f,'new content');
fclose($f);
Warning for those using file_put_contents
It'll affect a lot in performance, for example [on the same class/situation] file_get_contents too: if you have a BIG FILE, it'll read the whole content in one shot and that operation could take a long waiting time
Options -Indexes should work to prevent directory listings.
If you are using a .htaccess file make sure you have at least the "allowoverride options" setting in your main apache config file.
You can use partial value of an attribute to detect a DOM element using (^) sign. For example you have divs like this:
<div id="abc_1"></div>
<div id="abc_2"></div>
<div id="xyz_3"></div>
<div id="xyz_4"></div>...
You can use the code:
var abc = $('div[id^=abc]')
This will return a DOM array of divs which have id starting with abc
:
<div id="abc_1"></div>
<div id="abc_2"></div>
Here is the demo: http://jsfiddle.net/mCuWS/
This is the way to execute remote script with passing to it some arguments (arg1 arg2):
curl -s http://server/path/script.sh | bash /dev/stdin arg1 arg2
In Swift3, I have used in this way
var hasAddedGeofencesAtleastOnce: Bool {
get {
return UserDefaults.standard.object(forKey: "hasAddedGeofencesAtleastOnce") != nil
}
}
The answer is great if you are to use that multiple times.
I hope it helps :)
Yes, just delete this span from your code: <span class="navbar-toggler-icon"></span>
, then paste this font awesome icon that called bars: <i class="fas fa-bars"></i>
, add a class to this icon, then put any color you want.
Then, the second step is to hide this icon from the devices that have width more than 992px
(desktops width), due to this icon will appear in your interface at any device if you won't add this @media
in your css code:
/* Large devices (desktops, 992px and up) */
@media (min-width: 992px) {
/* the class you gave of the bars icon ? */
.iconClass{
display: none;
}
/* the bootstrap toogler button class */
.navbar-toggler{
display: none;
}
}
It worked for me as well and I found it so easy.
First you should drop the problematic DEFAULT constraint
, after that you can drop the column
alter table tbloffers drop constraint [ConstraintName]
go
alter table tbloffers drop column checkin
But the error may appear from other reasons - for example the user defined function or view with SCHEMABINDING
option set for them.
UPD: Completely automated dropping of constraints script:
DECLARE @sql NVARCHAR(MAX)
WHILE 1=1
BEGIN
SELECT TOP 1 @sql = N'alter table tbloffers drop constraint ['+dc.NAME+N']'
from sys.default_constraints dc
JOIN sys.columns c
ON c.default_object_id = dc.object_id
WHERE
dc.parent_object_id = OBJECT_ID('tbloffers')
AND c.name = N'checkin'
IF @@ROWCOUNT = 0 BREAK
EXEC (@sql)
END
const remoteReq = request({
method: 'POST',
uri: 'http://host.com/api/upload',
headers: {
'Authorization': 'Bearer ' + req.query.token,
'Content-Type': req.headers['content-type'] || 'multipart/form-data;'
}
})
req.pipe(remoteReq);
remoteReq.pipe(res);
Some special characters give this type of error, so use
$query="INSERT INTO `tablename` (`name`, `email`)
VALUES
('$_POST[name]','$_POST[email]')";
Visual studio’s smart indenting does automatically indenting, but we can select a block or all the code for indentation.
Select all the code: Ctrl+a
Use either of the two ways to indentation the code:
Shift+Tab,
Ctrl+k+f.
I tried use [disabled]="!editmode"
but it not work in my case.
This is my solution [disabled]="!editmode ? 'disabled': null"
, I share for whom concern.
<button [disabled]="!editmode ? 'disabled': null"
(click)='loadChart()'>
<div class="btn-primary">Load Chart</div>
</button>
ngAttr
directive can totally be of help here, as introduced in the official documentation
https://docs.angularjs.org/guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes
For instance, to set the id
attribute value of a div
element, so that it contains an index, a view fragment might contain
<div ng-attr-id="{{ 'object-' + myScopeObject.index }}"></div>
which would get interpolated to
<div id="object-1"></div>
Maybe the 40 bytes fits into the pipe buffer, and the 40000 bytes doesn't?
Edit:
The sending process is sent a SIGPIPE signal when you try to write to a closed pipe. I don't know exactly when the signal is sent, or what effect the pipe buffer has on this. You may be able to recover by trapping the signal with the sigaction call.
Will something like this work for you? What this does is query the content resolver to find the file path data that is stored for that content entry
public static String getRealPathFromUri(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
This will end up giving you an absolute file path that you can construct a file uri from
If you have PHP & PHP-memcached installed, you can run
$ php -r '$c = new Memcached(); $c->addServer("localhost", 11211); var_dump( $c->getAllKeys() );'
A single way to remove sessions is setting it to null;
Session["your_session"] = null;
Here is what I use
function windowSizes(){
var e = window,
a = 'inner';
if (!('innerWidth' in window)) {
a = 'client';
e = document.documentElement || document.body;
}
return {
width: e[a + 'Width'],
height: e[a + 'Height']
};
}
$(window).on('resize', function () {
console.log( windowSizes().width,windowSizes().height );
});
Give a try to this
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
// TODO Auto-generated method stub
FragmentManager manager = ((Fragment) object).getFragmentManager();
FragmentTransaction trans = manager.beginTransaction();
trans.remove((Fragment) object);
trans.commit();
super.destroyItem(container, position, object);
}
In JavaScript you declare variables or functions by using the keywords var, let or function. In TypeScript classes you declare class members or methods without these keywords followed by a colon and the type or interface of that class member.
It’s just syntax sugar, there is no difference between:
var el: HTMLElement = document.getElementById('content');
and:
var el = document.getElementById('content');
On the other hand, because you specify the type you get all the information of your HTMLElement object.
Use a character set: [a-zA-Z]
matches one letter from A–Z in lowercase and uppercase. [a-zA-Z]+
matches one or more letters and ^[a-zA-Z]+$
matches only strings that consist of one or more letters only (^
and $
mark the begin and end of a string respectively).
If you want to match other letters than A–Z, you can either add them to the character set: [a-zA-ZäöüßÄÖÜ]
. Or you use predefined character classes like the Unicode character property class \p{L}
that describes the Unicode characters that are letters.
You do not want the '='
Use .libPaths("C:/R/library")
in you Rprofile
.site file
And make sure you have correct " symbol (Shift-2)
Alternative solution: A More Userfriendly solution than command line:
If you are looking for a user friendly way to send and request data using HTTP Methods other than simple GET's probably you are looking for a chrome extention just like this one http://goo.gl/rVW22f called AVANCED REST CLIENT
For guys looking to stay with command-line i recommend cygwin:
I ended up installing cygwin with CURL which allow us to Get that Linux feeling - on Windows!
Using Cygwin command line this issues have stopped and most important, the request syntax used on 1. worked fine.
Useful links:
Where i was downloading the curl for windows command line?
For more information on how to install and get curl working with cygwin just go here
I hope it helps someone because i spent all morning on this.
You can use CSS3 transitions with rotate()
to spin the image on hover.
img {_x000D_
border-radius: 50%;_x000D_
-webkit-transition: -webkit-transform .8s ease-in-out;_x000D_
transition: transform .8s ease-in-out;_x000D_
}_x000D_
img:hover {_x000D_
-webkit-transform: rotate(360deg);_x000D_
transform: rotate(360deg);_x000D_
}
_x000D_
<img src="https://i.stack.imgur.com/BLkKe.jpg" width="100" height="100"/>
_x000D_
Here is a fiddle DEMO
More info and references :
Using regex:
str = 'string'
n = 1 #to remove first n characters
str[/.{#{str.size-n}}\z/] #=> "tring"
Yes, there are software algorithms for calculating sin
too. Basically, calculating these kind of stuff with a digital computer is usually done using numerical methods like approximating the Taylor series representing the function.
Numerical methods can approximate functions to an arbitrary amount of accuracy and since the amount of accuracy you have in a floating number is finite, they suit these tasks pretty well.
The second line should have been pixels[0]
, with an S. You probably have a tuple named pixel
, and tuples are immutable. Construct new pixels instead:
image = Image.open('balloon.jpg')
pixels = [(pix[0] + 20,) + pix[1:] for pix in image.getdata()]
image.putdate(pixels)
_ [$%-4009] * #,##0_ ;_ [$%-4009] * -#,##0_ ;_ [$%-4009] * "-"??_ ;_ @_
Since objects are dynamically allocated by using the new operator,
you might be wondering how such objects are destroyed and their
memory released for later reallocation.
In some languages, such as C++, dynamically allocated objects must be manually released by use of a delete operator.
there are 6 ways to do this in React,
number 1 and 2 and 3 are the best:
1-config CORS in the Server-Side
2-set headers manually like this:
resonse_object.header("Access-Control-Allow-Origin", "*");
resonse_object.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
3-config NGINX for proxy_pass which is explained here.
4-bypass the Cross-Origin-Policy with chrom extension(only for development and not recommended !)
5-bypass the cross-origin-policy with URL bellow(only for development)
"https://cors-anywhere.herokuapp.com/{type_your_url_here}"
6-use proxy
in your package.json
file:(only for development)
if this is your API: http://45.456.200.5:7000/api/profile/
add this part in your package.json
file:
"proxy": "http://45.456.200.5:7000/",
and then make your request with the next parts of the api:
React.useEffect(() => {
axios
.get('api/profile/')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
});
The question did not state precisely what output is expected but assuming that for month you want the month number (January = 1) and for the year you want the numeric 4 digit year then assuming that we have just run the code in the question:
cycle(date1)
## [1] 3
as.integer(date1)
## [1] 2012
I ended up fixing our Ubuntu 18.04 / Apache 2.4.29 / PHP 7.2 install for Chrome 80 by installing mod_headers:
a2enmod headers
Adding the following directive to our Apache VirtualHost configurations:
Header edit Set-Cookie ^(.*)$ "$1; Secure; SameSite=None"
And restarting Apache:
service apache2 restart
In reviewing the docs (http://www.balkangreenfoundation.org/manual/en/mod/mod_headers.html) I noticed the "always" condition has certain situations where it does not work from the same pool of response headers. Thus not using "always" is what worked for me with PHP but the docs suggest that if you want to cover all your bases you could add the directive both with and without "always". I have not tested that.
Step 1 :
Create ts : app/_helpers/must-match.validator.ts
import { FormGroup } from '@angular/forms';
export function MustMatch(controlName: string, matchingControlName: string) {
return (formGroup: FormGroup) => {
const control = formGroup.controls[controlName];
const matchingControl = formGroup.controls[matchingControlName];
if (matchingControl.errors && !matchingControl.errors.mustMatch) {
return;
}
if (control.value !== matchingControl.value) {
matchingControl.setErrors({ mustMatch: true });
} else {
matchingControl.setErrors(null);
}
}
}
Step 2 :
Use in your component.ts
import { MustMatch } from '../_helpers/must-match.validator';
ngOnInit() {
this.loginForm = this.formbuilder.group({
Password: ['', [Validators.required, Validators.minLength(6)]],
ConfirmPassword: ['', [Validators.required]],
}, {
validator: MustMatch('Password', 'ConfirmPassword')
});
}
Step 3 :
Use In View/Html
<input type="password" formControlName="Password" class="form-control" autofocus>
<div *ngIf="loginForm.controls['Password'].invalid && (loginForm.controls['Password'].dirty || loginForm.controls['Password'].touched)" class="alert alert-danger">
<div *ngIf="loginForm.controls['Password'].errors.required">Password Required. </div>
<div *ngIf="loginForm.controls['Password'].errors.minlength">Password must be at least 6 characters</div>
</div>
<input type="password" formControlName="ConfirmPassword" class="form-control" >
<div *ngIf="loginForm.controls['ConfirmPassword'].invalid && (loginForm.controls['ConfirmPassword'].dirty || loginForm.controls['ConfirmPassword'].touched)" class="alert alert-danger">
<div *ngIf="loginForm.controls['ConfirmPassword'].errors.required">ConfirmPassword Required. </div>
<div *ngIf="loginForm.controls['ConfirmPassword'].errors.mustMatch">Your password and confirmation password do not match.</div>
</div>
There is only one basic type of Stream
. However in various circumstances some members will throw an exception when called because in that context the operation was not available.
For example a MemoryStream
is simply a way to moves bytes into and out of a chunk of memory. Hence you can call Read and Write on it.
On the other hand a FileStream
allows you to read or write (or both) from/to a file. Whether you can actually Read or Write depends on how the file was opened. You can't Write to a file if you only opened it for Read access.
I'm not sure if this breaks any rules but
sudo bash script.sh
seems to work for me.
Just want to add this for the future programmer.
This code limits the date min and max. The year is fully controlled by getting the current year as max year.
Hope this could help to anyone.
Here's the code.
var dateToday = new Date();
var yrRange = '2014' + ":" + (dateToday.getFullYear());
$(function () {
$("[id$=txtDate]").datepicker({
showOn: 'button',
changeMonth: true,
changeYear: true,
showButtonPanel: true,
buttonImageOnly: true,
yearRange: yrRange,
buttonImage: 'calendar3.png',
buttonImageOnly: true,
minDate: new Date(2014,1-1,1),
maxDate: '+50Y',
inline:true
});
});
you can get it by
var element = document.getElementById(canvasId);
element.onmousemove = function(e) {
var xCoor = e.clientX;
var yCoor = e.clientY;
}
I think they updated the html5 video and deprecated some codecs. It worked for me after removing the codecs.
In the below example:
<video>_x000D_
<source src="sample-clip.mp4" type="video/mp4; codecs='avc1.42E01E, mp4a.40.2'">_x000D_
<source src="sample-clip.webm" type="video/webm; codecs='vp8, vorbis'"> _x000D_
</video>_x000D_
_x000D_
must be changed to_x000D_
_x000D_
<video>_x000D_
<source src="sample-clip.mp4" type="video/mp4">_x000D_
<source src="sample-clip.webm" type="video/webm">_x000D_
</video>
_x000D_
This is the C ternary operator (Objective-C is a superset of C):
label.frame = (inPseudoEditMode) ? kLabelIndentedRect : kLabelRect;
is semantically equivalent to
if(inPseudoEditMode) {
label.frame = kLabelIndentedRect;
} else {
label.frame = kLabelRect;
}
The ternary with no first element (e.g. variable ?: anotherVariable
) means the same as (valOrVar != 0) ? valOrVar : anotherValOrVar
How about this?
INSERT OR IGNORE INTO EVENTTYPE (EventTypeName) VALUES 'ANI Received'
(Untested as I don't have SQLite... however this link is quite descriptive.)
Additionally, this should also work:
INSERT INTO EVENTTYPE (EventTypeName)
SELECT 'ANI Received'
WHERE NOT EXISTS (SELECT 1 FROM EVENTTYPE WHERE EventTypeName = 'ANI Received');
Public Sub UpdateMyFunctions()
Dim myRange As Range
Dim rng As Range
'Considering The Functions are in Range A1:B10
Set myRange = ActiveSheet.Range("A1:B10")
For Each rng In myRange
rng.Formula = rng.Formula
Next
End Sub
(Tested for pandas 1.0.5)
Based on @athlonshi answer (it had ValueError: could not convert string to float: 'big', on C column), full working example without warning:
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
scale = preprocessing.MinMaxScaler()
df = pd.DataFrame({
'A':[14.00,90.20,90.95,96.27,91.21],
'B':[103.02,107.26,110.35,114.23,114.68],
'C':['big','small','big','small','small']
})
print(df)
df[["A","B"]] = pd.DataFrame(scale.fit_transform(df[["A","B"]].values), columns=["A","B"], index=df.index)
print(df)
A B C
0 14.00 103.02 big
1 90.20 107.26 small
2 90.95 110.35 big
3 96.27 114.23 small
4 91.21 114.68 small
A B C
0 0.000000 0.000000 big
1 0.926219 0.363636 small
2 0.935335 0.628645 big
3 1.000000 0.961407 small
4 0.938495 1.000000 small
To keep images from stretching in either axis inside a flex parent I have found a couple of solutions.
You can try using object-fit on the image which, e.g.
object-fit: contain;
Or you can add flex-specfic rules which may work better in some cases.
align-self: center;
flex: 0 0 auto;
According to my humble opinion and my work experience with git, staging area is not the same as index. I may be wrong of course, but as I said, my experience in using git and my logic tell me, that index is a structure that follows your changes to your working area(local repository) that are not excluded by ignoring settings and staging area is to keep files that are already confirmed to be committed, aka files in index on which add command was run on. You don't notice and realize that "slight" difference, because you use
git commit -a -m "comment"
adding indexed and cached files to stage area and committing in one command or using IDEs like IDEA for that too often. And cache is that what keeps changes in indexed files.
If you want to remove file from index that has not been added to staging area before, options proposed before match for you, but...
If you have done that already, you will need to use
Git restore --staged <file>
And, please, don't ask me where I was 10 years ago... I missed you, this answer is for further generations)
You can set any pointer to NULL
, though NULL
is simply defined as 0 in C++:
myObject *foo = NULL;
Also note that NULL
is defined if you include standard headers, but is not built into the language itself. If NULL
is undefined, you can use 0 instead, or include this:
#ifndef NULL
#define NULL 0
#endif
As an aside, if you really want to set an object, not a pointer, to NULL
, you can read about the Null Object Pattern.
This has been fixed in Bootstrap v4.1 and above by adding data-boundary="viewport"
(Bootstrap Dropdowns Docs)
But for earlier versions (v4.0 and below), I found this javascript snippet that works perfectly. It works for small tables and scrolling tables:
$('.table-responsive').on('shown.bs.dropdown', function (e) {
var t = $(this),
m = $(e.target).find('.dropdown-menu'),
tb = t.offset().top + t.height(),
mb = m.offset().top + m.outerHeight(true),
d = 20; // Space for shadow + scrollbar.
if (t[0].scrollWidth > t.innerWidth()) {
if (mb + d > tb) {
t.css('padding-bottom', ((mb + d) - tb));
}
}
else {
t.css('overflow', 'visible');
}
}).on('hidden.bs.dropdown', function () {
$(this).css({'padding-bottom': '', 'overflow': ''});
});
Assuming your table has auto-numbered field "RowID" and you want to select only records where RowID is even or odd.
To show odd:
Select * from MEN where (RowID % 2) = 1
To show even:
Select * from MEN where (RowID % 2) = 0
I think this is what you are looking for? If you are looking to add a blur effect to a div element, you can do this directly through CSS Filters-- See fiddle: http://jsfiddle.net/ayhj9vb0/
div {
-webkit-filter: blur(5px);
-moz-filter: blur(5px);
-o-filter: blur(5px);
-ms-filter: blur(5px);
filter: blur(5px);
width: 100px;
height: 100px;
background-color: #ccc;
}
If you are using vim in MAC OSX, unfortunately it comes with older verion, and not complied with clipboard options. Luckily, homebrew can easily solve this problem.
install vim:
brew install vim
install gui verion of vim:
brew install macvim
restart the terminal to take effect.
append the following line to ~/.vimrc
set clipboard=unnamed
now you can copy the line in vim with yy
and paste it system-wide.
Updated Method:
I was never satisfied with set clipboard method for years. The biggest drawback is it will mess up your clipboard history, even when you use x
for deletion. Here is a better and more elegant solution.
Copy the text [range] of vim into the system clipboard. (Hint: use v
or V
to select the range first, and then type the colon :
to activate the Ex command):
:[line-range]yank +
e.g.,
:5,10y *
(copy/yank lines 5-10 to the system clipboard *
register)
Paste the content from the system clipboard into vim on a new line:
:put +
Note:
brew info vim
will be able to see other options for installing vim. Currrently it does not have any other options.Auto-incrementing the index in a loop:
myArr[(len(myArr)+1)]={"key":"val"}
Try the cex
argument:
?par
cex
Our first thought is that the site is down or the like, but the truth is that this is not the problem or disability. Nor is it a problem because a simple connection when tested under Firefox, Opera or services Explorer open as normal.
The error in Chrome displays a sign that says "This site is not available" and clarification with the legend "Error 15 (net :: ERR_SOCKET_NOT_CONNECTED): Unknown error". The error is quite usual in Google Chrome, more precisely in its updates, and its workaround is to restart the computer.
As partial solutions are not much we offer a tutorial for you solve the fault in less than a minute. To avoid this problem and ensure that services are normally open in Google Chrome should insert the following into the address bar: chrome: // net-internals (then give "Enter"). They then have to go to the "Socket" in the left menu and choose "Flush Socket Pools" (look at the following screenshots to guide http://www.fixotip.com/how-to-fix-error-waiting-for-available-sockets-in-google-chrome/) This has the problem solved and no longer will experience problems accessing Gmail, Google or any of the services of the Mountain View giant. I hope you found it useful and share the tutorial with whom they need or social networks: Facebook, Twitter or Google+.
the easiest way, you can copy the newline (copy empty 2 line in text editor) then paste on replace with.
Step 1:Create a XML File
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="@+id/lvItems"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
Step 2:Studnet.java
package com.scancode.acutesoft.telephonymanagerapp;
public class Student
{
String email,phone,address;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Step 3:MainActivity.java
package com.scancode.acutesoft.telephonymanagerapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends Activity {
ListView lvItems;
ArrayList<Student> studentArrayList ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvItems = (ListView) findViewById(R.id.lvItems);
studentArrayList = new ArrayList<Student>();
dataSaving();
CustomAdapter adapter = new CustomAdapter(MainActivity.this,studentArrayList);
lvItems.setAdapter(adapter);
}
private void dataSaving() {
Student student = new Student();
student.setEmail("[email protected]");
student.setPhone("1234567890");
student.setAddress("Hyderabad");
studentArrayList.add(student);
student = new Student();
student.setEmail("[email protected]");
student.setPhone("1234567890");
student.setAddress("Banglore");
studentArrayList.add(student);
student = new Student();
student.setEmail("[email protected]");
student.setPhone("1234567890");
student.setAddress("Banglore");
studentArrayList.add(student);
student = new Student();
student.setEmail("[email protected]");
student.setPhone("1234567890");
student.setAddress("Banglore");
studentArrayList.add(student);
}
}
Step 4:CustomAdapter.java
package com.scancode.acutesoft.telephonymanagerapp;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomAdapter extends BaseAdapter
{
ArrayList<Student> studentList;
Context mContext;
public CustomAdapter(Context context, ArrayList<Student> studentArrayList) {
this.mContext = context;
this.studentList = studentArrayList;
}
@Override
public int getCount() {
return studentList.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Student student = studentList.get(position);
convertView = LayoutInflater.from(mContext).inflate(R.layout.student_row,null);
TextView tvStudEmail = (TextView) convertView.findViewById(R.id.tvStudEmail);
TextView tvStudPhone = (TextView) convertView.findViewById(R.id.tvStudPhone);
TextView tvStudAddress = (TextView) convertView.findViewById(R.id.tvStudAddress);
tvStudEmail.setText(student.getEmail());
tvStudPhone.setText(student.getPhone());
tvStudAddress.setText(student.getAddress());
return convertView;
}
}
A fragment is a ViewGroup which can be shown in an Activity. But it needs a Container. The container can be any Layout (FragmeLayout, LinearLayout, etc. It does not matter).
Step 1:
Define Activity Layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/fragmentHolder"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</RelativeLayout>
Step 2:
Define Fragment Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<EditText
android:id="@+id/user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<EditText
android:id="@+id/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPassword"/>
<Button
android:id="@+id/login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login"/>
</LinearLayout>
Step 3:
Create Fragment class
public class LoginFragment extends Fragment {
private Button login;
private EditText username, password;
public static LoginFragment getInstance(String username){
Bundle bundle = new Bundle();
bundle.putInt("USERNAME", username);
LoginFragment fragment = new LoginFragment();
fragment.setArguments(bundle);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.login_fragment, parent, false);
login = view.findViewById(R.id.login);
username = view.findViewById(R.id.user);
password = view.findViewById(R.id.password);
String name = getArguments().getInt("USERNAME");
username.setText(username);
return view;
}
}
Step 4:
Add fragment in Activity
public class ActivityB extends AppCompatActivity{
private Fragment currentFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
currentFragment = LoginFragment.getInstance("Rohit");
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragmentHolder, currentFragment, "LOGIN_TAG")
.commit();
}
}
This is code is very basic. If you want to learn more advanced topics in Fragment then you can check out these resources:
In [56]: df = pd.DataFrame(np.abs(randn(3, 4)), index=[1,2,3], columns=['A','B','C','D'])
In [57]: df.divide(df.sum(axis=1), axis=0)
Out[57]:
A B C D
1 0.319124 0.296653 0.138206 0.246017
2 0.376994 0.326481 0.230464 0.066062
3 0.036134 0.192954 0.430341 0.340571
Another option besides awk is nl which allows for options -v
for setting starting value and -n <lf,rf,rz>
for left, right and right with leading zeros justified. You can also include -s
for a field separator such as -s ","
for comma separation between line numbers and your data.
In a Unix environment, this can be done as
cat <infile> | ...other stuff... | nl -v 0 -n rz
or simply
nl -v 0 -n rz <infile>
Example:
echo "Here
are
some
words" > words.txt
cat words.txt | nl -v 0 -n rz
Out:
000000 Here
000001 are
000002 some
000003 words
another trick is to use the atomic tool to do something like:
mkdir -p /path/to/mnt && atomic mount IMAGE /path/to/mnt
The Docker image will be mounted to /path/to/mnt for you to inspect it.
you can get distance and time using google Map API Google Map API
just pass downloaded JSON to this method you will get real time Distance and Time between two latlong's
void parseJSONForDurationAndKMS(String json) throws JSONException {
Log.d(TAG, "called parseJSONForDurationAndKMS");
JSONObject jsonObject = new JSONObject(json);
String distance;
String duration;
distance = jsonObject.getJSONArray("routes").getJSONObject(0).getJSONArray("legs").getJSONObject(0).getJSONObject("distance").getString("text");
duration = jsonObject.getJSONArray("routes").getJSONObject(0).getJSONArray("legs").getJSONObject(0).getJSONObject("duration").getString("text");
Log.d(TAG, "distance : " + distance);
Log.d(TAG, "duration : " + duration);
distanceBWLats.setText("Distance : " + distance + "\n" + "Duration : " + duration);
}
Set the scrollable div to have a max-size
and add overflow-y: scroll;
to it's properties.
Edit: trying to get the jsfiddle to work, but it's not scrolling properly. This will take some time to figure out.
using jQuery you can get the keys like this:
var bobject = {primary:"red",bg:"maroon",hilite:"green"};
var keys = [];
$.each(bobject, function(key,val){ keys.push(key); });
console.log(keys); // ["primary", "bg", "hilite"]
Or:
var bobject = {primary:"red",bg:"maroon",hilite:"green"};
$.map(bobject, function(v,k){return k;});
thanks to @pimlottc
No, I think you are thinking of stack space. Heap space is occupied by objects. The way to increase it is -Xmx256m, replacing the 256 with the amount you need on the command line.
In your_controller write this...
public function update_title()
{
$data = array
(
'table_id' => $this->input->post('table_id'),
'table_title' => $this->input->post('table_title')
);
$this->load->model('your_model'); // First load the model
if($this->your_model->update_title($data)) // call the method from the controller
{
// update successful...
}
else
{
// update not successful...
}
}
While in your_model...
public function update_title($data)
{
$this->db->set('table_title',$data['title'])
->where('table_id',$data['table_id'])
->update('your_table');
}
This will works fine...
To determine if a String contains an upper case and a lower case char, you can use the following:
boolean hasUppercase = !password.equals(password.toLowerCase());
boolean hasLowercase = !password.equals(password.toUpperCase());
This allows you to check:
if(!hasUppercase)System.out.println("Must have an uppercase Character");
if(!hasLowercase)System.out.println("Must have a lowercase Character");
Essentially, this works by checking if the String is equal to its entirely lowercase, or uppercase equivalent. If this is not true, then there must be at least one character that is uppercase or lowercase.
As for your other conditions, these can be satisfied in a similar way:
boolean isAtLeast8 = password.length() >= 8;//Checks for at least 8 characters
boolean hasSpecial = !password.matches("[A-Za-z0-9 ]*");//Checks at least one char is not alpha numeric
boolean noConditions = !(password.contains("AND") || password.contains("NOT"));//Check that it doesn't contain AND or NOT
With suitable error messages as above.
You might want to take a look at the timeit
module:
http://docs.python.org/library/timeit.html
or the profile
module:
http://docs.python.org/library/profile.html
There are some additionally some nice tutorials here:
http://www.doughellmann.com/PyMOTW/profile/index.html
http://www.doughellmann.com/PyMOTW/timeit/index.html
And the time
module also might come in handy, although I prefer the later two recommendations for benchmarking and profiling code performance:
if (Control.ModifierKeys == Keys.Shift)
//Shift is pressed
The cursor x/y position is a property, and a keypress (like a mouse click/mousemove) is an event. Best practice is usually to let the interface be event driven. About the only time you would need the above is if you're trying to do a shift + mouseclick thing.
And even the OO design pattern solutions are language specific.
Design patterns are solutions to common problems that your programming language doesn't solve for you. In Java, the Singleton pattern solves the one-of-something (simplified) problem.
In Scala, you have a top level construct called Object in addition to Class. It's lazily instantiated and there is only one.You don't have to use the Singleton pattern to get a Singleton. It's part of the language.
Main purpose for Boolean is null value. Null value says, that property is undefined, for example take database nullable column.
If you really need to convert everyting from primitive boolean to wrapper Boolean, then you could use following to support old code:
Boolean set = Boolean.FALSE; //set to default value primitive value (false)
...
if (set) ...
The onbeforeunload
Microsoft-ism is the closest thing we have to a standard solution, but be aware that browser support is uneven; e.g. for Opera it only works in version 12 and later (still in beta as of this writing).
Also, for maximum compatibility, you need to do more than simply return a string, as explained on the Mozilla Developer Network.
Example: Define the following two functions for enabling/disabling the navigation prompt (cf. the MDN example):
function enableBeforeUnload() {
window.onbeforeunload = function (e) {
return "Discard changes?";
};
}
function disableBeforeUnload() {
window.onbeforeunload = null;
}
Then define a form like this:
<form method="POST" action="" onsubmit="disableBeforeUnload();">
<textarea name="text"
onchange="enableBeforeUnload();"
onkeyup="enableBeforeUnload();">
</textarea>
<button type="submit">Save</button>
</form>
This way, the user will only be warned about navigating away if he has changed the text area, and will not be prompted when he's actually submitting the form.
Slight improvement to 360Airwalk solution. This imbeds the Anti Forgery Token within the javascript function, so @Html.AntiForgeryToken() no longer needs to be included on every view.
$(document).ready(function () {
var securityToken = $('@Html.AntiForgeryToken()').attr('value');
$('body').bind('ajaxSend', function (elm, xhr, s) {
if (s.type == 'POST' && typeof securityToken != 'undefined') {
if (s.data.length > 0) {
s.data += "&__RequestVerificationToken=" + encodeURIComponent(securityToken);
}
else {
s.data = "__RequestVerificationToken=" + encodeURIComponent(securityToken);
}
}
});
});
That line should be sufficient:
BooleanUtils.and(boolean... array)
but to calm the link-only purists:
Performs an and on a set of booleans.
In case you want to use directoryIterator
Following function is a re-implementation of @Shef answer with directoryIterator
function listFolderFiles($dir)
{
echo '<ol>';
foreach (new DirectoryIterator($dir) as $fileInfo) {
if (!$fileInfo->isDot()) {
echo '<li>' . $fileInfo->getFilename();
if ($fileInfo->isDir()) {
listFolderFiles($fileInfo->getPathname());
}
echo '</li>';
}
}
echo '</ol>';
}
listFolderFiles('Main Dir');
The resolution provided by Soheil was successful in my case.
To clarify, the only change I needed to make was with MySQL's server configuration;
bind-address = **INSERT-IP-HERE**
I am using an external MySQL server for my application. It is a basic Debian 7.5 installation with MySQL Server 5.5 - default configuration.
IMPORTANT:
Always backup the original of any configuration files you may modify. Always take care when elevated as super user.
File
/etc/mysql/my.cnf
Line
bind-address = 192.168.0.103 #127.0.0.1
Restart your MySQL Server service:
/usr/sbin/service mysql restart
As you can see, I simply provided the network IP of the server and commented out the default entry. Please note that simply copy and paste my solution will not work for you, unless by some miracle our hosts share the same IP.
Thanks @ Soheil
From Microsoft documentation:
PAGEIOLATCH_SH
Occurs when a task is waiting on a latch for a buffer that is in an
I/O
request. The latch request is in Shared mode. Long waits may indicate problems with the disk subsystem.
In practice, this almost always happens due to large scans over big tables. It almost never happens in queries that use indexes efficiently.
If your query is like this:
Select * from <table> where <col1> = <value> order by <PrimaryKey>
, check that you have a composite index on (col1, col_primary_key)
.
If you don't have one, then you'll need either a full INDEX SCAN
if the PRIMARY KEY
is chosen, or a SORT
if an index on col1
is chosen.
Both of them are very disk I/O
consuming operations on large tables.
Try this
HttpServletResponse response;
response.sendRedirect(".../webpage.xhtml");
::1
is the loopback address in IPv6.
Within a URL, use square brackets []
:
http://[::1]/
http://[::1]:80/
Enclosing the IPv6 literal in square brackets for use in a URL is defined in RFC 2732 – Format for Literal IPv6 Addresses in URL's.
Mirko Froehlich's answer worked for me, except when i wanted to use custom colors. The trick is to specify UI color with Hue, saturation and brightness instead of RGB.
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = myView.bounds;
UIColor *startColour = [UIColor colorWithHue:.580555 saturation:0.31 brightness:0.90 alpha:1.0];
UIColor *endColour = [UIColor colorWithHue:.58333 saturation:0.50 brightness:0.62 alpha:1.0];
gradient.colors = [NSArray arrayWithObjects:(id)[startColour CGColor], (id)[endColour CGColor], nil];
[myView.layer insertSublayer:gradient atIndex:0];
To get the Hue, Saturation and Brightness of a color, use the in built xcode color picker and go to the HSB tab. Hue is measured in degrees in this view, so divide the value by 360 to get the value you will want to enter in code.
I wrestled with this for some time. It became a huge pain to simply get to my local sqlite db. I wrote this script and made it a code snippet inside XCode. I place it inside my appDidFinishLaunching inside my appDelegate.
//xcode 6 moves the documents dir every time. haven't found out why yet.
#if DEBUG
NSLog(@"caching documents dir for xcode 6. %@", [NSBundle mainBundle]);
NSString *toFile = @"XCodePaths/lastBuild.txt"; NSError *err = nil;
[DOCS_DIR writeToFile:toFile atomically:YES encoding:NSUTF8StringEncoding error:&err];
if(err)
NSLog(@"%@", [err localizedDescription]);
NSString *appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"];
NSString *aliasPath = [NSString stringWithFormat:@"XCodePaths/%@", appName];
remove([aliasPath UTF8String]);
[[NSFileManager defaultManager] createSymbolicLinkAtPath:aliasPath withDestinationPath:DOCS_DIR error:nil];
#endif
This creates a simlink at the root of your drive. (You might have to create this folder yourself the first time, and chmod it, or you can change the location to some other place) Then I installed the xcodeway plugin https://github.com/onmyway133/XcodeWay
I modified it a bit so that it will allow me to simply press cmd+d and it will open a finder winder to my current application's persistent Documents directory. This way, not matter how many times XCode changes your path, it only changes on run, and it updates your simlink immediately on each run.
I hope this is useful for others!
You can't do this 100% accurately with JavaScript alone.
There's a Qt Webkit tool out there, and a python version. If you want to do it yourself, I've had success with Cocoa:
[self startTraverse:pagesArray performBlock:^(int collectionIndex, int pageIndex) {
NSString *locale = [self selectedLocale];
NSRect offscreenRect = NSMakeRect(0.0, 0.0, webView.frame.size.width, webView.frame.size.height);
NSBitmapImageRep* offscreenRep = nil;
offscreenRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:nil
pixelsWide:offscreenRect.size.width
pixelsHigh:offscreenRect.size.height
bitsPerSample:8
samplesPerPixel:4
hasAlpha:YES
isPlanar:NO
colorSpaceName:NSCalibratedRGBColorSpace
bitmapFormat:0
bytesPerRow:(4 * offscreenRect.size.width)
bitsPerPixel:32];
[NSGraphicsContext saveGraphicsState];
NSGraphicsContext *bitmapContext = [NSGraphicsContext graphicsContextWithBitmapImageRep:offscreenRep];
[NSGraphicsContext setCurrentContext:bitmapContext];
[webView displayRectIgnoringOpacity:offscreenRect inContext:bitmapContext];
[NSGraphicsContext restoreGraphicsState];
// Create a small + large thumbs
NSImage *smallThumbImage = [[NSImage alloc] initWithSize:thumbSizeSmall];
NSImage *largeThumbImage = [[NSImage alloc] initWithSize:thumbSizeLarge];
[smallThumbImage lockFocus];
[[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
[offscreenRep drawInRect:CGRectMake(0, 0, thumbSizeSmall.width, thumbSizeSmall.height)];
NSBitmapImageRep *smallThumbOutput = [[NSBitmapImageRep alloc] initWithFocusedViewRect:CGRectMake(0, 0, thumbSizeSmall.width, thumbSizeSmall.height)];
[smallThumbImage unlockFocus];
[largeThumbImage lockFocus];
[[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
[offscreenRep drawInRect:CGRectMake(0, 0, thumbSizeLarge.width, thumbSizeLarge.height)];
NSBitmapImageRep *largeThumbOutput = [[NSBitmapImageRep alloc] initWithFocusedViewRect:CGRectMake(0, 0, thumbSizeLarge.width, thumbSizeLarge.height)];
[largeThumbImage unlockFocus];
// Write out small
NSString *writePathSmall = [issueProvider.imageDestinationPath stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@-collection-%03d-page-%03d_small.png", locale, collectionIndex, pageIndex]];
NSData *dataSmall = [smallThumbOutput representationUsingType:NSPNGFileType properties: nil];
[dataSmall writeToFile:writePathSmall atomically: NO];
// Write out lage
NSString *writePathLarge = [issueProvider.imageDestinationPath stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@-collection-%03d-page-%03d_large.png", locale, collectionIndex, pageIndex]];
NSData *dataLarge = [largeThumbOutput representationUsingType:NSPNGFileType properties: nil];
[dataLarge writeToFile:writePathLarge atomically: NO];
}];
Hope this helps!
~dp0
: d=drive, p=path, %0=full path\name of this batch-file.
cd /d %~dp0
will change the path to the same, where the batch file resides.
See for /?
or call /
for more details about the %~...
modifiers.
See cd /?
about the /d
switch.
You can use : Query grouping allows you to create groups of WHERE clauses by enclosing them in parentheses. This will allow you to create queries with complex WHERE clauses. Nested groups are supported. Example:
$this->db->select('*')->from('my_table')
->group_start()
->where('a', 'a')
->or_group_start()
->where('b', 'b')
->where('c', 'c')
->group_end()
->group_end()
->where('d', 'd')
->get();
https://www.codeigniter.com/userguide3/database/query_builder.html#query-grouping
I don't know where the hang comes from, but redirecting (or piping) commands into an interactive ssh is in general a recipe for problems. It is more robust to use the command-to-run-as-a-last-argument style and pass the script on the ssh command line:
ssh user@server 'DEP_ROOT="/home/matthewr/releases"
datestamp=$(date +%Y%m%d%H%M%S)
REL_DIR=$DEP_ROOT"/"$datestamp
if [ ! -d "$DEP_ROOT" ]; then
echo "creating the root directory"
mkdir $DEP_ROOT
fi
mkdir $REL_DIR'
(All in one giant '
-delimited multiline command-line argument).
The pseudo-terminal message is because of your -t
which asks ssh to try to make the environment it runs on the remote machine look like an actual terminal to the programs that run there. Your ssh client is refusing to do that because its own standard input is not a terminal, so it has no way to pass the special terminal APIs onwards from the remote machine to your actual terminal at the local end.
What were you trying to achieve with -t
anyway?
Sum all cells
double X=0;
if (datagrid.Rows.Count-1 > 0)
{
for(int i = 0; i < datagrid.Rows.Count-1; i++)
{
for(int j = 0; j < datagrid.Rows.Count-1; j++)
{
X+=Convert.ToDouble(datagrid.Rows[i].Cells[j].Value.ToString());
}
}
}
Postgres documentation describes the differences between UUID
s. A couple of them:
V3:
uuid_generate_v3(namespace uuid, name text)
- This function generates a version 3 UUID in the given namespace using the specified input name.
V4:
uuid_generate_v4
- This function generates a version 4 UUID, which is derived entirely from random numbers.
on windows 10, Notepad 7.8.5, i found this solution to convert from CRLF to LF.
Edit > Format end of line
and choose either Windows(CR+LF)
or Unix(LF)
You can create another script file separately for the functions and invoke the script file whenever you want to call the function. This will help you to keep your code clean.
Function Definition : Create a new script file
Function Call : Invoke the script file
Always preferred using a connection service file (lookup/google 'psql connection service file')
Then simply:
psql service={yourservicename} < {myfile.sql}
Where yourservicename
is a section name from the service file.
You can change the color of EditText programmatically just using this line of code easily:
edittext.setBackgroundTintList(ColorStateList.valueOf(yourcolor));
You could also use INDEX MATCH
, which is more "powerful" than vlookup. This would give you exactly what you are looking for:
There is also a nice web app to see the dependencies in a weighted map kind of view.
For example:
var exec = require('child_process').exec;
exec('pwd', function callback(error, stdout, stderr){
// result
});
I had this issue on a service that I was deploying, and none of the other suggestions on this question worked. In my case, it was because my .config (xml) wasn't valid. I made a copy and paste error when copying from qualif to prod.
You can double click directly on the .cs file representing your form in the Solution Explorer :
This will open Form1.cs [Design]
, which contains the drag&drop controls.
If you are directly in the code behind (The file named Form1.cs
, without "[Design]"), you can press Shift + F7 (or only F7 depending on the project type) instead to open it.
From the design view, you can switch back to the Code Behind by pressing F7.
const tifOptions = [];
for (const [key, value] of Object.entries(tifs)) {
tifOptions.push(<option value={key} key={key}>{value}</option>);
}
return (
<select id="tif" name="tif" onChange={this.handleChange}>
{ tifOptions }
</select>
)
Helper to fetch multiple files from a given revision
When trying to resolve merge conflicts, this helper is very useful:
#!/usr/bin/env python3
import argparse
import os
import subprocess
parser = argparse.ArgumentParser()
parser.add_argument('revision')
parser.add_argument('files', nargs='+')
args = parser.parse_args()
toplevel = subprocess.check_output(['git', 'rev-parse', '--show-toplevel']).rstrip().decode()
for path in args.files:
file_relative = os.path.relpath(os.path.abspath(path), toplevel)
base, ext = os.path.splitext(path)
new_path = base + '.old' + ext
with open(new_path, 'w') as f:
subprocess.call(['git', 'show', '{}:./{}'.format(args.revision, path)], stdout=f)
Usage:
git-show-save other-branch file1.c path/to/file2.cpp
Outcome: the following contain the alternate versions of the files:
file1.old.c
path/to/file2.old.cpp
This way, you keep the file extension so your editor won't complain, and can easily find the old file just next to the newer one.
ahaliav fox 's answer is correct, however there's a small coding problem.
Change
<%=Button1.UniqueId%>
to
<%=Button1.UniqueID%>
it is case sensitive. Control.UniqueID Property
Error 14 'System.Web.UI.WebControls.Button' does not contain a definition for 'UniqueId' and no extension method 'UniqueId' accepting a first argument of type 'System.Web.UI.WebControls.Button' could be found (are you missing a using directive or an assembly reference?)
N.b. I tried the TextChanged
event myself on AutoPostBack
before searching for the answer, and although it is almost right it doesn't give the desired result I wanted nor for the question asked. It fires on losing focus on the Textbox
and not when pressing the return key.
Adding on, you can turn off the creation of vshost files for your Release build configuration and have it enabled for Debug.
Steps
Reference
Excerpt from MSDN How to: Disable the Hosting Process
Calls to certain APIs can be affected when the hosting process is enabled. In these cases, it is necessary to disable the hosting process to return the correct results.
To disable the hosting process
When the hosting process is disabled, several debugging features are unavailable or experience decreased performance. For more information, see Debugging and the Hosting Process.
In general, when the hosting process is disabled:
- The time needed to begin debugging .NET Framework applications increases.
- Design-time expression evaluation is unavailable.
- Partial trust debugging is unavailable.
- Line Feed and Carriage Return
These HTML entities will insert a new line or carriage return inside a text area.
@Ahmed
Below is code that specifies fields from a named range for insertion into MS Access. The nice thing about this code is that you can name your fields in Excel whatever the hell you want (If you use * then the fields have to match exactly between Excel and Access) as you can see I have named an Excel column "Haha" even though the Access column is called "dte".
Sub test()
dbWb = Application.ActiveWorkbook.FullName
dsh = "[" & Application.ActiveSheet.Name & "$]" & "Data2" 'Data2 is a named range
sdbpath = "C:\Users\myname\Desktop\Database2.mdb"
sCommand = "INSERT INTO [main] ([dte], [test1], [values], [values2]) SELECT [haha],[test1],[values],[values2] FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh
Dim dbCon As New ADODB.Connection
Dim dbCommand As New ADODB.Command
dbCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sdbpath & "; Jet OLEDB:Database Password=;"
dbCommand.ActiveConnection = dbCon
dbCommand.CommandText = sCommand
dbCommand.Execute
dbCon.Close
End Sub
Copying by plain assignment is best, since it's shorter, easier to read, and has a higher level of abstraction. Instead of saying (to the human reader of the code) "copy these bits from here to there", and requiring the reader to think about the size argument to the copy, you're just doing a plain assignment ("copy this value from here to here"). There can be no hesitation about whether or not the size is correct.
Also, if the structure is heavily padded, assignment might make the compiler emit something more efficient, since it doesn't have to copy the padding (and it knows where it is), but mempcy()
doesn't so it will always copy the exact number of bytes you tell it to copy.
If your string is an actual array, i.e.:
struct {
char string[32];
size_t len;
} a, b;
strcpy(a.string, "hello");
a.len = strlen(a.string);
Then you can still use plain assignment:
b = a;
To get a complete copy. For variable-length data modelled like this though, this is not the most efficient way to do the copy since the entire array will always be copied.
Beware though, that copying structs that contain pointers to heap-allocated memory can be a bit dangerous, since by doing so you're aliasing the pointer, and typically making it ambiguous who owns the pointer after the copying operation.
For these situations a "deep copy" is really the only choice, and that needs to go in a function.
Use following in your CSS
div {
-webkit-transform: rotate(90deg); /* Safari and Chrome */
-moz-transform: rotate(90deg); /* Firefox */
-ms-transform: rotate(90deg); /* IE 9 */
-o-transform: rotate(90deg); /* Opera */
transform: rotate(90deg);
}
If you are using PHP, try calling htmlentities
or htmlspecialchars
function.
This can now be done as of docker-compose v2+ as part of the build
object;
docker-compose.yml
version: '2'
services:
my_image_name:
build:
context: . #current dir as build context
args:
var1: 1
var2: c
In the above example "var1" and "var2" will be sent to the build environment.
Note: any env variables (specified by using the environment
block) which have the same name as args
variable(s) will override that variable.
boolean is a primitive data type in Java and primitive data types can not be null like other primitives int, float etc, they should be containing default values if not assigned.
In Java, only objects can assigned to null, it means the corresponding object has no reference and so does not contain any representation in memory.
Hence If you want to work with object as null , you should be using Boolean class which wraps a primitive boolean type value inside its object.
These are called wrapper classes in Java
For Example:
Boolean bool = readValue(...); // Read Your Value
if (bool == null) { do This ...}
Look at the HttpServletResponse#sendRedirect(String location)
method.
Use it as:
response.sendRedirect(request.getContextPath() + "/welcome.jsp")
Alternatively, look at HttpServletResponse#setHeader(String name, String value)
method.
The redirection is set by adding the location header:
response.setHeader("Location", request.getContextPath() + "/welcome.jsp");
You could use underscore.js and the each function:
_.each({key1: "value1", key2: "value2"}, function(value) {
console.log(value);
});
Below command will display the modfied files alone in windows.
svn status | findstr "^M"
you could try by using a function like that :
<div ng-class='whatClassIsIt(call.State)'>
Then put your logic in the function itself :
$scope.whatClassIsIt= function(someValue){
if(someValue=="first")
return "ClassA"
else if(someValue=="second")
return "ClassB";
else
return "ClassC";
}
I made a fiddle with an example : http://jsfiddle.net/DotDotDot/nMk6M/
You also can get some benefit using knitr and puting your script in Rmd chuncks.
I usually divide the code in different chunks and select which one will save a checkpoint to cache or to a RDS file, and
Over there you can set a chunk to be saved to "cache", or you can decide to run or not a particular chunk. In this way, in a first run you can process only "part 1", another execution you can select only "part 2", etc.
Example:
part1
```{r corpus, warning=FALSE, cache=TRUE, message=FALSE, eval=TRUE}
corpusTw <- corpus(twitter) # build the corpus
```
part2
```{r trigrams, warning=FALSE, cache=TRUE, message=FALSE, eval=FALSE}
dfmTw <- dfm(corpusTw, verbose=TRUE, removeTwitter=TRUE, ngrams=3)
```
As a side effect, this also could save you some headaches in terms of reproducibility :)
This might work for you (GNU sed):
sed -i -r 's/\S+//3' file
If you want to delete the white space before the 3rd field:
sed -i -r 's/(\s+)?\S+//3' file
I encountered this issue in my conda environment. The reason is that packages have been installed into two different folders, only one of which is recognised by the Python executable.
~/anaconda2/envs/[my_env]/site-packages ~/anaconda2/envs/[my_env]/lib/python2.7/site-packages
A proved solution is to add both folders to python path, using the following steps in command line (Please replace [my_env] with your own environment):
To ensure this works, try to activate Python in this environment, and import the package that was not found.
This is caused by Security settings for internet explorer. You can fix this,by changing internet explorer settings.Go To Settings->Internet Options->Security Tabs. You will see different zones:i)Internet ii)Local Intranet iii)Trusted Sites iv)Restricted Sites. Depending on your requirement select one zone. I am running my application in localhost so i selected Local intranet and then click Custom Level button. It opens security settings window. Please enable Initialize and script Activex controls not marked as safe for scripting option.It should work.
Have you tried HttpServerUtility.UrlDecode
or HttpUtility.UrlDecode
?
You can use merge to combine two dataframes into one:
import pandas as pd
pd.merge(restaurant_ids_dataframe, restaurant_review_frame, on='business_id', how='outer')
where on specifies field name that exists in both dataframes to join on, and how
defines whether its inner/outer/left/right join, with outer using 'union of keys from both frames (SQL: full outer join).' Since you have 'star' column in both dataframes, this by default will create two columns star_x and star_y in the combined dataframe. As @DanAllan mentioned for the join method, you can modify the suffixes for merge by passing it as a kwarg. Default is suffixes=('_x', '_y')
. if you wanted to do something like star_restaurant_id
and star_restaurant_review
, you can do:
pd.merge(restaurant_ids_dataframe, restaurant_review_frame, on='business_id', how='outer', suffixes=('_restaurant_id', '_restaurant_review'))
The parameters are explained in detail in this link.
Python does not have such a mechanism. Prepend a #
to each line to block comment. For more information see PEP 8. Most Python IDEs support a mechanism to do the block-commenting-with-pound-signs automatically for you. For example, in IDLE on my machine, it's Alt+3 and Alt+4.
Don't use triple-quotes; as you discovered, this is for documentation strings not block comments, although it has a similar effect. If you're just commenting things out temporarily, this is fine as a temporary measure.
This will do it:
window.history.pushState(null,null,'https://www.google.com');
This is an interesting question, but I don't think this is actually possible. Whether or not two colors "fit" as background and foreground colors is dependent upon display technology and physiological characteristics of human vision, but most importantly on upon personal tastes shaped by experience. A quick run through MySpace shows pretty clearly that not all human beings perceive colors in the same way. I don't think this is a problem that can be solved algorithmically, although there may be a huge database somewhere of acceptable matching colors.
What you may want to do is include a script on all pages that does the following ... 1. find the youtube-iframe : searching for it by width and height by title or by finding www.youtube.com in its source. You can do that by ... - looping through the window.frames by a for-in loop and then filter out by the properties
inject jscript in the iframe of the current page adding the onYoutubePlayerReady must-include-function http://shazwazza.com/post/Injecting-JavaScript-into-other-frames.aspx
Add the event listeners etc..
Hope this helps
You may try this (using jQuery
)
$(function(){_x000D_
$('#MainPopupIframe').load(function(){_x000D_
$(this).show();_x000D_
console.log('iframe loaded successfully')_x000D_
});_x000D_
_x000D_
$('#click').on('click', function(){_x000D_
$('#MainPopupIframe').attr('src', 'https://heera.it'); _x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id='click'>click me</button>_x000D_
_x000D_
<iframe style="display:none" id='MainPopupIframe' src='' /></iframe>
_x000D_
Update: Using plain javascript
window.onload=function(){_x000D_
var ifr=document.getElementById('MainPopupIframe');_x000D_
ifr.onload=function(){_x000D_
this.style.display='block';_x000D_
console.log('laod the iframe')_x000D_
};_x000D_
var btn=document.getElementById('click'); _x000D_
btn.onclick=function(){_x000D_
ifr.src='https://heera.it'; _x000D_
};_x000D_
};
_x000D_
<button id='click'>click me</button>_x000D_
_x000D_
<iframe style="display:none" id='MainPopupIframe' src='' /></iframe>
_x000D_
Update: Also you can try this (dynamic iframe)
$(function(){_x000D_
$('#click').on('click', function(){_x000D_
var ifr=$('<iframe/>', {_x000D_
id:'MainPopupIframe',_x000D_
src:'https://heera.it',_x000D_
style:'display:none;width:320px;height:400px',_x000D_
load:function(){_x000D_
$(this).show();_x000D_
alert('iframe loaded !');_x000D_
}_x000D_
});_x000D_
$('body').append(ifr); _x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id='click'>click me</button><br />
_x000D_
For those who are looking for the shortest possible "item renderer" solution from a partial, so a combo of ng-repeat and ng-include:
<div ng-repeat="item in items" ng-include src="'views/partials/item.html'" />
Actually, if you use it like this for one repeater, it will work, but won't for 2 of them! Angular (v1.2.16) will freak out for some reason if you have 2 of these one after another, so it is safer to close the div the pre-xhtml way:
<div ng-repeat="item in items" ng-include src="'views/partials/item.html'"></div>
I just noticed that if you do:
monthCalendar1.SelectionRange.Start.ToShortDateString()
you will get only the date (e.g. 1/25/2014
) from a MonthCalendar
control.
It's opposite to:
monthCalendar1.SelectionRange.Start.ToString()
//The OUTPUT will be (e.g. 1/25/2014 12:00:00 AM)
Because these MonthCalendar
properties are of type DateTime. See the msdn and the methods available to convert to a String representation. Also this may help to convert from a String to a DateTime object where applicable.
use the helper function in laravel 5.1 instead:
return response()->json(['name' => 'Abigail', 'state' => 'CA']);
This will create an instance of \Illuminate\Routing\ResponseFactory
. See the phpDocs for possible parameters below:
/**
* Return a new JSON response from the application.
*
* @param string|array $data
* @param int $status
* @param array $headers
* @param int $options
* @return \Symfony\Component\HttpFoundation\Response
* @static
*/
public static function json($data = array(), $status = 200, $headers = array(), $options = 0){
return \Illuminate\Routing\ResponseFactory::json($data, $status, $headers, $options);
}
Here is how I fixed the problem on Linux while I cloned a project that was created on Windows:
on linux in order for things to work properly you have to have this setting: core.autocrlf=input
this is how to set it: git config --global core.autocrlf input
Then clone the project again from github.
Suppose gamma1 and gamma2 are two such columns for which df.isnull().any() gives True value , the following code can be used to print the rows.
bool1 = pd.isnull(df['gamma1'])
bool2 = pd.isnull(df['gamma2'])
df[bool1]
df[bool2]
Here is my enableOk function for a jQuery dialog:
function enableOk(enable)
{
var dlgFirstButton = $('.ui-dialog-buttonpane').find('button:first');
if (enable) {
dlgFirstButton.attr('disabled', '');
dlgFirstButton.removeClass('ui-state-disabled');
} else {
dlgFirstButton.attr('disabled', 'disabled');
dlgFirstButton.addClass('ui-state-disabled');
}
}
The "first" button is the one furthest to the right. You both disable the button and set the dialog's disabled class, for the proper visual effect.