You need to look for the Increase Font Size
and Decrease Font Size
options on the Keymap menu, you can see the options on my screenshot. You will find the Keymap menu under Preferences > Keymap
.
Assigning on those will have the expected effect for font zoom.
One more approach using Recursive CTE..
declare @string varchar(100)
set @string ='te165st1230004616161616'
;With cte
as
(
select @string as string,0 as n
union all
select cast(replace(string,n,'') as varchar(100)),n+1
from cte
where n<9
)
select top 1 string from cte
order by n desc
**Output:**
test
Things are much easier nowadays: the builtin Snippet Generator supports the 'build' step (I don't know since when though).
Echoing justanotherdev's comment:
Mind-blowing and useful:
CTRL
+ SHIFT
+ p
(Mac: CMD
+ SHIFT
+ p
)>transform
pick upper/lower case and press enterA kotlin verison with fallback and current syntax
fun openAppInPlayStore() {
val uri = Uri.parse("market://details?id=" + context.packageName)
val goToMarketIntent = Intent(Intent.ACTION_VIEW, uri)
var flags = Intent.FLAG_ACTIVITY_NO_HISTORY or Intent.FLAG_ACTIVITY_MULTIPLE_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
flags = if (Build.VERSION.SDK_INT >= 21) {
flags or Intent.FLAG_ACTIVITY_NEW_DOCUMENT
} else {
flags or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
goToMarketIntent.addFlags(flags)
try {
startActivity(context, goToMarketIntent, null)
} catch (e: ActivityNotFoundException) {
val intent = Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + context.packageName))
startActivity(context, intent, null)
}
}
Use the display: inline
CSS property.
Ideal: In the stylesheet:
#container p { display: inline }
Bad/Extreme situation: Inline:
<p style="display:inline">...</p>
go to tsconfig.json and comment the line the //strict:true this worked for me
This topic is old but if other people like me search a solution, this is a solution that I have found:
Public Function DBStats() As Boolean
On Error GoTo errorHandler
If Not IsNull(myBase.Version) Then
DBStats = True
End If
Exit Function
errorHandler:
DBStats = False
End Function
So "myBase" is a Database Object, I have made a class to access to database (class with insert, update etc...) and on the module the class is use declare in an object (obviously) and I can test the connection with "[the Object].DBStats":
Dim BaseAccess As New myClass
BaseAccess.DBOpen 'I open connection
Debug.Print BaseAccess.DBStats ' I test and that tell me true
BaseAccess.DBClose ' I close the connection
Debug.Print BaseAccess.DBStats ' I test and tell me false
Edit : In DBOpen I use "OpenDatabase" and in DBClose I use ".Close" and "set myBase = nothing" Edit 2: In the function, if you are not connect, .version give you an error so if aren't connect, the errorHandler give you false
try this its work fine
document.getElementById('fileUpload').parentNode.innerHTML = document.getElementById('fileUpload').parentNode.innerHTML;
svn:// doesn't talk http, therefor there's nothing a http proxy could do.
Any reason why http doesn't work? Have you considered https? If you really need it, you probably have to have port 3690 opened in your firewall.
Günter Zöchbauer's answer is the right one. Just consider adding the following line:
showImageBrowseDlg() {
// from http://stackoverflow.com/a/32010791/217408
let event = new MouseEvent('click', {bubbles: true});
event.stopPropagation();
this.renderer.invokeElementMethod(
this.fileInput.nativeElement, 'dispatchEvent', [event]);
}
In my case I would get a "caught RangeError: Maximum call stack size exceeded" error if not. (I have a div card firing on click and the input file inside)
{yourImageName.Source = new BitmapImage(new Uri("ms-appx:///Assets/LOGO.png"));}
LOGO refers to your image
Hoping to help anyone. :)
In Simple Rails terms:
h
remove html tags into number characters so that rendering won't break your html
html_safe
sets a boolean in string so that the string is considered as html save
raw
It converts to html_safe to string
Just about every modern operating system will recover all the allocated memory space after a program exits. The only exception I can think of might be something like Palm OS where the program's static storage and runtime memory are pretty much the same thing, so not freeing might cause the program to take up more storage. (I'm only speculating here.)
So generally, there's no harm in it, except the runtime cost of having more storage than you need. Certainly in the example you give, you want to keep the memory for a variable that might be used until it's cleared.
However, it's considered good style to free memory as soon as you don't need it any more, and to free anything you still have around on program exit. It's more of an exercise in knowing what memory you're using, and thinking about whether you still need it. If you don't keep track, you might have memory leaks.
On the other hand, the similar admonition to close your files on exit has a much more concrete result - if you don't, the data you wrote to them might not get flushed, or if they're a temp file, they might not get deleted when you're done. Also, database handles should have their transactions committed and then closed when you're done with them. Similarly, if you're using an object oriented language like C++ or Objective C, not freeing an object when you're done with it will mean the destructor will never get called, and any resources the class is responsible might not get cleaned up.
I am not completely sure what you're trying to achieve by seeking to a specific offset and attempting to load individual values manually, the typical usage of the pickle
module is:
# save data to a file
with open('myfile.pickle','wb') as fout:
pickle.dump([1,2,3],fout)
# read data from a file
with open('myfile.pickle') as fin:
print pickle.load(fin)
# output
>> [1, 2, 3]
If you dumped a list, you'll load a list, there's no need to load each item individually.
you're saying that you got an error before you were seeking to the -5000 offset, maybe the file you're trying to read is corrupted.
If you have access to the original data, I suggest you try saving it to a new file and reading it as in the example.
Once you have a library downloaded you can execute this from the MS-DOS command box:
python setup.py install
The setup.py
is located inside every library main folder.
*Using Robot class you can do this, Try following code:
Actions action = new Actions(driver);
action.contextClick(WebElement).build().perform();
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_DOWN);
robot.keyRelease(KeyEvent.VK_DOWN);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
[UPDATE]
CAUTION: Your Browser should always be in focus i.e. running in foreground while performing Robot Actions, other-wise any other application in foreground will receive the actions.
I found this in the PHP manual comments:
/**
* function xml2array
*
* This function is part of the PHP manual.
*
* The PHP manual text and comments are covered by the Creative Commons
* Attribution 3.0 License, copyright (c) the PHP Documentation Group
*
* @author k dot antczak at livedata dot pl
* @date 2011-04-22 06:08 UTC
* @link http://www.php.net/manual/en/ref.simplexml.php#103617
* @license http://www.php.net/license/index.php#doc-lic
* @license http://creativecommons.org/licenses/by/3.0/
* @license CC-BY-3.0 <http://spdx.org/licenses/CC-BY-3.0>
*/
function xml2array ( $xmlObject, $out = array () )
{
foreach ( (array) $xmlObject as $index => $node )
$out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;
return $out;
}
It could help you. However, if you convert XML to an array you will loose all attributes that might be present, so you cannot go back to XML and get the same XML.
I wrote a module for this: win-node-env.
It creates a NODE_ENV.cmd
that sets the NODE_ENV
environment variable and spawns a child process with the rest of the command and its args.
Just install it (globally), and run your npm script commands, it should automatically make them work.
npm install -g win-node-env
Go to file \phpMyAdmin\config.inc.php at the very bottom, change the hosting details such as host, username, password etc.
Imports System.Net
Imports System.Net.Sockets
Function LocalIP()
Dim strHostName = Dns.GetHostName
Dim Host = Dns.GetHostEntry(strHostName)
For Each ip In Host.AddressList
If ip.AddressFamily = AddressFamily.InterNetwork Then
txtIP.Text = ip.ToString
End If
Next
Return True
End Function
Below same action
Function LocalIP()
Dim Host As String =Dns.GetHostEntry(Dns.GetHostName).AddressList(1).MapToIPv4.ToString
txtIP.Text = Host
Return True
End Function
Have you tried to use the "CSVIMPORT" function found in the file exchange? I haven't tried it myself, but it claims to handle all combinations of text and numbers.
http://www.mathworks.com/matlabcentral/fileexchange/23573-csvimport
You can easily use Apache File Utils. Look at function writeStringToFile
. We use this library in our projects.
I found a better solutions in following link. Only use "object-fit" https://medium.com/@chrisnager/center-and-crop-images-with-a-single-line-of-css-ad140d5b4a87
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
foreach(DataRow row in dt.Rows)
{
TextBox1.Text = row["ImagePath"].ToString();
}
...assumes the connection is open and the command is set up properly. I also didn't check the syntax, but it should give you the idea.
Use a backslash as such
"From time to \"time\"";
Backslashes are used in PHP to escape special characters within quotes. As PHP does not distinguish between strings and characters, you could also use this
'From time to "time"';
The difference between single and double quotes is that double quotes allows for string interpolation, meaning that you can reference variables inline in the string and their values will be evaluated in the string like such
$name = 'Chris';
$greeting = "Hello my name is $name"; //equals "Hello my name is Chris"
As per your last edit of your question I think the easiest thing you may be able to do that this point is to use a 'heredoc.' They aren't commonly used and honestly I wouldn't normally recommend it but if you want a fast way to get this wall of text in to a single string. The syntax can be found here: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc and here is an example:
$someVar = "hello";
$someOtherVar = "goodbye";
$heredoc = <<<term
This is a long line of text that include variables such as $someVar
and additionally some other variable $someOtherVar. It also supports having
'single quotes' and "double quotes" without terminating the string itself.
heredocs have additional functionality that most likely falls outside
the scope of what you aim to accomplish.
term;
I usually print the logs on screen and write into a file as well. Hope this helps someone.
f, err := os.OpenFile("/tmp/orders.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatalf("error opening file: %v", err)
}
defer f.Close()
wrt := io.MultiWriter(os.Stdout, f)
log.SetOutput(wrt)
log.Println(" Orders API Called")
The correct way, as SAM write before is:
reg Query "HKLM\Hardware\Description\System\CentralProcessor\0" /v "Identifier" | find /i "x86" > NUL && set OS=32BIT || set OS=64BIT
but with /v "Identifier" a little bit correct.
You might also encounter an error message. "Operand type clash: date is incompatible with int.
Use single quotes around the dates. E.g.: $this->db->where("$accommodation BETWEEN '$minvalue' AND '$maxvalue'");
Those are the basic decision orders that you have in most of the programming language; it helps you to decide the flow of actions that your program is gonna do. The if is telling the compiler that you have a question, and the question is the condition between parenthesis
if (condition) {
thingsToDo()..
}
the else part is an addition to this structure to tell the compiler what to do if the condition is false
if (condition) {
thingsToDo()..
} else {
thingsToDoInOtherCase()..
}
you can combine those to form a else if which is when the first condition is false but you want to do another question before to decide what to do.
if (condition) {
thingsToDo()..
} else if (condition2) {
thingsToDoInTheSecondCase()..
}else {
thingsToDoInOtherCase()..
}
Many people use both 2.X and 3.X python. You can use pip -V
to show default pip version.
If you have many python versions, and you want to install some packages through different pip, I advise this way:
sudo python2.X -m pip install some-package==0.16
Java 8 Collection has a nice method called removeIf that makes things easier and safer. From the API docs:
default boolean removeIf(Predicate<? super E> filter)
Removes all of the elements of this collection that satisfy the given predicate.
Errors or runtime exceptions thrown during iteration or by the predicate
are relayed to the caller.
Interesting note:
The default implementation traverses all elements of the collection using its iterator().
Each matching element is removed using Iterator.remove().
The element.getBoundingClientRect()
method will return the proper coordinates of an element relative to the viewport regardless of whether the svg has been scaled and/or translated.
While getBBox() works for an untransformed space, if scale and translation have been applied to the layout then it will no longer be accurate. The getBoundingClientRect() function has worked well for me in a force layout project when pan and zoom are in effect, where I wanted to attach HTML Div elements as labels to the nodes instead of using SVG Text elements.
I'd recommend the Range object's AutoFill method for this:
rngSource.AutoFill Destination:=rngDest
Specify the Source range that contains the values or formulas you want to fill down, and the Destination range as the whole range that you want the cells filled to. The Destination range must include the Source range. You can fill across as well as down.
It works exactly the same way as it would if you manually "dragged" the cells at the corner with the mouse; absolute and relative formulas work as expected.
Here's an example:
'Set some example values'
Range("A1").Value = "1"
Range("B1").Formula = "=NOW()"
Range("C1").Formula = "=B1+A1"
'AutoFill the values / formulas to row 20'
Range("A1:C1").AutoFill Destination:=Range("A1:C20")
Hope this helps.
img {
max-width: 100%;
}
Should set the image to take up 100% of its containing element.
Per Debian policy, python
refers to Python 2 and python3
refers to Python 3. Don't try to change this system-wide or you are in for the sort of trouble you already discovered.
Virtual environments allow you to run an isolated Python installation with whatever version of Python and whatever libraries you need without messing with the system Python install.
With recent Python 3, venv
is part of the standard library; with older versions, you might need to install python3-venv
or a similar package.
$HOME~$ python --version
Python 2.7.11
$HOME~$ python3 -m venv myenv
... stuff happens ...
$HOME~$ . ./myenv/bin/activate
(myenv) $HOME~$ type python # "type" is preferred over which; see POSIX
python is /home/you/myenv/bin/python
(myenv) $HOME~$ python --version
Python 3.5.1
A common practice is to have a separate environment for each project you work on, anyway; but if you want this to look like it's effectively system-wide for your own login, you could add the activation stanza to your .profile
or similar.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row align-items-center justify-content-center" style="height:100vh;">
<div>Center Div Here</div>
</div>
</div>
</body>
</html>
You're grouping with BillDate
, but the bill dates are different for each account so your rows are not being grouped. If you think about it, that doesn't even make sense - they are different bills, and have different dates. The same goes for the Bill
- you're attempting to sum bills for an account, why would you group by that?
If you leave BillDate
and Bill
off of the select and group by clauses you'll get the correct results.
SELECT AccountNumber, SUM(Bill)
FROM Table1
GROUP BY AccountNumber
Do you want iteration? itertools.combinations. Common usage:
>>> import itertools
>>> itertools.combinations('abcd',2)
<itertools.combinations object at 0x01348F30>
>>> list(itertools.combinations('abcd',2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
>>> [''.join(x) for x in itertools.combinations('abcd',2)]
['ab', 'ac', 'ad', 'bc', 'bd', 'cd']
If you just need to compute the formula, use math.factorial:
import math
def nCr(n,r):
f = math.factorial
return f(n) / f(r) / f(n-r)
if __name__ == '__main__':
print nCr(4,2)
In Python 3, use the integer division //
instead of /
to avoid overflows:
return f(n) // f(r) // f(n-r)
6
Have you tried using dictionary comprehension with dictionary mapping:
a = {'a': 1, 'b': 2}
b = {'c': 3, 'd': 4}
c = {**a, **b}
# c = {"a": 1, "b": 2, "c": 3, "d": 4}
Another way of doing is by Using dict(iterable, **kwarg)
c = dict(a, **b)
# c = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
In Python 3.9 you can add two dict using union | operator
# use the merging operator |
c = a | b
# c = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
There is a proper way to split the filename and the extension: Extract filename and extension in Bash
You can apply it like this:
date=$(date +"%m%d%y")
for FILE in folder1/*.csv
do
bname=$(basename "$FILE")
extension="${bname##*.}"
filenamewoext="${bname%.*}"
newfilename="${filenamewoext}${date}.${extension}
cp folder1/${FILE} folder2/${newfilename}
done
Include 'use strict';
as the first statement in a wrapping function, so it only affects that function. This prevents problems when concatenating scripts that aren't strict.
See Douglas Crockford's latest blog post Strict Mode Is Coming To Town.
Example from that post:
(function () {
'use strict';
// this function is strict...
}());
(function () {
// but this function is sloppy...
}());
Update: In case you don't want to wrap in immediate function (e.g. it is a node module), then you can disable the warning.
For JSLint (per Zhami):
/*jslint node: true */
For JSHint:
/*jshint strict:false */
or (per Laith Shadeed)
/* jshint -W097 */
To disable any arbitrary warning from JSHint, check the map in JSHint source code (details in docs).
Update 2: JSHint supports node:boolean
option. See .jshintrc
at github.
/* jshint node: true */
On Windows 10, curl 7.28.1 within powershell, I found the following to work for me:
$filePath = "c:\temp\dir with spaces\myfile.wav"
$curlPath = ("myfilename=@" + $filePath)
curl -v -F $curlPath URL
Do this:
$(document).ready(function(){
$(".header").click(function(){
$(this).children(".children").toggle();
});
$(".header a").click(function(e) {
e.stopPropagation();
});
});
If you want to read more on .stopPropagation(), look here.
If you want to discard modifications you made to the file, you can do:
git reset first_Name.txt
git checkout first_Name.txt
Solution for those working with Huawei phones - You will get this error when ADB interface is not installed. Check if you have installed Huawei HiSuite. USB driver gets installed when you install HiSuite (I suppose this is true for most of the new phones that come with a Sync Software). If the ADB interface is installed on your computer you should see 'Android Composite ADB Interface' under Android Phone in your Device Manager as shown in this picture.
In my case, the patch was generated perfectly fine by IDEA, however, I edited the patch and saved it which changed CRLF to LF and then the patch stopped working. Curiously, converting it back to CRLF did not work. I noticed in VI editor, that even after setting to DOS format, the '^M' were not added to the end of lines. This forced me to only make changes in VI, so that the EOLs were preserved.
This may apply to you, if you make changes in a non-Windows environment to a patch covering changes between two versions both coming from Windows environment. You want to be careful how you edit such files.
BTW ignore-whitespace
did not help.
The defaultdict solution is better. But for completeness you could also check and create empty list before the append. Add the + lines:
+ if not u in self.adj.keys():
+ self.adj[u] = []
self.adj[u].append(edge)
.
.
There is also proc.time()
You can use in the same way as Sys.time
but it gives you a similar result to system.time
.
ptm <- proc.time()
#your function here
proc.time() - ptm
the main difference between using
system.time({ #your function here })
is that the proc.time()
method still does execute your function instead of just measuring the time...
and by the way, I like to use system.time
with {}
inside so you can put a set of things...
Try this one:
var object = this.window;
console.log(object,'this is window object');
Output:
The solution is to use the same IP and Port number in both client and server. Try, in client to use TCP_IP = 'write the ip number here' TCP_PORT = writ the port number here s.connect((TCP_IP, TCP_PORT))
If in your site you have ajax calls loading some data, and this is the reason the page is loading slow, the best solution I found is with
$(document).ajaxStop(function(){
alert("All AJAX requests completed");
});
https://jsfiddle.net/44t5a8zm/ - here you can add some ajax calls and test it.
in a very simple sentence: The significant difference being that Repositories represent collections, whilst DAOs are closer to the database, often being far more table-centric.
you can use altsoft xml2pdf lib for this
They are user-defined signals, so they aren't triggered by any particular action. You can explicitly send them programmatically:
#include <signal.h>
kill(pid, SIGUSR1);
where pid
is the process id of the receiving process. At the receiving end, you can register a signal handler for them:
#include <signal.h>
void my_handler(int signum)
{
if (signum == SIGUSR1)
{
printf("Received SIGUSR1!\n");
}
}
signal(SIGUSR1, my_handler);
From server to local(Exporting)
mysqldump -u username -p db_name table_name > path/filename.sql;
mysqldump -u root -p remotelab welcome_ulink >
/home_local/ladmin/kakalwar/base/welcome_ulink.sql;
From local to server(Importing)
mysql -u username -p -D databasename < path/x/y/z/welcome_queue.sql
mysql -u root -p -D remotelab <
/home_local/ladmin/kakalwar/instant_status/db_04_12/welcome_queue.sql
Another way that allows you to change the text of "Delete" and add more buttons when sliding a cell is to use editActionsForRowAtIndexPath
.
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: (UITableView!), commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: (NSIndexPath!)) {
}
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {
var deleteAction = UITableViewRowAction(style: .Default, title: "Delete") {action in
//handle delete
}
var editAction = UITableViewRowAction(style: .Normal, title: "Edit") {action in
//handle edit
}
return [deleteAction, editAction]
}
canEditRowAtIndexPath
and commitEditingStyle
are still required, but you can leave commitEditingStyle
empty since deletion is handled in editActionsForRowAtIndexPath
.
Go to Attributes Inspector(right top corner) In the Simulated Metrics, which has Size, Orientation, Status Bar, Top Bar, Bottom Bar properties. For SIZE, change Inferred --> Freeform.
var test = parseInt($("#testid").val());
Just adding another idea you could use a child selector to get immediate children
document.querySelectorAll(".parent > .child1");
should return all the immediate children with class .child1
I know its late to post, but I use the site for my own reference and so I wanted to put an answer here for myself to reference in the future too. I hope you (and others) find it helpful.
Lets pretend a bunch of super Einstein experts designed our database. Our super perfect database has 3 tables, and the following relationships defined between them:
TblA 1:M TblB
TblB 1:M TblC
Notice there is no relationship between TblA and TblC
In most scenarios such a simple database is easy to navigate but in commercial databases it is usually impossible to be able to tell at the design stage all the possible uses and combination of uses for data, tables, and even whole databases, especially as systems get built upon and other systems get integrated or switched around or out. This simple fact has spawned a whole industry built on top of databases called Business Intelligence. But I digress...
In the above case, the structure is so simple to understand that its easy to see you can join from TblA, through to B, and through to C and vice versa to get at what you need. It also very vaguely highlights some of the problems with doing it. Now expand this simple chain to 10 or 20 or 50 relationships long. Now all of a sudden you start to envision a need for exactly your scenario. In simple terms, a join from A to C or vice versa or A to F or B to Z or whatever as our system grows.
There are many ways this can indeed be done. The one mentioned above being the most popular, that is driving through all the links. The major problem is that its very slow. And gets progressively slower the more tables you add to the chain, the more those tables grow, and the further you want to go through it.
Solution 1: Look for a common link. It must be there if you taught of a reason to join A to C. If it is not obvious, create a relationship and then join on it. i.e. To join A through B through C there must be some commonality or your join would either produce zero results or a massive number or results (Cartesian product). If you know this commonality, simply add the needed columns to A and C and link them directly.
The rule for relationships is that they simply must have a reason to exist. Nothing more. If you can find a good reason to link from A to C then do it. But you must ensure your reason is not redundant (i.e. its already handled in some other way).
Now a word of warning. There are some pitfalls. But I don't do a good job of explaining them so I will refer you to my source instead of talking about it here. But remember, this is getting into some heavy stuff, so this video about fan and chasm traps is really only a starting point. You can join without relationships. But I advise watching this video first as this goes beyond what most people learn in college and well into the territory of the BI and SAP guys. These guys, while they can program, their day job is to specialise in exactly this kind of thing. How to get massive amounts of data to talk to each other and make sense.
This video is one of the better videos I have come across on the subject. And it's worth looking over some of his other videos. I learned a lot from him.
To remove untracked files / directories do:
git clean -fdx
-f - force
-d - directories too
-x - remove ignored files too ( don't use this if you don't want to remove ignored files)
Use with Caution!
These commands can permanently delete arbitrary files, that you havn't thought of at first. Please double check and read all the comments below this answer and the --help section, etc., so to know all details to fine-tune your commands and surely get the expected result.
Since the suggestion of a loop implies the request for a procedure type solution. Here is mine.
Any query which works on any single record taken from a table can be wrapped in a procedure to make it run through each row of a table like so:
First delete any existing procedure with the same name, and change the delimiter so your SQL doesn't try to run each line as you're trying to write the procedure.
DROP PROCEDURE IF EXISTS ROWPERROW;
DELIMITER ;;
Then here's the procedure as per your example (table_A and table_B used for clarity)
CREATE PROCEDURE ROWPERROW()
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
SELECT COUNT(*) FROM table_A INTO n;
SET i=0;
WHILE i<n DO
INSERT INTO table_B(ID, VAL) SELECT (ID, VAL) FROM table_A LIMIT i,1;
SET i = i + 1;
END WHILE;
End;
;;
Then dont forget to reset the delimiter
DELIMITER ;
And run the new procedure
CALL ROWPERROW();
You can do whatever you like at the "INSERT INTO" line which I simply copied from your example request.
Note CAREFULLY that the "INSERT INTO" line used here mirrors the line in the question. As per the comments to this answer you need to ensure that your query is syntactically correct for which ever version of SQL you are running.
In the simple case where your ID field is incremented and starts at 1 the line in the example could become:
INSERT INTO table_B(ID, VAL) VALUES(ID, VAL) FROM table_A WHERE ID=i;
Replacing the "SELECT COUNT" line with
SET n=10;
Will let you test your query on the first 10 record in table_A only.
One last thing. This process is also very easy to nest across different tables and was the only way I could carry out a process on one table which dynamically inserted different numbers of records into a new table from each row of a parent table.
If you need it to run faster then sure try to make it set based, if not then this is fine. You could also rewrite the above in cursor form but it may not improve performance. eg:
DROP PROCEDURE IF EXISTS cursor_ROWPERROW;
DELIMITER ;;
CREATE PROCEDURE cursor_ROWPERROW()
BEGIN
DECLARE cursor_ID INT;
DECLARE cursor_VAL VARCHAR;
DECLARE done INT DEFAULT FALSE;
DECLARE cursor_i CURSOR FOR SELECT ID,VAL FROM table_A;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cursor_i;
read_loop: LOOP
FETCH cursor_i INTO cursor_ID, cursor_VAL;
IF done THEN
LEAVE read_loop;
END IF;
INSERT INTO table_B(ID, VAL) VALUES(cursor_ID, cursor_VAL);
END LOOP;
CLOSE cursor_i;
END;
;;
Remember to declare the variables you will use as the same type as those from the queried tables.
My advise is to go with setbased queries when you can, and only use simple loops or cursors if you have to.
We had a situation where IE forced us to post as text/plain, so we had to manually parse the parameters using getReader. The servlet was being used for long polling, so when AsyncContext::dispatch was executed after a delay, it was literally reposting the request empty handed.
So I just stored the post in the request when it first appeared by using HttpServletRequest::setAttribute. The getReader method empties the buffer, where getParameter empties the buffer too but stores the parameters automagically.
String input = null;
// we have to store the string, which can only be read one time, because when the
// servlet awakens an AsyncContext, it reposts the request and returns here empty handed
if ((input = (String) request.getAttribute("com.xp.input")) == null) {
StringBuilder buffer = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while((line = reader.readLine()) != null){
buffer.append(line);
}
// reqBytes = buffer.toString().getBytes();
input = buffer.toString();
request.setAttribute("com.xp.input", input);
}
if (input == null) {
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.print("{\"act\":\"fail\",\"msg\":\"invalid\"}");
}
As Matt said, the curly braces are for concatenation. The extra curly braces around 16{a[15]}
are the replication operator. They are described in the IEEE Standard for Verilog document (Std 1364-2005), section "5.1.14 Concatenations".
{16{a[15]}}
is the same as
{
a[15], a[15], a[15], a[15], a[15], a[15], a[15], a[15],
a[15], a[15], a[15], a[15], a[15], a[15], a[15], a[15]
}
In bit-blasted form,
assign result = {{16{a[15]}}, {a[15:0]}};
is the same as:
assign result[ 0] = a[ 0];
assign result[ 1] = a[ 1];
assign result[ 2] = a[ 2];
assign result[ 3] = a[ 3];
assign result[ 4] = a[ 4];
assign result[ 5] = a[ 5];
assign result[ 6] = a[ 6];
assign result[ 7] = a[ 7];
assign result[ 8] = a[ 8];
assign result[ 9] = a[ 9];
assign result[10] = a[10];
assign result[11] = a[11];
assign result[12] = a[12];
assign result[13] = a[13];
assign result[14] = a[14];
assign result[15] = a[15];
assign result[16] = a[15];
assign result[17] = a[15];
assign result[18] = a[15];
assign result[19] = a[15];
assign result[20] = a[15];
assign result[21] = a[15];
assign result[22] = a[15];
assign result[23] = a[15];
assign result[24] = a[15];
assign result[25] = a[15];
assign result[26] = a[15];
assign result[27] = a[15];
assign result[28] = a[15];
assign result[29] = a[15];
assign result[30] = a[15];
assign result[31] = a[15];
A simpler way would be to create a link called cudart64_101.dll
to point to cudart64_102.dll
. This is not very orthodox but since TensorFlow is looking for cudart64_101.dll
exported symbols and the nvidia folks are not amateurs, they would most likely not remove symbols from 101 to 102. It works, based on this assumption (mileage may vary).
If you already have an existent data frame, let's say df
that has the columns you want, then you can just create an empty data frame by removing all the rows:
empty_df = df[FALSE,]
Notice that df
still contains the data, but empty_df
doesn't.
I found this question looking for how to create a new instance with empty rows, so I think it might be helpful for some people.
They always say it depends but when it comes to mirroring a website The best exists httrack. It is super fast and easy to work. The only downside is it's so called support forum but you can find your way using official documentation. It has both GUI and CLI interface and it Supports cookies just read the docs This is the best.(Be cureful with this tool you can download the whole web on your harddrive)
httrack -c8 [url]
By default maximum number of simultaneous connections limited to 8 to avoid server overload
I use highcharts. They are very interactive (and very fancy I might add). You do have to get a little creative to access data from MySQL database, but if you have a general understanding of JavaScript and PHP, you should have no problems.
Firstly, do not use the Tab key in Vim for manual indentation. Vim has a pair of commands in insert mode for manually increasing or decreasing the indentation amount. Those commands are Ctrl-T and Ctrl-D. These commands observe the values of tabstop
, shiftwidth
and expandtab
, and maintain the correct mixture of spaces and tabs (maximum number of tabs followed by any necessary number of spaces).
Secondly, these manual indenting keys don't have to be used very much anyway if you use automatic indentation.
If Ctrl-T instead of Tab bothers you, you can remap it:
:imap <Tab> ^T
You can also remap Shift-Tab to do the Ctrl-D deindent:
:imap <S-Tab> ^D
Here ^T and ^D are literal control characters that can be inserted as Ctrl-VCtrl-T.
With this mapping in place, you can still type literal Tab into the buffer using Ctrl-VTab. Note that if you do this, even if :set expandtab
is on, you get an unexpanded tab character.
A similar effect to the <Tab>
map is achieved using :set smarttab
, which also causes backspace at the front of a line to behave smart.
In smarttab
mode, when Tab is used not at the start of a line, it has no special meaning. That's different from my above mapping of Tab to Ctrl-T, because a Ctrl-T used anywhere in a line (in insert mode) will increase that line's indentation.
Other useful mappings may be:
:map <Tab> >
:map <S-Tab> <
Now we can do things like select some lines, and hit Tab to indent them over. Or hit Tab twice on a line (in command mode) to increase its indentation.
If you use the proper indentation management commands, then everything is controlled by the three parameters: shiftwidth
, tabstop
and expandtab
.
The shiftwidth
parameter controls your indentation size; if you want four space indents, use :set shiftwidth=4
, or the abbreviation :set sw=4
.
If only this is done, then indentation will be created using a mixture of spaces and tabs, because noexpandtab
is the default. Use :set expandtab
. This causes tab characters which you type into the buffer to expand into spaces, and for Vim-managed indentation to use only spaces.
When expandtab
is on, and if you manage your indentation through all the proper Vim mechanisms, the value of tabstop
becomes irrelevant. It controls how tabs appear if they happen to occur in the file. If you have set tabstop=8 expandtab
and then sneak a hard tab into the file using Ctrl-VTab, it will produce an alignment to the next 8-column-based tab position, as usual.
I'd like to point out few more solutions to transposing columns and rows in SQL.
The first one is - using CURSOR. Although the general consensus in the professional community is to stay away from SQL Server Cursors, there are still instances whereby the use of cursors is recommended. Anyway, Cursors present us with another option to transpose rows into columns.
Vertical expansion
Similar to the PIVOT, the cursor has the dynamic capability to append more rows as your dataset expands to include more policy numbers.
Horizontal expansion
Unlike the PIVOT, the cursor excels in this area as it is able to expand to include newly added document, without altering the script.
Performance breakdown
The major limitation of transposing rows into columns using CURSOR is a disadvantage that is linked to using cursors in general – they come at significant performance cost. This is because the Cursor generates a separate query for each FETCH NEXT operation.
Another solution of transposing rows into columns is by using XML.
The XML solution to transposing rows into columns is basically an optimal version of the PIVOT in that it addresses the dynamic column limitation.
The XML version of the script addresses this limitation by using a combination of XML Path, dynamic T-SQL and some built-in functions (i.e. STUFF, QUOTENAME).
Vertical expansion
Similar to the PIVOT and the Cursor, newly added policies are able to be retrieved in the XML version of the script without altering the original script.
Horizontal expansion
Unlike the PIVOT, newly added documents can be displayed without altering the script.
Performance breakdown
In terms of IO, the statistics of the XML version of the script is almost similar to the PIVOT – the only difference is that the XML has a second scan of dtTranspose table but this time from a logical read – data cache.
You can find some more about these solutions (including some actual T-SQL exmaples) in this article: https://www.sqlshack.com/multiple-options-to-transposing-rows-into-columns/
public static byte[] serialize(Object obj) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(out);
os.writeObject(obj);
return out.toByteArray();
}
public static Object deserialize(byte[] data) throws IOException, ClassNotFoundException {
ByteArrayInputStream in = new ByteArrayInputStream(data);
ObjectInputStream is = new ObjectInputStream(in);
return is.readObject();
}
Slightly shorter jQuery version:
$('your-element').focus(function(e) {
e.target.select();
jQuery(e.target).one('mouseup', function(e) {
e.preventDefault();
});
});
It handles the Chrome corner case correctly. See http://jsfiddle.net/Ztyx/XMkwm/ for an example.
You can use:
str.replace(/text/g, "replaced text");
As an extension to existing answers. For those trying to continue a numbered list after something other than a code block. For example a second paragraph. Just indent the second paragraph by at least 1 space.
Markdown:
1. one
2. two
three
3. four
Output:
one
two
three
four
You are testing if the values of the variables error
and Already
are present in RepoOutput[RepoName.index(repo)]
. If these variables don't exist then an undefined object is used.
Both of your if
and elif
tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].
I think you wanted to test if certain strings are in the value instead:
{% if "error" in RepoOutput[RepoName.index(repo)] %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
<td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>
Other corrections I made:
{% elif ... %}
instead of {$ elif ... %}
.</tr>
tag out of the if
conditional structure, it needs to be there always.id
attributeNote that most likely you want to use a class
attribute instead here, not an id
, the latter must have a value that must be unique across your HTML document.
Personally, I'd set the class value here and reduce the duplication a little:
{% if "Already" in RepoOutput[RepoName.index(repo)] %}
{% set row_class = "good" %}
{% else %}
{% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>
This took a while to get right. I had this issue when cross-compiling in Ubuntu for an ARM target. I solved it with:
PATH=$PATH:/ccpath/bin CC=ccname-gcc AR=ccname-ar LD=ccname-ld CPPFLAGS="-nostdinc -I/ccrootfs/usr/include ..." LDFLAGS=-L/ccrootfs/usr/lib ./autogen.sh --build=`config.guess` --host=armv5tejl-unknown-linux-gnueabihf
Notice CFLAGS is not used with autogen.sh/configure, using it gave me the error: "configure: error: C compiler cannot create executables". In the build environment I was using an autogen.sh script was provided, if you don't have an autogen.sh script substitute ./autogen.sh with ./configure in the command above. I ran config.guess on the target system to get the --host parameter.
After successfully running autogen.sh/configure, compile with:
PATH=$PATH:/ccpath/bin CC=ccname-gcc AR=ccname-ar LD=ccname-ld CPPFLAGS="-nostdinc -I/ccrootfs/usr/include ..." LDFLAGS=-L/ccrootfs/usr/lib CFLAGS="-march=... -mcpu=... etc." make
The CFLAGS I chose to use were: "-march=armv5te -fno-tree-vectorize -mthumb-interwork -mcpu=arm926ej-s". It will take a while to get all of the include directories set up correctly: you might want some includes pointing to your cross-compiler and some pointing to your root file system includes, and there will likely be some conflicts.
I'm sure this is not the perfect answer. And I am still seeing some include directories pointing to / and not /ccrootfs in the Makefiles. Would love to know how to correct this. Hope this helps someone.
This will give you a nice object to work with
function queryParameters () {
var result = {};
var params = window.location.search.split(/\?|\&/);
params.forEach( function(it) {
if (it) {
var param = it.split("=");
result[param[0]] = param[1];
}
});
return result;
}
And then;
if (queryParameters().sent === 'yes') { .....
Just add this...or you can change the colors as per your demand.
Highcharts.setOptions({
colors: ['#811010', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4'],
plotOptions: {
column: {
colorByPoint: true
}
}
});
Aside from using the edit menu commands, you can directly paste into the git bash window using the keyboard shortcut, Insert.
If you are using Java with Hibernate then using NUMBER(1,0) is the best approach. As you can see in here, this value is automatically translated to Boolean by Hibernate.
You can add Apache Commons Lang
in Gradle like compile 'org.apache.commons:commons-lang3:3.4'
And use WordUtils.capitalizeFully(name)
try this. There are in general three ways to use mysqldump—
in order to dump a set of one or more tables,
shell> mysqldump [options] db_name [tbl_name ...]
a set of one or more complete databases
shell> mysqldump [options] --databases db_name ...
or an entire MySQL server—as shown here:
shell> mysqldump [options] --all-databases
In your form tag just paste this:
onkeypress="return event.keyCode != 13;"
Example
<input type="text" class="search" placeholder="search" onkeypress="return event.keyCode != 13;">
This can be useful if you want to do search when typing and ignoring ENTER.
/// Grab the search term
const searchInput = document.querySelector('.search')
/// Update search term when typing
searchInput.addEventListener('keyup', displayMatches)
Here is the solution for API < 21 and above
Drawable drawable = yourEditText.getBackground(); // get current EditText drawable
drawable.setColorFilter(Color.GREEN, PorterDuff.Mode.SRC_ATOP); // change the drawable color
if(Build.VERSION.SDK_INT > 16) {
yourEditText.setBackground(drawable); // set the new drawable to EditText
}else{
yourEditText.setBackgroundDrawable(drawable); // use setBackgroundDrawable because setBackground required API 16
}
Hope it help
I managed to find a blog post on the subject, which links off to an open source project that implements RestSharp. Hopefully of some help to you.
http://dkdevelopment.net/2010/05/18/dropbox-api-and-restsharp-for-a-c-developer/ The blog post is a 2 parter, and the project is here: https://github.com/dkarzon/DropNet
It might help if you had a full example of what wasn't working. It's difficult to get context on how the client was set up if you don't provide the code.
This is because there is not only 1 answer...
shell
command line expansionxargs
dedicated toolwhile read
with some remarkswhile read -u
using dedicated fd
, for interactive processing (sample)Regarding the OP request: running chmod
on all targets listed in file, xargs
is the indicated tool. But for some other applications, small amount of files, etc...
If your file is not too big and all files are well named (without spaces or other special chars like quotes), you could use shell
command line expansion. Simply:
chmod 755 $(<file.txt)
For small amount of files (lines), this command is the lighter one.
xargs
is the right toolFor bigger amount of files, or almost any number of lines in your input file...
For many binutils tools, like chown
, chmod
, rm
, cp -t
...
xargs chmod 755 <file.txt
If you have special chars and/or a lot of lines in file.txt
.
xargs -0 chmod 755 < <(tr \\n \\0 <file.txt)
if your command need to be run exactly 1 time by entry:
xargs -0 -n 1 chmod 755 < <(tr \\n \\0 <file.txt)
This is not needed for this sample, as chmod
accept multiple files as argument, but this match the title of question.
For some special case, you could even define location of file argument in commands generateds by xargs
:
xargs -0 -I '{}' -n 1 myWrapper -arg1 -file='{}' wrapCmd < <(tr \\n \\0 <file.txt)
seq 1 5
as inputTry this:
xargs -n 1 -I{} echo Blah {} blabla {}.. < <(seq 1 5)
Blah 1 blabla 1..
Blah 2 blabla 2..
Blah 3 blabla 3..
Blah 4 blabla 4..
Blah 5 blabla 5..
Where commande is done once per line.
while read
and variants.As OP suggest cat file.txt | while read in; do chmod 755 "$in"; done
will work, but there is 2 issues:
cat |
is an useless fork, and
| while ... ;done
will become a subshell where environment will disapear after ;done
.
So this could be better written:
while read in; do chmod 755 "$in"; done < file.txt
But,
You may be warned about $IFS
and read
flags:
help read
read: read [-r] ... [-d delim] ... [name ...] ... Reads a single line from the standard input... The line is split into fields as with word splitting, and the first word is assigned to the first NAME, the second word to the second NAME, and so on... Only the characters found in $IFS are recognized as word delimiters. ... Options: ... -d delim continue until the first character of DELIM is read, rather than newline ... -r do not allow backslashes to escape any characters ... Exit Status: The return code is zero, unless end-of-file is encountered...
In some case, you may need to use
while IFS= read -r in;do chmod 755 "$in";done <file.txt
For avoiding problems with stranges filenames. And maybe if you encouter problems with UTF-8
:
while LANG=C IFS= read -r in ; do chmod 755 "$in";done <file.txt
While you use STDIN
for reading file.txt
, your script could not be interactive (you cannot use STDIN
anymore).
while read -u
, using dedicated fd
.Syntax: while read ...;done <file.txt
will redirect STDIN
to file.txt
. That mean, you won't be able to deal with process, until they finish.
If you plan to create interactive tool, you have to avoid use of STDIN
and use some alternative file descriptor.
Constants file descriptors are: 0
for STDIN, 1
for STDOUT and 2
for STDERR. You could see them by:
ls -l /dev/fd/
or
ls -l /proc/self/fd/
From there, you have to choose unused number, between 0
and 63
(more, in fact, depending on sysctl
superuser tool) as file descriptor:
For this demo, I will use fd 7
:
exec 7<file.txt # Without spaces between `7` and `<`!
ls -l /dev/fd/
Then you could use read -u 7
this way:
while read -u 7 filename;do
ans=;while [ -z "$ans" ];do
read -p "Process file '$filename' (y/n)? " -sn1 foo
[ "$foo" ]&& [ -z "${foo/[yn]}" ]&& ans=$foo || echo '??'
done
if [ "$ans" = "y" ] ;then
echo Yes
echo "Processing '$filename'."
else
echo No
fi
done 7<file.txt
done
To close fd/7
:
exec 7<&- # This will close file descriptor 7.
ls -l /dev/fd/
Nota: I let striked version because this syntax could be usefull, when doing many I/O with parallels process:
mkfifo sshfifo
exec 7> >(ssh -t user@host sh >sshfifo)
exec 6<sshfifo
Random rand = new Random();
int name = rand.Next()
Put whatever values you want in the second parentheses make sure you have set a name by writing prop and double tab to generate the code
To check configuration files for syntax errors:
# Red Hat-based (Fedora, CentOS) and OSX
httpd -t
# Debian-based (Ubuntu)
apache2ctl -t
# MacOS
apachectl -t
To list all virtual hosts, and their locations:
# Red Hat-based (Fedora, CentOS) and OSX
httpd -S
# Debian-based (Ubuntu)
apache2ctl -S
# MacOS
apachectl -S
file.delete();
if the file doesn't exist, it will return false.
You can't just take the returned string and construct a string from it... it's not a byte[]
data type anymore, it's already a string; you need to parse it. For example :
String response = "[-47, 1, 16, 84, 2, 101, 110, 83, 111, 109, 101, 32, 78, 70, 67, 32, 68, 97, 116, 97]"; // response from the Python script
String[] byteValues = response.substring(1, response.length() - 1).split(",");
byte[] bytes = new byte[byteValues.length];
for (int i=0, len=bytes.length; i<len; i++) {
bytes[i] = Byte.parseByte(byteValues[i].trim());
}
String str = new String(bytes);
** EDIT **
You get an hint of your problem in your question, where you say "Whatever I seem to try I end up getting a byte array which looks as follows... [91, 45, ...
", because 91
is the byte value for [
, so [91, 45, ...
is the byte array of the string "[-45, 1, 16, ...
" string.
The method Arrays.toString()
will return a String
representation of the specified array; meaning that the returned value will not be a array anymore. For example :
byte[] b1 = new byte[] {97, 98, 99};
String s1 = Arrays.toString(b1);
String s2 = new String(b1);
System.out.println(s1); // -> "[97, 98, 99]"
System.out.println(s2); // -> "abc";
As you can see, s1
holds the string representation of the array b1
, while s2
holds the string representation of the bytes contained in b1
.
Now, in your problem, your server returns a string similar to s1
, therefore to get the array representation back, you need the opposite constructor method. If s2.getBytes()
is the opposite of new String(b1)
, you need to find the opposite of Arrays.toString(b1)
, thus the code I pasted in the first snippet of this answer.
Use arbitrary, extensible object, and then serialize it to JSON:
import json
class Object(object):
pass
response = Object()
response.debug = []
response.result = Object()
# Any manipulations with the object:
response.debug.append("Debug string here")
response.result.body = "404 Not Found"
response.result.code = 404
# Proper JSON output, with nice formatting:
print(json.dumps(response, indent=4, default=lambda x: x.__dict__))
Here's one solution that I'd use:
var div = '<div id="yourId" class="yourClass" yourAttribute="yourAttributeValue">blah</div>';
If you wanted the attribute and/or attribute values to be based on variables:
var id = "hello";
var classAttr = "class";
var div = '<div id='+id+' '+classAttr+'="world" >Blah</div>';
Then, to append to the body:
document.getElementsByTagName("body").innerHTML = div;
Easy as pie.
A method I use in my login servlet to verify reCaptcha responses. Uses classes from the java.json package. Returns the API response in a JsonObject.
Check the success field for true or false
private JsonObject validateCaptcha(String secret, String response, String remoteip)
{
JsonObject jsonObject = null;
URLConnection connection = null;
InputStream is = null;
String charset = java.nio.charset.StandardCharsets.UTF_8.name();
String url = "https://www.google.com/recaptcha/api/siteverify";
try {
String query = String.format("secret=%s&response=%s&remoteip=%s",
URLEncoder.encode(secret, charset),
URLEncoder.encode(response, charset),
URLEncoder.encode(remoteip, charset));
connection = new URL(url + "?" + query).openConnection();
is = connection.getInputStream();
JsonReader rdr = Json.createReader(is);
jsonObject = rdr.readObject();
} catch (IOException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
return jsonObject;
}
test.php
<?php
return [
'my_key_1'=>'1111111',
'my_key_2'=>'2222222',
];
index.php
// Read array from file
$my_arr = include './test.php';
$my_arr["my_key_1"] = "3333333";
echo write_arr_to_file($my_arr, "./test.php");
/**
* @param array $arr <p>array</p>
* @param string $path <p>path to file</p>
* example :: "./test.php"
* @return bool <b>FALSE</b> occurred error
* more info: about "file_put_contents" https://www.php.net/manual/ru/function.file-put-contents.php
**/
function write_arr_to_file($arr, $path){
$data = "\n";
foreach ($arr as $key => $value) {
$data = $data." '".$key."'=>'".$value."',\n";
}
return file_put_contents($path, "<?php \nreturn [".$data."];");
}
I had similar error. When i use
<style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">#673AB7</item>
<item name="colorPrimaryDark">#512DA8</item>
<item name="colorAccent">#00BCD4</item>
<item name="android:textColorPrimary">#212121</item>
<item name="android:textColorSecondary">#727272</item>
</style>
works for me when i remove the android:textColorPrimary and android:textColorSecondary theme items.
<style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">#673AB7</item>
<item name="colorPrimaryDark">#512DA8</item>
<item name="colorAccent">#00BCD4</item>
</style>
Try working with a very simple App theme to start off with.
EDIT:
This tutorial will help. My understanding is that using "android:textColorPrimary" requires minimum api level 21. Using the same tag without "android:" uses the design support library. Any support library widget will try to find the "textColorPrimary" item instead of "android:textColorPrimary" and if it fails to find the same it throws the above mentioned error.
None of the other solutions worked for me, but this does:
Create your own subclass of UINavigationController, make it implement the UINavigationBarDelegate (no need to manually set the navigation bar's delegate), add a UIViewController extension that defines a method to be called on a back button press, and then implement this method in your UINavigationController subclass:
func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {
self.topViewController?.methodToBeCalledOnBackButtonPress()
self.popViewController(animated: true)
return true
}
I use ExpressMaint.
To backup all user databases I do for example:
C:\>ExpressMaint.exe -S (local)\sqlexpress -D ALL_USER -T DB -BU HOURS -BV 1 -B c:\backupdir\ -DS
Use fgets
and strtol
,
A pointer to the first character following the integer representation in s
is stored in the object pointed by p
, if *p
is different to \n
then you have a bad input.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *p, s[100];
long n;
while (fgets(s, sizeof(s), stdin)) {
n = strtol(s, &p, 10);
if (p == s || *p != '\n') {
printf("Please enter an integer: ");
} else break;
}
printf("You entered: %ld\n", n);
return 0;
}
No, the methods don't need to be synchronized, and you don't need to define any methods; they are already in ConcurrentLinkedQueue, just use them. ConcurrentLinkedQueue does all the locking and other operations you need internally; your producer(s) adds data into the queue, and your consumers poll for it.
First, create your queue:
Queue<YourObject> queue = new ConcurrentLinkedQueue<YourObject>();
Now, wherever you are creating your producer/consumer objects, pass in the queue so they have somewhere to put their objects (you could use a setter for this, instead, but I prefer to do this kind of thing in a constructor):
YourProducer producer = new YourProducer(queue);
and:
YourConsumer consumer = new YourConsumer(queue);
and add stuff to it in your producer:
queue.offer(myObject);
and take stuff out in your consumer (if the queue is empty, poll() will return null, so check it):
YourObject myObject = queue.poll();
For more info see the Javadoc
If you need to block waiting for the queue to not be empty, you probably want to use a LinkedBlockingQueue, and use the take() method. However, LinkedBlockingQueue has a maximum capacity (defaults to Integer.MAX_VALUE, which is over two billion) and thus may or may not be appropriate depending on your circumstances.
If you only have one thread putting stuff into the queue, and another thread taking stuff out of the queue, ConcurrentLinkedQueue is probably overkill. It's more for when you may have hundreds or even thousands of threads accessing the queue at the same time. Your needs will probably be met by using:
Queue<YourObject> queue = Collections.synchronizedList(new LinkedList<YourObject>());
A plus of this is that it locks on the instance (queue), so you can synchronize on queue to ensure atomicity of composite operations (as explained by Jared). You CANNOT do this with a ConcurrentLinkedQueue, as all operations are done WITHOUT locking on the instance (using java.util.concurrent.atomic variables). You will NOT need to do this if you want to block while the queue is empty, because poll() will simply return null while the queue is empty, and poll() is atomic. Check to see if poll() returns null. If it does, wait(), then try again. No need to lock.
Honestly, I'd just use a LinkedBlockingQueue. It is still overkill for your application, but odds are it will work fine. If it isn't performant enough (PROFILE!), you can always try something else, and it means you don't have to deal with ANY synchronized stuff:
BlockingQueue<YourObject> queue = new LinkedBlockingQueue<YourObject>();
queue.put(myObject); // Blocks until queue isn't full.
YourObject myObject = queue.take(); // Blocks until queue isn't empty.
Everything else is the same. Put probably won't block, because you aren't likely to put two billion objects into the queue.
All you are wanting to do is to see if computers are connected to the network and to gather their IP addresses. You can utilize angryIP scanner: http://angryip.org/ to see what IP addresses are in use on a particular subnet or groups of subnets.
I have found this tool very helpful when trying to see what IPs are being used that are not located inside of my DHCP.
The -s
switch disables per-test capturing (only if a test fails).
Use android vollley, it is very fast and you can betterm manipulate requests. Send post request using Volley and receive in PHP
Basically, you will create a map with key-value params for the php request(POST/GET), the php will do the desired processing and you will return the data as JSON(json_encode()). Then you can either parse the JSON as needed or use GSON from Google to let it do the parsing.
I was able to resolve this by writing the code below. I used executeUpdate instead of .delete()
def publicSupport = caseObj?.client?.publicSupport
if(publicSupport)
PublicSupport.executeUpdate("delete PublicSupport c where c.id = :publicSupportId", [publicSupportId:publicSupport.id])
//publicSupport.delete()
test.xml:
<?xml version="1.0" encoding="utf-8"?>
<Contacts>
<Node>
<ID>123</ID>
<Name>ABC</Name>
</Node>
<Node>
<ID>124</ID>
<Name>DEF</Name>
</Node>
</Contacts>
Select a single node:
XDocument XMLDoc = XDocument.Load("test.xml");
string id = "123"; // id to be selected
XElement Contact = (from xml2 in XMLDoc.Descendants("Node")
where xml2.Element("ID").Value == id
select xml2).FirstOrDefault();
Console.WriteLine(Contact.ToString());
Delete a single node:
XDocument XMLDoc = XDocument.Load("test.xml");
string id = "123";
var Contact = (from xml2 in XMLDoc.Descendants("Node")
where xml2.Element("ID").Value == id
select xml2).FirstOrDefault();
Contact.Remove();
XMLDoc.Save("test.xml");
Add new node:
XDocument XMLDoc = XDocument.Load("test.xml");
XElement newNode = new XElement("Node",
new XElement("ID", "500"),
new XElement("Name", "Whatever")
);
XMLDoc.Element("Contacts").Add(newNode);
XMLDoc.Save("test.xml");
#1 Using Jest
This is how I use the Jest mock callback function to test the click event:
import React from 'react';
import { shallow } from 'enzyme';
import Button from './Button';
describe('Test Button component', () => {
it('Test click event', () => {
const mockCallBack = jest.fn();
const button = shallow((<Button onClick={mockCallBack}>Ok!</Button>));
button.find('button').simulate('click');
expect(mockCallBack.mock.calls.length).toEqual(1);
});
});
I am also using a module called enzyme. Enzyme is a testing utility that makes it easier to assert and select your React Components
#2 Using Sinon
Also, you can use another module called Sinon which is a standalone test spy, stubs and mocks for JavaScript. This is how it looks:
import React from 'react';
import { shallow } from 'enzyme';
import sinon from 'sinon';
import Button from './Button';
describe('Test Button component', () => {
it('simulates click events', () => {
const mockCallBack = sinon.spy();
const button = shallow((<Button onClick={mockCallBack}>Ok!</Button>));
button.find('button').simulate('click');
expect(mockCallBack).toHaveProperty('callCount', 1);
});
});
#3 Using Your own Spy
Finally, you can make your own naive spy (I don't recommend this approach unless you have a valid reason for that).
function MySpy() {
this.calls = 0;
}
MySpy.prototype.fn = function () {
return () => this.calls++;
}
it('Test Button component', () => {
const mySpy = new MySpy();
const mockCallBack = mySpy.fn();
const button = shallow((<Button onClick={mockCallBack}>Ok!</Button>));
button.find('button').simulate('click');
expect(mySpy.calls).toEqual(1);
});
Pushing multiple objects at once often depends on how are you declaring your array
.
This is how I did
//declaration
productList= [] as any;
now push
records
this.productList.push(obj.lenght, obj2.lenght, items);
I hope you cant wait till apple gives you what ever you need right? So here is my option.
Create a custom cell. Have two uiviews in it
1. upper
2. lower
In lower view, add what ever buttons you need. Deal its actions just like any other IBActions. you can decide the animation time, style and anything.
now add a uiswipegesture to the upper view and reveal your lower view on swipe gesture. I have done this before and its the simplest option as far as I am concerned.
Hope that help.
Write below code into your MainActivity file after setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
And below import statement into your java file.
import android.os.StrictMode;
You can also try adding the Motumedia PPA to your apt sources and update your ffmpeg packages.
Your variable energies
probably has the wrong shape:
>>> from numpy import array
>>> set([1,2,3]) & set(range(2, 10))
set([2, 3])
>>> set(array([1,2,3])) & set(range(2,10))
set([2, 3])
>>> set(array([[1,2,3],])) & set(range(2,10))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'numpy.ndarray'
And that's what happens if you read columnar data using your approach:
>>> data
array([[ 1., 2., 3.],
[ 3., 4., 5.],
[ 5., 6., 7.],
[ 8., 9., 10.]])
>>> hsplit(data,3)[0]
array([[ 1.],
[ 3.],
[ 5.],
[ 8.]])
Probably you can simply use
>>> data[:,0]
array([ 1., 3., 5., 8.])
instead.
(P.S. Your code looks like it's undecided about whether it's data
or elementdata
. I've assumed it's simply a typo.)
You dont need to use a regex for this, PHP has an inbuilt function ctype_alnum
which will do this for you, and execute faster:
<?php
$strings = array('AbCd1zyZ9', 'foo!#$bar');
foreach ($strings as $testcase) {
if (ctype_alnum($testcase)) {
echo "The string $testcase consists of all letters or digits.\n";
} else {
echo "The string $testcase does not consist of all letters or digits.\n";
}
}
?>
If you desperately want to use a regex, you have a few options.
Firstly:
preg_match('/^[\w]+$/', $string);
\w
includes more than alphanumeric (it includes underscore), but includes all
of \d
.
Alternatively:
/^[a-zA-Z\d]+$/
Or even just:
/^[^\W_]+$/
An alternative to other layouts, might be to put your panel with the GridLayout, inside another panel that is a FlowLayout. That way your spacing will be intact but will not expand across the entire available space.
Start with the use of tabs - the \t character modifier. It will advance to a fixed location (columns, terminal lingo).
However, it doesn't help if there are differences of more than the column width (4 characters, if I recall correctly).
To fix that, write your "OK/NOK" stuff using a fixed number of tabs (5? 6?, try it). Then return (\r) without new-lining, and write your message.
Note your code contains Dir("thesentence")
which should be Dir(thesentence)
.
Change your code to this
Sub test()
thesentence = InputBox("Type the filename with full extension", "Raw Data File")
Range("A1").Value = thesentence
If Dir(thesentence) <> "" Then
MsgBox "File exists."
Else
MsgBox "File doesn't exist."
End If
End Sub
I found xip.io which automatically converts a fixed url to a embedded localhost domain.
For example lets say your localhost server is running on 127.0.0.1:8000
You can go to http://www.127.0.0.1.xip.io:5555/
to access this server.
You can then add this address to Oauth configuration for Facebook or Google.
Using bash
:
echo "|${COMMAND/$'\n'}|"
(Note that the control character in this question is a 'newline' (\n
), not a carriage return (\r
); the latter would have output REBOOT|
on a single line.)
Uses the Bash Shell Parameter Expansion ${parameter/pattern/string}
:
The pattern is expanded to produce a pattern just as in filename expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. [...] If string is null, matches of pattern are deleted and the / following pattern may be omitted.
Also uses the $''
ANSI-C quoting construct to specify a newline as $'\n'
. Using a newline directly would work as well, though less pretty:
echo "|${COMMAND/
}|"
#!/bin/bash
COMMAND="$'\n'REBOOT"
echo "|${COMMAND/$'\n'}|"
# Outputs |REBOOT|
Or, using newlines:
#!/bin/bash
COMMAND="
REBOOT"
echo "|${COMMAND/
}|"
# Outputs |REBOOT|
(Tested on Oracle 11g
)
About AS
:
AS
is optional.AS
shouldn't be added, otherwise it's an error.About double quote
:
e.g
-- 'AS' is optional for result column
select (1+1) as result from dual;
select (1+1) result from dual;
-- 'AS' shouldn't be used for table name
select 'hi' from dual d;
-- Adding double quotes for alias name is optional, but valid for both result column & table name,
select (1+1) as "result" from dual;
select (1+1) "result" from dual;
select 'hi' from dual "d";
This is how to get JavaScriptSerializer available in your application, targetting .NET 4.0
(full)
using System.Web.Script.Serialization;
This should allow you to create a new JavaScriptSerializer
object!
In the special case that you are creating a new repository starting from an old repository that you used as template (Don't do this if this is not your case). Completely erase the git files of the old repository so you can start a new one:
rm -rf .git
And then restart a new git repository as usual:
git init
git add whatever.wvr ("git add --all" if you want to add all files)
git commit -m "first commit"
git remote add origin [email protected]:ppreyer/first_app.git
git push -u origin master
If I understand your question correctly, you need %p
to show the address that a pointer is using, for example:
int main() {
int a = 5;
int *p = &a;
printf("%d, %u, %p", p, p, p);
return 0;
}
will output something like:
-1083791044, 3211176252, 0xbf66a93c
As of Django 1.5, there is an update_fields property on model save. eg:
obj.save(update_fields=['field1', 'field2', ...])
https://docs.djangoproject.com/en/dev/ref/models/instances/
I prefer this approach because it doesn't create an atomicity problem if you have multiple web app instances changing different parts of a model instance.
You can get the instance of the controller from the FXMLLoader
after initialization via getController()
, but you need to instantiate an FXMLLoader
instead of using the static methods then.
I'd pass the stage after calling load()
directly to the controller afterwards:
FXMLLoader loader = new FXMLLoader(getClass().getResource("MyGui.fxml"));
Parent root = (Parent)loader.load();
MyController controller = (MyController)loader.getController();
controller.setStageAndSetupListeners(stage); // or what you want to do
My DBA asked me when I asked about the best way to store GUIDs for my objects why I needed to store 16 bytes when I could do the same thing in 4 bytes with an Integer. Since he put that challenge out there to me I thought now was a good time to mention it. That being said...
You can store a guid as a CHAR(16) binary if you want to make the most optimal use of storage space.
The problem is with slashes: your variable contains them and the final command will be something like sed "s/string/path/to/something/g"
, containing way too many slashes.
Since sed
can take any char as delimiter (without having to declare the new delimiter), you can try using another one that doesn't appear in your replacement string:
replacement="/my/path"
sed --expression "s@pattern@$replacement@"
Note that this is not bullet proof: if the replacement string later contains @
it will break for the same reason, and any backslash sequences like \1
will still be interpreted according to sed
rules. Using |
as a delimiter is also a nice option as it is similar in readability to /
.
Try this:
var myarray =[],
i = myarray.lenght;
while(i--){
// do somthing
}
This can happen if curl is asked to do plain HTTP on a server that does HTTPS.
Example:
$ curl http://google.com:443
curl: (52) Empty reply from server
In my case, this error occurred because I was typing the commit message and my notebook turned off.
I did these steps to fix the error:
git checkout -b backup-branch
# Create a backup branchgit reset --hard HEAD~4
# Reset to the commit where everything works well. In my case, I had to back 4 commits in the head, that is until my head be at the point before I was typing the commit message. Before doing this step, copy the hash of the commits you will reset, in my case I copied the hash of the 4 last commitsgit cherry-pick <commit-hash>
# Cherry pick the reseted commits (in my case are 4 commits, so I did this step 4 times) from the old branch to the new branch. git push origin backup-branch
# Push the new branch to be sure everything works wellgit branch -D your-branch
# Delete the branch locally ('your-branch' is the branch with problem)git push origin :your-branch
# Delete the branch from remotegit branch -m backup-branch your-branch
# Rename the backup branch to have the name of the branch that had the problemgit push origin your-branch
# Push the new branchgit push origin :backup-branch
# Delete the backup branch from remoteSet the form's .TopMost
property to true.
You probably don't want to leave it this way all the time: set it when your external process starts and put it back when it finishes.
It might also be an OpenJDK bug... (not in this case but it is the same error)
If somebody like me stumbles upon this answer regarding the
java.lang.IllegalArgumentException: Comparison method violates its general contract!
then it might also be a bug in the Java-Version. I have a compareTo running since several years now in some applications. But suddenly it stopped working and throws the error after all compares were done (i compare 6 Attributes before returning "0").
Now I just found this Bugreport of OpenJDK:
Let's go over the basics: "Accessor" and "Mutator" are just fancy names fot a getter and a setter. A getter, "Accessor", returns a class's variable or its value. A setter, "Mutator", sets a class variable pointer or its value.
So first you need to set up a class with some variables to get/set:
public class IDCard
{
private String mName;
private String mFileName;
private int mID;
}
But oh no! If you instantiate this class the default values for these variables will be meaningless. B.T.W. "instantiate" is a fancy word for doing:
IDCard test = new IDCard();
So - let's set up a default constructor, this is the method being called when you "instantiate" a class.
public IDCard()
{
mName = "";
mFileName = "";
mID = -1;
}
But what if we do know the values we wanna give our variables? So let's make another constructor, one that takes parameters:
public IDCard(String name, int ID, String filename)
{
mName = name;
mID = ID;
mFileName = filename;
}
Wow - this is nice. But stupid. Because we have no way of accessing (=reading) the values of our variables. So let's add a getter, and while we're at it, add a setter as well:
public String getName()
{
return mName;
}
public void setName( String name )
{
mName = name;
}
Nice. Now we can access mName
. Add the rest of the accessors and mutators and you're now a certified Java newbie.
Good luck.
@ is a shortcut option for v-on. Use @ only when you want to execute some Vue methods. As you are not executing Vue methods, instead you are calling javascript function, you need to use onchange attribute to call javascript function
<select name="LeaveType" onchange="onChange(this.value)" class="form-control">
<option value="1">Annual Leave/ Off-Day</option>
<option value="2">On Demand Leave</option>
</select>
function onChange(value) {
console.log(value);
}
If you want to call Vue methods, do it like this-
<select name="LeaveType" @change="onChange($event)" class="form-control">
<option value="1">Annual Leave/ Off-Day</option>
<option value="2">On Demand Leave</option>
</select>
new Vue({
...
...
methods:{
onChange:function(event){
console.log(event.target.value);
}
}
})
You can use v-model data attribute on the select element to bind the value.
<select v-model="selectedValue" name="LeaveType" onchange="onChange(this.value)" class="form-control">
<option value="1">Annual Leave/ Off-Day</option>
<option value="2">On Demand Leave</option>
</select>
new Vue({
data:{
selectedValue : 1, // First option will be selected by default
},
...
...
methods:{
onChange:function(event){
console.log(this.selectedValue);
}
}
})
Hope this Helps :-)
This is the command to use to tell Gradle to upgrade the wrapper such that it will grab the distribution versions of libraries that includes source code:
./gradlew wrapper --gradle-version <version> --distribution-type all
Specifying the distribution-type with "all" will make sure Gradle downloads source files for use by your development environment.
Pros:
Cons:
Please comment or provide another answer if you know of any command line option to tell Gradle not to download sources on a build server.
Here is a way to check is virtualization is enabled or disabled by the firmware as suggested by this link in parallels.com.
How to check that Intel VT-x is supported in CPU:
Open Terminal application from Application/Utilities
Copy/paste command bellow
sysctl -a | grep machdep.cpu.features
Mac:~ user$ sysctl -a | grep machdep.cpu.features
kern.exec: unknown type returned
machdep.cpu.features: FPU VME DE PSE TSC MSR PAE MCE CX8 APIC SEP MTRR PGE MCA CMOV PAT CLFSH DS ACPI MMX FXSR SSE SSE2 SS HTT TM SSE3 MON VMX EST TM2 TPR PDCM
If you see VMX entry then CPU supports Intel VT-x feature, but it still may be disabled.
Refer to this link on Apple.com to enable hardware support for virtualization:
public class InitHelloWorld implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean,
String beanName) throws BeansException {
System.out.println("BeforeInitialization : " + beanName);
return bean; // you can return any other object as well
}
public Object postProcessAfterInitialization(Object bean,
String beanName) throws BeansException {
System.out.println("AfterInitialization : " + beanName);
return bean; // you can return any other object as well
}
}
If you don't mind a third party dependency, there is a class named Collectors2 in Eclipse Collections which contains methods returning Collectors for summing and summarizing BigDecimal and BigInteger. These methods take a Function as a parameter so you can extract a BigDecimal or BigInteger value from an object.
List<BigDecimal> list = mList(
BigDecimal.valueOf(0.1),
BigDecimal.valueOf(1.1),
BigDecimal.valueOf(2.1),
BigDecimal.valueOf(0.1));
BigDecimal sum =
list.stream().collect(Collectors2.summingBigDecimal(e -> e));
Assert.assertEquals(BigDecimal.valueOf(3.4), sum);
BigDecimalSummaryStatistics statistics =
list.stream().collect(Collectors2.summarizingBigDecimal(e -> e));
Assert.assertEquals(BigDecimal.valueOf(3.4), statistics.getSum());
Assert.assertEquals(BigDecimal.valueOf(0.1), statistics.getMin());
Assert.assertEquals(BigDecimal.valueOf(2.1), statistics.getMax());
Assert.assertEquals(BigDecimal.valueOf(0.85), statistics.getAverage());
Note: I am a committer for Eclipse Collections.
just refresh your layout by clicking this:
there will be a blue logo at the top left of the "layout-design" page
click and choose "Force Refresh Layout"
According to the documentation you can simply return false;
to break:
$(xml).find("strengths").each(function() {
if (iWantToBreak)
return false;
});
There is a new, open source library on GitHub that does ANPR for US and European plates. It looks pretty accurate and it should do exactly what you need (recognize the plate regions). Here is the GitHub project: https://github.com/openalpr/openalpr
Cstr()
is compiled inline for better performance.
CType
allows for casts between types if a conversion operator is defined
ToString()
Between base type and string throws an exception if conversion is not possible.
TryParse()
From String to base typeif
possible otherwise returns false
DirectCast
used if the types are related via inheritance or share a common interface , will throw an exception if the cast is not possible, trycast
will return nothing in this instance
To make sure it does not fail for string
, date
and timestamp
columns:
import pyspark.sql.functions as F
def count_missings(spark_df,sort=True):
"""
Counts number of nulls and nans in each column
"""
df = spark_df.select([F.count(F.when(F.isnan(c) | F.isnull(c), c)).alias(c) for (c,c_type) in spark_df.dtypes if c_type not in ('timestamp', 'string', 'date')]).toPandas()
if len(df) == 0:
print("There are no any missing values!")
return None
if sort:
return df.rename(index={0: 'count'}).T.sort_values("count",ascending=False)
return df
If you want to see the columns sorted based on the number of nans and nulls in descending:
count_missings(spark_df)
# | Col_A | 10 |
# | Col_C | 2 |
# | Col_B | 1 |
If you don't want ordering and see them as a single row:
count_missings(spark_df, False)
# | Col_A | Col_B | Col_C |
# | 10 | 1 | 2 |
For my case, none of other solutions worked. I had to do a backup of new modified files (shown with git status
), and run a git reset --hard
. This allowed me to realign with the remote server. Adding new modified files, and running
git add .
git commit -am "my comment"
git push
Did the trick. I hope this helps someone, as a "last chance" solution.
Did you try using t.Text
?
In recent browsers you can use:
Object.keys(obj.Data).length
See MDN
For older browsers, use the for-in
loop in Michael Geary's answer.
I have a similar situation, but I use the key and the certificate in different files.
in my case you can check the matching of the key and the lock by comparing the hashes (see https://michaelheap.com/curl-58-unable-to-set-private-key-file-server-key-type-pem/). This helped me to identify inconsistencies.
if (var === undefined)
or more precisely
if (typeof var === 'undefined')
Note the ===
is used
Look for the official 2.7 setuptools installer (which contains easy_install). You only need to install from sources for windows 64 bits.
$ENV{FOO}
for usage, where FOO
is being picked up from the environment variable. otherwise use as ${FOO}
, where FOO
is some other variable. For setting, SET(FOO "foo")
would be used in CMake.
If you have a String
, you can do that:
String s = "test";
try {
s.getBytes("UTF-8");
} catch(UnsupportedEncodingException uee) {
uee.printStackTrace();
}
If you have a 'broken' String
, you did something wrong, converting a String
to a String
in another encoding is defenetely not the way to go! You can convert a String
to a byte[]
and vice-versa (given an encoding). In Java String
s are AFAIK encoded with UTF-16
but that's an implementation detail.
Say you have a InputStream
, you can read in a byte[]
and then convert that to a String
using
byte[] bs = ...;
String s;
try {
s = new String(bs, encoding);
} catch(UnsupportedEncodingException uee) {
uee.printStackTrace();
}
or even better (thanks to erickson) use InputStreamReader
like that:
InputStreamReader isr;
try {
isr = new InputStreamReader(inputStream, encoding);
} catch(UnsupportedEncodingException uee) {
uee.printStackTrace();
}
grep
matches, grep -v
does the inverse. If you need to "match A but not B" you usually use pipes:
grep "${PATT}" file | grep -v "${NOTPATT}"
<td class="first"> <?php echo $proxy ?> </td>
is inside a literal string that you are echo
ing. End the string, or concatenate it correctly:
<td class="first">' . $proxy . '</td>
In general, if you don't know how something works, look for an example which you can learn from.
For this problem, consider this DEMO
You can see loading content with AJAX is very easily accomplished with jQuery:
$(function(){
// don't cache ajax or content won't be fresh
$.ajaxSetup ({
cache: false
});
var ajax_load = "<img src='http://automobiles.honda.com/images/current-offers/small-loading.gif' alt='loading...' />";
// load() functions
var loadUrl = "http://fiddle.jshell.net/deborah/pkmvD/show/";
$("#loadbasic").click(function(){
$("#result").html(ajax_load).load(loadUrl);
});
// end
});
Try to understand how this works and then try replicating it. Good luck.
You can find the corresponding tutorial HERE
Right now the following event starts the ajax load
function:
$("#loadbasic").click(function(){
$("#result").html(ajax_load).load(loadUrl);
});
You can also do this periodically: How to fire AJAX request Periodically?
(function worker() {
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(worker, 5000);
}
});
})();
I made a demo of this implementation for you HERE. In this demo, every 2 seconds (setTimeout(worker, 2000);
) the content is updated.
You can also just load the data immediately:
$("#result").html(ajax_load).load(loadUrl);
Which has THIS corresponding demo.
Use the class
function
>> b = 2
b =
2
>> a = 'Hi'
a =
Hi
>> class(b)
ans =
double
>> class(a)
ans =
char
The Docker machine is running. But you need to export some environment to connect to the Docker machine. By default, the docker
CLI client is trying to communicate to the daemon using http+unix://var/run/docker.sock
(as shown in the error message).
Export the correct environment variables using eval $(docker-machine env dev)
and then try again. You can also just run docker-machine env dev
to see the environment variables it will export. Notice that one of them is DOCKER_HOST
, just as the error message suggests you may need to set.
For anyone who may stumble across this old question ...
There is one thing that I think needs to be addressed.
~/.nanorc
is used to apply your user specific settings to nano, so if you are editing files that require the use of sudo nano
for permissions then this is not going to work.
When using sudo
your custom user configuration files will not be loaded when opening a program, as you are not running the program from your account so none of your configuration changes in ~/.nanorc
will be applied.
If this is the situation you find yourself in (wanting to run sudo nano
and use your own config settings) then you have three options :
sudo nano
/root/.nanorc
file/etc/nanorc
global config fileKeep in mind that /etc/nanorc
is a global configuration file and as such it affects all users, which may or may not be a problem depending on whether you have a multi-user system.
Also, user config files will override the global one, so if you were to edit /etc/nanorc
and ~/.nanorc
with different settings, when you run nano
it will load the settings from ~/.nanorc
but if you run sudo nano
then it will load the settings from /etc/nanorc
.
Same goes for /root/.nanorc
this will override /etc/nanorc
when running sudo nano
Using flags is probably the best option unless you have a lot of options.
The only way to change the $type
of the data is to perform an update on the data where the data has the correct type.
In this case, it looks like you're trying to change the $type
from 1 (double) to 2 (string).
So simply load the document from the DB, perform the cast (new String(x)
) and then save the document again.
If you need to do this programmatically and entirely from the shell, you can use the find(...).forEach(function(x) {})
syntax.
In response to the second comment below. Change the field bad
from a number to a string in collection foo
.
db.foo.find( { 'bad' : { $type : 1 } } ).forEach( function (x) {
x.bad = new String(x.bad); // convert field to string
db.foo.save(x);
});
I found the correct solution you can use this code
$('.close').click();
In my case, I ran into this error this way. pom.xml
of my project defined two dependencies A
and B
. And both A
and B
defined dependency on same artifact (call it C
) but different versions of it (C.1
and C.2
). When this happens, for each class in C
maven can only select one version of the class from the two versions (while building an uber-jar). It will select the "nearest" version based on its dependency mediation rules and will output a warning "We have a duplicate class..." If a method/class signature changes between the versions, it can cause a java.lang.IncompatibleClassChangeError
exception if the incorrect version is used at runtime.
Advanced: If A
must use v1 of C
and B
must use v2 of C
, then we must relocate C
in A
and B
's poms to avoid class conflict (we have a duplicate class warning) when building the final project that depends on both A
and B
.
I'd try doing this with jQuery's .hover() event handler system, it makes it easy to show a div with the tooltip when the mouse is over the text, and hide it once it's gone.
Here's a simple example.
HTML:
?<p id="testText">Some Text</p>
<div id="tooltip">Tooltip Hint Text</div>???????????????????????????????????????????
Basic CSS:
?#?tooltip {
display:none;
border:1px solid #F00;
width:150px;
}?
jQuery:
$("#testText").hover(
function(e){
$("#tooltip").show();
},
function(e){
$("#tooltip").hide();
});??????????
You can use my plugin waitForImages to handle this...
$(document).waitForImages(function() {
// Loaded.
});
The advantage of this is you can localise it to one ancestor element and it can optionally detect images referenced in the CSS.
This is just the tip of the iceberg though, check the documentation for more functionality.
Semicolon ;
on the end of command had caused the same error on me.
cmd.CommandText = "INSERT INTO U_USERS_TABLE (USERNAME, PASSWORD, FIRSTNAME, LASTNAME) VALUES ("
+ "'" + txtUsername.Text + "',"
+ "'" + txtPassword.Text + "',"
+ "'" + txtFirstname.Text + "',"
+ "'" + txtLastname.Text + "');"; <== Semicolon in "" is the cause.
Removing it will be fine.
Hope it helps.
Disabling "Google App Engine Support" in pycharm preferences fixed this issue for me.
Assuming you are referring to Django's Auth User, in your view:
def game(request):
user = request.user
gta = Game.objects.create(name="gta", owner=user)
I have a project in which I have the following TextView
:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="@string/app_name"
android:layout_gravity="center"
/>
So, I'm guessing you need to use android:textStyle
You can't have two elements with the same ID.
Aside from that, you are defining them as block elemnts, meaning (in layman's terms) that they are being forced to appear on their own line.
Instead, try something like this:
<div class="link"><a href="..."><img src="..."... /></a></div>
<div class="link"><a href="..."><img src="..."... /></a></div>
CSS:
.link {
width: 50%;
float: left;
text-align: center;
}
curl's --data
will by default send Content-Type: application/x-www-form-urlencoded
in the request header. However, when using Postman's raw
body mode, Postman sends Content-Type: text/plain
in the request header.
So to achieve the same thing as Postman, specify -H "Content-Type: text/plain"
for curl:
curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/
Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network
tab :
Once you've done this
group p by p.SomeId into pg
you no longer have access to the range variables used in the initial from
. That is, you can no longer talk about p
or bp
, you can only talk about pg
.
Now, pg
is a group and so contains more than one product. All the products in a given pg
group have the same SomeId
(since that's what you grouped by), but I don't know if that means they all have the same BaseProductId
.
To get a base product name, you have to pick a particular product in the pg
group (As you are doing with SomeId
and CountryCode
), and then join to BaseProducts
.
var result = from p in Products
group p by p.SomeId into pg
// join *after* group
join bp in BaseProducts on pg.FirstOrDefault().BaseProductId equals bp.Id
select new ProductPriceMinMax {
SomeId = pg.FirstOrDefault().SomeId,
CountryCode = pg.FirstOrDefault().CountryCode,
MinPrice = pg.Min(m => m.Price),
MaxPrice = pg.Max(m => m.Price),
BaseProductName = bp.Name // now there is a 'bp' in scope
};
That said, this looks pretty unusual and I think you should step back and consider what you are actually trying to retrieve.
$what=/path/to/file;
$dest=/dest/path;
mkdir -p "$(dirname "$dest")";
mv "$what" "$dest"
I found a really cool library, try this out. this is really smooth and easy to use.
I would suggest going the lxml route and using xpath.
from lxml import etree
# data is the variable containing the html
data = etree.HTML(data)
anchor = data.xpath('//a[@class="title"]/text()')
Twitter Bootstrap v3.0.3 has a class: center-block
Center content blocks
Set an element to display: block and center via margin. Available as a mixin and class.
Just need to add a class .center-block
in the img
tag, looks like this
<div class="container">
<div class="row">
<div class="span4"></div>
<div class="span4"><img class="center-block" src="logo.png" /></div>
<div class="span4"></div>
</div>
</div>
In Bootstrap already has css style call .center-block
.center-block {
display: block;
margin-left: auto;
margin-right: auto;
}
You can see a sample from here
Two possible approaches.
If you have a foreign key, declare it as on-delete-cascade and delete the parent rows older than 30 days. All the child rows will be deleted automatically.
Based on your description, it looks like you know the parent rows that you want to delete and need to delete the corresponding child rows. Have you tried SQL like this?
delete from child_table
where parent_id in (
select parent_id from parent_table
where updd_tms != (sysdate-30)
-- now delete the parent table records
delete from parent_table
where updd_tms != (sysdate-30);
---- Based on your requirement, it looks like you might have to use PL/SQL. I'll see if someone can post a pure SQL solution to this (in which case that would definitely be the way to go).
declare
v_sqlcode number;
PRAGMA EXCEPTION_INIT(foreign_key_violated, -02291);
begin
for v_rec in (select parent_id, child id from child_table
where updd_tms != (sysdate-30) ) loop
-- delete the children
delete from child_table where child_id = v_rec.child_id;
-- delete the parent. If we get foreign key violation,
-- stop this step and continue the loop
begin
delete from parent_table
where parent_id = v_rec.parent_id;
exception
when foreign_key_violated
then null;
end;
end loop;
end;
/
Problem with DIR is that it will return wrong answers.
If you are looking for DOC in a folder by using DIR *.DOC
it will also give you the DOCX. Searching for *.HTM
will also give the HTML and so on...
Use isinstance
:
if isinstance(e, list):
If you want to check that an object is a list or a tuple, pass several classes to isinstance
:
if isinstance(e, (list, tuple)):
I'd use a UIViewController subclass containing a "Container View" that embeds your others view controllers. You'll then be able to add the navigation controller inside the Container View (using the embed relationship segue for example).
I know this is an old post, but this may help clarify:
$('#searchField')
.val('')// [property value] e.g. what is visible / will be submitted
.attr('value', '');// [attribute value] e.g. <input value="preset" ...
Changing [attribute value] has no effect if there is a [property value]. (user || js altered input)
Above answers are in python2. So for python 3 users I am giving this answer. You can use the bellow code:
import pandas as pd
fields = ['star_name', 'ra']
df = pd.read_csv('data.csv', skipinitialspace=True, usecols=fields)
# See the keys
print(df.keys())
# See content in 'star_name'
print(df.star_name)
Use dataType: "jsonp"
. I had the same error before. It fixed for me.
This is because findViewById()
searches in the activity_main
layout, while the button is located in the fragment's layout fragment_main
.
Move that piece of code in the onCreateView()
method of the fragment:
//...
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button buttonClick = (Button)rootView.findViewById(R.id.button);
buttonClick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onButtonClick((Button) view);
}
});
Notice that now you access it through rootView
view:
Button buttonClick = (Button)rootView.findViewById(R.id.button);
otherwise you would get again NullPointerException.
May be by:-
for(Row row : sheet) {
for(Cell cell : row) {
System.out.print(cell.getStringCellValue());
}
}
For specific type of cell you can try:
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
cellValue = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_FORMULA:
cellValue = cell.getCellFormula();
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
cellValue = cell.getDateCellValue().toString();
} else {
cellValue = Double.toString(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BLANK:
cellValue = "";
break;
case Cell.CELL_TYPE_BOOLEAN:
cellValue = Boolean.toString(cell.getBooleanCellValue());
break;
}
Since you are creating a markup as a string you don't have convert it into json. Just send it as it is combining all the array elements using implode
method. Try this.
PHP change
$response = array();
$response[] = "<a href=''>link</a>";
$response[] = 1;
echo implode("", $response);//<-----Combine array items into single string
JS (Change the dataType from json to html or just don't set it jQuery will figure it out)
$.ajax({
type: "POST",
dataType: "html",
url: "main.php",
data: "action=loadall&id=" + id,
success: function(response){
$('#main').html(response);
}
});
You can save generated diagram for future use.
I was able to do it with justify-content: space-between
on the container
Here's what I did which worked:
yum install python-pip
pip install -U multi-mechanize
Wrap that up in a function and then just return
.
I had a moment, so, although you've already accepted an answer, I thought I'd contribute the following:
Number.prototype.between = function(a, b) {_x000D_
var min = Math.min.apply(Math, [a, b]),_x000D_
max = Math.max.apply(Math, [a, b]);_x000D_
return this > min && this < max;_x000D_
};_x000D_
_x000D_
var windowSize = 550;_x000D_
_x000D_
console.log(windowSize.between(500, 600));
_x000D_
Or, if you'd prefer to have the option to check a number is in the defined range including the end-points:
Number.prototype.between = function(a, b, inclusive) {_x000D_
var min = Math.min.apply(Math, [a, b]),_x000D_
max = Math.max.apply(Math, [a, b]);_x000D_
return inclusive ? this >= min && this <= max : this > min && this < max;_x000D_
};_x000D_
_x000D_
var windowSize = 500;_x000D_
_x000D_
console.log(windowSize.between(500, 603, true));
_x000D_
Edited to add a minor amendment to the above, given that – as noted in the comments –
…
Function.prototype.apply()
is slow! Besides calling it when you have a fixed amount of arguments is pointless…
it was worth removing the use of Function.prototype.apply()
, which yields the amended versions of the above methods, firstly without the 'inclusive' option:
Number.prototype.between = function(a, b) {_x000D_
var min = Math.min(a, b),_x000D_
max = Math.max(a, b);_x000D_
_x000D_
return this > min && this < max;_x000D_
};_x000D_
_x000D_
var windowSize = 550;_x000D_
_x000D_
console.log(windowSize.between(500, 600));
_x000D_
And with the 'inclusive' option:
Number.prototype.between = function(a, b, inclusive) {_x000D_
var min = Math.min(a, b),_x000D_
max = Math.max(a, b);_x000D_
_x000D_
return inclusive ? this >= min && this <= max : this > min && this < max;_x000D_
}_x000D_
_x000D_
var windowSize = 500;_x000D_
_x000D_
console.log(windowSize.between(500, 603, true));
_x000D_
References:
You'll want to include double quotes (") before and after the imageUrl like this:
$('myOjbect').css('background-image', 'url("' + imageUrl + '")');
This way, if the image has spaces it will still be set as a property.
In Content page you can access the label and set the text such as
Here 'lblStatus' is the your master page label ID
Label lblMasterStatus = (Label)Master.FindControl("lblStatus"); lblMasterStatus.Text = "Meaasage from content page";
If downgrading from pip version 10 because of PyCharm manage.py or other python errors:
python -m pip install pip==9.0.1
I suppose better would be to use re.match() function. here is an example which may help you.
import re
import nltk
from nltk.tokenize import word_tokenize
nltk.download('punkt')
sentences = word_tokenize("I love to learn NLP \n 'a :(")
#for i in range(len(sentences)):
sentences = [word.lower() for word in sentences if re.match('^[a-zA-Z]+', word)]
sentences
You can easily find the size of each of your repository in your Accounts settings
In addition to the accepted answer, if you are using Android Studio you can
Android Device Monitor
,Devices
tab on the left,File Explorer
tab on the right,Pull a file from the device
button to save it to your local file systemHere is an answer to your question that goes into detail: http://www.velocityreviews.com/forums/t372598-maximum-size-of-byte-array.html
You may want to mention which version of .NET you are using and your memory size.
You will be stuck to a 2G, for your application, limit though, so it depends on what is in your array.
Make #site_nav_global_primary
positioned as fixed and set width to 100 % and desired height.
One very quick way is to do something like:
substr(md5(rand()),0,10);
This will generate a random string with the length of 10 chars. Of course, some might say it's a bit more heavy on the computation side, but nowadays processors are optimized to run md5 or sha256 algorithm very quickly. And of course, if the rand()
function returns the same value, the result will be the same, having a 1 / 32767 chance of being the same. If security's the issue, then just change rand()
to mt_rand()
Even accepted answer is ConcurrentBag, I don't think it's real replacement of list in all cases, as Radek's comment to the answer says: "ConcurrentBag is unordered collection, so unlike List it does not guarantee ordering. Also you cannot access items by index".
So if you use .NET 4.0 or higher, a workaround could be to use ConcurrentDictionary with integer TKey as array index and TValue as array value. This is recommended way of replacing list in Pluralsight's C# Concurrent Collections course. ConcurrentDictionary solves both problems mentioned above: index accessing and ordering (we can not rely on ordering as it's hash table under the hood, but current .NET implementation saves order of elements adding).
Had a similar problem; a pid file was blocking postgres from starting up. To fix it:
$ rm /usr/local/var/postgres/postmaster.pid
$ brew services restart postgresql
and then all is well.
Yes. I updated my answer DEMO
table td {
border-top: thin solid;
border-bottom: thin solid;
}
table td:first-child {
border-left: thin solid;
}
table td:last-child {
border-right: thin solid;
}
If you want to style only one <tr>
you can do it with a class: Second DEMO
Works the best. If you want to use it sitewide, without having to add this syntax to every class or ID, add the following CSS to your css body:
body {
-webkit-font-smoothing: antialiased;
text-shadow: 1px 1px 1px rgba(0,0,0,0.004);
background: url('./images/background.png');
text-align: left;
margin: auto;
}