Do not even try to use flex; stay with css grid!! :)
https://jsfiddle.net/ctt3bqr0/
place-self: center;
is doing the centering work here.
If you want to center something that is inside div
that is inside grid cell you need to define nested grid in order to make it work. (Please look at the fiddle both examples shown there.)
https://css-tricks.com/snippets/css/complete-guide-grid/
Cheers!
I think you should use "textAlign" instead of "text-align".
In my case, the issue caused by the wrong order of class definitions. For example, I had added another class definition before my Form class:
namespace MyBuggyWorld
{
public class BackendObject //This hack broke the VS 2017 winform designer and resources linker!
{
public TcpClient ActiveClient { get; set; }
public BackgroundWorker ActiveWorker { get; set; }
}
public partial class FormMain : Form
{
}
}
After moving BackendObject
to the end of the file (better yet would be to move it to a separate file), doing project clean + rebuild resolved the issue.
I believe the sprintf is the right function for you. I's in the standard library, like printf. Follow the link below for more information:
Here Is my code For Zip the folders and its sub folders and its files and make it downloadable in zip Format
function zip()
{
$source='path/folder'// Path To the folder;
$destination='path/folder/abc.zip'// Path to the file and file name ;
$include_dir = false;
$archive = 'abc.zip'// File Name ;
if (!extension_loaded('zip') || !file_exists($source)) {
return false;
}
if (file_exists($destination)) {
unlink ($destination);
}
$zip = new ZipArchive;
if (!$zip->open($archive, ZipArchive::CREATE)) {
return false;
}
$source = str_replace('\\', '/', realpath($source));
if (is_dir($source) === true)
{
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
if ($include_dir) {
$arr = explode("/",$source);
$maindir = $arr[count($arr)- 1];
$source = "";
for ($i=0; $i < count($arr) - 1; $i++) {
$source .= '/' . $arr[$i];
}
$source = substr($source, 1);
$zip->addEmptyDir($maindir);
}
foreach ($files as $file)
{
$file = str_replace('\\', '/', $file);
// Ignore "." and ".." folders
if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
continue;
$file = realpath($file);
if (is_dir($file) === true)
{
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
}
else if (is_file($file) === true)
{
$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
}
}
}
else if (is_file($source) === true)
{
$zip->addFromString(basename($source), file_get_contents($source));
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$archive);
header('Content-Length: '.filesize($archive));
readfile($archive);
unlink($archive);
}
If Any Issue With the Code Let Me know.
for those used to php:
//add this function
function foreach(arr, func){
for(var i in arr){
func(i, arr[i]);
}
}
usage:
foreach(myArray, function(i, v){
//run code here
});
similar to php version:
foreach(myArray as i=>v){
//run code here
}
I've used it in real-time programming. We typically don't want to perform any dynamic allocation (or deallocation) after the system starts up, because there's no guarantee how long that is going to take.
What I can do is preallocate a large chunk of memory (large enough to hold any amount of whatever that the class may require). Then, once I figure out at runtime how to construct the things, placement new can be used to construct objects right where I want them. One situation I know I used it in was to help create a heterogeneous circular buffer.
It's certainly not for the faint of heart, but that's why they make the syntax for it kinda gnarly.
As long as pip lives within the scripts folder you can run
python -m pip ....
This will tell python to get pip from inside the scripts folder. This is also a good way to have both python2.7 and pyhton3.5 on you computer and have them in different locations. I currently have both python2 and pyhton3 installed on windows. When I type python
it defaults to python2. But if I type python3
I can use python3. (I also had to change the python.exe file for python3 to "python3.exe")If I need to install flask for python 2 I can run
python -m pip install flask
and it will be installed in the pyhton2 folder, but if I need flask for python 3 I run:
python3 -m pip install flask
and I now have it in the python3 folder
string connectionString= ServerName + DatabaseName + SecurityType;
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection)) {
connection.Open();
bulkCopy.DestinationTableName = "TableName";
try {
bulkCopy.WriteToServer(dataTableName);
} catch (Exception e) {
Console.Write(e.Message);
}
}
Please note that the structure of the database table and the table name should be the same or it will throw an exception.
You might want to take a look at Standard Compression Scheme for Unicode.
SQL Server 2008 R2 use it internally and can achieve up to 50% compression.
jQuery:
$('#foo').click(function() { alert('foo'); });
Or if you don't want it to follow the link href:
$('#foo').click(function() { alert('foo'); return false; });
As already mentioned in comments to the first answer, the return std::move(...);
construct can make a difference in cases other than returning of local variables. Here's a runnable example that documents what happens when you return a member object with and without std::move()
:
#include <iostream>
#include <utility>
struct A {
A() = default;
A(const A&) { std::cout << "A copied\n"; }
A(A&&) { std::cout << "A moved\n"; }
};
class B {
A a;
public:
operator A() const & { std::cout << "B C-value: "; return a; }
operator A() & { std::cout << "B L-value: "; return a; }
operator A() && { std::cout << "B R-value: "; return a; }
};
class C {
A a;
public:
operator A() const & { std::cout << "C C-value: "; return std::move(a); }
operator A() & { std::cout << "C L-value: "; return std::move(a); }
operator A() && { std::cout << "C R-value: "; return std::move(a); }
};
int main() {
// Non-constant L-values
B b;
C c;
A{b}; // B L-value: A copied
A{c}; // C L-value: A moved
// R-values
A{B{}}; // B R-value: A copied
A{C{}}; // C R-value: A moved
// Constant L-values
const B bc;
const C cc;
A{bc}; // B C-value: A copied
A{cc}; // C C-value: A copied
return 0;
}
Presumably, return std::move(some_member);
only makes sense if you actually want to move the particular class member, e.g. in a case where class C
represents short-lived adapter objects with the sole purpose of creating instances of struct A
.
Notice how struct A
always gets copied out of class B
, even when the class B
object is an R-value. This is because the compiler has no way to tell that class B
's instance of struct A
won't be used any more. In class C
, the compiler does have this information from std::move()
, which is why struct A
gets moved, unless the instance of class C
is constant.
First of all, you tried to replace the entire 12.00 with '', which isn't going to give your desired results.
Second you are trying to do replace directly on a decimal. Replace must be performed on a string, so you have to CAST.
There are many ways to get your desired results, but this replace would have worked (assuming your column name is "height":
REPLACE(CAST(height as varchar(31)),'.00','')
EDIT:
This script works:
DECLARE @Height decimal(6,2);
SET @Height = 12.00;
SELECT @Height, REPLACE(CAST(@Height AS varchar(31)),'.00','');
Usually, if you have big python objects it's quite hard to format them. I personally prefer using some tools for that.
Here is python-beautifier - www.cleancss.com/python-beautify that instantly turns your data into customizable style.
For Windows:
$ ssh-keygen -t rsa -b 4096 -C [email protected]
I suggest IGNITION this is even better than Droid fu
https://github.com/kaeppler/ignition
https://github.com/kaeppler/ignition/wiki/Sample-applications
Regardless of what you're trying to do there should be no need to read to and write to a file at the same time. It would also use more memory which should always be avoided. I'd suggest reading the entire file using the .ReadAll method and then close it and do whatever you need to do with the data (assuming you read the contents into a variable) and then do a write to the same file and overwrite the file. If you're concerned with having something go wrong when over-writing the current file you could always try to write it to a different file and throw an error if that doesn't work before trying to over-write the original.
@SuppressWarnings({ "deprecation", "unchecked" })
public void swipeTopToBottom(AppiumDriver<MobileElement> driver)
throws InterruptedException {
Dimension dimensions = driver.manage().window().getSize();
Double screenHeightStart = dimensions.getHeight() * 0.30;
int scrollStart = screenHeightStart.intValue();
System.out.println("s="+scrollStart);
Double screenHeightEnd = dimensions.getHeight()*0.90;
int scrollEnd = screenHeightEnd.intValue();
driver.swipe(0,scrollStart,0,scrollEnd,2000);
CommonUtils.threadWait(driver, 3000);
}
You should also check you JSON (not in DevTools, but on a backend). Angular HttpClient having a hard time parsing JSON with \0
characters and DevTools will ignore then, so it's quite hard to spot in Chrome.
Based on this article
Below query will provide exactly the same result as given in the desired response:
db.books.aggregate([
{
$group: {
_id: { addresses: "$addr", books: "$book" },
num: { $sum :1 }
}
},
{
$group: {
_id: "$_id.addresses",
bookCounts: { $push: { bookName: "$_id.books",count: "$num" } }
}
},
{
$project: {
_id: 1,
bookCounts:1,
"totalBookAtAddress": {
"$sum": "$bookCounts.count"
}
}
}
])
The response will be looking like below:
/* 1 */
{
"_id" : "address4",
"bookCounts" : [
{
"bookName" : "book3",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 2 */
{
"_id" : "address90",
"bookCounts" : [
{
"bookName" : "book33",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 3 */
{
"_id" : "address15",
"bookCounts" : [
{
"bookName" : "book1",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 4 */
{
"_id" : "address3",
"bookCounts" : [
{
"bookName" : "book9",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 5 */
{
"_id" : "address5",
"bookCounts" : [
{
"bookName" : "book1",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 6 */
{
"_id" : "address1",
"bookCounts" : [
{
"bookName" : "book1",
"count" : 3
},
{
"bookName" : "book5",
"count" : 1
}
],
"totalBookAtAddress" : 4
},
/* 7 */
{
"_id" : "address2",
"bookCounts" : [
{
"bookName" : "book1",
"count" : 2
},
{
"bookName" : "book5",
"count" : 1
}
],
"totalBookAtAddress" : 3
},
/* 8 */
{
"_id" : "address77",
"bookCounts" : [
{
"bookName" : "book11",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 9 */
{
"_id" : "address9",
"bookCounts" : [
{
"bookName" : "book99",
"count" : 1
}
],
"totalBookAtAddress" : 1
}
For your specific case, just use the reduce
method of Arrays:
var sumArray = function() {
// Use one adding function rather than create a new one each
// time sumArray is called
function add(a, b) {
return a + b;
}
return function(arr) {
return arr.reduce(add);
};
}();
alert( sumArray([2, 3, 4]) );
"break" is a command that breaks out of the "closest" loop.
While there are many good uses for break, you shouldn't use it if you don't have to -- it can be seen as just another way to use goto, which is considered bad.
For example, why not:
while (!(the condition you're using to break))
{
//Your code here.
}
If the reason you're using "break" is because you don't want to continue execution of that iteration of the loop, you may want to use the "continue" keyword, which immediately jumps to the next iteration of the loop, whether it be while or for.
while (!condition) {
//Some code
if (condition) continue;
//More code that will be skipped over if the condition was true
}
Brute force it:
first_name_relation = User.where(:first_name => 'Tobias') # ActiveRecord::Relation
last_name_relation = User.where(:last_name => 'Fünke') # ActiveRecord::Relation
all_name_relations = User.none
first_name_relation.each do |ar|
all_name_relations.new(ar)
end
last_name_relation.each do |ar|
all_name_relations.new(ar)
end
I found that setting the file's Copy To Output Directory parameter to Copy Always seems to have cleared up the locking issue. Although now I have 2 copies of the files and need to delete one.
Use float-right
for block elements, or text-right
for inline elements:
<div class="row">
<div class="col">left</div>
<div class="col text-right">inline content needs to be right aligned</div>
</div>
<div class="row">
<div class="col">left</div>
<div class="col">
<div class="float-right">element needs to be right aligned</div>
</div>
</div>
http://www.codeply.com/go/oPTBdCw1JV
If float-right
is not working, remember that Bootstrap 4 is now flexbox, and many elements are display:flex
which can prevent float-right
from working.
In some cases, the utility classes like align-self-end
or ml-auto
work to right align elements that are inside a flexbox container like the Bootstrap 4 .row, Card or Nav. The ml-auto
(margin-left:auto) is used in a flexbox element to push elements to the right.
Checkout TickTick.
It's a true Bash JSON parser.
#!/bin/bash
. /path/to/ticktick.sh
# File
DATA=`cat data.json`
# cURL
#DATA=`curl http://foobar3000.com/echo/request.json`
tickParse "$DATA"
echo ``pathname``
echo ``headers["user-agent"]``
I found this worked in my scenario.
The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
$.get("urlToCheck.com").done(function () {
alert("success");
}).fail(function () {
alert("failed.");
});
jezrael's answer is good, but did not answer a question I had: Will getting the "sort" flag wrong mess up my data in any way? The answer is apparently "no", you are fine either way.
from pandas import DataFrame, concat
a = DataFrame([{'a':1, 'c':2,'d':3 }])
b = DataFrame([{'a':4,'b':5, 'd':6,'e':7}])
>>> concat([a,b],sort=False)
a c d b e
0 1 2.0 3 NaN NaN
0 4 NaN 6 5.0 7.0
>>> concat([a,b],sort=True)
a b c d e
0 1 NaN 2.0 3 NaN
0 4 5.0 NaN 6 7.0
str = str.split('');
str[3] = 'h';
str = str.join('');
I had this problem of no .env files showing up in the project.
Turns out the IDE I was using (Netbeans, try not to judge) will show certain types of .hidden files but not all.
After racking my brains for a bit I checked the file system and found the .env + .env.example files / modified them with a text editor.
Leaving this answer for the rare situation someones using a dodgy IDE like myself.
Going to keep this pithier, this is already asked and answered above .
I'd step back however and answer it slightly differently, the docker engine itself adds orchestration as one of its extras and this is the disruptive part. Once you start running an app as a combination of containers running 'somewhere' across multiple container engines it gets really exciting. Robustness, Horizontal Scaling, complete abstraction from the underlying hardware, i could go on and on...
Its not just Docker that gives you this, in fact the de facto Container Orchestration standard is Kubernetes which comes in a lot of flavours, a Docker one, but also OpenShift, SuSe, Azure, AWS...
Then beneath K8S there are alternative container engines; the interesting ones are Docker and CRIO - recently built, daemonless, intended as a container engine specifically for Kubernetes but immature. Its the competition between these that I think will be the real long term choice for a container engine.
Replace all require
statements with import
statements. Example:
// Before:
const Web3 = require('web3');
// After:
import Web3 from 'web3';
It worked for me.
Yes, the moment jQuery sees the URL belongs to a different domain, it assumes that call as a cross domain call, thus crossdomain:true
is not required here.
Also, important to note that you cannot make a synchronous call with $.ajax
if your URL belongs to a different domain (cross domain) or you are using JSONP. Only async calls are allowed.
Note: you can call the service synchronously if you specify the async:false
with your request.
I do a fair amount of vibration analysis and look at large data sets (tens and hundreds of millions of points). My testing showed the pandas.read_csv() function to be 20 times faster than numpy.genfromtxt(). And the genfromtxt() function is 3 times faster than the numpy.loadtxt(). It seems that you need pandas for large data sets.
I posted the code and data sets I used in this testing on a blog discussing MATLAB vs Python for vibration analysis.
When you want to show an URL of remote branches, try:
git remote -v
Just Change the query like this:
SELECT TOP 1 * FROM [HumanResources].[Employee]
where Employee
is your table name and HumanResources
is your Schema name if I am not wrong.
Hope your problem will be resolved. :)
There is an easy tool for timing. https://github.com/RalphMao/PyTimer
It can work like a decorator:
from pytimer import Timer
@Timer(average=False)
def matmul(a,b, times=100):
for i in range(times):
np.dot(a,b)
Output:
matmul:0.368434
matmul:2.839355
It can also work like a plug-in timer with namespace control(helpful if you are inserting it to a function which has a lot of codes and may be called anywhere else).
timer = Timer()
def any_function():
timer.start()
for i in range(10):
timer.reset()
np.dot(np.ones((100,1000)), np.zeros((1000,500)))
timer.checkpoint('block1')
np.dot(np.ones((100,1000)), np.zeros((1000,500)))
np.dot(np.ones((100,1000)), np.zeros((1000,500)))
timer.checkpoint('block2')
np.dot(np.ones((100,1000)), np.zeros((1000,1000)))
for j in range(20):
np.dot(np.ones((100,1000)), np.zeros((1000,500)))
timer.summary()
for i in range(2):
any_function()
Output:
========Timing Summary of Default Timer========
block2:0.065062
block1:0.032529
========Timing Summary of Default Timer========
block2:0.065838
block1:0.032891
Hope it will help
As an alternative to hide()
mentioned in other answers, you can use css()
to set the display
value explicitly:
$("#msform").css("display","none")
It's the other way around: B.class.isInstance(view)
As of Ubuntu 20.04 with MySql 8.0 : the function PASSWORD
do not exists any more, hence the right way is:
login to mysql with sudo mysql -u root
change the password:
USE mysql; UPDATE user set authentication_string=NULL where User='root'; FLUSH privileges; ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'My-N7w_And.5ecure-P@s5w0rd'; FLUSH privileges; QUIT
now you should be able to login with mysql -u root -p
(or to phpMyAdmin with username root) and your chosen password.
P,S:
You can also login with user debian-sys-maint
, the password is in the file /etc/mysql/debian.cnf
you need quotes around the string in javascript
var htmlString="<?php echo $htmlString; ?>";
Strings are immutable in Python, which means you cannot change the existing string. But if you want to change any character in it, you could create a new string out it as follows,
def replace(s, position, character):
return s[:position] + character + s[position+1:]
replace('King', 1, 'o')
// result: Kong
Note: If you give the position value greater than the length of the string, it will append the character at the end.
replace('Dog', 10, 's')
// result: Dogs
I was doing some extensive mathematics with FORTRAN and C for a couple of years. From my own experience I can tell that FORTRAN is sometimes really better than C but not for its speed (one can make C perform as fast as FORTRAN by using appropriate coding style) but rather because of very well optimized libraries like LAPACK, and because of great parallelization. On my opinion, FORTRAN is really awkward to work with, and its advantages are not good enough to cancel that drawback, so now I am using C+GSL to do calculations.
In my case the problem occured from php
file.
It gave unwanted characters.That is why a json parsing
problem occured.
Then I paste my php code
in Notepad++
and select Encode in utf-8 without BOM
from Encoding
tab and running this code-
My problem gone away.
If PowerShell is open in a directory other than the target file, e.g.:
If someScript.ps1
is located here: C:\SlowLearner\some_missing_path\someScript.ps1
, then C:\SlowLearner>. ./someScript.ps1
wont work.
In that case, navigate to the path: cd some_missing_path
then this would work:
C:\SlowLearner\some_missing_path>. ./someScript.ps1
Yes, finally
will be called after the execution of the try
or catch
code blocks.
The only times finally
won't be called are:
System.exit()
Runtime.getRuntime().halt(exitStatus)
try
or catch
blockkill -9 <pid>
on UNIXfinally
block is going to be executed by a daemon thread and all other non-daemon threads exit before finally
is calledendstring = ''
for s in list:
endstring += s
Here are some methods that may help others, though they aren't really services as much as they may be described as "methods that may, after some torture of effort or logic, lead to a claim of on-demand access to Mac OS X" (no doubt I should patent that phrase).
Fundamentally, I am inclined to believe that on-demand (per-hour) hosting does not exist, and @Erik has given information for the shortest feasible services, i.e. monthly hosting.
It seems that one may use EC2 itself, but install OS X on the instance through a lot of elbow grease.
Where this gets tricky is I'm not sure if this will work for a cluster compute instance. In fact, I think this is likely to be a royal pain. A similar approach may work for Rackspace or other cloud services.
I found only this site claiming on-demand Mac hosting, with a Mac Mini. It doesn't look particularly accurate: it offers free on-demand access to a Mini if one pays for a month of bandwidth. That's like free bandwidth if one rents a Mini for a month. That's not really how "on-demand" works.
Update 1: In the end, it seems that nobody offers a comparable service. An outfit called Media Temple claims they will offer the first virtual servers using Parallels, OS X Leopard, and some other stuff (in other words, I wonder if there is some caveat that makes them unique, but, without that caveat, someone else may have a usable offering).
After this search, I think that a counterpart to EC2 does not exist for the OS X operating system. It is extraordinarily unlikely that one would exist, offer a scalable solution, and yet be very difficult to find. One could set it up internally, but there's no reseller/vendor offering on-demand, hourly virtual servers. This may be disappointing, but not surprising - apparently iCloud is running on Amazon and Microsoft systems.
this is pretty good as well
clear breaks
clear computes
Prompt
Prompt Tablespace Usage
Prompt
SET lines 120 pages 500
col percent_used format 999.99
SELECT a.TABLESPACE_NAME,
NVL(ROUND((a.BYTES /1024)/1024/1024,2),2) GB_TOTAL,
NVL(ROUND((b.BYTES /1024)/1024/1024,2),2) GB_FREE,
NVL(ROUND((b.largest/1024),2),0) KB_Chunk,
NVL(ROUND(((a.BYTES -NVL(b.BYTES,1))/a.BYTES)*100,4),0) percent_used
FROM
(SELECT TABLESPACE_NAME,
NVL(SUM(BYTES),0) BYTES
FROM dba_data_files
GROUP BY TABLESPACE_NAME
) a,
(SELECT TABLESPACE_NAME,
NVL(SUM(BYTES),1) BYTES ,
NVL(MAX(BYTES),1) largest
FROM dba_free_space
GROUP BY TABLESPACE_NAME
) b
WHERE a.TABLESPACE_NAME=b.TABLESPACE_NAME(+)
ORDER BY ((a.BYTES-b.BYTES)/a.BYTES) DESC;
output
TABLESPACE_NAME GB_TOTAL GB_FREE KB_CHUNK PERCENT_USED
------------------------------ ---------- ---------- ---------- ------------
SYSTEM .84 .02 9216 97.36
SYSAUX .57 .05 32768 91.10
UNDOTBS1 .06 .05 36864 23.13
USERS 0 0 4096 20.00
OK, I found it finally.
Key Event This document lists volume up as 24. The key code I was looking for is Alt-Menu and apparently it executes regardless of having the key intercepted.
Thanks to those those who took the time to reply.
Just start emulator by command line as follow:
emulator -avd <your avd name> -partition-size 1024 -wipe-data
Update your SP and handle exception in it using declare handler with get diagnostics so that you will know if there is an exception. e.g.
CREATE DEFINER=`root`@`localhost` PROCEDURE `validar_egreso`(
IN codigo_producto VARCHAR(100),
IN cantidad INT,
OUT valido INT(11)
)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
GET DIAGNOSTICS CONDITION 1
@p1 = RETURNED_SQLSTATE, @p2 = MESSAGE_TEXT;
SELECT @p1, @p2;
END
DECLARE resta INT(11);
SET resta = 0;
SELECT (s.stock - cantidad) INTO resta
FROM stock AS s
WHERE codigo_producto = s.codigo;
IF (resta > s.stock_minimo) THEN
SET valido = 1;
ELSE
SET valido = -1;
END IF;
SELECT valido;
END
I agree with micmdk.. I had a development environment setup with Push Notifications and needed a way to reset my phone to look like an initial install… and only these precise steps worked for me… requires TWO reboots of Device:
From APPLE TECH DOC:
Resetting the Push Notifications Permissions Alert on iOS The first time a push-enabled app registers for push notifications, iOS asks the user if they wish to receive notifications for that app. Once the user has responded to this alert it is not presented again unless the device is restored or the app has been uninstalled for at least a day.
If you want to simulate a first-time run of your app, you can leave the app uninstalled for a day. You can achieve the latter without actually waiting a day by following these steps:
Delete your app from the device.
Turn the device off completely and turn it back on.
Go to Settings > General > Date & Time and set the date ahead a day or more.
Turn the device off completely again and turn it back on.
Direct to remove the '\n' from the fgets output if every line has '\n'
line[strlen(line) - 1] = '\0';
Otherwise:
void remove_newline_ch(char *line)
{
int new_line = strlen(line) -1;
if (line[new_line] == '\n')
line[new_line] = '\0';
}
$ foo=${string#"$prefix"}
$ foo=${foo%"$suffix"}
$ echo "${foo}"
o-wor
This is documented in the Shell Parameter Expansion section of the manual:
${parameter#word}
${parameter##word}
The word is expanded to produce a pattern and matched according to the rules described below (see Pattern Matching). If the pattern matches the beginning of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the
#
case) or the longest matching pattern (the##
case) deleted. […]
${parameter%word}
${parameter%%word}
The word is expanded to produce a pattern and matched according to the rules described below (see Pattern Matching). If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the
%
case) or the longest matching pattern (the%%
case) deleted. […]
Probably better here for a regex replace
// Strip HTML Tags
$clear = strip_tags($des);
// Clean up things like &
$clear = html_entity_decode($clear);
// Strip out any url-encoded stuff
$clear = urldecode($clear);
// Replace non-AlNum characters with space
$clear = preg_replace('/[^A-Za-z0-9]/', ' ', $clear);
// Replace Multiple spaces with single space
$clear = preg_replace('/ +/', ' ', $clear);
// Trim the string of leading/trailing space
$clear = trim($clear);
Or, in one go
$clear = trim(preg_replace('/ +/', ' ', preg_replace('/[^A-Za-z0-9 ]/', ' ', urldecode(html_entity_decode(strip_tags($des))))));
Two options:
1: Add following code in the initialization Script:
if (function_exists('xdebug_disable')) {
xdebug_disable();
}
2: Add following flag to php.ini
xdebug.remote_autostart=0
xdebug.remote_enable=0
1st option is recommended.
Fixed-length arrays are not yet supported. What does that actually mean? Not that you can't create an array of n
many things — obviously you can just do let a = [ 1, 2, 3 ]
to get an array of three Int
s. It means simply that array size is not something that you can declare as type information.
If you want an array of nil
s, you'll first need an array of an optional type — [SKSpriteNode?]
, not [SKSpriteNode]
— if you declare a variable of non-optional type, whether it's an array or a single value, it cannot be nil
. (Also note that [SKSpriteNode?]
is different from [SKSpriteNode]?
... you want an array of optionals, not an optional array.)
Swift is very explicit by design about requiring that variables be initialized, because assumptions about the content of uninitialized references are one of the ways that programs in C (and some other languages) can become buggy. So, you need to explicitly ask for an [SKSpriteNode?]
array that contains 64 nil
s:
var sprites = [SKSpriteNode?](repeating: nil, count: 64)
This actually returns a [SKSpriteNode?]?
, though: an optional array of optional sprites. (A bit odd, since init(count:,repeatedValue:)
shouldn't be able to return nil.) To work with the array, you'll need to unwrap it. There's a few ways to do that, but in this case I'd favor optional binding syntax:
if var sprites = [SKSpriteNode?](repeating: nil, count: 64){
sprites[0] = pawnSprite
}
Here is a piece of code that has no dependency on an external COM object (WSH), and supports 32-bit and 64-bit programs:
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
namespace TestShortcut
{
class Program
{
static void Main(string[] args)
{
IShellLink link = (IShellLink)new ShellLink();
// setup shortcut information
link.SetDescription("My Description");
link.SetPath(@"c:\MyPath\MyProgram.exe");
// save it
IPersistFile file = (IPersistFile)link;
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
file.Save(Path.Combine(desktopPath, "MyLink.lnk"), false);
}
}
[ComImport]
[Guid("00021401-0000-0000-C000-000000000046")]
internal class ShellLink
{
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("000214F9-0000-0000-C000-000000000046")]
internal interface IShellLink
{
void GetPath([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile, int cchMaxPath, out IntPtr pfd, int fFlags);
void GetIDList(out IntPtr ppidl);
void SetIDList(IntPtr pidl);
void GetDescription([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, int cchMaxName);
void SetDescription([MarshalAs(UnmanagedType.LPWStr)] string pszName);
void GetWorkingDirectory([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszDir, int cchMaxPath);
void SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string pszDir);
void GetArguments([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszArgs, int cchMaxPath);
void SetArguments([MarshalAs(UnmanagedType.LPWStr)] string pszArgs);
void GetHotkey(out short pwHotkey);
void SetHotkey(short wHotkey);
void GetShowCmd(out int piShowCmd);
void SetShowCmd(int iShowCmd);
void GetIconLocation([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszIconPath, int cchIconPath, out int piIcon);
void SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, int iIcon);
void SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string pszPathRel, int dwReserved);
void Resolve(IntPtr hwnd, int fFlags);
void SetPath([MarshalAs(UnmanagedType.LPWStr)] string pszFile);
}
}
Declaration, generally, refers to the introduction of a new name in the program. For example, you can declare a new function by describing it's "signature":
void xyz();
or declare an incomplete type:
class klass;
struct ztruct;
and last but not least, to declare an object:
int x;
It is described, in the C++ standard, at §3.1/1 as:
A declaration (Clause 7) may introduce one or more names into a translation unit or redeclare names introduced by previous declarations.
A definition is a definition of a previously declared name (or it can be both definition and declaration). For example:
int x;
void xyz() {...}
class klass {...};
struct ztruct {...};
enum { x, y, z };
Specifically the C++ standard defines it, at §3.1/1, as:
A declaration is a definition unless it declares a function without specifying the function’s body (8.4), it contains the extern specifier (7.1.1) or a linkage-specification25 (7.5) and neither an initializer nor a function- body, it declares a static data member in a class definition (9.2, 9.4), it is a class name declaration (9.1), it is an opaque-enum-declaration (7.2), it is a template-parameter (14.1), it is a parameter-declaration (8.3.5) in a function declarator that is not the declarator of a function-definition, or it is a typedef declaration (7.1.3), an alias-declaration (7.1.3), a using-declaration (7.3.3), a static_assert-declaration (Clause 7), an attribute- declaration (Clause 7), an empty-declaration (Clause 7), or a using-directive (7.3.4).
Initialization refers to the "assignment" of a value, at construction time. For a generic object of type T
, it's often in the form:
T x = i;
but in C++ it can be:
T x(i);
or even:
T x {i};
with C++11.
So does it mean definition equals declaration plus initialization?
It depends. On what you are talking about. If you are talking about an object, for example:
int x;
This is a definition without initialization. The following, instead, is a definition with initialization:
int x = 0;
In certain context, it doesn't make sense to talk about "initialization", "definition" and "declaration". If you are talking about a function, for example, initialization does not mean much.
So, the answer is no: definition does not automatically mean declaration plus initialization.
This gets parent if it is a div. Then it gets class.
var div = $(this).parent("div");
var _class = div.attr("class");
Your code "for /f "tokens=* delims=" %%x in (a.txt) do echo %%x" will work on most Windows Operating Systems unless you have modified commands.
So you could instead "cd" into the directory to read from before executing the "for /f" command to follow out the string. For instance if the file "a.txt" is located at C:\documents and settings\%USERNAME%\desktop\a.txt then you'd use the following.
cd "C:\documents and settings\%USERNAME%\desktop"
for /f "tokens=* delims=" %%x in (a.txt) do echo %%x
echo.
echo.
echo.
pause >nul
exit
But since this doesn't work on your computer for x reason there is an easier and more efficient way of doing this. Using the "type" command.
@echo off
color a
cls
cd "C:\documents and settings\%USERNAME%\desktop"
type a.txt
echo.
echo.
pause >nul
exit
Or if you'd like them to select the file from which to write in the batch you could do the following.
@echo off
:A
color a
cls
echo Choose the file that you want to read.
echo.
echo.
tree
echo.
echo.
echo.
set file=
set /p file=File:
cls
echo Reading from %file%
echo.
type %file%
echo.
echo.
echo.
set re=
set /p re=Y/N?:
if %re%==Y goto :A
if %re%==y goto :A
exit
Its more likely that the path to file.js from the page is what is wrong. as long as when you view the page, and view-source you see the tag, its working, now its time to debug whether or not your path is too relative, maybe you need a / in front of it.
The CSS by Paulius Marciukaitis worked nicely for my Genesis theme, here's what how I further modified it for my requirement:
@media only screen and (max-width: 480px) {
.entry {
background-color: #fff;
margin-bottom: 0;
padding: 10px 8px;
}
yourproject
+- pom.xml
+- src
yourproject
+- pom.xml
+- src
+- repo
mvn deploy:deploy-file -Durl=file:///pathtoyour/repo -Dfile=your.jar -DgroupId=your.group.id -DartifactId=yourid -Dpackaging=jar -Dversion=1.0
mvn install:install-file -Dfile=/path-to-your-jar-1.0.jar -DpomFile=/path-to-your-pom-1.0.pom
<repositories>
<!--other repositories if any-->
<repository>
<id>project.local</id>
<name>project</name>
<url>file:${project.basedir}/repo</url>
</repository>
</repositories>
<dependency>
<groupId>com.groupid</groupId>
<artifactId>myid</artifactId>
<version>1.0</version>
</dependency>
Best & Recommended way to set App Icon in Flutter.
I found one plugin to set app icon in flutter named flutter_launcher_icons. We can use this plugin to set the app icon in flutter.
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^0.1.2
flutter_launcher_icons: ^0.7.2+1**
Save the file and run flutter pub get on terminal.
Create a folder assets in the root of the project in folder assets also create a folder icon and place your app icon inside this folder. I will recommend to user 1024x1024 app icon size. I have placed app icon inside icon folder and now I have app icon path as assets/icon/icon.png
Now, in pubspec.yaml add the below code,
flutter_icons:
android: "launcher_icon"
ios: true
image_path: "assets/icon/icon.png"
flutter pub run flutter_launcher_icons:main -f pubspec.yaml
Then Run App
5000 lines isn't big (well, depends on how long the lines are...)
Anyway: assuming the string will be a word and will be seperated by whitespace...
lines=open(file_path,'r').readlines()
str_wanted="whatever_youre_looking_for"
for i in range(len(lines)):
l1=lines.split()
for p in range(len(l1)):
if l1[p]==str_wanted:
#found
# i is the file line, lines[i] is the full line, etc.
For Ubuntu 17.0 +
Adding to @netcoder answer above, If you are using Ubuntu 17+, installing libcurl header files is half of the solution. The installation path in ubuntu 17.0+ is different than the installation path in older Ubuntu version. After installing libcurl, you will still get the "cURL not found" error. You need to perform one extra step (as suggested by @minhajul in the OP comment section).
Add a symlink in /usr/include of the cURL installation folder (cURL installation path in Ubuntu 17.0.4 is /usr/include/x86_64-linux-gnu/curl).
My server was running Ubuntu 17.0.4, the commands to enable cURL support were
sudo apt-get install libcurl4-gnutls-dev
Then create a link to cURL installation
cd /usr/include
sudo ln -s x86_64-linux-gnu/curl
I wanted something pretty close to this - the moment a user picks an item, even by just hitting the arrow keys to one (focus), I want that data item attached to the tag in question. When they type again without picking another item, I want that data cleared.
(function() {
var lastText = '';
$('#MyTextBox'), {
source: MyData
})
.on('autocompleteselect autocompletefocus', function(ev, ui) {
lastText = ui.item.label;
jqTag.data('autocomplete-item', ui.item);
})
.keyup(function(ev) {
if (lastText != jqTag.val()) {
// Clear when they stop typing
jqTag.data('autocomplete-item', null);
// Pass the event on as autocompleteclear so callers can listen for select/clear
var clearEv = $.extend({}, ev, { type: 'autocompleteclear' });
return jqTag.trigger(clearEv);
});
})();
With this in place, 'autocompleteselect' and 'autocompletefocus' still fire right when you expect, but the full data item that was selected is always available right on the tag as a result. 'autocompleteclear' now fires when that selection is cleared, generally by typing something else.
On a Python version where dicts actually are ordered, you can do
my_dict = {'foo': 'bar', 'spam': 'eggs'}
next(iter(my_dict)) # outputs 'foo'
For dicts to be ordered, you need Python 3.7+, or 3.6+ if you're okay with relying on the technically-an-implementation-detail ordered nature of dicts on Python 3.6.
For earlier Python versions, there is no "first key".
If you are using jupyter notebook Try:
!python --version
If you are using terminal Try:
python --version
200
Ugh... (309, 400, 403, 409, 415, 422)... a lot of answers trying to guess, argue and standardize what is the best return code for a successful HTTP request but a failed REST call.
It is wrong to mix HTTP status codes and REST status codes.
However, I saw many implementations mixing them, and many developers may not agree with me.
HTTP return codes are related to the HTTP Request
itself. A REST call is done using a Hypertext Transfer Protocol request and it works at a lower level than invoked REST method itself. REST is a concept/approach, and its output is a business/logical result, while HTTP result code is a transport one.
For example, returning "404 Not found" when you call /users/ is confuse, because it may mean:
"403 Forbidden/Access Denied" may mean:
And the list may continue with '500 Server error" (an Apache/Nginx HTTP thrown error or a business constraint error in REST) or other HTTP errors etc...
From the code, it's hard to understand what was the failure reason, a HTTP (transport) failure or a REST (logical) failure.
If the HTTP request physically was performed successfully it should always return 200 code, regardless is the record(s) found or not. Because URI resource is found and was handled by the HTTP server. Yes, it may return an empty set. Is it possible to receive an empty web-page with 200 as HTTP result, right?
Instead of this you may return 200 HTTP code with some options:
Also, some internet providers may intercept your requests and return you a 404 HTTP code. This does not means that your data are not found, but it's something wrong at transport level.
From Wiki:
In July 2004, the UK telecom provider BT Group deployed the Cleanfeed content blocking system, which returns a 404 error to any request for content identified as potentially illegal by the Internet Watch Foundation. Other ISPs return a HTTP 403 "forbidden" error in the same circumstances. The practice of employing fake 404 errors as a means to conceal censorship has also been reported in Thailand and Tunisia. In Tunisia, where censorship was severe before the 2011 revolution, people became aware of the nature of the fake 404 errors and created an imaginary character named "Ammar 404" who represents "the invisible censor".
Why not simply answer with something like this?
{
"result": false,
"error": {"code": 102, "message": "Validation failed: Wrong NAME."}
}
Google always returns 200 as status code in their Geocoding API, even if the request logically fails: https://developers.google.com/maps/documentation/geocoding/intro#StatusCodes
Facebook always return 200 for successful HTTP requests, even if REST request fails: https://developers.facebook.com/docs/graph-api/using-graph-api/error-handling
It's simple, HTTP status codes are for HTTP requests. REST API is Your, define Your status codes.
You can use a goto
to skip over code.
goto comment
...skip this...
:comment
Remember that by default the return value from the input will be a string and not an integer. You cannot compare strings with booleans like <, >, =>, <= (unless you are comparing the length). Therefore your code should look like this:
number = 23
guess = int(input('Enter a number: ')) # The var guess will be an integer
if guess == number:
print('Congratulations! You guessed it.')
elif guess != number:
print('Wrong Number')
This can be caused by App ID prefix, when you switching different developer accounts. See https://developer.apple.com/library/content/technotes/tn2311/_index.html for Apple's support.
With Go 1.5 they seem to have improved the cross compilation process, meaning it is built in now. No ./make.bash
-ing or brew
-ing required. The process is described here but for the TLDR-ers (like me) out there: you just set the GOOS
and the GOARCH
environment variables and run the go build.
For the even lazier copy-pasters (like me) out there, do something like this if you're on a *nix system:
env GOOS=linux GOARCH=arm go build -v github.com/path/to/your/app
You even learned the env
trick, which let you set environment variables for that command only, completely free of charge.
In the specific case of react-router
, using context
is a valid case scenario, e.g.
class MyComponent extends React.Component {
props: PropsType;
static contextTypes = {
router: PropTypes.object
};
render () {
this.context.router;
}
}
You can access an instance of the history via the router context, e.g. this.context.router.history
.
- Create a Class
with public static final
fields.
- And then you can access these fields from any class using the Class_Name.Field_Name
.
- You can declare the class
as final
, so that the class
can't be extended(Inherited) and modify....
datetime.replace() will provide the best options. Also, it provides facility for replacing day, year, and month.
Suppose we have a datetime
object and date is represented as:
"2017-05-04"
>>> from datetime import datetime
>>> date = datetime.strptime('2017-05-04',"%Y-%m-%d")
>>> print(date)
2017-05-04 00:00:00
>>> date = date.replace(minute=59, hour=23, second=59, year=2018, month=6, day=1)
>>> print(date)
2018-06-01 23:59:59
windowSoftInputMode will either pan or resize your activity layout. One thing that you can do is to attach an onFocusChanged listener to your EditText and when the user selects/taps the EditText then you hide or move your navigation buttons out of the screen. When the EditText loses focus then you can put the navigation buttons back at the bottom of the activity.
There are multiple libraries on SVG graphics using Javascript like: Snap, Raphael, D3. Or you can directly interface the SVG with plain javascript.
Currently all latest versions of the browsers support SVG v1.1. SVG v2.0 is in Working Draft and too early to use it.
This article shows how to interact with SVG using Javascript and has reference to links for browser support. Interfacing with SVG
Instead of style changes, just put these two lines of code to your activity.
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.arrowleft);
For a line in a pull request.
https://github.com/foo/bar/pull/90/files#diff-ce6bf647d5a531e54ef0502c7fe799deR27
https://github.com/foo/bar/pull/
90 <- PR number
/files#diff-
ce6bf647d5a531e54ef0502c7fe799de <- MD5 has of file name from repo root
R <- Which side of the diff to reference (merge-base or head). Can be L or R.
27 <- Line number
This will take you to a line as long as L and R are correct. I am not sure if there is a way to visit L OR R. I.e If the PR adds a line you must use R
. If it removes a line you must use L
.
If you are converting html to pdf on the html server side you can use Rotativa :
Install-Package Rotativa
This is based on wkhtmltopdf but it has better css support than iTextSharp has and is very simple to integrate with MVC (which is mostly used) as you can simply return the view as pdf:
public ActionResult GetPdf()
{
//...
return new ViewAsPdf(model);// and you are done!
}
Late answer, I know but I too wanted this so I could log the SQL. The following is short and meets my needs.
The following produces SQL you can copy/paste in SSMS (it replaces the parameters with the values properly). You can add more types but this meets all I use in this case.
private static void LogSQL(SqlCommand cmd)
{
string query = cmd.CommandText;
foreach (SqlParameter prm in cmd.Parameters)
{
switch (prm.SqlDbType)
{
case SqlDbType.Bit:
int boolToInt = (bool)prm.Value ? 1 : 0;
query = query.Replace(prm.ParameterName, string.Format("{0}", (bool)prm.Value ? 1 : 0));
break;
case SqlDbType.Int:
query = query.Replace(prm.ParameterName, string.Format("{0}", prm.Value));
break;
case SqlDbType.VarChar:
query = query.Replace(prm.ParameterName, string.Format("'{0}'", prm.Value));
break;
default:
query = query.Replace(prm.ParameterName, string.Format("'{0}'", prm.Value));
break;
}
}
// the following is my how I write to my log - your use will vary
logger.Debug("{0}", query);
return;
}
Now I can log the SQL just before I execute it:
LogSQL(queryCmd)
queryCmd.ExecuteNonQuery()
Those are great answers in this thread. In order to better show the difference, here is just an example. The reason I put it here b/c during my work the numbers are required to be NOT half-up :
import org.apache.spark.sql.types._
val values = List(1.2345,2.9998,3.4567,4.0099,5.1231)
val df = values.toDF
df.show()
+------+
| value|
+------+
|1.2345|
|2.9998|
|3.4567|
|4.0099|
|5.1231|
+------+
val df2 = df.withColumn("floor_val", floor(col("value"))).
withColumn("dec_val", col("value").cast(DecimalType(26,2))).
withColumn("floor2", (floor(col("value") * 100.0)/100.0).cast(DecimalType(26,2)))
df2.show()
+------+---------+-------+------+
| value|floor_val|dec_val|floor2|
+------+---------+-------+------+
|1.2345| 1| 1.23| 1.23|
|2.9998| 2| 3.00| 2.99|
|3.4567| 3| 3.46| 3.45|
|4.0099| 4| 4.01| 4.00|
|5.1231| 5| 5.12| 5.12|
+------+---------+-------+------+
floor
function floors to the largest interger less than current value. DecimalType
by default will enable HALF_UP
mode, not just cut to precision you want. If you want to cut to a certain precision without using HALF_UP
mode, you can use above solution instead ( or use scala.math.BigDecimal
(where you have to explicitly define rounding modes).
You can still use NSLog in Swift as in Objective-C just without the @ sign.
NSLog("%.02f %.02f %.02f", r, g, b)
Edit: After working with Swift since a while I would like to add also this variation
var r=1.2
var g=1.3
var b=1.4
NSLog("\(r) \(g) \(b)")
Output:
2014-12-07 21:00:42.128 MyApp[1626:60b] 1.2 1.3 1.4
Go to the folder where Python is installed, e.g., in my case (Mac OS) it is installed in the Applications folder with the folder name 'Python 3.6'. Now double click on 'Install Certificates.command'. You will no longer face this error.
For those not running a mac, or having a different setup and can't find this file, the file merely runs:
pip install --upgrade certifi
Hope that helps someone :)
You can also use
lblExamlple.ForeColor = System.Drawing.Color.FromArgb(0,255,0);
If the numeric values are seq indexes, then we could have simpler ways... Here's my code submission, My Ruby is a bit rusty
input = ["cat", 1, "dog", 2, "wombat", 3]
hash = Hash.new
input.each_with_index {|item, index|
if (index%2 == 0) hash[item] = input[index+1]
}
hash #=> {"cat"=>1, "wombat"=>3, "dog"=>2}
It is completely fine to leave memory unfreed when you exit; malloc() allocates the memory from the memory area called "the heap", and the complete heap of a process is freed when the process exits.
That being said, one reason why people still insist that it is good to free everything before exiting is that memory debuggers (e.g. valgrind on Linux) detect the unfreed blocks as memory leaks, and if you have also "real" memory leaks, it becomes more difficult to spot them if you also get "fake" results at the end.
(Using Web Forms ASP.NET)
My issue was I was trying to fire Ajax off the click event of a submit button that had a server side click event setup. I had to make the button just a simple button (i.e. <input type="button">
)
Interfaces cannot require instance variables to be defined -- only methods.
(Variables can be defined in interfaces, but they do not behave as might be expected: they are treated as final static
.)
Happy coding.
You can get free Virtual Machine and many more things online for 3 months provided by Microsoft Azure. I guess you need VPN for learning purpose. For that it would suffice.
Fastest approach, if you need to perform more than just one or two such removal operations (or even just one, but on a very long string!-), is to rely on the translate
method of strings, even though it does need some prep:
>>> import string
>>> allchars = ''.join(chr(i) for i in xrange(256))
>>> identity = string.maketrans('', '')
>>> nondigits = allchars.translate(identity, string.digits)
>>> s = 'abc123def456'
>>> s.translate(identity, nondigits)
'123456'
The translate
method is different, and maybe a tad simpler simpler to use, on Unicode strings than it is on byte strings, btw:
>>> unondig = dict.fromkeys(xrange(65536))
>>> for x in string.digits: del unondig[ord(x)]
...
>>> s = u'abc123def456'
>>> s.translate(unondig)
u'123456'
You might want to use a mapping class rather than an actual dict, especially if your Unicode string may potentially contain characters with very high ord values (that would make the dict excessively large;-). For example:
>>> class keeponly(object):
... def __init__(self, keep):
... self.keep = set(ord(c) for c in keep)
... def __getitem__(self, key):
... if key in self.keep:
... return key
... return None
...
>>> s.translate(keeponly(string.digits))
u'123456'
>>>
A regular expression can be used to offer more control over the whitespace characters that are combined.
To match unicode whitespace:
import re
_RE_COMBINE_WHITESPACE = re.compile(r"\s+")
my_str = _RE_COMBINE_WHITESPACE.sub(" ", my_str).strip()
To match ASCII whitespace only:
import re
_RE_COMBINE_WHITESPACE = re.compile(r"(?a:\s+)")
_RE_STRIP_WHITESPACE = re.compile(r"(?a:^\s+|\s+$)")
my_str = _RE_COMBINE_WHITESPACE.sub(" ", my_str)
my_str = _RE_STRIP_WHITESPACE.sub("", my_str)
Matching only ASCII whitespace is sometimes essential for keeping control characters such as x0b, x0c, x1c, x1d, x1e, x1f.
About \s
:
For Unicode (str) patterns: Matches Unicode whitespace characters (which includes [ \t\n\r\f\v], and also many other characters, for example the non-breaking spaces mandated by typography rules in many languages). If the ASCII flag is used, only [ \t\n\r\f\v] is matched.
About re.ASCII
:
Make \w, \W, \b, \B, \d, \D, \s and \S perform ASCII-only matching instead of full Unicode matching. This is only meaningful for Unicode patterns, and is ignored for byte patterns. Corresponds to the inline flag (?a).
strip()
will remote any leading and trailing whitespaces.
How can I protect all the app's resources, assets and source code so that hackers can't hack the APK file in any way?
An APK file is protected with the SHA-1 algorithm. You can see some files in the META-INF folder of APK. If you extract any APK file and change any of its content and zip it again and when you run that new APK file on an Android machine, it will not work, because the SHA-1 hashes will never match.
Use parentheses:
data(2)
But you don't really want to do that with lists very often, since linked lists take time to traverse. If you want to index into a collection, use Vector
(immutable) or ArrayBuffer
(mutable) or possibly Array
(which is just a Java array, except again you index into it with (i)
instead of [i]
).
Not a direct answer, but I've seen many borked prod data situations that could have been avoided by typing the WHERE
clause first! Sometimes a WHERE 1 = 0
can help with putting a working statement together safely too. And looking at an estimated execution plan, which will estimate rows affected, can be useful. Beyond that, in a transaction that you roll back as others have said.
You have two records in your json file, and json.loads()
is not able to decode more than one. You need to do it record by record.
See Python json.loads shows ValueError: Extra data
OR you need to reformat your json to contain an array:
{
"foo" : [
{"name": "XYZ", "address": "54.7168,94.0215", "country_of_residence": "PQR", "countries": "LMN;PQRST", "date": "28-AUG-2008", "type": null},
{"name": "OLMS", "address": null, "country_of_residence": null, "countries": "Not identified;No", "date": "23-FEB-2017", "type": null}
]
}
would be acceptable again. But there cannot be several top level objects.
Run this:
init = tf.global_variables_initializer()
sess.run(init)
Or (depending on the version of TF that you have):
init = tf.initialize_all_variables()
sess.run(init)
if you just need a timestamp in unix /epoch time, this one line works:
created_timestamp = int((datetime.datetime.now() - datetime.datetime(1970,1,1)).total_seconds())
>>> created_timestamp
1522942073L
and depends only on datetime
works in python2 and python3
Not all cultures use the same format for dates and decimal / currency values.
This will matter for you when you are converting input values (read) that are stored as strings to DateTime
, float
, double
or decimal
. It will also matter if you try to format the aforementioned data types to strings (write) for display or storage.
If you know what specific culture that your dates and decimal / currency values will be in ahead of time, you can use that specific CultureInfo
property (i.e. CultureInfo("en-GB")
). For example if you expect a user input.
The CultureInfo.InvariantCulture
property is used if you are formatting or parsing a string that should be parseable by a piece of software independent of the user's local settings.
The default value is CultureInfo.InstalledUICulture
so the default CultureInfo is depending on the executing OS's settings. This is why you should always make sure the culture info fits your intention (see Martin's answer for a good guideline).
The validate_required function seems to expect an HTML form control (e.g, text input field) as first argument, and check whether there is a value there at all. That is not what you want in this case.
Also, when you write ['password'].value
, you create a new array of length one, containing the string
'password'
, and then read the non-existing property "value"
from it, yielding the undefined value.
What you may want to try instead is:
if (password.value != cpassword.value) { cpassword.focus(); return false; }
(You also need to write the error message somehow, but I can't see from your code how that is done.).
The Web Site project is compiled on the fly. You end up with a lot more DLL files, which can be a pain. It also gives problems when you have pages or controls in one directory that need to reference pages and controls in another directory since the other directory may not be compiled into the code yet. Another problem can be in publishing.
If Visual Studio isn't told to re-use the same names constantly, it will come up with new names for the DLL files generated by pages all the time. That can lead to having several close copies of DLL files containing the same class name, which will generate plenty of errors. The Web Site project was introduced with Visual Studio 2005, but it has turned out not to be popular.
The Web Application Project was created as an add-in and now exists as part of SP 1 for Visual Studio 2005. The main differences are the Web Application Project was designed to work similarly to the Web projects that shipped with Visual Studio 2003. It will compile the application into a single DLL file at build time. To update the project, it must be recompiled and the DLL file published for changes to occur.
Another nice feature of the Web Application project is it's much easier to exclude files from the project view. In the Web Site project, each file that you exclude is renamed with an excluded keyword in the filename. In the Web Application Project, the project just keeps track of which files to include/exclude from the project view without renaming them, making things much tidier.
The article ASP.NET 2.0 - Web Site vs Web Application project also gives reasons on why to use one and not the other. Here is an excerpt of it:
- You need to migrate large Visual Studio .NET 2003 applications to VS 2005? use the Web Application project.
- You want to open and edit any directory as a Web project without creating a project file? use Web Site project.
- You need to add pre-build and post-build steps during compilation? use Web Application project.
- You need to build a Web application using multiple Web projects? use the Web Application project.
- You want to generate one assembly for each page? use the Web Site project.
- You prefer dynamic compilation and working on pages without building entire site on each page view? use Web Site project.
- You prefer single-page code model to code-behind model? use Web Site project.
Web Application Projects versus Web Site Projects (MSDN) explains the differences between the web site and web application projects. Also, it discusses the configuration to be made in Visual Studio.
if you want to store current date in table so you can use
GETDATE();
or pass this function as a parameter
eg. 'update tblname set curdate=GETDATE() where colname=123'
In this case, it is safe to cast away the unsigned portion unless your vector can get REALLY big.
I would pull out the where.size() to a local variable since it won't change during the call. Something like this:
int find( const vector<type>& where, int searchParameter ){
int size = static_cast<int>(where.size());
for( int i = 0; i < size; i++ ) {
if( conditionMet( where[i], searchParameter ) ) {
return i;
}
}
return -1;
}
In newer versions change was made to the flags: from the documentation:
--extended-insert, -e
Write INSERT statements using multiple-row syntax that includes several VALUES lists. This results in a smaller dump file and speeds up inserts when the file is reloaded.
--opt
This option, enabled by default, is shorthand for the combination of --add-drop-table --add-locks --create-options --disable-keys --extended-insert --lock-tables --quick --set-charset. It gives a fast dump operation and produces a dump file that can be reloaded into a MySQL server quickly.
Because the --opt option is enabled by default, you only specify its converse, the --skip-opt to turn off several default settings. See the discussion of mysqldump option groups for information about selectively enabling or disabling a subset of the options affected by --opt.
--skip-extended-insert
Turn off extended-insert
To answer the question "how can I find out if a given index in that dict has already been set to a non-None value", I would prefer this:
try:
nonNone = my_dict[key] is not None
except KeyError:
nonNone = False
This conforms to the already invoked concept of EAFP (easier to ask forgiveness then permission). It also avoids the duplicate key lookup in the dictionary as it would in key in my_dict and my_dict[key] is not None
what is interesting if lookup is expensive.
For the actual problem that you have posed, i.e. incrementing an int if it exists, or setting it to a default value otherwise, I also recommend the
my_dict[key] = my_dict.get(key, default) + 1
as in the answer of Andrew Wilkinson.
There is a third solution if you are storing modifyable objects in your dictionary. A common example for this is a multimap, where you store a list of elements for your keys. In that case, you can use:
my_dict.setdefault(key, []).append(item)
If a value for key does not exist in the dictionary, the setdefault method will set it to the second parameter of setdefault. It behaves just like a standard my_dict[key], returning the value for the key (which may be the newly set value).
There's also ShortGuid - A shorter and url friendly GUID class in C#. It's available as a Nuget. More information here.
PM> Install-Package CSharpVitamins.ShortGuid
Usage:
Guid guid = Guid.NewGuid();
ShortGuid sguid1 = guid; // implicitly cast the guid as a shortguid
Console.WriteLine(sguid1);
Console.WriteLine(sguid1.Guid);
This produces a new guid, uses that guid to create a ShortGuid, and displays the two equivalent values in the console. Results would be something along the lines of:
ShortGuid: FEx1sZbSD0ugmgMAF_RGHw
Guid: b1754c14-d296-4b0f-a09a-030017f4461f
res.setHeader('Access-Control-Allow-Headers',
'Access-Control-Allow-Headers, Origin,OPTIONS,Accept,Authorization, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers');
Blockquote : you have to add OPTIONS & Authorization to the setHeader()
this change has fixed my problem, just give a try!
if ( typeof variableName !== 'undefined' && variableName )
//// could throw an error if var doesnt exist at all
if ( window.variableName )
//// could be true if var == 0
////further on it depends on what is stored into that var
// if you expect an object to be stored in that var maybe
if ( !!window.variableName )
//could be the right way
best way => see what works for your case
I interpreted the question as using cast on a subquery. Yes, you can do that:
select cast((<subquery>) as <newtype>)
If you do so, then you need to be sure that the returns one row and one value. And, since it returns one value, you could put the cast in the subquery instead:
select (select cast(<val> as <newtype>) . . .)
Thank you Hero Editor example, where I found the correct definition:
When I generate app routing module:
ng generate module app-routing --flat --module=app
and update the app-routing.ts file to add:
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
Here are the full example:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';
import { HeroesComponent } from './heroes/heroes.component';
import { HeroDetailComponent } from './hero-detail/hero-detail.component';
const routes: Routes = [
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
{ path: 'dashboard', component: DashboardComponent },
{ path: 'detail/:id', component: HeroDetailComponent },
{ path: 'heroes', component: HeroesComponent }
];
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
and add AppRoutingModule into app.module.ts imports:
@NgModule({
declarations: [
AppComponent,
...
],
imports: [
BrowserModule,
FormsModule,
AppRoutingModule
],
providers: [...],
bootstrap: [AppComponent]
})
Hooks are composable, and since React Router v5.1 we have a useHistory()
hook. So based off @zurfyx's answer I've created a re-usable hook for this functionality:
// useScrollTop.ts
import { useHistory } from 'react-router-dom';
import { useEffect } from 'react';
/*
* Registers a history listener on mount which
* scrolls to the top of the page on route change
*/
export const useScrollTop = () => {
const history = useHistory();
useEffect(() => {
const unlisten = history.listen(() => {
window.scrollTo(0, 0);
});
return unlisten;
}, [history]);
};
int index= datagridview.rows.add();
datagridview.rows[index].cells[1].value=1;
datagridview.rows[index].cells[2].value="a";
datagridview.rows[index].cells[3].value="b";
hope this help! :)
There is no requirement of setting CATALINA-HOME.
Follow below instruction .
Right click on computer --> properties --> Advanced system setting --> Environment variables.
User variables section --> click on "New" --> variable name : CLASSPATH , variable value : D:\java\lib*.;D:\tomcat8\lib\servlet-api.jar.; --> Click "Ok"
New --> variable name : PATH , variable value : D:\java\bin; --> Click "Ok"
System variables section:-
Click on "New" --> variable name : PATH , variable value : D:\java\jre --> Click "Ok"
I've installed java and tomcat in D drive henceforth the locations above are under my respective paths.
Give location paths where java and tomcat are installed in your PC. Thank You
That's because you have the Date in American format in line[i]
and UK format in the FormatString
.
11/20/2011
M / d/yyyy
I'm guessing you might need to change the FormatString to:
"M/d/yyyy h:mm"
There is a batch file called resetroot.bat
located in the xammp folders 'C:\xampp\mysql' run this and it will delete the phpmyadmin
passwords. Then all you need to do is start the MySQL
service in xamp
and click the admin button.
I've seen
anEvent.isPopupTrigger()
be used before. I'm fairly new to Java so I'm happy to hear thoughts about this approach :)
Disagree with the suggested answer. The short answer is: NO.
The purpose of the primary key is to uniquely identify a row on the table in order to form a relationship with another table. Traditionally, an auto-incremented integer value is used for this purpose, but there are variations to this.
There are cases though, for example logging time-series data, where the existence of a such key is simply not needed and just takes up memory. Making a row unique is simply ...not required!
A small example: Table A: LogData
Columns: DateAndTime, UserId, AttribA, AttribB, AttribC etc...
No Primary Key needed.
Table B: User
Columns: Id, FirstName, LastName etc.
Primary Key (Id) needed in order to be used as a "foreign key" to LogData table.
The test has to be done on a page that queries a database so yes typically that is a login page because it's the page that can do the most harm but could be an unsecure page as well.
Generally you would have your database queries behind a secure login but if you just have a listing of items or something that you don't care if the world sees a hacker could append some sql injection to the end of the querystring.
The key with SQL Injection is the person doing the injection would have to know that your querying a database so if your not querying a database then no sql inject can be done. If your form is submitting to a database then yes they could SQL Inject that. It's always good practice to use either stored procedures to select/insert/update/delete or make sure you prepare or escape out all the statements that will be hitting the database.
Did you try
for line in open("masters", "r").readlines(): print line
?
readline()
only reads "a line", on the other hand
readlines()
reads whole lines and gives you a list of all lines.
Thank goodness I found this. The following is extremely important:
<meta http-equiv="X-UA-Compatible" content="IE=9" >
Without this, none of the reports I'd been generating would work post IE9 install despite having worked great in IE8. They would show up properly in a web browser control, but there would be missing letters, jacked up white space, etc, when I called .Print(). They were just basic HTML that should be capable of being rendered even in Mosaic. heh Not sure why the IE7 compatibility mode was going haywire. Notably, you could .Print() the same page 5 times and have it be missing different letters each time. It would even carry over into PDF output, so it's definitely the browser.
std::vector<std::string> parse(std::string str,std::string delim){
std::vector<std::string> tokens;
char *str_c = strdup(str.c_str());
char* token = NULL;
token = strtok(str_c, delim.c_str());
while (token != NULL) {
tokens.push_back(std::string(token));
token = strtok(NULL, delim.c_str());
}
delete[] str_c;
return tokens;
}
You should check for !test
, here is a fiddle showing that.
<span ng-if="!test">null</span>
Check eclipse.ini, there are two entries like:
-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.200.v20120913-144807
For some twisted reason jars have version in their name - so if you upgrade/have two different version of eclipse( while eclipse.ini is either linked or provided as system wide conf file for eclipse ) it will cause above error.
<a href="/">Clicking me refreshes the page</a>
<a href="?">Click Me To Reload the page</a>
Just an addition to what Greg said:
$("#whatever").offset().left + $("#whatever").outerWidth()
This code will get the right position relative to the left side. If the intention was to get the right side position relative to the right (like when using the CSS right
property) then an addition to the code is necessary as follows:
$("#parent_container").innerWidth() - ($("#whatever").offset().left + $("#whatever").outerWidth())
This code is useful in animations where you have to set the right side as a fixed anchor when you can't initially set the right
property in CSS.
Using data.frame
instead of cbind
should be helpful
x <- data.frame(col1=c(10, 20), col2=c("[]", "[]"), col3=c("[[1,2]]","[[1,3]]"))
x
col1 col2 col3
1 10 [] [[1,2]]
2 20 [] [[1,3]]
sapply(x, class) # looking into x to see the class of each element
col1 col2 col3
"numeric" "factor" "factor"
As you can see elements from col1 are numeric
as you wish.
data.frame
can have variables of different class
: numeric
, factor
and character
but matrix
doesn't, once you put a character
element into a matrix all the other will become into this class no matter what clase they were before.
Run this Command
alter user myuser with superuser;
If you want to see the permission to a user run following command
\du
android:background="#E1E1E1"
// background add in layout
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ffffff">
</EditText>
Changing the 'w' (write) in this line:
output = csv.DictWriter(open('file3.csv','w'), delimiter=',', fieldnames=headers)
To 'wb' (write binary) fixed this problem for me:
output = csv.DictWriter(open('file3.csv','wb'), delimiter=',', fieldnames=headers)
Credit to @dandrejvv for the solution in the comment on the original post above.
The following is equivalent to your second code block:
var f = function () {
//Some logic here...
};
var fr = f;
fr(pars);
If you want to actually pass a reference to a function to some other function, you can do something like this:
function fiz(x, y, z) {
return x + y + z;
}
// elsewhere...
function foo(fn, p, q, r) {
return function () {
return fn(p, q, r);
}
}
// finally...
f = foo(fiz, 1, 2, 3);
f(); // returns 6
You're almost certainly better off using a framework for this sort of thing, though.
While submitting form use reset method on form. The reset() method resets the values of all elements in a form.
$('#form-id')[0].reset();
OR
document.getElementById("form-id").reset();
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reset
$("#submit-button").on("click", function(){_x000D_
//code here_x000D_
$('#form-id')[0].reset();_x000D_
});
_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<form id="form-id">_x000D_
First name:<br>_x000D_
<input type="text" name="firstname">_x000D_
<br>_x000D_
Last name:<br>_x000D_
<input type="text" name="lastname">_x000D_
<br><br>_x000D_
<input id="submit-button" type="submit" value="Submit">_x000D_
</form> _x000D_
</body>_x000D_
</html>
_x000D_
FWIW, in case anyone revisits this question later, you might also check what you are handing to your onKeyPress handler function.
I ran into this error when I mistakenly passed onKeyPress(this) instead of onKeyPress(event).
Just something else to check.
Use the eq selector to selct the nth row (0-based) and add your row after it using after, so:
$('#my_table > tbody:last tr:eq(2)').after(html);
where html is a tr
Go inside your phpMyAdmin directory inside XAMPP installation folder. There will be a file called config.inc.php. Inside that file, find this line:
$cfg['Servers'][$i]['password'] = '';
you must make sure that this field has your mysql root password (the one that you set).
Thankfully, ECMA 5 introduced Array.isArray()
back in December 2009. If for some reason, you are using a version of JavaScript older than ECMA 5, please upgrade.
If you insist on it, though, then arrays do have certain properties that differentiate them from any other type. Properties that I haven't seen mentioned in any of the other answers. Let's get into some JavaScript politics.
An array is an object (typeof [] === "object"
), but unlike traditional objects, they have a length property (typeof ( {} ).length === "undefined"
). null
is also an object (typeof null === "object"
), but you can't access a property of null
because null
is not an object. This is a bug in the spec that goes all the way back to the very beginning of JavaScript, when objects had the type tag 0
and null
was represented as a literal null pointer 0x00
, which caused the interpreter to confuse it with objects.
Unfortunately, this doesn't account for []
vs {length:0}
. So we must now turn to the prototype chain.
( [] ).__proto__ === Array.prototype && ( [] ).__proto__ !== Object.prototype
.
Thus, without Array.isArray()
, this is just about the closest we can get:
function is_array(array){
return array !== null
&& typeof array === "object"
&& array.__proto__ === Array.prototype;
}
[ [], [1,2,3], {length: 0}, {},
1, 0, Infinity, NaN, "1", "[1,2,3]",
null, undefined, [null], [undefined], {a:[]},
[{}], [{length: 0}], [Infinity], [NaN],
{__proto__: Array.prototype}
].filter(is_array)
// Expected: [ [], [1,2,3], [null], [undefined], [{}], [{length: 0}], [Infinity], [NaN] ]
// Actual: [ [], [1,2,3], [null], [undefined], [{}], [{length: 0}], [Infinity], [NaN], {__proto__: Array.prototype} ]
The object maliciously designed to look just like an array actually passes the turing test. However, replacing the prototype chain with the Array prototype chain is enough to make it act just like an array, effectively making it an array. The only thing in the world that can tell such an object is actually not an array, is Array.isArray()
. But for the purposes you would usually be checking if an object is an array, said object should play nice with your code. Even the behavior when you change the length of the array artificially is the same: if the length is longer than the number of elements in the array, you WILL have "empty slots" of that special "implicit undefined" type that is somehow distinct from undefined while also being === undefined
; the very same type that is the reason we use typeof obj !== "undefined"
to avoid throwing a ReferenceError
because obj === undefined
only doesn't throw an error if obj
was explicitly defined as undefined
.
a = {__proto__: Array.prototype}; // Array {}
a.push(5)
a // [5]
a.length = 5
a // [5, empty x 4]
b = a.map(n => n*n) // [25, empty x 4]
b.push(undefined)
b.push(undefined)
b // [25, empty x 4, undefined, undefined]
b[1] // undefined
b[1] === b[5] // true
Array.isArray(a) // false
Array.isArray(b) // true
Don't use is_array()
, though. It's one thing to reinvent the wheel for learning purposes. It's another thing to do it in production code. Don't even use it as a polyfill. Supporting old JS versions means supporting old browsers means encouraging the use of insecure software means putting the user at risk for malware.
Blank parameter will result in a warning for best available.
soup = BeautifulSoup(html)
---------------/UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("html5lib"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.----------------------/
python --version Python 3.7.7
PyCharm 19.3.4 CE
Angular has a built-in filter
for showing JSON
<pre>{{data | json}}</pre>
Note the use of the pre
-tag to conserve whitespace and linebreaks
Demo:
angular.module('app', [])_x000D_
.controller('Ctrl', ['$scope',_x000D_
function($scope) {_x000D_
_x000D_
$scope.data = {_x000D_
a: 1,_x000D_
b: 2,_x000D_
c: {_x000D_
d: "3"_x000D_
},_x000D_
};_x000D_
_x000D_
}_x000D_
]);
_x000D_
<!DOCTYPE html>_x000D_
<html ng-app="app">_x000D_
_x000D_
<head>_x000D_
<script data-require="[email protected]" data-semver="1.2.15" src="//code.angularjs.org/1.2.15/angular.js"></script>_x000D_
</head>_x000D_
_x000D_
<body ng-controller="Ctrl">_x000D_
<pre>{{data | json}}</pre>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
There's also an angular.toJson
method, but I haven't played around with that (Docs)
Just as an alternative approach to you can do:
WITH inner_table AS
(SELECT A.identifier
, A.name
, TO_NUMBER(DECODE( A.month_no
, 1, 200803
, 2, 200804
, 3, 200805
, 4, 200806
, 5, 200807
, 6, 200808
, 7, 200809
, 8, 200810
, 9, 200811
, 10, 200812
, 11, 200701
, 12, 200702
, NULL)) as MONTH_NO
, TO_NUMBER(TO_CHAR(B.last_update_date, 'YYYYMM')) as UPD_DATE
FROM table_a A
, table_b B
WHERE A.identifier = B.identifier)
SELECT * FROM inner_table
WHERE MONTH_NO > UPD_DATE
Also you can create a permanent view for your queue and select from view.
CREATE OR REPLACE VIEW_1 AS (SELECT ...);
SELECT * FROM VIEW_1;
Personally this query has solved my problem:
SELECT `SUB_ID`, COUNT(SRV_KW_ID) as subscriptions FROM `SUB_SUBSCR` group by SUB_ID, SRV_KW_ID HAVING subscriptions > 1;
What this script does is showing all the subscriber ID's that exists more than once into the table and the number of duplicates found.
This are the table columns:
| SUB_SUBSCR_ID | int(11) | NO | PRI | NULL | auto_increment |
| MSI_ALIAS | varchar(64) | YES | UNI | NULL | |
| SUB_ID | int(11) | NO | MUL | NULL | |
| SRV_KW_ID | int(11) | NO | MUL | NULL | |
Hope it will be helpful for you either!
I was at the pgopen today benchmarks are way faster than mongodb, I believe it was around 500% faster for selects. Pretty much everything was faster at least by at 200% when contrasted with mongodb, than one exception right now is a update which requires completely rewriting the entire json column something mongodb handles better.
The gin indexing on on jsonb sounds amazing.
Also postgres will persist types of jsonb internally and basically match this with types such as numeric, text, boolean etc.
Joins will also be possible using jsonb
Add PLv8 for stored procedures and this will basically be a dream come true for node.js developers.
Being it's stored as binary jsonb will also strip all whitespace, change the ordering of properties and remove duplicate properties using the last occurance of the property.
Besides the index when querying against a jsonb column contrasted to a json column postgres doesn't have to actually run the functionality to convert the text to json on every row which will likely save a vast amount of time alone.
You can use
Dispatcher.Invoke(Delegate, object[])
on the Application
's (or any UIElement
's) dispatcher.
You can use it for example like this:
Application.Current.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));
or
someControl.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));
Use a SortedSet (TreeSet is the default one):
SortedSet<String> set=new TreeSet<String>();
set.add("12");
set.add("15");
set.add("5");
List<String> list=new ArrayList<String>(set);
No extra sorting code needed.
Oh, I see you want a different sort order. Supply a Comparator to the TreeSet:
new TreeSet<String>(Comparator.comparing(Integer::valueOf));
Now your TreeSet will sort Strings in numeric order (which implies that it will throw exceptions if you supply non-numeric strings)
Reference:
TreeSet
Comparator
If you use the php Datetime class you could use:
function time_ago(Datetime $date) {
$time_ago = '';
$diff = $date->diff(new Datetime('now'));
if (($t = $diff->format("%m")) > 0)
$time_ago = $t . ' months';
else if (($t = $diff->format("%d")) > 0)
$time_ago = $t . ' days';
else if (($t = $diff->format("%H")) > 0)
$time_ago = $t . ' hours';
else
$time_ago = 'minutes';
return $time_ago . ' ago (' . $date->format('M j, Y') . ')';
}
Open a terminal and take a look at:
/Applications/Python 3.6/Install Certificates.command
Python 3.6 on MacOS uses an embedded version of OpenSSL, which does not use the system certificate store. More details here.
(To be explicit: MacOS users can probably resolve by opening Finder and double clicking Install Certificates.command)
Another approach which allows you to specify how many numbers you want with size
and the min
and max
values of the returned numbers
public static int getRandomInt(int min, int max) {
Random random = new Random();
return random.nextInt((max - min) + 1) + min;
}
public static ArrayList<Integer> getRandomNonRepeatingIntegers(int size, int min,
int max) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
while (numbers.size() < size) {
int random = getRandomInt(min, max);
if (!numbers.contains(random)) {
numbers.add(random);
}
}
return numbers;
}
To use it returning 7 numbers between 0 and 25.
ArrayList<Integer> list = getRandomNonRepeatingIntegers(7, 0, 25);
for (int i = 0; i < list.size(); i++) {
System.out.println("" + list.get(i));
}
If Len(Dir(ThisWorkbook.Path & "\YOUR_DIRECTORY", vbDirectory)) = 0 Then
MkDir ThisWorkbook.Path & "\YOUR_DIRECTORY"
End If
Lets make it as simple if you don't want to hardcode the value of year and month and you want to take the value from current date and time:
Date d = new Date();
String myDate = new SimpleDateFormat("dd/MM/yyyy").format(d);
int iDayFromDate = Integer.parseInt(myDate.substring(0, 2));
int iMonthFromDate = Integer.parseInt(myDate.substring(3, 5));
int iYearfromDate = Integer.parseInt(myDate.substring(6, 10));
YearMonth CurrentYear = YearMonth.of(iYearfromDate, iMonthFromDate);
int lengthOfCurrentMonth = CurrentYear.lengthOfMonth();
System.out.println("Total number of days in current month is " + lengthOfCurrentMonth );
You might be better off using os.walk()
for this.
os.listdir()
doesn't distinguish files from directories and you will quickly get into trouble trying to unlink these. There is a good example of using os.walk()
to recursively remove a directory here, and hints on how to adapt it to your circumstances.
In my case I forgot to put double curly brace to escape. {{myobject}}
If you want to avoid modulo, you can also use a combination of the four basic operations :)
26 - (26 // 7 * 7) = 5
Another convenient way to copy the values from src ArrayList to dest Arraylist is as follows:
ArrayList<String> src = new ArrayList<String>();
src.add("test string1");
src.add("test string2");
ArrayList<String> dest= new ArrayList<String>();
dest.addAll(src);
This is actual copying of values and not just copying of reference.
Searching multiple fields at once can be done like so...
function search($search)
{
$sql = "SELECT * FROM some_table
WHERE UPPER(a_name) LIKE ?
OR
UPPER(a_full_name) LIKE ?
OR
UPPER(a_city) LIKE ?
OR
UPPER(a_code) LIKE ?
";
$arr = array_map(array($this,"wrapLIKE"),array($search, $search, $search, $search));
$r = $this->db->query($sql, $arr);
return $r;
}
function wrapLIKE($string)
{
return strtoupper("%$string%");
}
Include the sunfire and jacoco plugins in the pom.xml and Run the maven command as given below.
mvn jacoco:prepare-agent jacoco:report sonar:sonar
<properties>
<surefire.version>2.17</surefire.version>
<jacoco.version>0.7.2.201409121644</jacoco.version>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.version}</version>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>${jacoco.version}</version>
<executions>
<execution>
<id>default-prepare-agent</id>
<goals><goal>prepare-agent</goal></goals>
</execution>
<execution>
<id>default-report</id>
<phase>prepare-package</phase>
<goals><goal>report</goal></goals>
</execution>
</executions>
</plugin>
</plugins>
strtotime will convert your date string to a unix time stamp. (seconds since the unix epoch.
$ts1 = strtotime($date1);
$ts2 = strtotime($date2);
$seconds_diff = $ts2 - $ts1;
Objective-C:
NSString to NSData:
NSString* str= @"string";
NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];
NSData to NSString:
NSString* newStr = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];
Swift:
String to Data:
var testString = "string"
var somedata = testString.data(using: String.Encoding.utf8)
Data to String:
var backToString = String(data: somedata!, encoding: String.Encoding.utf8) as String!
Right click on the folder which is under SVN control, go to TortoiseSVN ? Show log. Write down the revision you want to revert to and then go to TortoiseSVN ? Update to revision....
I had this problem too, somehow my code did not present the exact values but rounded the number in seconds to 0.0 (if milliseconds was under 1 second). What helped me out is adding the decimal to the division value.
double time_seconds = time_milliseconds / 1000.0; // add the decimal
System.out.println(time_milliseconds); // Now this should give you the right value.
Yes strings must be quoted and in some cases like in applescript, quotes must be escaped
do JavaScript "document.querySelector('span[" & attrName & "=\"" & attrValue & "\"]').click();"
Would have left this as a comment but I need more rep, anyways I just wanted to mention to Nicholas Peterson that perhaps passing the second argument to the Redirect call to tell it to end the response would have worked. Not the most graceful way to handle this but it does in fact work.
So
filterContext.RequestContext.HttpContext.Response.Redirect("/Login", true);
instead of
filterContext.RequestContext.HttpContext.Response.Redirect("/Login);
So you'd have this in your controller:
protected override void OnAuthorization(AuthorizationContext filterContext)
{
if(!User.IsInRole("Admin")
{
base.OnAuthorization(filterContext);
filterContext.RequestContext.HttpContext.Response.Redirect("/Login", true);
}
}
Are you using an error handler? If you're ignoring errors and try to name a sheet the same as an existing sheet or a name with invalid characters, it could be just skipping over that line. See the CleanSheetName function here
http://www.dailydoseofexcel.com/archives/2005/01/04/naming-a-sheet-based-on-a-cell/
for a list of invalid characters that you may want to check for.
Update
Other things to try: Fully qualified references, throwing in a Doevents, code cleaning. This code qualifies your Sheets reference to ThisWorkbook (you can change it to ActiveWorkbook if that suits). It also adds a thousand DoEvents (stupid overkill, but if something's taking a while to get done, this will allow it to - you may only need one DoEvents if this actually fixes anything).
Dim WS As Worksheet
Dim i As Long
With ThisWorkbook
Set WS = .Worksheets.Add(After:=.Sheets(.Sheets.Count))
End With
For i = 1 To 1000
DoEvents
Next i
WS.Name = txtSheetName.Value
Finally, whenever I have a goofy VBA problem that just doesn't make sense, I use Rob Bovey's CodeCleaner. It's an add-in that exports all of your modules to text files then re-imports them. You can do it manually too. This process cleans out any corrupted p-code that's hanging around.
A view is a virtual table. A view consists of rows and columns just like a table. The difference between a view and a table is that views are definitions built on top of other tables (or views), and do not hold data themselves. If data is changing in the underlying table, the same change is reflected in the view. A view can be built on top of a single table or multiple tables. It can also be built on top of another view. In the SQL Create View page, we will see how a view can be built.
Views offer the following advantages:
Ease of use: A view hides the complexity of the database tables from end users. Essentially we can think of views as a layer of abstraction on top of the database tables.
Space savings: Views takes very little space to store, since they do not store actual data.
Additional data security: Views can include only certain columns in the table so that only the non-sensitive columns are included and exposed to the end user. In addition, some databases allow views to have different security settings, thus hiding sensitive data from prying eyes.
Answer from:http://www.1keydata.com/sql/sql-view.html
Integer.valueOf()
returns an Integer object, while Integer.parseInt()
returns an int
primitive.
Yes, open a postscript()
device with a filename ending in .eps
, do your plot(s) and call dev.off()
.
use:
import six
if isinstance(obj, six.text_type)
inside the six library it is represented as:
if PY3:
string_types = str,
else:
string_types = basestring,
As Mystere Man suggested, getting just a view first and then again making an ajax call again to get the json result is unnecessary in this case. that is 2 calls to the server. I think you can directly return an HTML table of Users in the first call.
We will do this in this way. We will have a strongly typed view which will return the markup of list of users to the browser and this data is being supplied by an action method which we will invoke from our browser using an http request.
Have a ViewModel for the User
public class UserViewModel
{
public int UserID { set;get;}
public string FirstName { set;get;}
//add remaining properties as per your requirement
}
and in your controller have a method to get a list of Users
public class UserController : Controller
{
[HttpGet]
public ActionResult List()
{
List<UserViewModel> objList=UserService.GetUsers(); // this method should returns list of Users
return View("users",objList)
}
}
Assuming that UserService.GetUsers() method will return a List of UserViewModel object which represents the list of usres in your datasource (Tables)
and in your users.cshtml ( which is under Views/User folder),
@model List<UserViewModel>
<table>
@foreach(UserViewModel objUser in Model)
{
<tr>
<td>@objUser.UserId.ToString()</td>
<td>@objUser.FirstName</td>
</tr>
}
</table>
All Set now you can access the url like yourdomain/User/List
and it will give you a list of users in an HTML table.
I suggest use javax.json.Json factory as less verbose possible solution:
JsonObject json = Json.createReader(yourInputStream).readObject();
Enjoy!
To expand on katrmr's answer, if the container is stopped and can't be started due to an error, you'll need to commit
it to an image. Then you can launch bash in the new image:
docker commit [CONTAINER_ID] temporary_image
docker run --entrypoint=bash -it temporary_image
If you are using Docker make sure you are not using the same port in another service, in my case i was mistakenly using the same port for both PostgreSQL and Redis.
This simple test syntax + code-style convention + small focused components is for me the most readable option out there. You just need to take special care of falsy values like false
, 0
or ""
.
render: function() {
var person= ...;
var counter= ...;
return (
<div className="component">
{person && (
<Person person={person}/>
)}
{(typeof counter !== 'undefined') && (
<Counter value={counter}/>
)}
</div>
);
}
ES7 stage-0 do notation syntax is also very nice and I'll definitively use it when my IDE supports it correctly:
const Users = ({users}) => (
<div>
{users.map(user =>
<User key={user.id} user={user}/>
)}
</div>
)
const UserList = ({users}) => do {
if (!users) <div>Loading</div>
else if (!users.length) <div>Empty</div>
else <Users users={users}/>
}
More details here: ReactJs - Creating an "If" component... a good idea?
See http://jsfiddle.net/qP8DY/24/
You can add a class (such as "success-dialog" in my example) to div#success, either directly in your HTML, or in your JavaScript by adding to the dialogClass option, as I've done.
$('#success').dialog({
height: 50,
width: 350,
modal: true,
resizable: true,
dialogClass: 'no-close success-dialog'
});
Then just add the success-dialog class to your CSS rules as appropriate. To indicate an element with two (or more) classes applied to it, just write them all together, with no spaces in between. For example:
.ui-dialog.success-dialog {
font-family: Verdana,Arial,sans-serif;
font-size: .8em;
}
In my case it happened cause i embedded a RecyclerView in a LinearLayout.
I previously had a layout file only containing one root RecyclerView as follows
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:listitem="@layout/fragment_products"
android:name="Products.ProductsFragment"
app:layoutManager="LinearLayoutManager"
tools:context=".Products.ProductsFragment"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"/>
I believe the problem is within the 3 lines separated. Anyway, I think its a simple problem, ill be working on it tomorrow; thought i should write what i found before forgetting about this thread.
Or, you can ignore the error:
declare
column_exists exception;
pragma exception_init (column_exists , -01430);
begin
execute immediate 'ALTER TABLE db.tablename ADD columnname NVARCHAR2(30)';
exception when column_exists then null;
end;
/
a = [[] for index in range(1, n)]
There is no REVOKE ALL PRIVILEGES ON ALL VIEWS
, so I ended with:
do $$
DECLARE r record;
begin
for r in select * from pg_views where schemaname = 'myschem'
loop
execute 'revoke all on ' || quote_ident(r.schemaname) ||'.'|| quote_ident(r.viewname) || ' from "XUSER"';
end loop;
end $$;
and usual:
REVOKE ALL PRIVILEGES ON DATABASE mydb FROM "XUSER";
REVOKE ALL PRIVILEGES ON SCHEMA myschem FROM "XUSER";
REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA myschem FROM "XUSER";
REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA myschem FROM "XUSER";
REVOKE ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA myschem FROM "XUSER";
for the following to succeed:
drop role "XUSER";
Note: You can first preview what your patch will do:
First the stats:
git apply --stat a_file.patch
Then a dry run to detect errors:
git apply --check a_file.patch
Finally, you can use git am
to apply your patch as a commit. This also allows you to sign off an applied patch.
This can be useful for later reference.
git am --signoff < a_file.patch
See an example in this article:
In your git log, you’ll find that the commit messages contain a “Signed-off-by” tag. This tag will be read by Github and others to provide useful info about how the commit ended up in the code.
A possible solution that would not depend on the specific IEEE representation for NaN used would be the following:
template<class T>
bool isnan( T f ) {
T _nan = (T)0.0/(T)0.0;
return 0 == memcmp( (void*)&f, (void*)&_nan, sizeof(T) );
}
You could query an LDAP server from the command line with ldap-utils: ldapsearch, ldapadd, ldapmodify
dataString = [];
$.ajax({
type: "POST",
url: "script.php",
data:{data: $(dataString).serializeArray()},
cache: false,
success: function(){
alert("OK");
}
});
you can't call sendRedirect(), after you have already used forward(). So, you get that exception.
You should place your script code after your HTML code and within your body tags. That way it doesn't run before the html code.
You already have a process bound to the default port (8000). If you already ran the same module before, it is most likely that process still bound to the port. Try and locate the other process first:
$ ps -fA | grep python
501 81651 12648 0 9:53PM ttys000 0:00.16 python -m SimpleHTTPServer
The command arguments are included, so you can spot the one running SimpleHTTPServer
if more than one python
process is active. You may want to test if http://localhost:8000/
still shows a directory listing for local files.
The second number is the process number; stop the server by sending it a signal:
kill 81651
This sends a standard SIGTERM
signal; if the process is unresponsive you may have to resort to tougher methods like sending a SIGKILL
(kill -s KILL <pid>
or kill -9 <pid>
) signal instead. See Wikipedia for more details.
Alternatively, run the server on a different port, by specifying the alternative port on the command line:
$ python -m SimpleHTTPServer 8910
Serving HTTP on 0.0.0.0 port 8910 ...
then access the server as http://localhost:8910
; where 8910
can be any number from 1024 and up, provided the port is not already taken.
Another Kotlin code
class DynamicViewPager @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null
) : ViewPager(context, attrs) {
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
var height = 0
(0 until childCount).forEach {
val child = getChildAt(it)
child.measure(
widthMeasureSpec,
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)
)
height = max(height, child.measuredHeight)
}
if (height > 0) {
super.onMeasure(
widthMeasureSpec,
MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)
)
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
}
}
}
your best bet is to use a javascript framework like jquery or prototype, but, failing that, you should use:
if (foo.addEventListener)
foo.addEventListener('click',doit,false); //everything else
else if (foo.attachEvent)
foo.attachEvent('onclick',doit); //IE only
edit:
also, your function is a little off. it should be
var doit = function(){
alert('hello world!');
}
Just different names for what is really ECMAScript. John Resig has a good explanation.
Here's the full version breakdown:
Assuming that "a" and "b" are bean properties
rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"
You may look at JSF EL operators
Another option is to use an array, e.g.
void method(SomeClass[] v) { v[0] = ...; }
but 1) the array must be initialized before method invoked, 2) still one cannot implement e.g. swap method in this way...
This way is used in JDK, e.g. in java.util.concurrent.atomic.AtomicMarkableReference.get(boolean[])
.
I add an example,
UNION, it is merging with distinct --> slower, because it need comparing (In Oracle SQL developer, choose query, press F10 to see cost analysis).
UNION ALL, it is merging without distinct --> faster.
SELECT to_date(sysdate, 'yyyy-mm-dd') FROM dual
UNION
SELECT to_date(sysdate, 'yyyy-mm-dd') FROM dual;
and
SELECT to_date(sysdate, 'yyyy-mm-dd') FROM dual
UNION ALL
SELECT to_date(sysdate, 'yyyy-mm-dd') FROM dual;
I had also the same problem. Please add this line in application tag in manifest. I hope it will also help you.
android:usesCleartextTraffic="true"
For powers of 2:
var twoToThePowerOf = 1 << yourExponent;
// eg: 1 << 12 == 4096
If you want to add this behaviour to a shorthand animation
property definition, the order of sub-properties is as follows
animation-name
- default none
animation-duration
- default 0s
animation-timing-function
- default ease
animation-delay
- default 0s
animation-iteration-count
- default 1
animation-direction
- default normal
animation-fill-mode
- you need to set this to forwards
animation-play-state
- default running
Therefore in the most common case, the result will be something like this
animation: colorchange 1s ease 0s 1 normal forwards;
See the MDN documentation here
I always add a target="_blank" to the download link. This will open a new window, but as soon as the user clicks save, the new window is closed.
I just did the same. I did it in helper controller, my code is:
def get_controller_name
controller_name
end
def get_action_name
action_name
end
These methods will return current contoller and action name. Hope it helps
This was helpful for me, if you use the
var dir = Directory.GetCurrentDirectory()
the path fill be beyond the current folder, it will incluide this path \bin\debug What I recommend you, is that you can use the
string dir = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName
then print the dir value and verify the path is giving you
NSLog(@"%.0f", [[UIScreen mainScreen] bounds].size.width);
NSLog(@"%.0f", [[UIScreen mainScreen] bounds].size.height);