jQuery would allow you to do that.
Look up the click()
function:
http://api.jquery.com/click/
Example:
$('#yourDIV').click(function() {
alert('You clicked the DIV.');
});
Same problem I faced, I added
@XmlRootElement(name="yourRootElementName")
@XmlAccessorType(XmlAccessType.FIELD)
and now it is working.
If the XML output requirement can be changed you can always use binary serialization - which is better suited for working with heterogeneous lists of objects. Here's an example:
private void SerializeList(List<Object> Targets, string TargetPath)
{
IFormatter Formatter = new BinaryFormatter();
using (FileStream OutputStream = System.IO.File.Create(TargetPath))
{
try
{
Formatter.Serialize(OutputStream, Targets);
} catch (SerializationException ex) {
//(Likely Failed to Mark Type as Serializable)
//...
}
}
Use as such:
[Serializable]
public class Animal
{
public string Home { get; set; }
}
[Serializable]
public class Person
{
public string Name { get; set; }
}
public void ExampleUsage() {
List<Object> SerializeMeBaby = new List<Object> {
new Animal { Home = "London, UK" },
new Person { Name = "Skittles" }
};
string TargetPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"Test1.dat");
SerializeList(SerializeMeBaby, TargetPath);
}
You can use the git merge-base
command to find the latest common commit between the two branches. If that commit is the same as your branch head, then the branch has been completely merged.
Note that
git branch -d
does this sort of thing already because it will refuse to delete a branch that hasn't already been completely merged.
If you just want to set the source of the image you can use this.
$("img").attr('src','http://somedomain.com/image.jpg');
I think I have the solution to your question, assuming you can use flexbox in your project. What you want to do is make #one
a flexbox using display: flex
and use flex-direction: column
to make it a column alignment.
html,_x000D_
body {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
.border {_x000D_
border: 1px solid black;_x000D_
}_x000D_
_x000D_
.margin {_x000D_
margin: 5px;_x000D_
}_x000D_
_x000D_
#one {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
}_x000D_
_x000D_
#two {_x000D_
height: 50px;_x000D_
}_x000D_
_x000D_
#three {_x000D_
width: 100px;_x000D_
height: 100%;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div id="one" class="border">_x000D_
<div id="two" class="border margin"></div>_x000D_
<div id="three" class="border margin"></div>_x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Use output buffering:
<?php
ob_start();
var_dump($someVar);
$result = ob_get_clean();
?>
text/xml is for documents that would be meaningful to a human if presented as text without further processing, application/xml is for everything else
Every XML entity is suitable for use with the application/xml media type without modification. But this does not exploit the fact that XML can be treated as plain text in many cases. MIME user agents (and web user agents) that do not have explicit support for application/xml will treat it as application/octet-stream, for example, by offering to save it to a file.
To indicate that an XML entity should be treated as plain text by default, use the text/xml media type. This restricts the encoding used in the XML entity to those that are compatible with the requirements for text media types as described in [RFC-2045] and [RFC-2046], e.g., UTF-8, but not UTF-16 (except for HTTP).
I closed and reopened visual studio and it worked.
As an echo to @Bactisme's response, the way one would go about retrieving the current timestamp (in milliseconds, for example) is:
msec := time.Now().UnixNano() / 1000000
Resource: https://gobyexample.com/epoch
Do something like this:
A <div>
with ID of #imageDIV
, another one with ID #download
and a hidden <div>
with ID #previewImage
.
Include the latest version of jquery, and jspdf.debug.js from the jspdf CDN
Then add this script:
var element = $("#imageDIV"); // global variable
var getCanvas; // global variable
$('document').ready(function(){
html2canvas(element, {
onrendered: function (canvas) {
$("#previewImage").append(canvas);
getCanvas = canvas;
}
});
});
$("#download").on('click', function () {
var imgageData = getCanvas.toDataURL("image/png");
// Now browser starts downloading it instead of just showing it
var newData = imageData.replace(/^data:image\/png/, "data:application/octet-stream");
$("#download").attr("download", "image.png").attr("href", newData);
});
The div will be saved as a PNG on clicking the #download
Combining some features of @HYRY and @arun's answers, you can print the top correlations for dataframe df
in a single line using:
df.corr().unstack().sort_values().drop_duplicates()
Note: the one downside is if you have 1.0 correlations that are not one variable to itself, the drop_duplicates()
addition would remove them
IE10 does not support DX filters as IE9 and earlier have done, nor does it support a prefixed version of the greyscale filter.
However, you can use an SVG overlay in IE10 to accomplish the greyscaling. Example:
img.grayscale:hover {
filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'1 0 0 0 0, 0 1 0 0 0, 0 0 1 0 0, 0 0 0 1 0\'/></filter></svg>#grayscale");
}
svg {
background:url(http://4.bp.blogspot.com/-IzPWLqY4gJ0/T01CPzNb1KI/AAAAAAAACgA/_8uyj68QhFE/s400/a2cf7051-5952-4b39-aca3-4481976cb242.jpg);
}
(from: http://www.karlhorky.com/2012/06/cross-browser-image-grayscale-with-css.html)
Simplified JSFiddle: http://jsfiddle.net/KatieK/qhU7d/2/
More about the IE10 SVG filter effects: http://blogs.msdn.com/b/ie/archive/2011/10/14/svg-filter-effects-in-ie10.aspx
HTML
<img id="theImage" src="yourImage.png">
<a id="showImage">Show image</a>
JavaScript:
document.getElementById("showImage").onclick = function() {
document.getElementById("theImage").style.display = "block";
}
CSS:
#theImage { display:none; }
How about sapply
(not really necessary for this simple case):
newData<- sapply(data, function(x) x^2)
(,*[\d]+,*[\d]*)+
This would match any small or large number as following with or without comma
1
100
1,262
1,56,262
10,78,999
12,34,56,789
or
1
100
1262
156262
1078999
123456789
With python 2.7 and newer there is also dictionary comprehension which makes it a bit shorter. If possible I would use getattr instead eval (eval is evil) like in the top answer. Self can be any object which has the context your a looking at. It can be an object or locals=locals() etc.
{name: getattr(self, name) for name in ['some', 'vars', 'here]}
I solved this issue. use below taglib
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
and add jstl-1.2.jar
When you get this error some annotation is missing. I was missing @service annotation on service. When I added that annotation it worked fine for me.
As the previous answer have said, there is no way to decode it back to url, even when you try to see it from the chrome devtools panel, the url may be still encoded as blob.
However, it's possible to get the data, another way to obtain the data is to put it into an anchor and directly download it.
<a href="blob:http://example.com/xxxx-xxxx-xxxx-xxxx" download>download</a>
Insert this to the page containing blob url and click the button, you get the content.
Another way is to intercept the ajax call via a proxy server, then you could view the true image url.
This worked on Windows 10 with Apache24:
1 - Add this at the bottom of C:/Apache24/conf/httpd.conf
Listen 443
<VirtualHost *:443>
DocumentRoot "C:/Apache24/htdocs"
ServerName localhost
SSLEngine on
SSLCertificateFile "C:/Apache24/conf/ssl/server.crt"
SSLCertificateKeyFile "C:/Apache24/conf/ssl/server.key"
</VirtualHost>
2 - Add the server.crt
and server.key
files in the C:/Apache24/conf/ssl
folder. See other answers on this page to find those 2 files.
That's it!
select date_format(str_to_date('31/12/2010', '%d/%m/%Y'), '%Y%m');
or
select date_format(str_to_date('12/31/2011', '%m/%d/%Y'), '%Y%m');
hard to tell from your example
Use the $@
variable, which expands to all command-line parameters separated by spaces.
abc "$@"
First check if the request object have the 'is_private' key parameter. Most of the case's this MultiValueDictKeyError occurred for missing key in the dictionary-like request object. Because dictionary is an unordered key, value pair “associative memories” or “associative arrays”
In another word. request.GET or request.POST is a dictionary-like object containing all request parameters. This is specific to Django.
The method get() returns a value for the given key if key is in the dictionary. If key is not available then returns default value None.
You can handle this error by putting :
is_private = request.POST.get('is_private', False);
Use JQuery
var scale=0.5;
minWidth=50;
minHeight=100;
if($("#id img").width()*scale>minWidth && $("#id img").height()*scale >minHeight)
{
$("#id img").width($("#id img").width()*scale);
$("#id img").height($("#id img").height()*scale);
}
Structured Query Language - SQL: is an ANSI-standard used by almost all SGBD's vendors around the world. Basically, SQL is a language used to define and manipulate data [DDL and DML].
PL/SQL is a language created by Oracle universe. PL/SQL combine programming procedural instructions and allows the creation of programs that operates directly on database scenario.
T-SQL is Microsoft product align SQL patterns, with some peculiarities. So, feel free to test your limits.
Do you mean include javascript variable values in the query string of the URL?
Yes:
window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat="+var1+"&lon="+var2+"&setLatLon="+varEtc;
use this command php artisan migrate --path=/database/migrations/my_migration.php
it worked for me..
Another solution:
select * from traintable
where (train, time) in (select train, max(time) from traintable group by train);
Try this:
first, *rest = ex.split(/, /)
Now first
will be the first value, rest
will be the rest of the array.
Best way is use DateTime object to convert your date.
$myDateTime = DateTime::createFromFormat('Y-m-d', $weddingdate);
$formattedweddingdate = $myDateTime->format('d-m-Y');
Note: It will support for PHP 5 >= 5.3.0 only.
Simple socket server app example
I've already posted a client example at: https://stackoverflow.com/a/35971718/895245 , so here goes a server example.
This example app runs a server that returns a ROT-1 cypher of the input.
You would then need to add an Exit
button + some sleep delays, but this should get you started.
To play with it:
netcat $PHONE_IP 12345
Android sockets are the same as Java's, except we have to deal with some permission issues.
src/com/cirosantilli/android_cheat/socket/Main.java
package com.cirosantilli.android_cheat.socket;
import android.app.Activity;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Main extends Activity {
static final String TAG = "AndroidCheatSocket";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(Main.TAG, "onCreate");
Main.this.startService(new Intent(Main.this, MyService.class));
}
public static class MyService extends IntentService {
public MyService() {
super("MyService");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d(Main.TAG, "onHandleIntent");
final int port = 12345;
ServerSocket listener = null;
try {
listener = new ServerSocket(port);
Log.d(Main.TAG, String.format("listening on port = %d", port));
while (true) {
Log.d(Main.TAG, "waiting for client");
Socket socket = listener.accept();
Log.d(Main.TAG, String.format("client connected from: %s", socket.getRemoteSocketAddress().toString()));
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream out = new PrintStream(socket.getOutputStream());
for (String inputLine; (inputLine = in.readLine()) != null;) {
Log.d(Main.TAG, "received");
Log.d(Main.TAG, inputLine);
StringBuilder outputStringBuilder = new StringBuilder("");
char inputLineChars[] = inputLine.toCharArray();
for (char c : inputLineChars)
outputStringBuilder.append(Character.toChars(c + 1));
out.println(outputStringBuilder);
}
}
} catch(IOException e) {
Log.d(Main.TAG, e.toString());
}
}
}
}
We need a Service
or other background method or else: How do I fix android.os.NetworkOnMainThreadException?
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cirosantilli.android_cheat.socket"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="22" />
<uses-permission android:name="android.permission.INTERNET" />
<application android:label="AndroidCheatsocket">
<activity android:name="Main">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".Main$MyService" />
</application>
</manifest>
We must add: <uses-permission android:name="android.permission.INTERNET" />
or else: Java socket IOException - permission denied
On GitHub with a build.xml
: https://github.com/cirosantilli/android-cheat/tree/92de020d0b708549a444ebd9f881de7b240b3fbc/socket
You simply need to do:
print 'lakjdfljsdf', # trailing comma
However in:
print 'lkajdlfjasd', 'ljkadfljasf'
There is implicit whitespace (ie ' '
).
You also have the option of:
import sys
sys.stdout.write('some data here without a new line')
Each RUN
instruction in a Dockerfile
is executed in a different layer (as explained in the documentation of RUN
).
In your Dockerfile
, you have three RUN
instructions. The problem is that MySQL server is only started in the first. In the others, no MySQL are running, that is why you get your connection error with mysql
client.
To solve this problem you have 2 solutions.
RUN
RUN /bin/bash -c "/usr/bin/mysqld_safe --skip-grant-tables &" && \
sleep 5 && \
mysql -u root -e "CREATE DATABASE mydb" && \
mysql -u root mydb < /tmp/dump.sql
Create an executable script init_db.sh
:
#!/bin/bash
/usr/bin/mysqld_safe --skip-grant-tables &
sleep 5
mysql -u root -e "CREATE DATABASE mydb"
mysql -u root mydb < /tmp/dump.sql
Add these lines to your Dockerfile
:
ADD init_db.sh /tmp/init_db.sh
RUN /tmp/init_db.sh
(Update: a few years later Google and Qwant "airlines" still send me here when searching for "git non-default ssh port") A probably better way in newer git versions is to use the GIT_SSH_COMMAND ENV.VAR like:
GIT_SSH_COMMAND="ssh -oPort=1234 -i ~/.ssh/myPrivate_rsa.key" \
git clone myuser@myGitRemoteServer:/my/remote/git_repo/path
This has the added advantage of allowing any other ssh suitable option (port, priv.key, IPv6, PKCS#11 device, ...).
It is worth noting that you can build upon Gavin Toweys answer by using multiple fields from across your query such as
SUM(table.field = 1 AND table2.field = 2)
You can also use this syntax for COUNT
and I am sure other functions as well.
X=foo
Y=X
eval "Z=\$$Y"
sets Z to "foo"
Take care using eval
since this may allow accidential excution of code through values in ${Y}
. This may cause harm through code injection.
For example
Y="\`touch /tmp/eval-is-evil\`"
would create /tmp/eval-is-evil
. This could also be some rm -rf /
, of course.
float("545.2222")
and int(float("545.2222"))
Several ways to do so, here are some possible one-line approaches:
Use getch()
(need #include <conio.h>
).
Use getchar()
(expected for Enter, need #include <iostream>
).
Use cin.get()
(expected for Enter, need #include <iostream>
).
Use system("pause")
(need #include <iostream>
).
PS: This method will also print Press any key to continue . . .
on the screen. (seems perfect choice for you :))
Edit: As discussed here, There is no completely portable solution for this. Question 19.1 of the comp.lang.c FAQ covers this in some depth, with solutions for Windows, Unix-like systems, and even MS-DOS and VMS.
Note: I wrote this answer when Entity Framework 4 was actual. The point of this answer was not to get into trivial .Any()
vs .Count()
performance testing. The point was to signal that EF is far from perfect. Newer versions are better... but if you have part of code that's slow and it uses EF, test with direct TSQL and compare performance rather than relying on assumptions (that .Any()
is ALWAYS faster than .Count() > 0
).
While I agree with most up-voted answer and comments - especially on the point Any
signals developer intent better than Count() > 0
- I've had situation in which Count is faster by order of magnitude on SQL Server (EntityFramework 4).
Here is query with Any
that thew timeout exception (on ~200.000 records):
con = db.Contacts.
Where(a => a.CompanyId == companyId && a.ContactStatusId <= (int) Const.ContactStatusEnum.Reactivated
&& !a.NewsletterLogs.Any(b => b.NewsletterLogTypeId == (int) Const.NewsletterLogTypeEnum.Unsubscr)
).OrderBy(a => a.ContactId).
Skip(position - 1).
Take(1).FirstOrDefault();
Count
version executed in matter of milliseconds:
con = db.Contacts.
Where(a => a.CompanyId == companyId && a.ContactStatusId <= (int) Const.ContactStatusEnum.Reactivated
&& a.NewsletterLogs.Count(b => b.NewsletterLogTypeId == (int) Const.NewsletterLogTypeEnum.Unsubscr) == 0
).OrderBy(a => a.ContactId).
Skip(position - 1).
Take(1).FirstOrDefault();
I need to find a way to see what exact SQL both LINQs produce - but it's obvious there is a huge performance difference between Count
and Any
in some cases, and unfortunately it seems you can't just stick with Any
in all cases.
EDIT: Here are generated SQLs. Beauties as you can see ;)
ANY
:
exec sp_executesql N'SELECT TOP (1) [Project2].[ContactId] AS [ContactId], [Project2].[CompanyId] AS [CompanyId], [Project2].[ContactName] AS [ContactName], [Project2].[FullName] AS [FullName], [Project2].[ContactStatusId] AS [ContactStatusId], [Project2].[Created] AS [Created] FROM ( SELECT [Project2].[ContactId] AS [ContactId], [Project2].[CompanyId] AS [CompanyId], [Project2].[ContactName] AS [ContactName], [Project2].[FullName] AS [FullName], [Project2].[ContactStatusId] AS [ContactStatusId], [Project2].[Created] AS [Created], row_number() OVER (ORDER BY [Project2].[ContactId] ASC) AS [row_number] FROM ( SELECT [Extent1].[ContactId] AS [ContactId], [Extent1].[CompanyId] AS [CompanyId], [Extent1].[ContactName] AS [ContactName], [Extent1].[FullName] AS [FullName], [Extent1].[ContactStatusId] AS [ContactStatusId], [Extent1].[Created] AS [Created] FROM [dbo].[Contact] AS [Extent1] WHERE ([Extent1].[CompanyId] = @p__linq__0) AND ([Extent1].[ContactStatusId] <= 3) AND ( NOT EXISTS (SELECT 1 AS [C1] FROM [dbo].[NewsletterLog] AS [Extent2] WHERE ([Extent1].[ContactId] = [Extent2].[ContactId]) AND (6 = [Extent2].[NewsletterLogTypeId]) )) ) AS [Project2] ) AS [Project2] WHERE [Project2].[row_number] > 99 ORDER BY [Project2].[ContactId] ASC',N'@p__linq__0 int',@p__linq__0=4
COUNT
:
exec sp_executesql N'SELECT TOP (1) [Project2].[ContactId] AS [ContactId], [Project2].[CompanyId] AS [CompanyId], [Project2].[ContactName] AS [ContactName], [Project2].[FullName] AS [FullName], [Project2].[ContactStatusId] AS [ContactStatusId], [Project2].[Created] AS [Created] FROM ( SELECT [Project2].[ContactId] AS [ContactId], [Project2].[CompanyId] AS [CompanyId], [Project2].[ContactName] AS [ContactName], [Project2].[FullName] AS [FullName], [Project2].[ContactStatusId] AS [ContactStatusId], [Project2].[Created] AS [Created], row_number() OVER (ORDER BY [Project2].[ContactId] ASC) AS [row_number] FROM ( SELECT [Project1].[ContactId] AS [ContactId], [Project1].[CompanyId] AS [CompanyId], [Project1].[ContactName] AS [ContactName], [Project1].[FullName] AS [FullName], [Project1].[ContactStatusId] AS [ContactStatusId], [Project1].[Created] AS [Created] FROM ( SELECT [Extent1].[ContactId] AS [ContactId], [Extent1].[CompanyId] AS [CompanyId], [Extent1].[ContactName] AS [ContactName], [Extent1].[FullName] AS [FullName], [Extent1].[ContactStatusId] AS [ContactStatusId], [Extent1].[Created] AS [Created], (SELECT COUNT(1) AS [A1] FROM [dbo].[NewsletterLog] AS [Extent2] WHERE ([Extent1].[ContactId] = [Extent2].[ContactId]) AND (6 = [Extent2].[NewsletterLogTypeId])) AS [C1] FROM [dbo].[Contact] AS [Extent1] ) AS [Project1] WHERE ([Project1].[CompanyId] = @p__linq__0) AND ([Project1].[ContactStatusId] <= 3) AND (0 = [Project1].[C1]) ) AS [Project2] ) AS [Project2] WHERE [Project2].[row_number] > 99 ORDER BY [Project2].[ContactId] ASC',N'@p__linq__0 int',@p__linq__0=4
Seems that pure Where with EXISTS works much worse than calculating Count and then doing Where with Count == 0.
Let me know if you guys see some error in my findings. What can be taken out of all this regardless of Any vs Count discussion is that any more complex LINQ is way better off when rewritten as Stored Procedure ;).
If you are on a POSIX system, you can use strcasecmp. This function is not part of standard C, though, nor is it available on Windows. This will perform a case-insensitive comparison on 8-bit chars, so long as the locale is POSIX. If the locale is not POSIX, the results are undefined (so it might do a localized compare, or it might not). A wide-character equivalent is not available.
Failing that, a large number of historic C library implementations have the functions stricmp() and strnicmp(). Visual C++ on Windows renamed all of these by prefixing them with an underscore because they aren’t part of the ANSI standard, so on that system they’re called _stricmp or _strnicmp. Some libraries may also have wide-character or multibyte equivalent functions (typically named e.g. wcsicmp, mbcsicmp and so on).
C and C++ are both largely ignorant of internationalization issues, so there's no good solution to this problem, except to use a third-party library. Check out IBM ICU (International Components for Unicode) if you need a robust library for C/C++. ICU is for both Windows and Unix systems.
Try adding this at the end of your code:
import matplotlib.pyplot as plt
plt.title('add title here')
This is not an answer to the original question. But, as an original question is not a real-world problem it should not be a problem. I tried to explain to a friend what are promises in JavaScript and the difference between promise and callback.
Code below serves as an explanation:
//very basic callback example using setTimeout
//function a is asynchronous function
//function b used as a callback
function a (callback){
setTimeout (function(){
console.log ('using callback:');
let mockResponseData = '{"data": "something for callback"}';
if (callback){
callback (mockResponseData);
}
}, 2000);
}
function b (dataJson) {
let dataObject = JSON.parse (dataJson);
console.log (dataObject.data);
}
a (b);
//rewriting above code using Promise
//function c is asynchronous function
function c () {
return new Promise(function (resolve, reject) {
setTimeout (function(){
console.log ('using promise:');
let mockResponseData = '{"data": "something for promise"}';
resolve(mockResponseData);
}, 2000);
});
}
c().then (b);
It's a convention so the *nix shell knows what kind of interpreter to run.
For example, older flavors of ATT defaulted to sh (the Bourne shell), while older versions of BSD defaulted to csh (the C shell).
Even today (where most systems run bash, the "Bourne Again Shell"), scripts can be in bash, python, perl, ruby, PHP, etc, etc. For example, you might see #!/bin/perl
or #!/bin/perl5
.
PS:
The exclamation mark (!
) is affectionately called "bang". The shell comment symbol (#
) is sometimes called "hash".
PPS:
Remember - under *nix, associating a suffix with a file type is merely a convention, not a "rule". An executable can be a binary program, any one of a million script types and other things as well. Hence the need for #!/bin/bash
.
In my case this was caused by a faulty deployment where a setting in my web.config was not made.
A collegue explained that the IP address in the error message represents the localhost.
When I corrected the web.config I was then using the correct url to make the server calls and it worked.
I thought I would post this in case it might help someone.
Use This for MAC users
keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android
You can write
i = 5 + tup()[0]
Tuples can be indexed just like lists.
The main difference between tuples and lists is that tuples are immutable - you can't set the elements of a tuple to different values, or add or remove elements like you can from a list. But other than that, in most situations, they work pretty much the same.
cart.push({"element":{ id: id, quantity: quantity }});
MS Office Interop is slow and even Microsoft does not recommend Interop usage on server side and cannot be use to import large Excel files. For more details see why not to use OLE Automation from Microsoft point of view.
Instead, you can use any Excel library, like EasyXLS for example. This is a code sample that shows how to read the Excel file:
ExcelDocument workbook = new ExcelDocument();
DataSet ds = workbook.easy_ReadXLSActiveSheet_AsDataSet("excel.xls");
DataTable dataTable = ds.Tables[0];
If your Excel file has multiple sheets or for importing only ranges of cells (for better performances) take a look to more code samples on how to import Excel to DataTable in C# using EasyXLS.
Write a function which, given a color (or any other characteristics), returns an SVG representation of the desired icon. Then, when creating the marker, reference this function with the appropriate parameter(s).
Easy:
SELECT question_id, wm_concat(element_id) as elements
FROM questions
GROUP BY question_id;
Pesonally tested on 10g ;-)
From http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php
I tried to update a field with
$table->update(['field' => 'val']);
But it wasn't working, i had to modify my table Model to authorize this field to be edited : add 'field' in the array "protected $fillable"
Hope it will help someone :)
You should use background instead of image.
.pdflink:after {
content: "";
background-image:url(your-image-url.png);
background-size: 100% 100%;
display: inline-block;
/*size of your image*/
height: 25px;
width:25px;
/*if you want to change the position you can use margins or:*/
position:relative;
top:5px;
}
Try to surround strings
(hoot
, story
, article
) with quotes '
:
<div ng-repeat = "data in comments">
<div ng-if="data.type == 'hoot' ">
//different template with hoot data
</div>
<div ng-if="data.type == 'story' ">
//different template with story data
</div>
<div ng-if="data.type == 'article' ">
//different template with article data
</div>
</div>
Your problem is in the Date
property that truncates DateTime
to date only. You could put the conversion like this:
DateTime myDateTime = DateTime.Now;
string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss");
If you're on Debian:
1) remove all installed package through Virtualbox Guest Additions ISO file:
sh /media/cdrom/VBoxLinuxAdditions.run uninstall
2) install Virtualbox packages:
apt-get install build-essential module-assistant virtualbox-guest-dkms virtualbox-guest-utils
Note that even with modprobe vboxsf
returning nothing (so the module is correctly loaded), the vboxsf.so
will call an executable named mount.vboxsf
, which is provided by virtualbox-guest-utils
. Ignoring this one will prevent you from understanding the real cause of the error.
strace mount /your-directory
was a great help (No such file or directory on /sbin/mount.vboxsf
).
This is a known issue in Chrome and resolved in latest versions. Please refer https://bugs.chromium.org/p/chromium/issues/detail?id=942440 for more details.
I recommend you wrap them both in an outer div with the desired background color.
@using (Html.BeginForm()) {
<p>Do you like pizza?
@Html.DropDownListFor(x => x.likesPizza, new[] {
new SelectListItem() {Text = "Yes", Value = bool.TrueString},
new SelectListItem() {Text = "No", Value = bool.FalseString}
}, "Choose an option")
</p>
<input type = "submit" value = "Submit my answer" />
}
I think this answer is similar to Berat's, in that you put all the code for your DropDownList directly in the view. But I think this is an efficient way of creating a y/n (boolean) drop down list, so I wanted to share it.
Some notes for beginners:
Hope this helps someone,
More example from my project architecture you can see here:
+-- Dockerfile
+-- README.md
+-- config
¦ +-- production.json
+-- package.json
+-- schema
¦ +-- create-db.sh
¦ +-- db.sql
+-- scripts
¦ +-- deploy-production.sh
+-- src
¦ +-- app -> Containes API routes
¦ +-- db -> DB Models (ORM)
¦ +-- server.js -> the Server initlializer.
+-- test
Basically, the logical app separated to DB and APP folders inside the SRC dir.
This is just the syntax of the case statement, it looks like this.
SELECT
CASE
WHEN FRUIT = 'A' THEN 'APPLE'
WHEN FRUIT = 'B' THEN 'BANANA'
END AS FRUIT
FROM FRUIT_TABLE;
As a reminder remember; no assignment is performed the value becomes the column contents. (If you wanted to assign that to a variable you would put it before the CASE statement).
If you're putting this in a string within a program, you may actually need to use four backslashes (because the string parser will remove two of them when "de-escaping" it for the string, and then the regex needs two for an escaped regex backslash).
For instance:
regex("\\\\")
is interpreted as...
regex("\\" [escaped backslash] followed by "\\" [escaped backslash])
is interpreted as...
regex(\\)
is interpreted as a regex that matches a single backslash.
Depending on the language, you might be able to use a different form of quoting that doesn't parse escape sequences to avoid having to use as many - for instance, in Python:
re.compile(r'\\')
The r
in front of the quotes makes it a raw string which doesn't parse backslash escapes.
If you put your const val valName = valValue
before the class name, this way it will creates a
public static final YourClass.Kt
that will have the public static final
values.
Kotlin:
const val MY_CONST0 = 0
const val MY_CONST1 = 1
data class MyClass(var some: String)
Java decompiled:
public final class MyClassKt {
public static final int MY_CONST0 = 0;
public static final int MY_CONST1 = 1;
}
// rest of MyClass.java
This is pure JavaScript.
There is nothing special about $
. It is just a character that may be used in variable names.
var $ = 1;
var $$ = 2;
alert($ + $$);
jQuery just assigns it's core function to a variable called $
. The code you have assigns this
to a local variable called self
and the results of calling jQuery with this
as an argument to a global variable called $self
.
It's ugly, dirty, confusing, but $
, self
and $self
are all different variables that happen to have similar names.
Setting the pointer to NULL before and after using is a good technique. This is easy to do in C++ if you manage pointers within a class for example (a string):
class SomeClass
{
public:
SomeClass();
~SomeClass();
void SetText( const char *text);
char *GetText() const { return MyText; }
void Clear();
private:
char * MyText;
};
SomeClass::SomeClass()
{
MyText = NULL;
}
SomeClass::~SomeClass()
{
Clear();
}
void SomeClass::Clear()
{
if (MyText)
free( MyText);
MyText = NULL;
}
void SomeClass::Settext( const char *text)
{
Clear();
MyText = malloc( strlen(text));
if (MyText)
strcpy( MyText, text);
}
Using the getBytes
method, giving it the appropriate Charset
(or Charset
name).
Example:
String s = "Hello, there.";
byte[] b = s.getBytes(StandardCharsets.US_ASCII);
(Before Java 7: byte[] b = s.getBytes("US-ASCII");
)
This can also happen if your package name is invalid.
For example, if your "package" is com.my-company
(which is not a valid Java package name due to the dash), IntelliJ will prevent you from creating a Java Class in that package.
The is no array.push(newValue)
in C#. You don't push to an Array in C#. What we use for this is a List<T>
. What you may want to consider (for teaching purpose only) is the ArrayList
(no generic and it is a IList, so ...).
static void Main()
{
// Create an ArrayList and add 3 elements.
ArrayList list = new ArrayList();
list.Add("One"); // Add is your push
list.Add("Two");
list.Add("Three");
}
For Files - svn revert filename
For Folders - svn revert -R folder
As much as I prefer this approach:-
api.com/users?id=id1,id2,id3,id4,id5
The correct way is
api.com/users?ids[]=id1&ids[]=id2&ids[]=id3&ids[]=id4&ids[]=id5
or
api.com/users?ids=id1&ids=id2&ids=id3&ids=id4&ids=id5
This is how rack does it. This is how php does it. This is how node does it as well...
If you're going to access your local computer (or any computer) using UNC, you'll need to setup a share. If you haven't already setup a share, you could use the default administrative shares. Example:
\\localhost\c$\my_dir
... accesses a folder called "my_dir" via UNC on your C: drive. By default all the hard drives on your machine are shared with hidden shares like c$, d$, etc.
To static either a row or a column, put a $ sign in front of it. So if you were to use the formula =AVERAGE($A1,$C1)
and drag it down the entire sheet, A and C would remain static while the 1 would change to the current row
If you're on Windows, you can achieve the same thing by repeatedly pressing F4 while in the formula editing bar. The first F4 press will static both (it will turn A1 into $A$1), then just the row (A$1) then just the column ($A1)
Although technically with the formulas that you have, dragging down for the entirety of the column shouldn't be a problem without putting a $ sign in front of the column. Setting the column as static would only come into play if you're dragging ACROSS columns and want to keep using the same column, and setting the row as static would be for dragging down rows but wanting to use the same row.
You can disable the event by applying following code:
with .attr()
API
$('#your_id').attr("disabled", "disabled");
or with .prop()
API
$('#your_id').prop('disabled', true);
I have recently released a tiny library for doing just that with tests in mind. Maven dependency is:
<dependency>
<groupId>me.alexpanov</groupId>
<artifactId>free-port-finder</artifactId>
<version>1.0</version>
</dependency>
Once installed, free port numbers can be obtained via:
int port = FreePortFinder.findFreeLocalPort();
An Assert is to check -
1. the valid condition,
2. the valid statement,
3. true logic;
of source code. Instead of failing the whole project it gives an alarm that something is not appropriate in your source file.
In example 1, since variable 'str' is not null. So no any assert or exception get raised.
Example 1:
#!/usr/bin/python
str = 'hello Python!'
strNull = 'string is Null'
if __debug__:
if not str: raise AssertionError(strNull)
print str
if __debug__:
print 'FileName '.ljust(30,'.'),(__name__)
print 'FilePath '.ljust(30,'.'),(__file__)
------------------------------------------------------
Output:
hello Python!
FileName ..................... hello
FilePath ..................... C:/Python\hello.py
In example 2, var 'str' is null. So we are saving the user from going ahead of faulty program by assert statement.
Example 2:
#!/usr/bin/python
str = ''
strNull = 'NULL String'
if __debug__:
if not str: raise AssertionError(strNull)
print str
if __debug__:
print 'FileName '.ljust(30,'.'),(__name__)
print 'FilePath '.ljust(30,'.'),(__file__)
------------------------------------------------------
Output:
AssertionError: NULL String
The moment we don't want debug and realized the assertion issue in the source code. Disable the optimization flag
python -O assertStatement.py
nothing will get print
2013 August. Facebook doesn't allow to set domain with port for an App, as example "localhost:3000".
So you can use https://pagekite.net to tunnel your localhost:port
to proper domain.
Rails developers can use http://progrium.com/localtunnel/ for free.
I'm assume you cannot get css working for your button using anchor tag. So you need to override the css styles which are being overwritten by other elements using !important
property.
HTML
<a href="#" class="selected_btn" data-role="button">Button name</a>
CSS
.selected_btn
{
border:1px solid red;
text-decoration:none;
font-family:helvetica;
color:red !important;
background:url('http://www.lessardstephens.com/layout/images/slideshow_big.png') repeat-x;
}
Here is the demo
Here is an example:
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Demo: Lazy Loader</title>_x000D_
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>_x000D_
<style>_x000D_
#myScroll {_x000D_
border: 1px solid #999;_x000D_
}_x000D_
_x000D_
p {_x000D_
border: 1px solid #ccc;_x000D_
padding: 50px;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
.loading {_x000D_
color: red;_x000D_
}_x000D_
.dynamic {_x000D_
background-color:#ccc;_x000D_
color:#000;_x000D_
}_x000D_
</style>_x000D_
<script>_x000D_
var counter=0;_x000D_
$(window).scroll(function () {_x000D_
if ($(window).scrollTop() == $(document).height() - $(window).height() && counter < 2) {_x000D_
appendData();_x000D_
}_x000D_
});_x000D_
function appendData() {_x000D_
var html = '';_x000D_
for (i = 0; i < 10; i++) {_x000D_
html += '<p class="dynamic">Dynamic Data : This is test data.<br />Next line.</p>';_x000D_
}_x000D_
$('#myScroll').append(html);_x000D_
counter++;_x000D_
_x000D_
if(counter==2)_x000D_
$('#myScroll').append('<button id="uniqueButton" style="margin-left: 50%; background-color: powderblue;">Click</button><br /><br />');_x000D_
}_x000D_
</script>_x000D_
</head>_x000D_
<body>_x000D_
<div id="myScroll">_x000D_
<p>_x000D_
Contents will load here!!!.<br />_x000D_
</p>_x000D_
<p >This is test data.<br />Next line.</p>_x000D_
<p >This is test data.<br />Next line.</p>_x000D_
<p >This is test data.<br />Next line.</p>_x000D_
<p >This is test data.<br />Next line.</p>_x000D_
<p >This is test data.<br />Next line.</p>_x000D_
<p >This is test data.<br />Next line.</p>_x000D_
<p >This is test data.<br />Next line.</p>_x000D_
<p >This is test data.<br />Next line.</p>_x000D_
<p >This is test data.<br />Next line.</p>_x000D_
<p >This is test data.<br />Next line.</p>_x000D_
<p >This is test data.<br />Next line.</p>_x000D_
<p >This is test data.<br />Next line.</p>_x000D_
<p >This is test data.<br />Next line.</p>_x000D_
<p >This is test data.<br />Next line.</p>_x000D_
<p >This is test data.<br />Next line.</p>_x000D_
<p >This is test data.<br />Next line.</p>_x000D_
<p >This is test data.<br />Next line.</p>_x000D_
<p >This is test data.<br />Next line.</p>_x000D_
<p >This is test data.<br />Next line.</p>_x000D_
<p >This is test data.<br />Next line.</p>_x000D_
<p >This is test data.<br />Next line.</p>_x000D_
<p >This is test data.<br />Next line.</p>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
I think your best bet would be to leverage an existing library that does that very thing:
http://imakewebthings.com/waypoints/
You can add listeners to your elements that will fire off when your element hits the top of the viewport:
$('#scroll-to').waypoint(function() {
alert('you have scrolled to the h1!');
});
For an amazing demo of it in use:
http://tympanus.net/codrops/2013/07/16/on-scroll-header-effects/
You need to change the directory permission so that web server process can change the directory.
To change ownership of the directory, use chown
:
chown -R user-id:group-id /path/to/the/directory
To see which user own the web server process (change httpd
accordingly):
ps aux | grep httpd | grep -v grep
OR
ps -efl | grep httpd | grep -v grep
I have the same issue, when I try to export the content of email to csv and still keep it break line when importing to excel.
I export the conent as this: ="Line 1"&CHAR(10)&"Line 2"
When I import it to excel(google), excel understand it as string. It still not break new line.
We need to trigger excel to treat it as formula by: Format -> Number | Scientific.
This is not the good way but it resolve my issue.
For those who want to get height and width of device even when the display is resized (dynamically & in real-time):
In that Component do: import { HostListener } from "@angular/core";
In the component's class body write:
@HostListener('window:resize', ['$event'])
onResize(event?) {
this.screenHeight = window.innerHeight;
this.screenWidth = window.innerWidth;
}
In the component's constructor
call the onResize
method to initialize the variables. Also, don't forget to declare them first.
constructor() {
this.onResize();
}
Complete code:
import { Component, OnInit } from "@angular/core";
import { HostListener } from "@angular/core";
@Component({
selector: "app-login",
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class FooComponent implements OnInit {
screenHeight: number;
screenWidth: number;
constructor() {
this.getScreenSize();
}
@HostListener('window:resize', ['$event'])
getScreenSize(event?) {
this.screenHeight = window.innerHeight;
this.screenWidth = window.innerWidth;
console.log(this.screenHeight, this.screenWidth);
}
}
In Gson 2.7.2 it's as easy as
Gson gson = new Gson();
String serialized = gson.toJson(map);
Here's another; a C# port of the Ooura FFT. It's reasonably fast. The package also includes overlap/add convolution and some other DSP stuff, under the MIT license.
https://github.com/hughpyle/inguz-DSPUtil/blob/master/Fourier.cs
Use this for every external link
$('a[href^="http://"], a[href^="https://"]').attr('target', '_blank');
Public SUB test()
Dim mdate As Date
mdate = now()
MsgBox (Round(CDbl(mdate), 0))
End SUB
Same problem with Anaconda running on Ubuntu 15.10. I closed the terminal and opened a new window and it worked fine.
You can try converting your image from tiff to PNG, here is how to do it:
import com.sun.media.jai.codec.ImageCodec;
import com.sun.media.jai.codec.ImageDecoder;
import com.sun.media.jai.codec.ImageEncoder;
import com.sun.media.jai.codec.PNGEncodeParam;
import com.sun.media.jai.codec.TIFFDecodeParam;
import java.awt.image.RenderedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import javaxt.io.Image;
public class ImgConvTiffToPng {
public static byte[] convert(byte[] tiff) throws Exception {
byte[] out = new byte[0];
InputStream inputStream = new ByteArrayInputStream(tiff);
TIFFDecodeParam param = null;
ImageDecoder dec = ImageCodec.createImageDecoder("tiff", inputStream, param);
RenderedImage op = dec.decodeAsRenderedImage(0);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PNGEncodeParam jpgparam = null;
ImageEncoder en = ImageCodec.createImageEncoder("png", outputStream, jpgparam);
en.encode(op);
outputStream = (ByteArrayOutputStream) en.getOutputStream();
out = outputStream.toByteArray();
outputStream.flush();
outputStream.close();
return out;
}
Based from this thread, you need to bookmark chrome://settings/languages
and then Drag and Drop the language to make it default. You have to click on the Display Google Chrome in this Language button and completely restart Chrome.
You can even set the prof. pic size to its high resolution that is '1080x1080'
replace "150x150" with 1080x1080 and remove /vp/ from the link.
Here's a plain javascript (no library required) solution:
function removeUndefinedProps(obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop) && obj[prop] === undefined) {
delete obj[prop];
}
}
}
Working demo: http://jsfiddle.net/jfriend00/djj5g5fu/
You can use the pluck
method:
Word_relation::where('word_one', $word_id)->pluck('word_two')->toArray();
For more info on what methods are available for using with collection, you can you can check out the Laravel Documentation.
You shouldn't care. You should use int
most of the time. It will help the porting of your program to a wider architecture in the future (currently int
is an alias to System.Int32
but that could change). Only when the bit width of the variable matters (for instance: to control the layout in memory of a struct
) you should use int32
and others (with the associated "using System;
").
Check out Leland Kwong's code.
Basic idea is to bind the wheeling event to the child element, and then use the native javascript property scrollHeight
and the jquery property outerHeight
of the child element to detect the end of the scroll, upon which return false
to the wheeling event to prevent any scrolling.
var scrollableDist,curScrollPos,wheelEvent,dY;
$('#child-element').on('wheel', function(e){
scrollableDist = $(this)[0].scrollHeight - $(this).outerHeight();
curScrollPos = $(this).scrollTop();
wheelEvent = e.originalEvent;
dY = wheelEvent.deltaY;
if ((dY>0 && curScrollPos >= scrollableDist) ||
(dY<0 && curScrollPos <= 0)) {
return false;
}
});
If you need one item to be left aligned (like a header) but then multiple items right aligned (like 3 images), then you would do something like this:
h1 {
flex-basis: 100%; // forces this element to take up any remaining space
}
img {
margin: 0 5px; // small margin between images
height: 50px; // image width will be in relation to height, in case images are large - optional if images are already the proper size
}
Here's what that will look like (only relavent CSS was included in snippet above)
There are a couple different ways I would do this:
1) Mimic Excel Tables Using with a Named Range
In your example, you named the range A10:A20
"Age". Depending on how you wanted to reference a cell in that range you could either (as @Alex P wrote) use =INDEX(Age, 5)
or if you want to reference a cell in range "Age" that is on the same row as your formula, just use:
=INDEX(Age, ROW()-ROW(Age)+1)
This mimics the relative reference features built into Excel tables but is an alternative if you don't want to use a table.
If the named range is an entire column, the formula simplifies as:
=INDEX(Age, ROW())
2) Use an Excel Table
Alternatively if you set this up as an Excel table and type "Age" as the header title of the Age column, then your formula in columns to the right of the Age column can use a formula like this:
=[@[Age]]
It makes it clear that the method accepts null values, and that if you override the method, you should also accept null values.
It also serves as a hint for code analyzers like FindBugs. For example, if such a method dereferences its argument without checking for null first, FindBugs will emit a warning.
You can check the below code just create a index.html
and run it.
<!DOCTYPE html>
<html>
<head>
<style>
table {
border-spacing: 10px;
}
td {
padding: 10px;
}
</style>
</head>
<body>
<table cellspacing="0" cellpadding="0">
<th>Col 1</th>
<th>Col 2</th>
<th>Col 3</th>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</table>
</body>
</html>
_x000D_
OUTPUT :
You can run with this code
tsc .\src\index.ts --experimentalDecorators "true" --emitDecoratorMetadata "true"
This comment is for readers who have found this entry but are using mysql instead of oracle! on mysql you can do the following: Today
SELECT *
FROM
WHERE date(tran_date) = CURRENT_DATE()
Yesterday
SELECT *
FROM yourtable
WHERE date(tran_date) = DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)
You may also want to try two backslashes (\\")
to escape the escape character.
There are a few problems here.
1: onBlur expects a callback, and you are calling renderPasswordConfirmError
and using the return value, which is null.
2: you need a place to render the error.
3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.
handleBlur: function () {
this.setState({validating: true});
},
render: function () {
return <div>
...
<input
type="password"
placeholder="Password (confirm)"
valueLink={this.linkState('password2')}
onBlur={this.handleBlur}
/>
...
{this.renderPasswordConfirmError()}
</div>
},
renderPasswordConfirmError: function() {
if (this.state.validating && this.state.password !== this.state.password2) {
return (
<div>
<label className="error">Please enter the same password again.</label>
</div>
);
}
return null;
},
Since both projects are under the same solution, there's a simpler way for the include files and linker as described in https://docs.microsoft.com/en-us/cpp/build/adding-references-in-visual-cpp-projects?view=vs-2019 :
#include "../libProject/libHeader.h"
).Place cursor inside your field private int _i;
and then Edit menu or RMB - Refactor - Encapsulate Field... (CtrlR, CtrlE) to create the standard property accessors.
You'll want to use the specified market
protocol:
final String appPackageName = "com.example"; // Can also use getPackageName(), as below
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
Keep in mind, this will crash on any device that does not have the Market installed (the emulator, for example). Hence, I would suggest something like:
final String appPackageName = getPackageName(); // getPackageName() from Context or Activity object
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appPackageName)));
}
While using getPackageName()
from Context
or subclass thereof for consistency (thanks @cprcrack!). You can find more on Market Intents here: link.
Turn the axes off with:
plt.axis('off')
And gridlines with:
plt.grid(b=None)
I have not been able to find a Firefox option equivalent of --disable-web-security or an addon that does that for me. I really needed it for some testing scenarios where modifying the web server was not possible. What did help was to use Fiddler to auto-modify web responses so that they have the correct headers and CORS is no longer an issue.
The steps are:
Open fiddler.
If on https go to menu Tools -> Options -> Https and tick the Capture & Decrypt https options
Go to menu Rules -> Customize rules. Modify the OnBeforeResponseFunction so that it looks like the following, then save:
static function OnBeforeResponse(oSession: Session) {
//....
oSession.oResponse.headers.Remove("Access-Control-Allow-Origin");
oSession.oResponse.headers.Add("Access-Control-Allow-Origin", "*");
//...
}
This will make every web response to have the Access-Control-Allow-Origin: * header.
This still won't work as the OPTIONS preflight will pass through and cause the request to block before our above rule gets the chance to modify the headers. So to fix this, in the fiddler main window, on the right hand side there's an AutoResponder tab. Add a new rule and response: METHOD:OPTIONS https://yoursite.com/ with auto response: *CORSPreflightAllow and tick the boxes: "Enable Rules" and "Unmatched requests passthrough".
See picture below for reference:
Unfortunately, git branch -a
and git branch -r
do not show you all remote branches, if you haven't executed a "git fetch".
git remote show origin
works consistently all the time. Also git show-ref
shows all references in the Git repository. However, it works just like the git branch
command.
Compare them as other values:
if($array_a == $array_b) {
//they are the same
}
You can read about all array operators here:
http://php.net/manual/en/language.operators.array.php
Note for example that ===
also checks that the types and order of the elements in the arrays are the same.
Finally I got the solution
sudo ln -s /etc/phpmyadmin/apache.conf /etc/apache2/conf-available/phpmyadmin.conf
sudo a2enconf phpmyadmin
sudo service apache2 reload
More about https://askubuntu.com/questions/55280/phpmyadmin-is-not-working-after-i-installed-it
Please check whether this helps:
select TOP 1
product,
price
from
table1
where
(project=1 OR Customer=2 OR company=3) AND
price IS NOT NULL
ORDER BY company
The error you are getting i.e. "unexpected token o" is because json is expected but object is obtained while parsing. That "o" is the first letter of word "object".
2020 UPDATE: Just add this to your Gradle file. It works perfectly!
repositories {
jcenter()
}
implementation 'me.dm7.barcodescanner:zxing:1.9.13'
Use defaultdict instead:
from collections import defaultdict
data = defaultdict(list)
data[1].append('hello')
This way you don't have to initialize all the keys you want to use to lists beforehand.
What is happening in your example is that you use one (mutable) list:
alist = [1]
data = dict.fromkeys(range(2), alist)
alist.append(2)
print data
would output {0: [1, 2], 1: [1, 2]}
.
Instead of inverting, you can achieve the same goal by using a generic IValueConverter
implementation that can convert a Boolean value to configurable target values for true and false. Below is one such implementation:
public class BooleanConverter<T> : IValueConverter
{
public BooleanConverter(T trueValue, T falseValue)
{
True = trueValue;
False = falseValue;
}
public T True { get; set; }
public T False { get; set; }
public virtual object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value is bool && ((bool) value) ? True : False;
}
public virtual object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value is T && EqualityComparer<T>.Default.Equals((T) value, True);
}
}
Next, subclass it where T
is Visibility
:
public sealed class BooleanToVisibilityConverter : BooleanConverter<Visibility>
{
public BooleanToVisibilityConverter() :
base(Visibility.Visible, Visibility.Collapsed) {}
}
Finally, this is how you could use BooleanToVisibilityConverter
above in XAML and configure it to, for example, use Collapsed
for true and Visible
for false:
<Application.Resources>
<app:BooleanToVisibilityConverter
x:Key="BooleanToVisibilityConverter"
True="Collapsed"
False="Visible" />
</Application.Resources>
This inversion is useful when you want to bind to a Boolean property named IsHidden
as opposed IsVisible
.
Here is an ES6 method chain using .map()
and .includes()
:
const arr = [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]
const checkForUser = (newUsername) => {
arr.map(user => {
return user.username
}).includes(newUsername)
}
if (!checkForUser('fred')){
// add fred
}
I followed these instructions but then found that the menu hover color was wrong.
I am using the Spacegray theme in Sublime 3 beta 3074. So to accomplish the sidebar font color change and also hover color change, on OSX, I created a new file ~/Library/"Application Support"/"Sublime Text 3"/Packages/User/Spacegray.sublime-theme
then added this code to it:
[
{
"class": "sidebar_label",
"color": [192,197,203],
"font.bold": false,
"font.size": 15
},
{
"class": "sidebar_label",
"parents": [{"class": "tree_row","attributes": ["hover"]}],
"color": [255,255,255]
},
]
It is possible to tweak many other settings for your theme if you can see the original default:
https://gist.github.com/nateflink/0355eee823b89fe7681e
I extracted this file from the sublime package zip file by installing the PackageResourceViewer following MattDMo's instructions (https://stackoverflow.com/users/1426065/mattdmo) here:
Which Mac version are you using? try these paths
/System/Library/Frameworks/JavaVM.framework/ OR
/usr/libexec/java_home
This link might help - How To Set $JAVA_HOME Environment Variable On Mac OS X
It might not be the best practice, but you can simply target a specific column using collect()
, export it as a list of Rows, and loop through the list.
Assume this is your df:
+----------+----------+-------------------+-----------+-----------+------------------+
| Date| New_Date| New_Timestamp|date_sub_10|date_add_10|time_diff_from_now|
+----------+----------+-------------------+-----------+-----------+------------------+
|2020-09-23|2020-09-23|2020-09-23 00:00:00| 2020-09-13| 2020-10-03| 51148 |
|2020-09-24|2020-09-24|2020-09-24 00:00:00| 2020-09-14| 2020-10-04| -35252 |
|2020-01-25|2020-01-25|2020-01-25 00:00:00| 2020-01-15| 2020-02-04| 20963548 |
|2020-01-11|2020-01-11|2020-01-11 00:00:00| 2020-01-01| 2020-01-21| 22173148 |
+----------+----------+-------------------+-----------+-----------+------------------+
to loop through rows in Date column:
rows = df3.select('Date').collect()
final_list = []
for i in rows:
final_list.append(i[0])
print(final_list)
From docs and example it is not clear that classpath manipulation is not allowed.
<configuration>
<compilerArgs>
<arg>classpath=${basedir}/lib/bad.jar</arg>
</compilerArgs>
</configuration>
But see Java docs (also https://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/tooldocs/solaris/javac.html)
-classpath path Specifies the path javac uses to look up classes needed to run javac or being referenced by other classes you are compiling. Overrides the default or the CLASSPATH environment variable if it is set.
Maybe it is possible to get current classpath and extend it,
see in maven, how output the classpath being used?
<properties>
<cpfile>cp.txt</cpfile>
</properties>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.9</version>
<executions>
<execution>
<id>build-classpath</id>
<phase>generate-sources</phase>
<goals>
<goal>build-classpath</goal>
</goals>
<configuration>
<outputFile>${cpfile}</outputFile>
</configuration>
</execution>
</executions>
</plugin>
Read file (Read a file into a Maven property)
<plugin>
<groupId>org.codehaus.gmaven</groupId>
<artifactId>gmaven-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<phase>generate-resources</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<source>
def file = new File(project.properties.cpfile)
project.properties.cp = file.getText()
</source>
</configuration>
</execution>
</executions>
</plugin>
and finally
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<compilerArgs>
<arg>classpath=${cp}:${basedir}/lib/bad.jar</arg>
</compilerArgs>
</configuration>
</plugin>
Adding /show does not present a pure source code, it's an embedded working example. To display it without any additional scripts, css and html, use:
http://fiddle.jshell.net/<fiddle id>/show/light/
An example: http://fiddle.jshell.net/Ua8Cv/show/light/
You can get the channel ID with the username (in your case "klauskkpm") using the filter "forUsername", like this:
https://www.googleapis.com/youtube/v3/channels?key={YOUR_API_KEY}&forUsername=klauskkpm&part=id
More info here: https://developers.google.com/youtube/v3/docs/channels/list
Swift 5
I call present in viewDidLayoutSubviews
as presenting in viewDidAppear
causes a split second showing of the view controller before the modal is loaded which looks like an ugly glitch
make sure to check for the window existence and execute code just once
var alreadyPresentedVCOnDisplay = false
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// we call present in viewDidLayoutSubviews as
// presenting in viewDidAppear causes a split second showing
// of the view controller before the modal is loaded
guard let _ = view?.window else {
// window must be assigned
return
}
if !alreadyPresentedVCOnDisplay {
alreadyPresentedVCOnDisplay = true
present(...)
}
}
Security warning: This code is not secure.
working example
define('SALT', 'whateveryouwant');
function encrypt($text)
{
return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, SALT, $text, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))));
}
function decrypt($text)
{
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, SALT, base64_decode($text), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)));
}
$encryptedmessage = encrypt("your message");
echo decrypt($encryptedmessage);
In cmd
C:\Users\Downloads>install.exe LAX_VM "C:\Program Files\Java\jdk1.8.0_60\bin\java.exe"
This is where the window function row_number()
comes in handy:
SELECT s.siteName, s.siteIP, h.date
FROM sites s INNER JOIN
(select h.*, row_number() over (partition by siteName order by date desc) as seqnum
from history h
) h
ON s.siteName = h.siteName and seqnum = 1
ORDER BY s.siteName, h.date
There is a php library (pdfparser) that does exactly what you want.
project website
github
https://github.com/smalot/pdfparser
Demo page/api
After including pdfparser in your project you can get all text from mypdf.pdf
like so:
<?php
$parser = new \installpath\PdfParser\Parser();
$pdf = $parser->parseFile('mypdf.pdf');
$text = $pdf->getText();
echo $text;//all text from mypdf.pdf
?>
Simular you can get the metadata from the pdf as wel as getting the pdf objects (for example images).
This error can also happen if you have circular dependencies. Check your imports and make sure you do not have any cycles.
An alternative solution to floats is to use absolute positioning:
.title {
position: relative;
}
.title span:last-child {
position: absolute;
right: 6px; /* must be equal to parent's right padding */
}
See also the fiddle.
Declare a variable for active window
var activeInfoWindow;
and bind this code in marker listener
marker.addListener('click', function () {
if (activeInfoWindow) { activeInfoWindow.close();}
infowindow.open(map, marker);
activeInfoWindow = infowindow;
});
I use this solution:
It's a bit more concise since I use: ng-repeat="obj in objects | filter : paginate"
to filter the rows. Also made it working with $resource:
check this same effect with less code
$(".item").mouseover(function(){
$('.info').animate({ marginTop: '-50px' , opacity: 0.5 }, 1000);
});
remove global reference
npm uninstall -g angular-cli
npm cache clean
I had the same issue and could fix it with the solution from dougwilson: from Apr 5, 2017, Github.
index.js
to index.pug
'/'
route: res.render('index.pug')
- instead of res.render('index')
DEBUG=express:view
Now it works like a charm.You should work with padding on the inner container rather than with margin. Try this!
HTML
<div class="row info-panel">
<div class="col-md-4" id="server_1">
<div class="server-action-menu">
Server 1
</div>
</div>
</div>
CSS
.server-action-menu {
background-color: transparent;
background-image: linear-gradient(to bottom, rgba(30, 87, 153, 0.2) 0%, rgba(125, 185, 232, 0) 100%);
background-repeat: repeat;
border-radius:10px;
padding: 5px;
}
@{
var baseurl = Request.Url.Scheme + "://" + Request.Url.Host + ":" + Request.Url.Port + Url.Content("~");
}
@baseurl
--output http://localhost:49626/TEST/
First we'll consider loops where the number of iterations of the inner loop is independent of the value of the outer loop's index. For example:
for (i = 0; i < N; i++) {
for (j = 0; j < M; j++) {
sequence of statements
}
}
The outer loop executes N times. Every time the outer loop executes, the inner loop executes M times. As a result, the statements in the inner loop execute a total of N * M times. Thus, the total complexity for the two loops is O(N2).
Open the hosts file located at : **C:\windows\system32\drivers\etc**.
Add the following at end of this file :
YourServerIP YourDNS
Example:
198.168.1.1 maps.google.com
This is an interesting question and since it isn't explained very explicitly in the documentation I'll answer this by going through the sourcecode of mod_rewrite; demonstrating a big benefit of open-source.
In the top section you'll quickly spot the defines used to name these flags:
#define CONDFLAG_NONE 1<<0
#define CONDFLAG_NOCASE 1<<1
#define CONDFLAG_NOTMATCH 1<<2
#define CONDFLAG_ORNEXT 1<<3
#define CONDFLAG_NOVARY 1<<4
and searching for CONDFLAG_ORNEXT confirms that it is used based on the existence of the [OR] flag:
else if ( strcasecmp(key, "ornext") == 0
|| strcasecmp(key, "OR") == 0 ) {
cfg->flags |= CONDFLAG_ORNEXT;
}
The next occurrence of the flag is the actual implementation where you'll find the loop that goes through all the RewriteConditions a RewriteRule has, and what it basically does is (stripped, comments added for clarity):
# loop through all Conditions that precede this Rule
for (i = 0; i < rewriteconds->nelts; ++i) {
rewritecond_entry *c = &conds[i];
# execute the current Condition, see if it matches
rc = apply_rewrite_cond(c, ctx);
# does this Condition have an 'OR' flag?
if (c->flags & CONDFLAG_ORNEXT) {
if (!rc) {
/* One condition is false, but another can be still true. */
continue;
}
else {
/* skip the rest of the chained OR conditions */
while ( i < rewriteconds->nelts
&& c->flags & CONDFLAG_ORNEXT) {
c = &conds[++i];
}
}
}
else if (!rc) {
return 0;
}
}
You should be able to interpret this; it means that OR has a higher precedence, and your example indeed leads to if ( (A OR B) AND (C OR D) )
. If you would, for example, have these Conditions:
RewriteCond A [or]
RewriteCond B [or]
RewriteCond C
RewriteCond D
it would be interpreted as if ( (A OR B OR C) and D )
.
I was getting this error in PyroCMS.
You can improve the error message in the Loader.php file that is in the code of the library.
Open the Loader.php file and find any calls to show_error
. I replaced mine with the following:
show_error(sprintf("Unable to load the requested file: \"%s\" with instance title of \"%s\"", $_ci_file, $_ci_data['_ci_vars']['options']['instance_title']));
I was then able to see which file was causing the issues for me.
You could try git reset --hard HEAD to reset the repo to the expected default state.
We use a sonicwall vpn. It launches a java applet that launches mstc with all the credentials setup. You really can't do this without a java applet or activex plugin.
Microsoft uses this technique itself on their small business server for getting inside the network. I wouldn't say it is a terrible idea, as long as platform independence isn't important.
The ErrorDocument
directive, when supplied a local URL path, expects the path to be fully qualified from the DocumentRoot
. In your case, this means that the actual path to the ErrorDocument
is
ErrorDocument 404 /hellothere/error/404page.html
There is no better way but since it's an operation you usually do quite often, you'd better automatize the process.
Most frameworks offer a way to make arguments parsing an easy task. You can build you own object for that. Quick and dirty example :
class Request
{
// This is the spirit but you may want to make that cleaner :-)
function get($key, $default=null, $from=null)
{
if ($from) :
if (isset(${'_'.$from}[$key]));
return sanitize(${'_'.strtoupper($from)}[$key]); // didn't test that but it should work
else
if isset($_REQUEST[$key])
return sanitize($_REQUEST[$key]);
return $default;
}
// basics. Enforce it with filters according to your needs
function sanitize($data)
{
return addslashes(trim($data));
}
// your rules here
function isEmptyString($data)
{
return (trim($data) === "" or $data === null);
}
function exists($key) {}
function setFlash($name, $value) {}
[...]
}
$request = new Request();
$question= $request->get('question', '', 'post');
print $request->isEmptyString($question);
Symfony use that kind of sugar massively.
But you are talking about more than that, with your "// Handle error here ". You are mixing 2 jobs : getting the data and processing it. This is not the same at all.
There are other mechanisms you can use to validate data. Again, frameworks can show you best pratices.
Create objects that represent the data of your form, then attach processses and fall back to it. It sounds far more work that hacking a quick PHP script (and it is the first time), but it's reusable, flexible, and much less error prone since form validation with usual PHP tends to quickly become spaguetti code.
to Set Variable:
item Assignment method using key:
import os
os.environ['DEBUSSY'] = '1' #Environ Variable must be string not Int
to get or to check whether its existed or not,
since os.environ is an instance you can try object way.
Method 1:
os.environ.get('DEBUSSY') # this is error free method if not will return None by default
will get '1'
as return value
Method 2:
os.environ['DEBUSSY'] # will throw an key error if not found!
Method 3:
'DEBUSSY' in os.environ # will return Boolean True/False
Method 4:
os.environ.has_key('DEBUSSY') #last 2 methods are Boolean Return so can use for conditional statements
Problem is synchronization. Separate out regions of conflict.
Name the file as : (server-name)_(thread/process-name)_(millisecond/timestamp).(extension)
example : aws1_t1_1447402821007.png
In case you're using VS Code and happen to have the affected files open, you can undo the changes made by Git on a per-file basis. (so CTRL
+ Z
)
Try regular expressions. You can find a certain pattern in your text and replace it with something that you want. I can't give you the exact code right now but you can test out your expressions using this.
First of all you need to remove the data-toggle attribute. We will use some JQuery, so make sure you include it.
<ul class='nav nav-tabs'>
<li class='active'><a href='#home'>Home</a></li>
<li><a href='#menu1'>Menu 1</a></li>
<li><a href='#menu2'>Menu 2</a></li>
<li><a href='#menu3'>Menu 3</a></li>
</ul>
<div class='tab-content'>
<div id='home' class='tab-pane fade in active'>
<h3>HOME</h3>
<div id='menu1' class='tab-pane fade'>
<h3>Menu 1</h3>
</div>
<div id='menu2' class='tab-pane fade'>
<h3>Menu 2</h3>
</div>
<div id='menu3' class='tab-pane fade'>
<h3>Menu 3</h3>
</div>
</div>
</div>
<script>
$(document).ready(function(){
// Handling data-toggle manually
$('.nav-tabs a').click(function(){
$(this).tab('show');
});
// The on tab shown event
$('.nav-tabs a').on('shown.bs.tab', function (e) {
alert('Hello from the other siiiiiide!');
var current_tab = e.target;
var previous_tab = e.relatedTarget;
});
});
</script>
The DisplayHtml(string html) recommended by m3z worked for me.
In case it helps somebody, I would also like to mention that initially there were some spaces in my HTML that invalidated the HTML and so the text appeared as a string. The spaces were introduced (around the angular brackets) when I pasted the HTML into Visual Studio. So if your text is still appearing as text after you try the solutions mentioned in this post, then it may be worth checking that the HTML syntax is correct.
Below will reinitialize your local repo; also clearing remote repos (ie origin):
git init
Then below, will create 'origin' if it doesn't exist:
git remote add origin [repo-url]
Else, you can use the set-url
subcommand to edit an existing remote:
git remote set-url origin [repo-url]
Also, you can check existing remotes with
git remote -v
Hope this helps!
You can use console.dir()
, which is a shortcut for console.log(util.inspect())
.
(The only difference is that it bypasses any custom inspect()
function defined on an object.)
It uses syntax-highlighting, smart indentation, removes quotes from keys and just makes the output as pretty as it gets.
const object = JSON.parse(jsonString)
console.dir(object, {depth: null, colors: true})
and for the command line:
cat package.json | node -e "process.stdin.pipe(new stream.Writable({write: chunk => console.dir(JSON.parse(chunk), {depth: null, colors: true})}))"
As a late corolloary to the earlier answers here, you probably end up in situations where you want some but not all variables to be interpolated. You can solve that by using backslashes to escape dollar signs and backticks; or you can put the static text in a variable.
Name='Rich Ba$tard'
dough='$$$dollars$$$'
cat <<____HERE
$Name, you can win a lot of $dough this week!
Notice that \`backticks' need escaping if you want
literal text, not `pwd`, just like in variables like
\$HOME (current value: $HOME)
____HERE
Demo: https://ideone.com/rMF2XA
Note that any of the quoting mechanisms -- \____HERE
or "____HERE"
or '____HERE'
-- will disable all variable interpolation, and turn the here-document into a piece of literal text.
A common task is to combine local variables with script which should be evaluated by a different shell, programming language, or remote host.
local=$(uname)
ssh -t remote <<:
echo "$local is the value from the host which ran the ssh command"
# Prevent here doc from expanding locally; remote won't see backslash
remote=\$(uname)
# Same here
echo "\$remote is the value from the host we ssh:ed to"
:
The others got you the right answer, but I thought I'd demonstrate another neat thing you can do:
mkdir -p /tmp/a/{b,c}/d
Will create the following paths:
/tmp/a/b/d
/tmp/a/c/d
The braces allow you to create multiple directories at once on the same level of the hierarchy, whereas the -p
option means "create parent directories as needed".
In case you want a quicker (but still very clean) way of achieving it for a personal purpose (for instance if you want to build a specific project having some strong requirements concerning the version of the compiler), just follow the following steps:
echo $PATH
and look for a personal directory having a very high priority (in my case, I have ~/.local/bin
);For instance:
ln -s /usr/bin/gcc-WHATEVER ~/.local/bin/gcc
ln -s /usr/bin/g++-WHATEVER ~/.local/bin/g++
Of course, this will work for a single user (it isn't a system wide solution), but on the other hand I don't like to change too many things in my installation.
If you have a datetime.timedelta
value td
, td.days
already gives you the "days" you want. timedelta
values keep fraction-of-day as seconds (not directly hours or minutes) so you'll indeed have to perform "nauseatingly simple mathematics", e.g.:
def days_hours_minutes(td):
return td.days, td.seconds//3600, (td.seconds//60)%60
Make sure you are not facing a "cross module" problem
If the component which is using the pipe, doesn't belong to the module which has declared the pipe component "globally" then the pipe is not found and you get this error message.
In my case I've declared the pipe in a separate module and imported this pipe module in any other module having components using the pipe.
I have declared a that the component in which you are using the pipe is
the Pipe Module
import { NgModule } from '@angular/core';
import { myDateFormat } from '../directives/myDateFormat';
@NgModule({
imports: [],
declarations: [myDateFormat],
exports: [myDateFormat],
})
export class PipeModule {
static forRoot() {
return {
ngModule: PipeModule,
providers: [],
};
}
}
Usage in another module (e.g. app.module)
// Import APPLICATION MODULES
...
import { PipeModule } from './tools/PipeModule';
@NgModule({
imports: [
...
, PipeModule.forRoot()
....
],
Use bs3-upgrade library for spacings and text aligment...
https://github.com/studija/bs3-upgrade
col-xs-text-center col-sm-text-left
col-xs-text-center col-sm-text-right
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-6 col-xs-text-center col-sm-text-left">
<p>
© 2015 example.com. All rights reserved.
</p>
</div>
<div class="col-xs-12 col-sm-6 col-xs-text-center col-sm-text-right">
<p>
<a href="#"><i class="fa fa-facebook"></i></a>
<a href="#"><i class="fa fa-twitter"></i></a>
<a href="#"><i class="fa fa-google-plus"></i></a>
</p>
</div>
</div>
</div>
For people just stumbling upon this now, I resolved an error of this type that was thrown with all the references and using statements placed properly. There's evidently some confusion with substituting in a function that returns DataTable instead of calling it on a declared DataTable. For example:
This worked for me:
DataTable dt = SomeObject.ReturnsDataTable();
List<string> ls = dt.AsEnumerable().Select(dr => dr["name"].ToString()).ToList<string>();
But this didn't:
List<string> ls = SomeObject.ReturnsDataTable().AsEnumerable().Select(dr => dr["name"].ToString()).ToList<string>();
I'm still not 100% sure why, but if anyone is frustrated by an error of this type, give this a try.
<script type="text/javascript">
document.write(document.referrer);
</script>
document.referrer
serves your purpose, but it doesn't work for Internet Explorer versions earlier than IE9.
It will work for other popular browsers, like Chrome, Mozilla, Opera, Safari etc.
You can try this:
SELECT * FROM MYTABLE WHERE DATE BETWEEN '03/10/2014 06:25:00' and '03/12/2010 6:25:00'
lowercase-with-hyphens
is the style I most often see on GitHub.*
lowercase_with_underscores
is probably the second most popular style I see.
The former is my preference because it saves keystrokes.
* Anecdotal; I haven't collected any data.
There are two steps to fix this.
First edit phpMyAdmin/libraries/DatabaseInterface.class.php
Change:
if (PMA_MYSQL_INT_VERSION > 50503) {
$default_charset = 'utf8mb4';
$default_collation = 'utf8mb4_general_ci';
} else {
$default_charset = 'utf8';
$default_collation = 'utf8_general_ci';
}
To:
//if (PMA_MYSQL_INT_VERSION > 50503) {
// $default_charset = 'utf8mb4';
// $default_collation = 'utf8mb4_general_ci';
//} else {
$default_charset = 'utf8';
$default_collation = 'utf8_general_ci';
//}
Then delete this cookie from your browser "pma_collation_connection".
Or delete all Cookies.
Then restart your phpMyAdmin.
(It would be nice if phpMyAdmin allowed you to set the charset and collation per server in the config.inc.php)
git rm --cached
is used to remove a file from the index. In the case where the file is already in the repo, git rm --cached
will remove the file from the index, leaving it in the working directory and a commit will now remove it from the repo as well. Basically, after the commit, you would have unversioned the file and kept a local copy.
git reset HEAD file
( which by default is using the --mixed
flag) is different in that in the case where the file is already in the repo, it replaces the index version of the file with the one from repo (HEAD), effectively unstaging the modifications to it.
In the case of unversioned file, it is going to unstage the entire file as the file was not there in the HEAD. In this aspect git reset HEAD file
and git rm --cached
are same, but they are not same ( as explained in the case of files already in the repo)
To the question of Why are there 2 ways to unstage a file in git?
- there is never really only one way to do anything in git. that is the beauty of it :)
See http://api.jquery.com/jQuery.ajax/, there's mention of datatype and contentType there.
They are both used in the request to the server so the server knows what kind of data to receive/send.
Determining of root cause is not an issue since Go 1.8; field name now is shown in the error message:
json: cannot unmarshal object into Go struct field Comment.author of type string
I was trying something like this using the $(...).val()
function, but the function did not exist. It turns out that you can manually set the value the same way you do it for an <input>
:
// Set value to Indonesia ("ID"):
$('#country').value = 'ID'
...and it get's automatically updated in the select. Works on Firefox at least; you might want to try it out in the others.
with loss tolerant
Do you mean "with loss tolerance" ?
Basically, UDP is not "loss tolerant". You can send 100 packets to someone, and they might only get 95 of those packets, and some might be in the wrong order.
For things like video streaming, and multiplayer gaming, where it is better to miss a packet than to delay all the other packets behind it, this is the obvious choice
For most other things though, a missing or 'rearranged' packet is critical. You'd have to write some extra code to run on top of UDP to retry if things got missed, and enforce correct order. This would add a small bit of overhead in certain places.
Thankfully, some very very smart people have done this, and they called it TCP.
Think of it this way: If a packet goes missing, would you rather just get the next packet as quickly as possible and continue (use UDP), or do you actually need that missing data (use TCP). The overhead won't matter unless you're in a really edge-case scenario.
One can create an empty array, fill it (otherwise map will skip it) and then map indexes to values:
Array(8).fill().map((_, i) => i * i);
If you guys are generating your stylesheets with LESS/SASS and are importing Bootstrap there, I've found that overriding the @navbar-height variable lets your set the height of the navbar, which is originally defined in the variables.less file.
Change the checkboxes so that the name includes the index inside the brackets:
<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>">
The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.
jQuery('#testID2').find('.test2').replaceWith('.test3');
Semantically, you are selecting the element with the ID testID2
, then you are looking for any descendent elements with the class test2
(does not exist) and then you are replacing that element with another element (elements anywhere in the page with the class test3
) that also do not exist.
You need to do this:
jQuery('#testID2').addClass('test3').removeClass('test2');
This selects the element with the ID testID2
, then adds the class test3
to it. Last, it removes the class test2
from that element.
Not so hard:
#include <thread>
void Test::runMultiThread()
{
std::thread t1(&Test::calculate, this, 0, 10);
std::thread t2(&Test::calculate, this, 11, 20);
t1.join();
t2.join();
}
If the result of the computation is still needed, use a future instead:
#include <future>
void Test::runMultiThread()
{
auto f1 = std::async(&Test::calculate, this, 0, 10);
auto f2 = std::async(&Test::calculate, this, 11, 20);
auto res1 = f1.get();
auto res2 = f2.get();
}
I have met the same issue today. After trying various method, I realize that just put the code of sizing inside $(window).load(function() {})
instead of document.ready
would solve part of issue (if you are not ajaxing the page).
Consider:
Sub SheetKiller()
Dim s As Worksheet, t As String
Dim i As Long, K As Long
K = Sheets.Count
For i = K To 1 Step -1
t = Sheets(i).Name
If t = "ID Sheet" Or t = "Summary" Then
Application.DisplayAlerts = False
Sheets(i).Delete
Application.DisplayAlerts = True
End If
Next i
End Sub
NOTE:
Because we are deleting, we run the loop backwards.
I've used this successfully inside R script:
library("reshape2",lib.loc="/path/to/R-packages/")
useful if for whatever reason libraries are in more than one place.
You could run your JUnit test from a main method and repeat it so many times you need:
package tests;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.Result;
public class RepeatedTest {
@Test
public void test() {
fail("Not yet implemented");
}
public static void main(String args[]) {
boolean runForever = true;
while (runForever) {
Result result = org.junit.runner.JUnitCore.runClasses(RepeatedTest.class);
if (result.getFailureCount() > 0) {
runForever = false;
//Do something with the result object
}
}
}
}
You are setting your cron to run on 10th minute in every hour.
To set it to every 5 mins
change to */5 * * * * /usr/bin/php /mydomain.in/cronmail.php > /dev/null 2>&1
Use the Application.DispatcherUnhandledException Event
. See this question for a summary (see Drew Noakes' answer).
Be aware that there'll be still exceptions which preclude a successful resuming of your application, like after a stack overflow, exhausted memory, or lost network connectivity while you're trying to save to the database.
call function on load:
<video onload="doWhatYouNeedTo()" src="demo.mp4" id="video">
get video duration
var video = document.getElementById("video");
var duration = video.duration;
One thing to note is that jQuery event methods do not fire/trap load
on embed
tags that contain SVG DOM which loads as a separate document in the embed
tag. The only way I found to trap a load
event on these were to use raw JavaScript.
This will not work (I've tried on
/bind
/load
methods):
$img.on('load', function () {
console.log('FOO!');
});
However, this works:
$img[0].addEventListener('load', function () {
console.log('FOO!');
}, false);
As the compiler says, grid
was not declared in the scope of your function :) "Scope" basically means a set of curly braces. Every variable is limited to the scope in which it is declared (it cannot be accessed outside that scope). In your case, you're declaring the grid
variable in your main()
function and trying to use it in nonrecursivecountcells()
. You seem to be passing it as the argument colors
however, so I suggest you just rename your uses of grid
in nonrecursivecountcells()
to colors
. I think there may be something wrong with trying to pass the array that way, too, so you should probably investigate passing it as a pointer (unless someone else says something to the contrary).
print "Number of lines: $nids\n";
print "Content: $ids\n";
How did Perl complain? print $ids
should work, though you probably want a newline at the end, either explicitly with print
as above or implicitly by using say
or -l/$\.
If you want to interpolate a variable in a string and have something immediately after it that would looks like part of the variable but isn't, enclose the variable name in {}
:
print "foo${ids}bar";
Adding to the pile.
Mine was the assembly name of the WPF application was the same assembly name as a referenced dll. So make sure you don't have duplicate assembly names in any of your projects.
calloc()
gives you a zero-initialized buffer, while malloc()
leaves the memory uninitialized.
For large allocations, most calloc
implementations under mainstream OSes will get known-zeroed pages from the OS (e.g. via POSIX mmap(MAP_ANONYMOUS)
or Windows VirtualAlloc
) so it doesn't need to write them in user-space. This is how normal malloc
gets more pages from the OS as well; calloc
just takes advantage of the OS's guarantee.
This means calloc
memory can still be "clean" and lazily-allocated, and copy-on-write mapped to a system-wide shared physical page of zeros. (Assuming a system with virtual memory.)
Some compilers even can optimize malloc + memset(0) into calloc for you, but you should use calloc explicitly if you want the memory to read as 0
.
If you aren't going to ever read memory before writing it, use malloc
so it can (potentially) give you dirty memory from its internal free list instead of getting new pages from the OS. (Or instead of zeroing a block of memory on the free list for a small allocation).
Embedded implementations of calloc
may leave it up to calloc
itself to zero memory if there's no OS, or it's not a fancy multi-user OS that zeros pages to stop information leaks between processes.
On embedded Linux, malloc could mmap(MAP_UNINITIALIZED|MAP_ANONYMOUS)
, which is only enabled for some embedded kernels because it's insecure on a multi-user system.
<form onSubmit={(e) => {this.doSomething(); e.preventDefault();}}></form>
it work fine for me
Elasticsearch 2.3 the option
action.destructive_requires_name: true
in elasticsearch.yml do the trip
curl -XDELETE http://localhost:9200/twitter/tweet
Correct, when you drag a view controller object onto your storyboard in order to create a new scene, it doesn't automatically make the new class for you, too.
Having added a new view controller scene to your storyboard, you then have to:
Create a UIViewController
subclass. For example, go to your target's folder in the project navigator panel on the left and then control-click and choose "New File...". Choose a "Cocoa Touch Class":
And then select a unique name for the new view controller subclass:
Specify this new subclass as the base class for the scene you just added to the storyboard.
Now hook up any IBOutlet
and IBAction
references for this new scene with the new view controller subclass.
Function pointers in C can be used to perform object-oriented programming in C.
For example, the following lines is written in C:
String s1 = newString();
s1->set(s1, "hello");
Yes, the ->
and the lack of a new
operator is a dead give away, but it sure seems to imply that we're setting the text of some String
class to be "hello"
.
By using function pointers, it is possible to emulate methods in C.
How is this accomplished?
The String
class is actually a struct
with a bunch of function pointers which act as a way to simulate methods. The following is a partial declaration of the String
class:
typedef struct String_Struct* String;
struct String_Struct
{
char* (*get)(const void* self);
void (*set)(const void* self, char* value);
int (*length)(const void* self);
};
char* getString(const void* self);
void setString(const void* self, char* value);
int lengthString(const void* self);
String newString();
As can be seen, the methods of the String
class are actually function pointers to the declared function. In preparing the instance of the String
, the newString
function is called in order to set up the function pointers to their respective functions:
String newString()
{
String self = (String)malloc(sizeof(struct String_Struct));
self->get = &getString;
self->set = &setString;
self->length = &lengthString;
self->set(self, "");
return self;
}
For example, the getString
function that is called by invoking the get
method is defined as the following:
char* getString(const void* self_obj)
{
return ((String)self_obj)->internal->value;
}
One thing that can be noticed is that there is no concept of an instance of an object and having methods that are actually a part of an object, so a "self object" must be passed in on each invocation. (And the internal
is just a hidden struct
which was omitted from the code listing earlier -- it is a way of performing information hiding, but that is not relevant to function pointers.)
So, rather than being able to do s1->set("hello");
, one must pass in the object to perform the action on s1->set(s1, "hello")
.
With that minor explanation having to pass in a reference to yourself out of the way, we'll move to the next part, which is inheritance in C.
Let's say we want to make a subclass of String
, say an ImmutableString
. In order to make the string immutable, the set
method will not be accessible, while maintaining access to get
and length
, and force the "constructor" to accept a char*
:
typedef struct ImmutableString_Struct* ImmutableString;
struct ImmutableString_Struct
{
String base;
char* (*get)(const void* self);
int (*length)(const void* self);
};
ImmutableString newImmutableString(const char* value);
Basically, for all subclasses, the available methods are once again function pointers. This time, the declaration for the set
method is not present, therefore, it cannot be called in a ImmutableString
.
As for the implementation of the ImmutableString
, the only relevant code is the "constructor" function, the newImmutableString
:
ImmutableString newImmutableString(const char* value)
{
ImmutableString self = (ImmutableString)malloc(sizeof(struct ImmutableString_Struct));
self->base = newString();
self->get = self->base->get;
self->length = self->base->length;
self->base->set(self->base, (char*)value);
return self;
}
In instantiating the ImmutableString
, the function pointers to the get
and length
methods actually refer to the String.get
and String.length
method, by going through the base
variable which is an internally stored String
object.
The use of a function pointer can achieve inheritance of a method from a superclass.
We can further continue to polymorphism in C.
If for example we wanted to change the behavior of the length
method to return 0
all the time in the ImmutableString
class for some reason, all that would have to be done is to:
length
method.length
method.Adding an overriding length
method in ImmutableString
may be performed by adding an lengthOverrideMethod
:
int lengthOverrideMethod(const void* self)
{
return 0;
}
Then, the function pointer for the length
method in the constructor is hooked up to the lengthOverrideMethod
:
ImmutableString newImmutableString(const char* value)
{
ImmutableString self = (ImmutableString)malloc(sizeof(struct ImmutableString_Struct));
self->base = newString();
self->get = self->base->get;
self->length = &lengthOverrideMethod;
self->base->set(self->base, (char*)value);
return self;
}
Now, rather than having an identical behavior for the length
method in ImmutableString
class as the String
class, now the length
method will refer to the behavior defined in the lengthOverrideMethod
function.
I must add a disclaimer that I am still learning how to write with an object-oriented programming style in C, so there probably are points that I didn't explain well, or may just be off mark in terms of how best to implement OOP in C. But my purpose was to try to illustrate one of many uses of function pointers.
For more information on how to perform object-oriented programming in C, please refer to the following questions:
On Mac, open a terminal and run the following two commands.
conda update conda
conda update anaconda
Make sure to run each command multiple times to update to the current version.
In the default settings, VS Code uses the following fonts (14 pt) in descending order:
How to verify: VS Code runs in a browser. In the first version, you could hit F12 to open the Developer Tools. Inspecting the DOM, you can find a containing several s that make up that line of code. Inspecting one of those spans, you can see that font-family is just the list above.
Host your service in any cloud service provider.
Although there are already some answers I found a nice comparison in which they tried several ways to serialize Pandas DataFrames: Efficiently Store Pandas DataFrames.
They compare:
In their experiment, they serialize a DataFrame of 1,000,000 rows with the two columns tested separately: one with text data, the other with numbers. Their disclaimer says:
You should not trust that what follows generalizes to your data. You should look at your own data and run benchmarks yourself
The source code for the test which they refer to is available online. Since this code did not work directly I made some minor changes, which you can get here: serialize.py I got the following results:
They also mention that with the conversion of text data to categorical data the serialization is much faster. In their test about 10 times as fast (also see the test code).
Edit: The higher times for pickle than CSV can be explained by the data format used. By default pickle
uses a printable ASCII representation, which generates larger data sets. As can be seen from the graph however, pickle using the newer binary data format (version 2, pickle-p2
) has much lower load times.
Some other references:
numpy.fromfile
is the fastest.Try this from different folder:
sudo tar -cvjSf folder.tar.bz2 folder/*
When you use QDir.mkpath() it returns true if the path already exists, in the other hand QDir.mkdir() returns false if the path already exists. So depending on your program you have to choose which fits better.
You can see more on Qt Documentation
I have this version about datetimepicker https://tempusdominus.github.io/bootstrap-4/ and for any reason doesn`t work the change event with jquery but with JS vanilla it does
I figure out like this
document.getElementById('date').onchange = function(){ ...the jquery code...}
I hope work for you
You probably need to update the remote URL since github puts your username in it. You can take a look at the original URL by typing
git config --get remote.origin.url
Or just go to the repository page on Github and get the new URL. Then use
git remote set-url origin https://{new url with username replaced}
to update the URL with your new username.
earl's answer gives you the solution, but I thought I'd add what the problem is that's causing your IllegalStateException
. You're calling group(1)
without having first called a matching operation (such as find()
). This isn't needed if you're just using $1
since the replaceAll()
is the matching operation.