You could use robocopy:
robocopy "$(TargetPath)" "$(SolutionDir)Prism4Demo.Shell\$(OutDir)Modules" /E
If none of the TargetDir or other macros point to the right place, use the ".." directory to go backwards up the folder hierarchy.
ie. Use $(SolutionDir)\..\..
to get your base directory.
For list of all macros, see here:
The Post-Build Event (under Build Events, in the properties dialog) of an imported project, had an environment variable which was not defined.
Navigated to Control Panel\All Control Panel Items\System\Advanced system settings
to add the appropriate environment variable, and doing no more than restarting VS2017 resolved the error.
Also, following on from @Seans and other answers regarding multiple project races/contentions, create a temp folder in the output folder like so,
and select the project producing the preferred output:
and build (no rebuild/clean) is a speedy solution.
You can easily append to the end of a file, by using the redirection char twice (>>
).
This will copy source.txt
to destination.txt
, overwriting destination in the process:
type source.txt > destination.txt
This will copy source.txt
to destination.txt
, appending to destination in the process:
type source.txt >> destination.txt
In Express 4.x
I used the following to load ejs
:
var path = require('path');
// Set the default templating engine to ejs
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// The views/index.ejs exists in the app directory
app.get('/hello', function (req, res) {
res.render('index', {title: 'title'});
});
Then you just need two files to make it work - views/index.ejs
:
<%- include partials/navigation.ejs %>
And the views/partials/navigation.ejs
:
<ul><li class="active">...</li>...</ul>
You can also tell Express to use ejs
for html templates:
var path = require('path');
var EJS = require('ejs');
app.engine('html', EJS.renderFile);
// Set the default templating engine to ejs
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// The views/index.html exists in the app directory
app.get('/hello', function (req, res) {
res.render('index.html', {title: 'title'});
});
Finally you can also use the ejs
layout module:
var EJSLayout = require('express-ejs-layouts');
app.use(EJSLayout);
This will use the views/layout.ejs
as your layout.
Don't do this at the view level. Just set the default value to the property in your view model's constructor. Clean and simple. In your post-backs, your selected value will automatically populate the correct selection.
For example
public class MyViewModel
{
public MyViewModel()
{
Gender = "Male";
}
}
<table>_x000D_
<tr>_x000D_
<td><label>@Html.RadioButtonFor(i => i.Gender, "Male")Male</label></td>_x000D_
<td><label>@Html.RadioButtonFor(i => i.Gender, "Female")Female</label></td>_x000D_
</tr>_x000D_
</table>
_x000D_
I dont know why but it worked for me. If you have comments like
//Comment
Then it gives this error. To fix this do
/*Comment*/
Doesn't make sense but it worked for me.
The solution posted by Bjorn results in a "RuntimeError: Calling Tcl from different appartment" message on my computer (RedHat Enterprise 5, python 2.6.1). Bjorn might not have gotten this message, since, according to one place I checked, mishandling threading with Tkinter is unpredictable and platform-dependent.
The problem seems to be that app.start()
counts as a reference to Tk, since app contains Tk elements. I fixed this by replacing app.start()
with a self.start()
inside __init__
. I also made it so that all Tk references are either inside the function that calls mainloop()
or are inside functions that are called by the function that calls mainloop()
(this is apparently critical to avoid the "different apartment" error).
Finally, I added a protocol handler with a callback, since without this the program exits with an error when the Tk window is closed by the user.
The revised code is as follows:
# Run tkinter code in another thread
import tkinter as tk
import threading
class App(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.start()
def callback(self):
self.root.quit()
def run(self):
self.root = tk.Tk()
self.root.protocol("WM_DELETE_WINDOW", self.callback)
label = tk.Label(self.root, text="Hello World")
label.pack()
self.root.mainloop()
app = App()
print('Now we can continue running code while mainloop runs!')
for i in range(100000):
print(i)
^\+[1-9]{1}[0-9]{7,11}$
The Regular Expression ^\+[1-9]{1}[0-9]{7,11}$
fails for "+290 8000" and similar valid numbers that are shorter than 8 digits.
The longest numbers could be something like 3 digit country code, 3 digit area code, 8 digit subscriber number, making 14 digits.
Alternatively you can use the views current layout parameters and modify them:
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewToLayout.getLayoutParams();
params.addRule(RelativeLayout.BELOW, R.id.below_id);
You might also find it useful to know generally what these data types are used for:
:string
- is for small data types such as a title. (Should you choose string or text?):text
- is for longer pieces of textual data, such as a paragraph of information:binary
- is for storing data such as images, audio, or movies.:boolean
- is for storing true or false values.:date
- store only the date:datetime
- store the date and time into a column. :time
- is for time only:timestamp
- for storing date and time into a column.(What's the difference between datetime and timestamp?):decimal
- is for decimals (example of how to use decimals).:float
- is for decimals. (What's the difference between decimal and float?):integer
- is for whole numbers.:primary_key
- unique key that can uniquely identify each row in a tableThere's also references used to create associations. But, I'm not sure this is an actual data type.
New Rails 4 datatypes available in PostgreSQL:
:hstore
- storing key/value pairs within a single value (learn more about this new data type):array
- an arrangement of numbers or strings in a particular row (learn more about it and see examples):cidr_address
- used for IPv4 or IPv6 host addresses:inet_address
- used for IPv4 or IPv6 host addresses, same as cidr_address but it also accepts values with nonzero bits to the right of the netmask:mac_address
- used for MAC host addressesLearn more about the address datatypes here and here.
Also, here's the official guide on migrations: http://edgeguides.rubyonrails.org/migrations.html
I think below explanation will help to you..
differentiation between those:
Correlated subquery
is an inner query referenced by main query (outer query) such that inner query considered as being excuted repeatedly.
non-correlated subquery
is a sub query that is an independent of the outer query and it can executed on it's own without relying on main outer query.
plain subquery
is not dependent on the outer query,
The answer lies in which constructors the LinkedHashSet
uses to construct the base class:
public LinkedHashSet(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor, true); // <-- boolean dummy argument
}
...
public LinkedHashSet(int initialCapacity) {
super(initialCapacity, .75f, true); // <-- boolean dummy argument
}
...
public LinkedHashSet() {
super(16, .75f, true); // <-- boolean dummy argument
}
...
public LinkedHashSet(Collection<? extends E> c) {
super(Math.max(2*c.size(), 11), .75f, true); // <-- boolean dummy argument
addAll(c);
}
And (one example of) a HashSet
constructor that takes a boolean argument is described, and looks like this:
/**
* Constructs a new, empty linked hash set. (This package private
* constructor is only used by LinkedHashSet.) The backing
* HashMap instance is a LinkedHashMap with the specified initial
* capacity and the specified load factor.
*
* @param initialCapacity the initial capacity of the hash map
* @param loadFactor the load factor of the hash map
* @param dummy ignored (distinguishes this
* constructor from other int, float constructor.)
* @throws IllegalArgumentException if the initial capacity is less
* than zero, or if the load factor is nonpositive
*/
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
map = new LinkedHashMap<E,Object>(initialCapacity, loadFactor);
}
Ok, yup you use the timeout
command to sleep. But to do the whole process silently, it's not possible with cmd/batch. One of the ways is to create a VBScript that will run the Batch File without opening/showing any window.
And here is the script:
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "PATH OF BATCH FILE WITH QUOTATION MARKS" & Chr(34), 0
Set WshShell = Nothing
Copy and paste the above code on notepad and save it as Anyname.**vbs ** An example of the *"PATH OF BATCH FILE WITH QUOTATION MARKS" * might be: "C:\ExampleFolder\MyBatchFile.bat"
This is a better directive in case you would like to use it:
you can scroll to any element in the page:
.directive('scrollToItem', function() {
return {
restrict: 'A',
scope: {
scrollTo: "@"
},
link: function(scope, $elm,attr) {
$elm.on('click', function() {
$('html,body').animate({scrollTop: $(scope.scrollTo).offset().top }, "slow");
});
}
}})
Usage (for example click on div 'back-to-top' will scroll to id scroll-top):
<a id="top-scroll" name="top"></a>
<div class="back-to-top" scroll-to-item scroll-to="#top-scroll">
It's also supported by chrome,firefox,safari and IE cause of the html,body element .
Minor changes required for Kafka 0.10 and the new consumer compared to laughing_man's answer:
message.max.bytes
and replica.fetch.max.bytes
. message.max.bytes
has to be equal or smaller(*) than replica.fetch.max.bytes
.max.request.size
to send the larger message.max.partition.fetch.bytes
to receive larger messages.(*) Read the comments to learn more about message.max.bytes
<=replica.fetch.max.bytes
How about something like this
PROXY = "149.215.113.110:70"
webdriver.DesiredCapabilities.FIREFOX['proxy'] = {
"httpProxy":PROXY,
"ftpProxy":PROXY,
"sslProxy":PROXY,
"noProxy":None,
"proxyType":"MANUAL",
"class":"org.openqa.selenium.Proxy",
"autodetect":False
}
# you have to use remote, otherwise you'll have to code it yourself in python to
driver = webdriver.Remote("http://localhost:4444/wd/hub", webdriver.DesiredCapabilities.FIREFOX)
You can read more about it here.
You should not place an using
directive in an header file, it creates unnecessary headaches.
Also you need an include guard in your header.
EDIT: of course, after having fixed the include guard issue, you also need a complete declaration of student in the header file. As pointed out by others the forward declaration is not sufficient in your case.
For Visual Studio Code (Not Visual Studio) do Ctrl+Shift+P
Type Debugger for Chrome in the search bar, install it and enable it.
In your launch.json
file add this config :
{
"version": "0.1.0",
"configurations": [
{
"name": "Launch localhost with sourcemaps",
"type": "chrome",
"request": "launch",
"url": "http://localhost/mypage.html",
"webRoot": "${workspaceRoot}/app/files",
"sourceMaps": true
},
{
"name": "Launch index.html (without sourcemaps)",
"type": "chrome",
"request": "launch",
"file": "${workspaceRoot}/index.html"
},
]
}
You must launch Chrome with remote debugging enabled in order for the extension to attach to it.
Right click the Chrome shortcut, and select properties In the "target" field, append --remote-debugging-port=9222 Or in a command prompt, execute /chrome.exe --remote-debugging-port=9222
In a terminal, execute /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222
In a terminal, launch google-chrome --remote-debugging-port=9222
Try this:
& "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\i386\CmRcViewer.exe" PCNAME
To PowerShell a string "..." is just a string and PowerShell evaluates it by echoing it to the screen. To get PowerShell to execute the command whose name is in a string, you use the call operator &
.
If we are talking Visual Studio Code nowadays you set a default formatter in your settings.json
:
// Defines a default formatter which takes precedence over all other formatter settings.
// Must be the identifier of an extension contributing a formatter.
"editor.defaultFormatter": null,
Point to the identifier of any installed extension, i.e.
"editor.defaultFormatter": "esbenp.prettier-vscode"
You can also do so format-specific:
"[html]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[scss]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[sass]": {
"editor.defaultFormatter": "michelemelluso.code-beautifier"
},
Also see here.
You could also assign other keys for different formatters in your keyboard shortcuts (keybindings.json
). By default, it reads:
{
"key": "shift+alt+f",
"command": "editor.action.formatDocument",
"when": "editorHasDocumentFormattingProvider && editorHasDocumentFormattingProvider && editorTextFocus && !editorReadonly"
}
Lastly, if you decide to use the Prettier plugin and prettier.rc
, and you want for example different indentation for html, scss, json...
{
"semi": true,
"singleQuote": false,
"trailingComma": "none",
"useTabs": false,
"overrides": [
{
"files": "*.component.html",
"options": {
"parser": "angular",
"tabWidth": 4
}
},
{
"files": "*.scss",
"options": {
"parser": "scss",
"tabWidth": 2
}
},
{
"files": ["*.json", ".prettierrc"],
"options": {
"parser": "json",
"tabWidth": 4
}
}
]
}
I think these are two really different cases. In the first case memory is allocated and initialized in compile-time. In the second - in runtime.
With Swift 3, JSONSerialization
has a method called json?Object(with:?options:?)
. json?Object(with:?options:?)
has the following declaration:
class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any
Returns a Foundation object from given JSON data.
When you use json?Object(with:?options:?)
, you have to deal with error handling (try
, try?
or try!
) and type casting (from Any
). Therefore, you can solve your problem with one of the following patterns.
import Foundation
func convertToDictionary(from text: String) throws -> [String: String] {
guard let data = text.data(using: .utf8) else { return [:] }
let anyResult: Any = try JSONSerialization.jsonObject(with: data, options: [])
return anyResult as? [String: String] ?? [:]
}
Usage:
let string1 = "{\"City\":\"Paris\"}"
do {
let dictionary = try convertToDictionary(from: string1)
print(dictionary) // prints: ["City": "Paris"]
} catch {
print(error)
}
let string2 = "{\"Quantity\":100}"
do {
let dictionary = try convertToDictionary(from: string2)
print(dictionary) // prints [:]
} catch {
print(error)
}
let string3 = "{\"Object\"}"
do {
let dictionary = try convertToDictionary(from: string3)
print(dictionary)
} catch {
print(error) // prints: Error Domain=NSCocoaErrorDomain Code=3840 "No value for key in object around character 9." UserInfo={NSDebugDescription=No value for key in object around character 9.}
}
import Foundation
func convertToDictionary(from text: String) throws -> [String: String]? {
guard let data = text.data(using: .utf8) else { return [:] }
let anyResult: Any = try JSONSerialization.jsonObject(with: data, options: [])
return anyResult as? [String: String]
}
Usage:
let string1 = "{\"City\":\"Paris\"}"
do {
let dictionary = try convertToDictionary(from: string1)
print(String(describing: dictionary)) // prints: Optional(["City": "Paris"])
} catch {
print(error)
}
let string2 = "{\"Quantity\":100}"
do {
let dictionary = try convertToDictionary(from: string2)
print(String(describing: dictionary)) // prints nil
} catch {
print(error)
}
let string3 = "{\"Object\"}"
do {
let dictionary = try convertToDictionary(from: string3)
print(String(describing: dictionary))
} catch {
print(error) // prints: Error Domain=NSCocoaErrorDomain Code=3840 "No value for key in object around character 9." UserInfo={NSDebugDescription=No value for key in object around character 9.}
}
import Foundation
func convertToDictionary(from text: String) -> [String: String] {
guard let data = text.data(using: .utf8) else { return [:] }
let anyResult: Any? = try? JSONSerialization.jsonObject(with: data, options: [])
return anyResult as? [String: String] ?? [:]
}
Usage:
let string1 = "{\"City\":\"Paris\"}"
let dictionary1 = convertToDictionary(from: string1)
print(dictionary1) // prints: ["City": "Paris"]
let string2 = "{\"Quantity\":100}"
let dictionary2 = convertToDictionary(from: string2)
print(dictionary2) // prints: [:]
let string3 = "{\"Object\"}"
let dictionary3 = convertToDictionary(from: string3)
print(dictionary3) // prints: [:]
import Foundation
func convertToDictionary(from text: String) -> [String: String]? {
guard let data = text.data(using: .utf8) else { return nil }
let anyResult = try? JSONSerialization.jsonObject(with: data, options: [])
return anyResult as? [String: String]
}
Usage:
let string1 = "{\"City\":\"Paris\"}"
let dictionary1 = convertToDictionary(from: string1)
print(String(describing: dictionary1)) // prints: Optional(["City": "Paris"])
let string2 = "{\"Quantity\":100}"
let dictionary2 = convertToDictionary(from: string2)
print(String(describing: dictionary2)) // prints: nil
let string3 = "{\"Object\"}"
let dictionary3 = convertToDictionary(from: string3)
print(String(describing: dictionary3)) // prints: nil
As far as I know, it's not possible to change the content of the buttons, at least not easily. It's fairly easy to have your own custom alert box using JQuery UI though
import com.github.fge.jackson.JsonLoader;
JsonLoader.fromString("{\"k1\":\"v1\"}")
== JsonNode = {"k1":"v1"}
I just wanted to add to the great Flexbox solution described by Pavlo, that, in my case, I had two lists/columns of data that I wanted to display side-by-side with just a little spacing between, horizontally-centered inside an enclosing div. By nesting another div within the first (leftmost) flex:1 div and floating it right, I got just what I wanted. I couldn't find any other way to do this with consistent success at all viewport widths:
<div style="display:flex">
<div style="flex:1;padding-right:15px">
<div style="float:right">
[My Left-hand list of stuff]
</div>
</div>
<div style="flex:1;padding-left:15px">
[My Right-hand list of stuff]
</div>
</div>
When the error happens in tests projects the prettiest solution is to decorate the test class with:
[DeploymentItem("EntityFramework.SqlServer.dll")]
This is exactly the feature I implemented in this lib XDDLib. (But, it's for android)
Lg.d("int array:", intArrayOf(1, 2, 3), "int list:", listOf(4, 5, 6))
One click on the underlined text to navigate to where the log command is
That StackTraceElement
is determined by the first element outside this library. Thus, anywhere outside this lib will be legal, including lambda expression
, static initialization block
, etc.
Or, create a new table as temp with the extra column, copy the data to this new table while manipulating it as necessary to fill the non-nullable new column, and then swap the table via a two-step name change.
Yes, it is more complicated, but you may need to do it this way if you don't want a big UPDATE on a live table.
Now, You need to add a "Privacy Policy URL" in the App Details tab (developers.facebook.com). This is a new Policy of Facebook.
var fields = {
teste:
{
Acess:
{
Edit: true,
View: false
}
},
teste1:
{
Acess:
{
Edit: false,
View: false
}
}
};
console.log(find(fields,'teste'));
function find(fields,field){
for(key in fields){
if(key == field){
return true;
}
}
return false;
}
If you have one Object with multiply objects inside, if you want know if some object are include on Master object, just put find(MasterObject,'Object to Search'), this function will return the response if exist or not (TRUE or FALSE), I hope help with this, can see the exemple on JSFiddle.
Check this answer: https://stackoverflow.com/a/7346598/1764509
$.getJSON("test.json", function(json) {
console.log(json); // this will show the info it in firebug console
});
I needed a faster ping sweep and I didn't want to use any external libraries, so I resolved to using concurrency using built-in asyncio
.
This code requires python 3.7+ and is made and tested on Linux only. It won't work on Windows but I am sure you can easily change it to work on Windows.
I ain't an expert with asyncio
but I used this great article Speed Up Your Python Program With Concurrency and I came up with these lines of codes. I tried to make it as simple as possible, so most likely you will need to add more code to it to suit your needs.
It doesn't return true or false, I thought it would be more convenient just to make it print the IP that responds to a ping request. I think it is pretty fast, pinging 255 ips in nearly 10 seconds.
#!/usr/bin/python3
import asyncio
async def ping(host):
"""
Prints the hosts that respond to ping request
"""
ping_process = await asyncio.create_subprocess_shell("ping -c 1 " + host + " > /dev/null 2>&1")
await ping_process.wait()
if ping_process.returncode == 0:
print(host)
return
async def ping_all():
tasks = []
for i in range(1,255):
ip = "192.168.1.{}".format(i)
task = asyncio.ensure_future(ping(ip))
tasks.append(task)
await asyncio.gather(*tasks, return_exceptions = True)
asyncio.run(ping_all())
Sample output:
192.168.1.1
192.168.1.3
192.168.1.102
192.168.1.106
192.168.1.6
Note that the IPs are not in order, as the IP is printed as soon it replies, so the one that responds first gets printed first.
If the following conditions are true, then rewrite the URL:
If the requested filename is not a directory,
RewriteCond %{REQUEST_FILENAME} !-d
and if the requested filename is not a regular file that exists,
RewriteCond %{REQUEST_FILENAME} !-f
and if the requested filename is not a symbolic link,
RewriteCond %{REQUEST_FILENAME} !-l
then rewrite the URL in the following way:
Take the whole request filename and provide it as the value of a "url" query parameter to index.php. Append any query string from the original URL as further query parameters (QSA), and stop processing this .htaccess file (L).
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
Another Example:
RewriteRule "/pages/(.+)" "/page.php?page=$1" [QSA]
With the [QSA] flag, a request for
/pages/123?one=two
will be mapped to
/page.php?page=123&one=two
The problem in my case was that I was running the command inside a python virtual environment and it didn't had the path to /usr/local/mysql/bin though I have put it in the .bash_profile file. Just exporting the path in the virtual env worked for me.
For your info sql_config resides inside bin directory.
What's worked for me recently is to remove all height=""
and width=""
attributes from the <svg>
tag and all child tags. Then you can use scaling using a percentage of the parent container's height or width.
Before:
<svg width="3212" height="3212" viewBox="0 0 3212 3212" fill="none" xmlns="http://www.w3.org/2000/svg">
circle cx="1606" cy="1606" r="1387" stroke="black" stroke-width="438"/>
</svg>
After:
<svg viewBox="0 0 3212 3212" fill="none" xmlns="http://www.w3.org/2000/svg">
circle cx="1606" cy="1606" r="1387" stroke="black" stroke-width="438"/>
</svg>
The dict.items
iterates over the key-value pairs of a dictionary. Therefore for key, value in dictionary.items()
will loop over each pair. This is documented information and you can check it out in the official web page, or even easier, open a python console and type help(dict.items)
. And now, just as an example:
>>> d = {'hello': 34, 'world': 2999}
>>> for key, value in d.items():
... print key, value
...
world 2999
hello 34
The AttributeError
is an exception thrown when an object does not have the attribute you tried to access. The class dict
does not have any predictors
attribute (now you know where to check it :) ), and therefore it complains when you try to access it. As easy as that.
I had some issues creating a file in Windows Explorer with a .
at the beginning.
A workaround was to go into the commandshell and create a new file using "edit".
You need to use return value of replaceAll()
method. replaceAll()
does not replace the characters in the current string, it returns a new string with replacement.
- String objects are immutable, their values cannot be changed after they are created.
- You may use replace() instead of replaceAll() if you don't need regex.
String str = "abcd=0; efgh=1";
String replacedStr = str.replaceAll("abcd", "dddd");
System.out.println(str);
System.out.println(replacedStr);
outputs
abcd=0; efgh=1
dddd=0; efgh=1
Copy the below script "ez_setup.py" from the below URL
https://bootstrap.pypa.io/ez_setup.py
And copy it into your Python location
C:\Python27>
Run the command
C:\Python27? python ez_setup.py
This will install the easy_install under Scripts directory
C:\Python27\Scripts
Run easy install from the Scripts directory >
C:\Python27\Scripts> easy_install
you cannot set target attribute to div, becacuse div does not know how to handle http requests. instead of you set target attribute for link tag.
$(this).find("a").target = "_blank";
window.location= $(this).find("a").attr("href")
If it's a single line string. wrapt it with b or B. e.g:
variable = b"This is a variable"
or
variable2 = B"This is also a variable"
You can use the simple and lightweight module https://github.com/nacholibre/nwc-l it supports both async and sync methods.
Note: this module was created by me.
You can do either…
$qb->where('e.fecha BETWEEN :monday AND :sunday')
->setParameter('monday', $monday->format('Y-m-d'))
->setParameter('sunday', $sunday->format('Y-m-d'));
or…
$qb->where('e.fecha > :monday')
->andWhere('e.fecha < :sunday')
->setParameter('monday', $monday->format('Y-m-d'))
->setParameter('sunday', $sunday->format('Y-m-d'));
inspired by this question I have written a blog along with the code snippet here. Below are some of the excerpts from the blog
SelectedItem – Selected Item helps to bind the actual value from the DataSource which will be displayed. This is of type object and we can bind any type derived from object type with this property. Since we will be using the MVVM binding for our combo boxes in that case this is the property which we can use to notify VM that item has been selected.
SelectedValue and SelectedValuePath – These are the two most confusing and misinterpreted properties for combobox. But these properties come to rescue when we want to bind our combobox with the value from already created object. Please check my last scenario in the following list to get a brief idea about the properties.
You can use this functions to check valid phone numbers and normalize them:
let formatPhone = (dirtyNumber) => {
return dirtyNumber.replace(/\D+/g, '').replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
}
let isPhone = (phone) => {
//normalize string and remove all unnecessary characters
phone = phone.replace(/\D+/g, '');
return phone.length == 10? true : false;
}
One scenario where your git repo will get seriously bigger with each commit is one where you are committing binary files that you generate regularly. Their storage won't be as efficient than text file.
Another is one where you have a huge number of files within one repo (which is a limit of git) instead of several subrepos (managed as submodules).
In this article on git space, AlBlue mentions:
Note that Git (and Hg, and other DVCSs) do suffer from a problem where (large) binaries are checked in, then deleted, as they'll still show up in the repository and take up space, even if they're not current.
If you have large binaries stored in your git repo, you may consider:
git filter-branch
(warning: this will rewrite the history, which is bad if you have already pushed your repo and if other have pulled from it)As I mentioned in "What are the file limits in Git (number and size)?", the more recent (2015, 5 years after this answer) Git LFS from GitHub is a way to manage those large files (by storing them outside the Git repository).
The data itself is one or more lucene indices, since you can have multiple shards. What you also need to backup is the cluster state, which contains all sorts of information regarding the cluster, the available indices, their mappings, the shards they are composed of etc.
It's all within the data
directory though, you can just copy it. Its structure is pretty intuitive. Right before copying it's better to disable automatic flush (in order to backup a consistent view of the index and avoiding writes on it while copying files), issue a manual flush, disable allocation as well. Remember to copy the directory from all nodes.
Also, next major version of elasticsearch is going to provide a new snapshot/restore api that will allow you to perform incremental snapshots and restore them too via api. Here is the related github issue: https://github.com/elasticsearch/elasticsearch/issues/3826.
I faced the similar issue on importing maven with testng project. This was solved by converting again into TestNg project by
right click on eclipse project > TestNG > Convert to TestNG
and replacing the existing testng.xml
file with the newly created. Clean and update the maven project with mvn install
Note: take backup of your testng.xml
There are several ways to authenticate to PostgreSQL. You may wish to investigate alternatives to password authentication at https://www.postgresql.org/docs/current/static/client-authentication.html.
To answer your question, there are a few ways provide a password for password-based authentication. The obvious way is via the password prompt. Instead of that, you can provide the password in a pgpass file or through the PGPASSWORD
environment variable. See these:
There is no option to provide the password as a command line argument because that information is often available to all users, and therefore insecure. However, in Linux/Unix environments you can provide an environment variable for a single command like this:
PGPASSWORD=yourpass psql ...
Intention of ConstraintLayout
is to optimize and flatten the view hierarchy of your layouts by applying some rules to each view to avoid nesting.
Rules remind you of RelativeLayout
, for example setting the left to the left of some other view.
app:layout_constraintBottom_toBottomOf="@+id/view1"
Unlike RelativeLayout
, ConstraintLayout
offers bias
value that is used to position a view in terms of 0% and 100% horizontal and vertical offset relative to the handles (marked with circle). These percentages (and fractions) offer seamless positioning of the view across different screen densities and sizes.
app:layout_constraintHorizontal_bias="0.33" <!-- from 0.0 to 1.0 -->
app:layout_constraintVertical_bias="0.53" <!-- from 0.0 to 1.0 -->
Baseline handle (long pipe with rounded corners, below the circle handle) is used to align content of the view with another view reference.
Square handles (on each corner of the view) are used to resize the view in dps.
This is totally opinion based and my impression of ConstraintLayout
If you previously installed Git, open a git-bash and try the command from there.
x <-c(1,2,3)
y <-c(100,200,300)
x_name <- "cond"
y_name <- "rating"
require(reshape2)
df <- melt(data.frame(x,y))
colnames(df) <- c(x_name, y_name)
print(df)
UPDATE (2017-02-07): As an answer to @cdaringe comment - there are multiple solutions possible, one of them is below.
library(dplyr)
library(magrittr)
x <- c(1, 2, 3)
y <- c(100, 200, 300)
z <- c(1, 2, 3, 4, 5)
x_name <- "cond"
y_name <- "rating"
# Helper function to create data.frame for the chunk of the data
prepare <- function(name, value, xname = x_name, yname = y_name) {
data_frame(rep(name, length(value)), value) %>%
set_colnames(c(xname, yname))
}
bind_rows(
prepare("x", x),
prepare("y", y),
prepare("z", z)
)
You would do that when the responsibility of creating/updating the referenced column isn't in the current entity, but in another entity.
I had the same issue. Tried all the above answers. It was actually complained about a .dll file. I clean the project in Visual Studio but the .dll file still remains, so I deleted in manually from the bin folder and it worked.
Don't pass db models directly to your views. You're lucky enough to be using MVC, so encapsulate using view models.
Create a view model class like this:
public class EmployeeAddViewModel
{
public Employee employee { get; set; }
public Dictionary<int, string> staffTypes { get; set; }
// really? a 1-to-many for genders
public Dictionary<int, string> genderTypes { get; set; }
public EmployeeAddViewModel() { }
public EmployeeAddViewModel(int id)
{
employee = someEntityContext.Employees
.Where(e => e.ID == id).SingleOrDefault();
// instantiate your dictionaries
foreach(var staffType in someEntityContext.StaffTypes)
{
staffTypes.Add(staffType.ID, staffType.Type);
}
// repeat similar loop for gender types
}
}
Controller:
[HttpGet]
public ActionResult Add()
{
return View(new EmployeeAddViewModel());
}
[HttpPost]
public ActionResult Add(EmployeeAddViewModel vm)
{
if(ModelState.IsValid)
{
Employee.Add(vm.Employee);
return View("Index"); // or wherever you go after successful add
}
return View(vm);
}
Then, finally in your view (which you can use Visual Studio to scaffold it first), change the inherited type to ShadowVenue.Models.EmployeeAddViewModel. Also, where the drop down lists go, use:
@Html.DropDownListFor(model => model.employee.staffTypeID,
new SelectList(model.staffTypes, "ID", "Type"))
and similarly for the gender dropdown
@Html.DropDownListFor(model => model.employee.genderID,
new SelectList(model.genderTypes, "ID", "Gender"))
Update per comments
For gender, you could also do this if you can be without the genderTypes in the above suggested view model (though, on second thought, maybe I'd generate this server side in the view model as IEnumerable). So, in place of new SelectList...
below, you would use your IEnumerable.
@Html.DropDownListFor(model => model.employee.genderID,
new SelectList(new SelectList()
{
new { ID = 1, Gender = "Male" },
new { ID = 2, Gender = "Female" }
}, "ID", "Gender"))
Finally, another option is a Lookup table. Basically, you keep key-value pairs associated with a Lookup type. One example of a type may be gender, while another may be State, etc. I like to structure mine like this:
ID | LookupType | LookupKey | LookupValue | LookupDescription | Active
1 | Gender | 1 | Male | male gender | 1
2 | State | 50 | Hawaii | 50th state | 1
3 | Gender | 2 | Female | female gender | 1
4 | State | 49 | Alaska | 49th state | 1
5 | OrderType | 1 | Web | online order | 1
I like to use these tables when a set of data doesn't change very often, but still needs to be enumerated from time to time.
Hope this helps!
From oldest to newer solutions:
The most portable solution, even older sh
(works with spaces and glob characters) (no loop, faster):
eval printf "'%s\n'" "\"\${$#}\""
Since version 2.01 of bash
$ set -- The quick brown fox jumps over the lazy dog
$ printf '%s\n' "${!#} ${@:(-1)} ${@: -1} ${@:~0} ${!#}"
dog dog dog dog dog
For ksh, zsh and bash:
$ printf '%s\n' "${@: -1} ${@:~0}" # the space beetwen `:`
# and `-1` is a must.
dog dog
And for "next to last":
$ printf '%s\n' "${@:~1:1}"
lazy
Using printf to workaround any issues with arguments that start with a dash (like -n
).
For all shells and for older sh
(works with spaces and glob characters) is:
$ set -- The quick brown fox jumps over the lazy dog "the * last argument"
$ eval printf "'%s\n'" "\"\${$#}\""
The last * argument
Or, if you want to set a last
var:
$ eval last=\${$#}; printf '%s\n' "$last"
The last * argument
And for "next to last":
$ eval printf "'%s\n'" "\"\${$(($#-1))}\""
dog
It for example happens in this case here:
void initializeJSP(unknownType Experiment);
Try using std::string
instead of just string
(and include the <string>
header). C++ Standard library classes are within the namespace std::
.
This function has some extra features:
error checking in case the end is older than the start
import datetime
from datetime import timedelta
DATE_FORMAT = '%Y/%m/%d'
def daterange(start, end):
def convert(date):
try:
date = datetime.datetime.strptime(date, DATE_FORMAT)
return date.date()
except TypeError:
return date
def get_date(n):
return datetime.datetime.strftime(convert(start) + timedelta(days=n), DATE_FORMAT)
days = (convert(end) - convert(start)).days
if days <= 0:
raise ValueError('The start date must be before the end date.')
for n in range(0, days):
yield get_date(n)
start = '2014/12/1'
end = '2014/12/31'
print list(daterange(start, end))
start_ = datetime.date.today()
end = '2015/12/1'
print list(daterange(start, end))
You can also use sets and get the commonalities in one line: subtract the set containing the differences from one of the sets.
A = [1,2,3,4]
B = [2,4,7,8]
commonalities = set(A) - (set(A) - set(B))
Yay thanks! This too has been driving me nuts forever.
In my particular case, this worked for me:
input {
width: 13px;
height: 13px;
padding: 0;
margin:0;
vertical-align: top;
position: relative;
*top: 1px;
*overflow: hidden;
}
label {
display: block;
padding: 0;
padding-left: 15px;
text-indent: -15px;
border: 0px solid;
margin-left: 5px;
vertical-align: top;
}
I am using the reset.css which might explain some of the differences, but this seems to work well for me.
You'll have to have a ContextLoaderListener in your web.xml - It loads your configuration files.
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
You need to understand the difference between Web application context and root application context .
In the web MVC framework, each DispatcherServlet has its own WebApplicationContext, which inherits all the beans already defined in the root WebApplicationContext. These inherited beans defined can be overridden in the servlet-specific scope, and new scope-specific beans can be defined local to a given servlet instance.
The dispatcher servlet's application context is a web application context which is only applicable for the Web classes . You cannot use these for your middle tier layers . These need a global app context using ContextLoaderListener .
Read the spring reference here for spring mvc .
To add multiple lines you can use lineinfile
module with with_items
also including variable vars
here to make it simple :)
---
- hosts: localhost #change Host group as par inventory
gather_facts: no
become: yes
vars:
test_server: "10.168.1.1"
test_server_name: "test-server"
file_dest: "/etc/test/test_agentd.conf"
- name: configuring test.conf
lineinfile:
dest: "{{ item.dest }}"
regexp: "{{ item.regexp }}"
line: "{{ item.line }}"
with_items:
- { dest: '"{{ file_dest }}"', regexp: 'Server=', line: 'Server="{{test_server}}"' }
- { dest: '"{{ file_dest }}"', regexp: 'ServerActive=', line: 'ServerActive="{{test_server}}"' }
- { dest: '"{{ file_dest }}"', regexp: 'Hostname=', line: 'Hostname="{{test_server_name}}"' }
This is quite simple.
yourtextfield.frame = CGRectMake (yourXAxis, yourYAxis, yourWidth, yourHeight);
Declare your textfield as a gloabal property & change its frame where ever you want to do it in your code.
Happy Coding!
As Ian already pointed out, there is a table-of-contents extension by minrk for the IPython Notebook. I had some trouble to make it work and made this IPython Notebook which semi-automatically generates the files for minrk's table of contents extension in Windows. It does not use the 'curl'-commands or links, but writes the *.js and *.css files directly into your IPython Notebook-profile-directory.
There is a section in the notebook called 'What you need to do' - follow it and have a nice floating table of contents : )
Here is an html version which already shows it: http://htmlpreview.github.io/?https://github.com/ahambi/140824-TOC/blob/master/A%20floating%20table%20of%20contents.htm
This may help:
function doAjax(url, callback) {
var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callback(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
Have you checked MZTools?? It does a lot of cool stuff...
If I'm not wrong, one of the functionalities it offers is to set your own shortcuts.
in my case, make sure you have a "Default" website
The answer is NEVER! (unless you really know what you're doing)
9/10 times the solution can be resolved with a proper understanding of encoding/decoding.
1/10 people have an incorrectly defined locale or environment and need to set:
PYTHONIOENCODING="UTF-8"
in their environment to fix console printing problems.
(struck through to avoid re-use) changes the default encoding/decoding used whenever Python 2.x needs to convert a Unicode() to a str() (and vice-versa) and the encoding is not given. I.e:sys.setdefaultencoding("utf-8")
str(u"\u20AC")
unicode("€")
"{}".format(u"\u20AC")
In Python 2.x, the default encoding is set to ASCII and the above examples will fail with:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128)
(My console is configured as UTF-8, so "€" = '\xe2\x82\xac'
, hence exception on \xe2
)
or
UnicodeEncodeError: 'ascii' codec can't encode character u'\u20ac' in position 0: ordinal not in range(128)
will allow these to work for me, but won't necessarily work for people who don't use UTF-8. The default of ASCII ensures that assumptions of encoding are not baked into codesys.setdefaultencoding("utf-8")
also has a side effect of appearing to fix sys.setdefaultencoding("utf-8")
sys.stdout.encoding
, used when printing characters to the console. Python uses the user's locale (Linux/OS X/Un*x) or codepage (Windows) to set this. Occasionally, a user's locale is broken and just requires PYTHONIOENCODING
to fix the console encoding.
Example:
$ export LANG=en_GB.gibberish
$ python
>>> import sys
>>> sys.stdout.encoding
'ANSI_X3.4-1968'
>>> print u"\u20AC"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u20ac' in position 0: ordinal not in range(128)
>>> exit()
$ PYTHONIOENCODING=UTF-8 python
>>> import sys
>>> sys.stdout.encoding
'UTF-8'
>>> print u"\u20AC"
€
People have been developing against Python 2.x for 16 years on the understanding that the default encoding is ASCII. UnicodeError
exception handling methods have been written to handle string to Unicode conversions on strings that are found to contain non-ASCII.
From https://anonbadger.wordpress.com/2015/06/16/why-sys-setdefaultencoding-will-break-code/
def welcome_message(byte_string):
try:
return u"%s runs your business" % byte_string
except UnicodeError:
return u"%s runs your business" % unicode(byte_string,
encoding=detect_encoding(byte_string))
print(welcome_message(u"Angstrom (Å®)".encode("latin-1"))
Previous to setting defaultencoding this code would be unable to decode the “Å” in the ascii encoding and then would enter the exception handler to guess the encoding and properly turn it into unicode. Printing: Angstrom (Å®) runs your business. Once you’ve set the defaultencoding to utf-8 the code will find that the byte_string can be interpreted as utf-8 and so it will mangle the data and return this instead: Angstrom (U) runs your business.
Changing what should be a constant will have dramatic effects on modules you depend upon. It's better to just fix the data coming in and out of your code.
While the setting of defaultencoding to UTF-8 isn't the root cause in the following example, it shows how problems are masked and how, when the input encoding changes, the code breaks in an unobvious way: UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 3131: invalid start byte
Very Simple answer
$("#table_name").DataTable().ajax.reload(null, false);
Update:
MongoServer.Create
is obsolete now (thanks to @aknuds1). Instead this use following code:
var _server = new MongoClient(connectionString).GetServer();
It's easy. You should first take database name from connection string and then get database by name. Complete example:
var connectionString = "mongodb://localhost:27020/mydb";
//take database name from connection string
var _databaseName = MongoUrl.Create(connectionString).DatabaseName;
var _server = MongoServer.Create(connectionString);
//and then get database by database name:
_server.GetDatabase(_databaseName);
Important: If your database and auth database are different, you can add a authSource= query parameter to specify a different auth database. (thank you to @chrisdrobison)
NOTE If you are using the database segment as the initial database to use, but the username and password specified are defined in a different database, you can use the authSource option to specify the database in which the credential is defined. For example, mongodb://user:pass@hostname/db1?authSource=userDb would authenticate the credential against the userDb database instead of db1.
Try AddRange-method:
GlobalStrings.AddRange(localStrings);
DataFrame.append
does not modify the DataFrame in place. You need to do df = df.append(...)
if you want to reassign it back to the original variable.
I thought my issue was due to my machine.config per answers I found online but the culprit turned out to be in the project's web.config that was clearing out the DbProviderFactories.
<system.data>
<DbProviderFactories>
<clear />
...
</DbProviderFactories>
</system.data>
Math.Floor(123456.646 * 100) / 100 Would return 123456.64
bool isFirst = compareString.Contains(firstString);
bool isSecond = compareString.Contains(secondString );
I was looking for the same solution and Pawel gave me 99% of the answer. The only thing that was missing that I needed for the Extension to display was adding the following Razor Code into the cshtml(view) page:
@using programname.Models.Extensions
I was looking for the FirstName, to display in the top right of my NavBar after the user logged in.
I thought I would post this incase it helps someone else, So here is my code:
I created a new folder called Extensions(Under my Models Folder) and created the new class as Pawel specified above: IdentityExtensions.cs
using System.Security.Claims;
using System.Security.Principal;
namespace ProgramName.Models.Extensions
{
public static class IdentityExtensions
{
public static string GetUserFirstname(this IIdentity identity)
{
var claim = ((ClaimsIdentity)identity).FindFirst("FirstName");
// Test for null to avoid issues during local testing
return (claim != null) ? claim.Value : string.Empty;
}
}
}
IdentityModels.cs
:
public class ApplicationUser : IdentityUser
{
//Extended Properties
public string FirstName { get; internal set; }
public string Surname { get; internal set; }
public bool isAuthorized { get; set; }
public bool isActive { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
userIdentity.AddClaim(new Claim("FirstName", this.FirstName));
return userIdentity;
}
}
Then in my _LoginPartial.cshtml
(Under Views/Shared
Folders) I added @using.ProgramName.Models.Extensions
I then added the change to the folling line of code that was going to use the Users First name after Logging in :
@Html.ActionLink("Hello " + User.Identity.GetUserFirstname() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
Perhaps this helps someone else down the line.
Sometimes you can reference a Windows "shortcut" file to launch an application instead of using a ".bat" file, and it won't have the residual prompt problem. But it's not as flexible as bat files.
If you want something that closely resembles the top answer but is also synchronous then this will work.
var execSync = require('child_process').execSync;
var cmd = "echo 'hello world'";
var options = {
encoding: 'utf8'
};
console.log(execSync(cmd, options));
This is for others (like me :) ). Don't forget to add the spring tx jar/maven dependency. Also correct configuration in appctx is:
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"
, by mistake wrong configuration which others may have
xmlns:tx="http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"
i.e., extra "/spring-tx-3.1.xsd"
xsi:schemaLocation="http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"
in other words what is there in xmlns(namespace) should have proper mapping in
schemaLocation (namespace vs schema).
namespace here is : http://www.springframework.org/schema/tx
schema Doc Of namespace is : http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
this schema of namespace later is mapped in jar to locate the path of actual xsd located in org.springframework.transaction.config
For opera just add this in header
<link rel='stylesheet' media='handheld' href='body.css' />
This makes opera use most of your customised css.
To set timeout on a per page level, you could use this simple code:
Page.Server.ScriptTimeout = 60;
Note: 60 means 60 seconds, this time-out applies only if the debug attribute in the compilation element is False.
The actual code to cast away the const-ness of your pointer would be:
BoxT<T> * nonConstObj = const_cast<BoxT<T> *>(constObj);
But note that this really is cheating. A better solution would either be to figure out why you want to modify a const object, and redesign your code so you don't have to.... or remove the const declaration from your vector, if it turns out you don't really want those items to be read-only after all.
I was having the same issue and was searching for a possible idea to solve this.
I had some CSS already in place for my tabs and this is what worked for me:
(Note specifically the padding-bottom: 2px;
inside #tabs #selected a {
. That hides the bottom box-shadow
neatly and worked great for me with the following CSS.)
#tabs {
margin-top: 1em;
margin-left: 0.5em;
}
#tabs li a {
padding: 1 1em;
position: relative;
top: 1px;
background: #FFFFFF;
}
#tabs #selected {
/* For the "selected" tab */
box-shadow: 0 0 3px #666666;
background: #FFFFFF;
}
#tabs #selected a {
position: relative;
top: 1px;
background: #FFFFFF;
padding-bottom: 2px;
}
#tabs ul {
list-style: none;
padding: 0;
margin: 0;
}
#tabs li {
float: left;
border: 1px solid;
border-bottom-width: 0;
margin: 0 0.5em 0 0;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
}
Thought I'd put this out there as another possible solution for anyone perusing SO for this.
Try this sample SQL scripts for easy understanding,
CREATE TABLE TABLE1 (REFNO VARCHAR(10))
CREATE TABLE TABLE2 (REFNO VARCHAR(10))
--TRUNCATE TABLE TABLE1
--TRUNCATE TABLE TABLE2
INSERT INTO TABLE1 SELECT 'TEST_NAME'
INSERT INTO TABLE1 SELECT 'KUMAR'
INSERT INTO TABLE1 SELECT 'SIVA'
INSERT INTO TABLE1 SELECT 'SUSHANT'
INSERT INTO TABLE2 SELECT 'KUMAR'
INSERT INTO TABLE2 SELECT 'SIVA'
INSERT INTO TABLE2 SELECT 'SUSHANT'
SELECT * FROM TABLE1
SELECT * FROM TABLE2
DELETE T1 FROM TABLE1 T1 JOIN TABLE2 T2 ON T1.REFNO = T2.REFNO
Your case is:
DELETE pgc
FROM guide_category pgc
LEFT JOIN guide g
ON g.id_guide = gc.id_guide
WHERE g.id_guide IS NULL
Use innerText
/textContent
:
var el = document.getElementById('*spaM4');
console.log(el.innerText || el.textContent);
Fiddle: http://jsfiddle.net/NeTgC/2/
The below code may help you,
List list = new ArrayList();
list.add("1");
list.add("2");
list.add("3");
String str = list.toString();
System.out.println("Step-1 : " + str);
str = str.replaceAll("[\\[\\]]", "");
System.out.println("Step-2 : " + str);
Output:
Step-1 : [1, 2, 3]
Step-2 : 1, 2, 3
I've spent a day on trying to put all the pieces together, been in hundreds of sites and tutorials, but they all skip trivial steps.
So here's the full guide:
New Project:
C:\Program Files\Java\jdk{version}
C:\Program Files\Android\android-sdk-windows
.Compiling:
Aside from getting decode
and encode
backwards, I think part of the answer here is actually don't use the ascii
encoding. It's probably not what you want.
To begin with, think of str
like you would a plain text file. It's just a bunch of bytes with no encoding actually attached to it. How it's interpreted is up to whatever piece of code is reading it. If you don't know what this paragraph is talking about, go read Joel's The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets right now before you go any further.
Naturally, we're all aware of the mess that created. The answer is to, at least within memory, have a standard encoding for all strings. That's where unicode
comes in. I'm having trouble tracking down exactly what encoding Python uses internally for sure, but it doesn't really matter just for this. The point is that you know it's a sequence of bytes that are interpreted a certain way. So you only need to think about the characters themselves, and not the bytes.
The problem is that in practice, you run into both. Some libraries give you a str
, and some expect a str
. Certainly that makes sense whenever you're streaming a series of bytes (such as to or from disk or over a web request). So you need to be able to translate back and forth.
Enter codecs
: it's the translation library between these two data types. You use encode
to generate a sequence of bytes (str
) from a text string (unicode
), and you use decode
to get a text string (unicode
) from a sequence of bytes (str
).
For example:
>>> s = "I look like a string, but I'm actually a sequence of bytes. \xe2\x9d\xa4"
>>> codecs.decode(s, 'utf-8')
u"I look like a string, but I'm actually a sequence of bytes. \u2764"
What happened here? I gave Python a sequence of bytes, and then I told it, "Give me the unicode
version of this, given that this sequence of bytes is in 'utf-8'
." It did as I asked, and those bytes (a heart character) are now treated as a whole, represented by their Unicode codepoint.
Let's go the other way around:
>>> u = u"I'm a string! Really! \u2764"
>>> codecs.encode(u, 'utf-8')
"I'm a string! Really! \xe2\x9d\xa4"
I gave Python a Unicode string, and I asked it to translate the string into a sequence of bytes using the 'utf-8'
encoding. So it did, and now the heart is just a bunch of bytes it can't print as ASCII; so it shows me the hexadecimal instead.
We can work with other encodings, too, of course:
>>> s = "I have a section \xa7"
>>> codecs.decode(s, 'latin1')
u'I have a section \xa7'
>>> codecs.decode(s, 'latin1')[-1] == u'\u00A7'
True
>>> u = u"I have a section \u00a7"
>>> u
u'I have a section \xa7'
>>> codecs.encode(u, 'latin1')
'I have a section \xa7'
('\xa7'
is the section character, in both
Unicode and Latin-1.)
So for your question, you first need to figure out what encoding your str
is in.
Did it come from a file? From a web request? From your database? Then the source determines the encoding. Find out the encoding of the source and use that to translate it into a unicode
.
s = [get from external source]
u = codecs.decode(s, 'utf-8') # Replace utf-8 with the actual input encoding
Or maybe you're trying to write it out somewhere. What encoding does the destination expect? Use that to translate it into a str
. UTF-8 is a good choice for plain text documents; most things can read it.
u = u'My string'
s = codecs.encode(u, 'utf-8') # Replace utf-8 with the actual output encoding
[Write s out somewhere]
Are you just translating back and forth in memory for interoperability or something? Then just pick an encoding and stick with it; 'utf-8'
is probably the best choice for that:
u = u'My string'
s = codecs.encode(u, 'utf-8')
newu = codecs.decode(s, 'utf-8')
In modern programming, you probably never want to use the 'ascii'
encoding for any of this. It's an extremely small subset of all possible characters, and no system I know of uses it by default or anything.
Python 3 does its best to make this immensely clearer simply by changing the names. In Python 3, str
was replaced with bytes
, and unicode
was replaced with str
.
What does const
mean
First, realize that the semantics of a "const" keyword means different things to different people:
final
semantics - reference variable itself cannot be reassigned to point to another instance (memory location), but the instance itself is modifiableconst
pointer/reference semantics - means this reference cannot be used to modify the instance (e.g. cannot assign to instance variables, cannot invoke mutable methods) - affects the reference variable only, so a non-const reference pointing to the same instance could modify the instanceWhy or Why Not const
Second, if you really want to dig into some of the "pro" vs "con" arguments, see the discussion under this request for enhancement (RFE) "bug". This RFE requests a "readable-only reference"-type "const" feature. Opened in 1999 and then closed/rejected by Sun in 2005, the "const" topic was vigorously debated:
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4211070
While there are a lot of good arguments on both sides, some of the oft-cited (but not necessarily compelling or clear-cut) reasons against const
include:
const
mean above)Before anyone tries to debate me about whether these are good or bad reasons, note that these are not my reasons. They are simply the "gist" of some of the reasons I gleaned from skimming the RFE discussion. I don't necessarily agree with them myself - I'm simply trying to cite why some people (not me) may feel a const
keyword may not be a good idea. Personally, I'd love more "const" semantics to be introduced to the language in an unambiguous manner.
More universal can be: for each v Selection : v.value = "'" & v.value : next and selecting range of cells before execution
If you did a new or clean install of OS X version 10.3 or more recent, the default user terminal shell is bash.
Bash is essentially an enhanced and GNU freeware version of the original Bourne shell, sh. If you have previous experience with bash (often the default on GNU/Linux installations), this makes the OS X command-line experience familiar, otherwise consider switching your shell either to tcsh or to zsh, as some find these more user-friendly.
If you upgraded from or use OS X version 10.2.x, 10.1.x or 10.0.x, the default user shell is tcsh, an enhanced version of csh('c-shell'). Early implementations were a bit buggy and the programming syntax a bit weird so it developed a bad rap.
There are still some fundamental differences between mac and linux as Gordon Davisson so aptly lists, for example no useradd
on Mac and ifconfig
works differently.
The following table is useful for knowing the various unix shells.
sh The original Bourne shell Present on every unix system
ksh Original Korn shell Richer shell programming environment than sh
csh Original C-shell C-like syntax; early versions buggy
tcsh Enhanced C-shell User-friendly and less buggy csh implementation
bash GNU Bourne-again shell Enhanced and free sh implementation
zsh Z shell Enhanced, user-friendly ksh-like shell
You may also find these guides helpful:
http://homepage.mac.com/rgriff/files/TerminalBasics.pdf
http://guides.macrumors.com/Terminal
http://www.ofb.biz/safari/article/476.html
On a final note, I am on Linux (Ubuntu 11) and Mac osX so I use bash and the thing I like the most is customizing the .bashrc (source'd from .bash_profile
on OSX) file with aliases, some examples below.
I now placed all my aliases in a separate .bash_aliases file and include it with:
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
in the .bashrc or .bash_profile file.
Note that this is an example of a mac-linux difference because on a Mac you can't have the --color=auto
. The first time I did this (without knowing) I redefined ls
to be invalid which was a bit alarming until I removed --auto-color
!
You may also find https://unix.stackexchange.com/q/127799/10043 useful
# ~/.bash_aliases
# ls variants
#alias l='ls -CF'
alias la='ls -A'
alias l='ls -alFtr'
alias lsd='ls -d .*'
# Various
alias h='history | tail'
alias hg='history | grep'
alias mv='mv -i'
alias zap='rm -i'
# One letter quickies:
alias p='pwd'
alias x='exit'
alias {ack,ak}='ack-grep'
# Directories
alias s='cd ..'
alias play='cd ~/play/'
# Rails
alias src='script/rails console'
alias srs='script/rails server'
alias raked='rake db:drop db:create db:migrate db:seed'
alias rvm-restart='source '\''/home/durrantm/.rvm/scripts/rvm'\'''
alias rrg='rake routes | grep '
alias rspecd='rspec --drb '
#
# DropBox - syncd
WORKBASE="~/Dropbox/97_2012/work"
alias work="cd $WORKBASE"
alias code="cd $WORKBASE/ror/code"
#
# DropNot - NOT syncd !
WORKBASE_GIT="~/Dropnot"
alias {dropnot,not}="cd $WORKBASE_GIT"
alias {webs,ww}="cd $WORKBASE_GIT/webs"
alias {setups,docs}="cd $WORKBASE_GIT/setups_and_docs"
alias {linker,lnk}="cd $WORKBASE_GIT/webs/rails_v3/linker"
#
# git
alias {gsta,gst}='git status'
# Warning: gst conflicts with gnu-smalltalk (when used).
alias {gbra,gb}='git branch'
alias {gco,go}='git checkout'
alias {gcob,gob}='git checkout -b '
alias {gadd,ga}='git add '
alias {gcom,gc}='git commit'
alias {gpul,gl}='git pull '
alias {gpus,gh}='git push '
alias glom='git pull origin master'
alias ghom='git push origin master'
alias gg='git grep '
#
# vim
alias v='vim'
#
# tmux
alias {ton,tn}='tmux set -g mode-mouse on'
alias {tof,tf}='tmux set -g mode-mouse off'
#
# dmc
alias {dmc,dm}='cd ~/Dropnot/webs/rails_v3/dmc/'
alias wf='cd ~/Dropnot/webs/rails_v3/dmc/dmWorkflow'
alias ws='cd ~/Dropnot/webs/rails_v3/dmc/dmStaffing'
After some testing this WILL remove the background color when deselected or cell is tapped a second time when table view Selection is set to "Multiple Selection". Also works when table view Style is set to "Grouped".
extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
cell.contentView.backgroundColor = UIColor.darkGray
}
}
}
Note: In order for this to work as you see below, your cell's Selection property can be set to anything BUT None.
Style: Plain, Selection: Single Selection
Style: Plain, Selection: Multiple Selection
Style: Grouped, Selection: Multiple Selection
For a smoother color transition, try some animation:
extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
UIView.animate(withDuration: 0.3, animations: {
cell.contentView.backgroundColor = UIColor.darkGray
})
}
}
}
You may notice the icon and text color also changing when cell is selected. This happens automatically when you set the UIImage and UILabel Highlighted properties
UIImage
UILabel
Just supply a color for the Highlighted property:
If you are using Bootstrap, look at padding
of your td
s.
In my case it was gcc 6 the one missing
sudo apt-get install gcc-6 g++-6 -y
sudo apt-get install gcc-7 g++-7 -y
Caucho Quercus can run PHP code on the jvm.
Found a strange behaviour about this hidden value () and we can't make it to work.
After playing around we found the best way is just defined the value in controller itself after the form scope.
.controller('AddController', [$scope, $http, $state, $stateParams, function($scope, $http, $state, $stateParams) {
$scope.routineForm = {};
$scope.routineForm.hiddenfield1 = "whatever_value_you_pass_on";
$scope.sendData = function {
// JSON http post action to API
}
}])
As of May 2018, you can find the full list here: https://developers.facebook.com/docs/reference/opengraph#object-type
apps.saves
An action representing someone saving an app to try later.
article
This object represents an article on a website. It is the preferred type for blog posts and news stories.
book
This object type represents a book or publication. This is an appropriate type for ebooks, as well as traditional paperback or hardback books. Do not use this type to represent magazines
books.author
This object type represents a single author of a book.
books.book
This object type represents a book or publication. This is an appropriate type for ebooks, as well as traditional paperback or hardback books
books.genre
This object type represents the genre of a book or publication.
books.quotes
Returns no data as of April 4, 2018.
An action representing someone quoting from a book.
books.rates
Returns no data as of April 4, 2018.
An action representing someone rating a book.
books.reads
Returns no data as of April 4, 2018.
An action representing someone reading a book.
books.wants_to_read
Returns no data as of April 4, 2018.
An action representing someone wanting to read a book.
business.business
This object type represents a place of business that has a location, operating hours and contact information.
fitness.bikes
Returns no data as of April 4, 2018.
An action representing someone cycling a course.
fitness.course
This object type represents the user's activity contributing to a particular run, walk, or bike course.
fitness.runs
Returns no data as of April 4, 2018.
An action representing someone running a course.
fitness.walks
Returns no data as of April 4, 2018.
An action representing someone walking a course.
game.achievement
This object type represents a specific achievement in a game. An app must be in the 'Games' category in App Dashboard to be able to use this object type. Every achievement has agame:points
value associate with it. This is not related to the points the user has scored in the game, but is a way for the app to indicate the relative importance and scarcity of different achievements: * Each game gets a total of 1,000 points to distribute across its achievements * Each game gets a maximum of 1,000 achievements * Achievements which are scarcer and have higher point values will receive more distribution in Facebook's social channels. For example, achievements which have point values of less than 10 will get almost no distribution. Apps should aim for between 50-100 achievements consisting of a mix of 50 (difficult), 25 (medium), and 10 (easy) point value achievements Read more on how to use achievements in this guide.
games.achieves
An action representing someone reaching a game achievement.
games.celebrate
An action representing someone celebrating a victory in a game.
games.plays
An action representing someone playing a game. Stories for this action will only appear in the activity log.
games.saves
An action representing someone saving a game.
music.album
This object type represents a music album; in other words, an ordered collection of songs from an artist or a collection of artists. An album can comprise multiple discs.
music.listens
Returns no data as of April 4, 2018.
An action representing someone listening to a song, album, radio station, playlist or musician
music.playlist
This object type represents a music playlist, an ordered collection of songs from a collection of artists.
music.playlists
Returns no data as of April 4, 2018.
An action representing someone creating a playlist.
music.radio_station
This object type represents a 'radio' station of a stream of audio. The audio properties should be used to identify the location of the stream itself.
music.song
This object type represents a single song.
news.publishes
An action representing someone publishing a news article.
news.reads
Returns no data as of April 4, 2018.
An action representing someone reading a news article.
og.follows
An action representing someone following a Facebook user
og.likes
An action representing someone liking any object.
pages.saves
An action representing someone saving a place.
place
This object type represents a place - such as a venue, a business, a landmark, or any other location which can be identified by longitude and latitude.
product
This object type represents a product. This includes both virtual and physical products, but it typically represents items that are available in an online store.
product.group
This object type represents a group of product items.
product.item
This object type represents a product item.
profile
This object type represents a person. While appropriate for celebrities, artists, or musicians, this object type can be used for the profile of any individual. Thefb:profile_id
field associates the object with a Facebook user.
restaurant.menu
This object type represents a restaurant's menu. A restaurant can have multiple menus, and each menu has multiple sections.
restaurant.menu_item
This object type represents a single item on a restaurant's menu. Every item belongs within a menu section.
restaurant.menu_section
This object type represents a section in a restaurant's menu. A section contains multiple menu items.
restaurant.restaurant
This object type represents a restaurant at a specific location.
restaurant.visited
An action representing someone visiting a restaurant.
restaurant.wants_to_visit
An action representing someone wanting to visit a restaurant
sellers.rates
An action representing a commerce seller has been given a rating.
video.episode
This object type represents an episode of a TV show and contains references to the actors and other professionals involved in its production. An episode is defined by us as a full-length episode that is part of a series. This type must reference the series this it is part of.
video.movie
This object type represents a movie, and contains references to the actors and other professionals involved in its production. A movie is defined by us as a full-length feature or short film. Do not use this type to represent movie trailers, movie clips, user-generated video content, etc.
video.other
This object type represents a generic video, and contains references to the actors and other professionals involved in its production. For specific types of video content, use thevideo.movie
orvideo.tv_show
object types. This type is for any other type of video content not represented elsewhere (eg. trailers, music videos, clips, news segments etc.)
video.rates
Returns no data as of April 4, 2018.
An action representing someone rating a movie, TV show, episode or another piece of video content.
video.tv_show
This object type represents a TV show, and contains references to the actors and other professionals involved in its production. For individual episodes of a series, use thevideo.episode
object type. A TV show is defined by us as a series or set of episodes that are produced under the same title (eg. a television or online series)
video.wants_to_watch
Returns no data as of April 4, 2018.
An action representing someone wanting to watch video content.
video.watches
Returns no data as of April 4, 2018.
An action representing someone watching video content.
The .Elements operation returns a LIST of XElements - but what you really want is a SINGLE element. Add this:
XElement Contacts = (from xml2 in XMLDoc.Elements("Contacts").Elements("Node")
where xml2.Element("ID").Value == variable
select xml2).FirstOrDefault();
This way, you tell LINQ to give you the first (or NULL, if none are there) from that LIST of XElements you're selecting.
Marc
There are at least three problems with putting a BOM in UTF-8 encoded files.
And, as others have mentioned, it is neither sufficient nor necessary to have a BOM to detect that something is UTF-8:
If you want to know all the shortcut in intellij hit Ctrl + J. This shows all the shortcuts. For System.out.println()
type sout
and press Tab.
Working unicode text JWT parser function:
function parseJwt (token) {
var base64Url = token.split('.')[1];
var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
var jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
return JSON.parse(jsonPayload);
};
The API docs give some good hints:
print() ? nil
print(obj, ...) ? nil
Writes the given object(s) to ios. Returns
nil
.The stream must be opened for writing. Each given object that isn't a string will be converted by calling its
to_s
method. When called without arguments, prints the contents of$_
.If the output field separator (
$,
) is notnil
, it is inserted between objects. If the output record separator ($\
) is notnil
, it is appended to the output....
puts(obj, ...) ? nil
Writes the given object(s) to ios. Writes a newline after any that do not already end with a newline sequence. Returns
nil
.The stream must be opened for writing. If called with an array argument, writes each element on a new line. Each given object that isn't a string or array will be converted by calling its
to_s
method. If called without arguments, outputs a single newline.
Experimenting a little with the points given above, the differences seem to be:
Called with multiple arguments, print
separates them by the 'output field separator' $,
(which defaults to nothing) while puts
separates them by newlines. puts
also puts a newline after the final argument, while print
does not.
2.1.3 :001 > print 'hello', 'world'
helloworld => nil
2.1.3 :002 > puts 'hello', 'world'
hello
world
=> nil
2.1.3 :003 > $, = 'fanodd'
=> "fanodd"
2.1.3 :004 > print 'hello', 'world'
hellofanoddworld => nil
2.1.3 :005 > puts 'hello', 'world'
hello
world
=> nil
puts
automatically unpacks arrays, while print
does not:
2.1.3 :001 > print [1, [2, 3]], [4] [1, [2, 3]][4] => nil 2.1.3 :002 > puts [1, [2, 3]], [4] 1 2 3 4 => nil
print
with no arguments prints $_
(the last thing read by gets
), while puts
prints a newline:
2.1.3 :001 > gets
hello world
=> "hello world\n"
2.1.3 :002 > puts
=> nil
2.1.3 :003 > print
hello world
=> nil
print
writes the output record separator $\
after whatever it prints, while puts
ignores this variable:
mark@lunchbox:~$ irb
2.1.3 :001 > $\ = 'MOOOOOOO!'
=> "MOOOOOOO!"
2.1.3 :002 > puts "Oink! Baa! Cluck! "
Oink! Baa! Cluck!
=> nil
2.1.3 :003 > print "Oink! Baa! Cluck! "
Oink! Baa! Cluck! MOOOOOOO! => nil
select field1, field2, 'example' as TempField
from table1
This should work across different SQL implementations.
Byte codes: https://cs.nyu.edu/courses/fall00/V22.0201-001/jvm2.html Byte codes Viewer: https://github.com/Konloch/bytecode-viewer
On my JDK (Windows 10 64 bit, 1.8.0_65-b17) I can reproduce and explain:
public static void main(String[] args) {
int repeat = 10;
long A = 0;
long B = 0;
for (int i = 0; i < repeat; i++) {
A += test();
B += testB();
}
System.out.println(A / repeat + " ms");
System.out.println(B / repeat + " ms");
}
private static long test() {
int n = 0;
for (int i = 0; i < 1000; i++) {
n += multi(i);
}
long startTime = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
n += multi(i);
}
long ms = (System.currentTimeMillis() - startTime);
System.out.println(ms + " ms A " + n);
return ms;
}
private static long testB() {
int n = 0;
for (int i = 0; i < 1000; i++) {
n += multiB(i);
}
long startTime = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
n += multiB(i);
}
long ms = (System.currentTimeMillis() - startTime);
System.out.println(ms + " ms B " + n);
return ms;
}
private static int multiB(int i) {
return 2 * (i * i);
}
private static int multi(int i) {
return 2 * i * i;
}
Output:
...
405 ms A 785527736
327 ms B 785527736
404 ms A 785527736
329 ms B 785527736
404 ms A 785527736
328 ms B 785527736
404 ms A 785527736
328 ms B 785527736
410 ms
333 ms
So why? The byte code is this:
private static multiB(int arg0) { // 2 * (i * i)
<localVar:index=0, name=i , desc=I, sig=null, start=L1, end=L2>
L1 {
iconst_2
iload0
iload0
imul
imul
ireturn
}
L2 {
}
}
private static multi(int arg0) { // 2 * i * i
<localVar:index=0, name=i , desc=I, sig=null, start=L1, end=L2>
L1 {
iconst_2
iload0
imul
iload0
imul
ireturn
}
L2 {
}
}
The difference being:
With brackets (2 * (i * i)
):
Without brackets (2 * i * i
):
Loading all on the stack and then working back down is faster than switching between putting on the stack and operating on it.
In addition the other great answers, I suggest that you try to separate the error flag and the error code in order to save one line on each call, i.e.:
if( !doit(a, b, c, &errcode) )
{ (* handle *)
(* thine *)
(* error *)
}
When you have lots of error-checking, this little simplification really helps.
Destination Host Unreachable
This message indicates one of two problems: either the local system has no route to the desired destination, or a remote router reports that it has no route to the destination.
If the message is simply "Destination Host Unreachable," then there is no route from the local system, and the packets to be sent were never put on the wire.
If the message is "Reply From < IP address >: Destination Host Unreachable," then the routing problem occurred at a remote router, whose address is indicated by the "< IP address >" field.
Request Timed Out
This message indicates that no Echo Reply messages were received within the default time of 1 second. This can be due to many different causes; the most common include network congestion, failure of the ARP request, packet filtering, routing error, or a silent discard.
For more info Refer: http://technet.microsoft.com/en-us/library/cc940095.aspx
This is a syntax issue, the jQuery library included with WordPress loads in "no conflict" mode. This is to prevent compatibility problems with other javascript libraries that WordPress can load. In "no-confict" mode, the $ shortcut is not available and the longer jQuery is used, i.e.
jQuery(document).ready(function ($) {
By including the $ in parenthesis after the function call you can then use this shortcut within the code block.
For full details see WordPress Codex
First step: write an extension method to find out if an input is prime
public static bool isPrime(this int number ) {
for (int i = 2; i < number; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
2 step: write the method that will print all prime numbers that are between 0 and the number input
public static void getAllPrimes(int number)
{
for (int i = 0; i < number; i++)
{
if (i.isPrime()) Console.WriteLine(i);
}
}
http://constc.blogspot.com/2008/07/undeclared-undefined-null-in-javascript.html
Depends on how specific you want the test to be. You could maybe get away with
if(page_name){ string += "&page_name=" + page_name; }
Using static cast would probably result in something like this:
// This does not prevent a possible type overflow
const char char_max = -1;
int i = 48;
char c = (i & char_max);
To prevent possible type overflow you could do this:
const char char_max = (char)(((unsigned char) char(-1)) / 2);
int i = 128;
char c = (i & char_max); // Would always result in positive signed values.
Where reinterpret_cast would probably just directly convert to char, without any cast safety. -> Never use reinterpret_cast if you can also use static_cast. If you're casting between classes, static_cast will also ensure, that the two types are matching (the object is a derivate of the cast type).
If your object a polymorphic type and you don't know which one it is, you should use dynamic_cast which will perform a type check at runtime and return nullptr if the types do not match.
IF you need const_cast you most likely did something wrong and should think about possible alternatives to fix const correctness in your code.
On client:
axios.get('/api', {
params: {
foo: 'bar'
}
});
On server:
function get(req, res, next) {
let param = req.query.foo
.....
}
Aman is correct that you can use normal matplotlib commands, but this is also built into the FacetGrid
:
import seaborn as sns
planets = sns.load_dataset("planets")
g = sns.factorplot("year", data=planets, aspect=1.5, kind="count", color="b")
g.set_xticklabels(rotation=30)
There are some comments and another answer claiming this "doesn't work", however, anyone can run the code as written here and see that it does work. The other answer does not provide a reproducible example of what isn't working, making it very difficult to address, but my guess is that people are trying to apply this solution to the output of functions that return an Axes
object instead of a Facet Grid
. These are different things, and the Axes.set_xticklabels()
method does indeed require a list of labels and cannot simply change the properties of the existing labels on the Axes
. The lesson is that it's important to pay attention to what kind of objects you are working with.
For clear all options en Important en FOR : remove(0) - Important: 0
var select = document.getElementById("element_select");
var length = select.length;
for (i = 0; i < length; i++) {
select.remove(0);
// or
// select.options[0] = null;
}
var q = from b in listOfBoxes
group b by b.Owner into g
select new
{
Owner = g.Key,
Boxes = g.Count(),
TotalWeight = g.Sum(item => item.Weight),
TotalVolume = g.Sum(item => item.Volume)
};
Just do this:
Dim sPath As String = "Folder path here"
If (My.Computer.FileSystem.DirectoryExists(sPath) = False) Then
My.Computer.FileSystem.CreateDirectory(sPath + "/<Folder name>")
Else
'Something else happens, because the folder exists
End If
I declared the folder path as a String (sPath) so that way if you do use it multiple times it can be changed easily but also it can be changed through the program itself.
Hope it helps!
-nfell2009
In my case I was loading a user control dynamically in a page and both the page and user control had the content tags
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
Removing this tag from the user control worked for me.
I had the same problem. Try this:
git pull origin master --allow-unrelated-histories
git push origin master
require_once('db/connect.php');
//rand(1000000 , 9999999);
$products_query = "SELECT id FROM products";
$products_result = mysqli_query($conn, $products_query);
$products_row = mysqli_fetch_array($products_result);
$ids_array = [];
do
{
array_push($ids_array, $products_row['id']);
}
while($products_row = mysqli_fetch_array($products_result));
/*
echo '<pre>';
print_r($ids_array);
echo '</pre>';
*/
$row_counter = count($ids_array);
for ($i=0; $i < $row_counter; $i++)
{
$current_row = $ids_array[$i];
$rand = rand(1000000 , 9999999);
mysqli_query($conn , "UPDATE products SET code='$rand' WHERE id='$current_row'");
}
You can use sprintf
in combination with std::string.c_str()
.
c_str()
returns a const char*
and works with sprintf
:
string a = "test";
string b = "text.txt";
string c = "text1.txt";
char* x = new char[a.length() + b.length() + c.length() + 32];
sprintf(x, "%s %s > %s", a.c_str(), b.c_str(), c.c_str() );
string str = x;
delete[] x;
or you can use a pre-allocated char
array if you know the size:
string a = "test";
string b = "text.txt";
string c = "text1.txt";
char x[256];
sprintf(x, "%s %s > %s", a.c_str(), b.c_str(), c.c_str() );
select CustomerName,count(1) from Customers group by CustomerName having count(1) > 1
Go to you MainActivity.java
and below this code
-> NavigationView navigationView = findViewById(R.id.nav_view);
Add single line of code -> navigationView.setItemIconTintList(null);
i.e. the last line of my code
I hope this might solve your problem.
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setItemIconTintList(null);
webBrowser.ScriptErrorsSuppressed = true;
As Josh has stated above, you want to give each one the same name (letter, button, etc.) and all of them work. Then you want to surround all of these with a form tag:
<form name="myLetters" action="yourScript.php" method="POST">
<!-- Enter your values here with the following syntax: -->
<input type="radio" name="letter" value="A" /> A
<!-- Then add a submit value & close your form -->
<input type="submit" name="submit" value="Choose Letter!" />
</form>
Then, in the PHP script "yourScript.php" as defined by the action attribute, you can use:
$_POST['letter']
To get the value chosen.
Review your first line. Your stack trace is clearly not from the code you've pasted here, so I don't know precisely what you've done.
>>> my_set=([1,2,3,4])
>>> my_set
[1, 2, 3, 4]
>>> type(my_set)
<type 'list'>
>>> list(my_set)
[1, 2, 3, 4]
>>> type(_)
<type 'list'>
What you wanted was set([1, 2, 3, 4])
.
>>> my_set = set([1, 2, 3, 4])
>>> my_set
set([1, 2, 3, 4])
>>> type(my_set)
<type 'set'>
>>> list(my_set)
[1, 2, 3, 4]
>>> type(_)
<type 'list'>
The "not callable" exception means you were doing something like set()()
- attempting to call a set
instance.
This is in the feature backlog for Compose but it doesn't look like work has been started yet. Github issue.
You can use the sys.dm_tran_locks
view, which returns information about the currently active lock manager resources.
Try this
SELECT
SessionID = s.Session_id,
resource_type,
DatabaseName = DB_NAME(resource_database_id),
request_mode,
request_type,
login_time,
host_name,
program_name,
client_interface_name,
login_name,
nt_domain,
nt_user_name,
s.status,
last_request_start_time,
last_request_end_time,
s.logical_reads,
s.reads,
request_status,
request_owner_type,
objectid,
dbid,
a.number,
a.encrypted ,
a.blocking_session_id,
a.text
FROM
sys.dm_tran_locks l
JOIN sys.dm_exec_sessions s ON l.request_session_id = s.session_id
LEFT JOIN
(
SELECT *
FROM sys.dm_exec_requests r
CROSS APPLY sys.dm_exec_sql_text(sql_handle)
) a ON s.session_id = a.session_id
WHERE
s.session_id > 50
I got the Similar issue while importing the project.
The issue is you select "Use an execution environment JRE" and which is lower then the libraries used in the projects being imported.
There are two ways to resolve this issue:
1.While first time importing the project:
in JRE tab select "USE project specific JRE" instead of "Use an execution environment JRE".
2.Delete the Project from your work space and import again. This time:
select "Check out as a project in the workspace" instead of "Check out as a project configured using the new Project Wizard"
You can use also "void*" (void pointer) to send an address to the function.
typedef struct pstring_t {
char * chars;
int(*length)(void*);
} PString;
int length(void* self) {
return strlen(((PString*)self)->chars);
}
PString initializeString() {
PString str;
str.length = &length;
return str;
}
int main()
{
PString p = initializeString();
p.chars = "Hello";
printf("Length: %i\n", p.length(&p));
return 0;
}
Output:
Length: 5
All have explained in great detail and nothing I could add further. Though I would like to explain it in Layman's Terms or plain ENGLISH
1.9 is less precise than 1.99
1.99 is less precise than 1.999
1.999 is less precise than 1.9999
.....
A variable, able to store or represent "1.9" provides less precision than the one able to hold or represent 1.9999. These Fraction can amount to a huge difference in large calculations.
I usually use Oracle Analytic function ROW_NUMBER().
Say you want to check the duplicates you have regarding a unique index or primary key built on columns (c1
, c2
, c3
).
Then you will go this way, bringing up ROWID
s of rows where the number of lines brought by ROW_NUMBER()
is >1
:
Select * From Table_With_Duplicates
Where Rowid In
(Select Rowid
From (Select Rowid,
ROW_NUMBER() Over (
Partition By c1 || c2 || c3
Order By c1 || c2 || c3
) nbLines
From Table_With_Duplicates) t2
Where nbLines > 1)
For a list of available flags:
grep --help
Returns all matches for the regexp texthere in the current directory, with the corresponding line number:
grep -rn "texthere" .
Returns all matches for texthere, starting at the root directory, with the corresponding line number and ignoring case:
grep -rni "texthere" /
flags used here:
-r
recursive -n
print line number with output -i
ignore caseChange .img-responsive inside bootstrap.css to the following:
.img-responsive {
display: block;
max-width: 100%;
width: 100%;
height: auto;
}
For some reason adding width: 100% to the mix makes img-responsive work.
try this out let me know what happens.
Form:
<form action="form.php" method="post">
Search: <input type="text" name="term" /><br />
<input type="submit" value="Submit" />
</form>
Form.php:
$term = mysql_real_escape_string($_REQUEST['term']);
$sql = "SELECT * FROM liam WHERE Description LIKE '%".$term."%'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_array($r_query)){
echo 'Primary key: ' .$row['PRIMARYKEY'];
echo '<br /> Code: ' .$row['Code'];
echo '<br /> Description: '.$row['Description'];
echo '<br /> Category: '.$row['Category'];
echo '<br /> Cut Size: '.$row['CutSize'];
}
Edit: Cleaned it up a little more.
Final Cut (my test file):
<?php
$db_hostname = 'localhost';
$db_username = 'demo';
$db_password = 'demo';
$db_database = 'demo';
// Database Connection String
$con = mysql_connect($db_hostname,$db_username,$db_password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db_database, $con);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="" method="post">
Search: <input type="text" name="term" /><br />
<input type="submit" value="Submit" />
</form>
<?php
if (!empty($_REQUEST['term'])) {
$term = mysql_real_escape_string($_REQUEST['term']);
$sql = "SELECT * FROM liam WHERE Description LIKE '%".$term."%'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_array($r_query)){
echo 'Primary key: ' .$row['PRIMARYKEY'];
echo '<br /> Code: ' .$row['Code'];
echo '<br /> Description: '.$row['Description'];
echo '<br /> Category: '.$row['Category'];
echo '<br /> Cut Size: '.$row['CutSize'];
}
}
?>
</body>
</html>
I know you can't edit the HTML, but if you can modify the CSS, can you add javascript?
if so, you can include jquery, then you could do
<script language="javascript">
$(document).ready(function() {
$('br').append('<span class="myclass"></span>');
});
</script>
I had the same problem, and resolved it. In my case it was error due to the non-proper format. Please check the first and last coordinates array in geometry coordinates they must be same then and only then it will work. Hope it may help you!
int position = 0;
listview.setItemChecked(position, true);
View wantedView = adapter.getView(position, null, listview);
How About this..
string str = "The quick brown fox jumps over the lazy dog,";
StringBuilder sb = new StringBuilder(str);
sb.Remove(str.Length - 1, 1);
Without your actual data or source, it will be hard for us to diagnose what is going wrong. However, I can make a few suggestions:
Given what you wrote, I suspect whatever converts the database data to XML is broken; it's propagating non-XML characters.
Create some database entries with non-XML characters (NULs, DELs, control characters, et al.) and run your XML converter on it. Output the XML to a file and look at it in a hex editor. If this contains non-XML characters, your converter is broken. Fix it or, if you cannot, create a preprocessor that rejects output with such characters.
If the converter output looks good, the problem is in your XML consumer; it's inserting non-XML characters somewhere. You will have to break your consumption process into separate steps, examine the output at each step, and narrow down what is introducing the bad characters.
Update: I just ran into an example of this myself! What was happening is that the producer was encoding the XML as UTF16 and the consumer was expecting UTF8. Since UTF16 uses 0x00 as the high byte for all ASCII characters and UTF8 doesn't, the consumer was seeing every second byte as a NUL. In my case I could change encoding, but suggested all XML payloads start with a BOM.
If $arrayofStringsNotInterestedIn is an [array] you should use -notcontains:
Get-Content $FileName | foreach-object { `
if ($arrayofStringsNotInterestedIn -notcontains $_) { $) }
or better (IMO)
Get-Content $FileName | where { $arrayofStringsNotInterestedIn -notcontains $_}
@sz3, funny enough today I had to do exactly what you were trying to achieve: 'load a specific CSS file only when a user access' a specific page. So I used the solution above.
But I am here to answer your last question: 'where exactly should I put the code. Any ideas?'
You were right including the code into the resolve, but you need to change a bit the format.
Take a look at the code below:
.when('/home', {
title:'Home - ' + siteName,
bodyClass: 'home',
templateUrl: function(params) {
return 'views/home.html';
},
controler: 'homeCtrl',
resolve: {
style : function(){
/* check if already exists first - note ID used on link element*/
/* could also track within scope object*/
if( !angular.element('link#mobile').length){
angular.element('head').append('<link id="home" href="home.css" rel="stylesheet">');
}
}
}
})
I've just tested and it's working fine, it injects the html and it loads my 'home.css' only when I hit the '/home' route.
Full explanation can be found here, but basically resolve: should get an object in the format
{
'key' : string or function()
}
You can name the 'key' anything you like - in my case I called 'style'.
Then for the value you have two options:
If it's a string, then it is an alias for a service.
If it's function, then it is injected and the return value is treated as the dependency.
The main point here is that the code inside the function is going to be executed before before the controller is instantiated and the $routeChangeSuccess event is fired.
Hope that helps.
Just add
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
to the .htaccess
file in the root of the website you are trying to connect with.
You can use also util methods mentioned in this blog: Getting cell witdth and height from excel with Apache POI. It can solve your problem.
Copy & paste from that blog:
static public class PixelUtil {
public static final short EXCEL_COLUMN_WIDTH_FACTOR = 256;
public static final short EXCEL_ROW_HEIGHT_FACTOR = 20;
public static final int UNIT_OFFSET_LENGTH = 7;
public static final int[] UNIT_OFFSET_MAP = new int[] { 0, 36, 73, 109, 146, 182, 219 };
public static short pixel2WidthUnits(int pxs) {
short widthUnits = (short) (EXCEL_COLUMN_WIDTH_FACTOR * (pxs / UNIT_OFFSET_LENGTH));
widthUnits += UNIT_OFFSET_MAP[(pxs % UNIT_OFFSET_LENGTH)];
return widthUnits;
}
public static int widthUnits2Pixel(short widthUnits) {
int pixels = (widthUnits / EXCEL_COLUMN_WIDTH_FACTOR) * UNIT_OFFSET_LENGTH;
int offsetWidthUnits = widthUnits % EXCEL_COLUMN_WIDTH_FACTOR;
pixels += Math.floor((float) offsetWidthUnits / ((float) EXCEL_COLUMN_WIDTH_FACTOR / UNIT_OFFSET_LENGTH));
return pixels;
}
public static int heightUnits2Pixel(short heightUnits) {
int pixels = (heightUnits / EXCEL_ROW_HEIGHT_FACTOR);
int offsetWidthUnits = heightUnits % EXCEL_ROW_HEIGHT_FACTOR;
pixels += Math.floor((float) offsetWidthUnits / ((float) EXCEL_ROW_HEIGHT_FACTOR / UNIT_OFFSET_LENGTH));
return pixels;
}
}
So when you want to get cell width and height you can use this to get value in pixel, values are approximately.
PixelUtil.heightUnits2Pixel((short) row.getHeight())
PixelUtil.widthUnits2Pixel((short) sh.getColumnWidth(columnIndex));
I just don't see the functional and seamless reason for nulls not to be comparable to other values or other nulls, cause we can clearly compare it and say they are the same or not in our context. It's funny. Just because of some logical conclusions and consistency we need to bother constantly with it. It's not functional, make it more functional and leave it to philosophers and scientists to conclude if it's consistent or not and does it hold "universal logic". :) Someone may say that it's because of indexes or something else, I doubt that those things couldn't be made to support nulls same as values. It's same as comparing two empty glasses, one is vine glass and other is beer glass, we are not comparing the types of objects but values they contain, same as you could compare int and varchar, with null it's even easier, it's nothing and what two nothingness have in common, they are the same, clearly comparable by me and by everyone else that write sql, because we are constantly breaking that logic by comparing them in weird ways because of some ANSI standards. Why not use computer power to do it for us and I doubt it would slow things down if everything related is constructed with that in mind. "It's not null it's nothing", it's not apple it's apfel, come on... Functionally is your friend and there is also logic here. In the end only thing that matter is functionality and does using nulls in that way brings more or less functionality and ease of use. Is it more useful?
Consider this code:
SELECT CASE WHEN NOT (1 = null or (1 is null and null is null)) THEN 1 ELSE 0 end
How many of you knows what will this code return? With or without NOT it returns 0. To me that is not functional and it's confusing. In c# it's all as it should be, comparison operations return value, logically this too produces value, because if it didn't there is nothing to compare (except. nothing :) ). They just "said": anything compared to null "returns" 0 and that creates many workarounds and headaches.
This is the code that brought me here:
where a != b OR (a is null and b IS not null) OR (a IS not null and b IS null)
I just need to compare if two fields (in where) have different values, I could use function, but...
I wonder why nobody mentioned the Minted package. It has far better syntax highlighting than the LaTeX listing package. It uses Pygments.
$ pip install Pygments
Example in LaTeX:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage{minted}
\begin{document}
\begin{minted}{python}
import numpy as np
def incmatrix(genl1,genl2):
m = len(genl1)
n = len(genl2)
M = None #to become the incidence matrix
VT = np.zeros((n*m,1), int) #dummy variable
#compute the bitwise xor matrix
M1 = bitxormatrix(genl1)
M2 = np.triu(bitxormatrix(genl2),1)
for i in range(m-1):
for j in range(i+1, m):
[r,c] = np.where(M2 == M1[i,j])
for k in range(len(r)):
VT[(i)*n + r[k]] = 1;
VT[(i)*n + c[k]] = 1;
VT[(j)*n + r[k]] = 1;
VT[(j)*n + c[k]] = 1;
if M is None:
M = np.copy(VT)
else:
M = np.concatenate((M, VT), 1)
VT = np.zeros((n*m,1), int)
return M
\end{minted}
\end{document}
Which results in:
You need to use the flag -shell-escape
with the pdflatex command.
For more information: https://www.sharelatex.com/learn/Code_Highlighting_with_minted
.apply()
takes in a function as the first parameter; pass in the label_race
function as so:
df['race_label'] = df.apply(label_race, axis=1)
You don't need to make a lambda function to pass in a function.
Java version of barycentric method:
class Triangle {
Triangle(double x1, double y1, double x2, double y2, double x3,
double y3) {
this.x3 = x3;
this.y3 = y3;
y23 = y2 - y3;
x32 = x3 - x2;
y31 = y3 - y1;
x13 = x1 - x3;
det = y23 * x13 - x32 * y31;
minD = Math.min(det, 0);
maxD = Math.max(det, 0);
}
boolean contains(double x, double y) {
double dx = x - x3;
double dy = y - y3;
double a = y23 * dx + x32 * dy;
if (a < minD || a > maxD)
return false;
double b = y31 * dx + x13 * dy;
if (b < minD || b > maxD)
return false;
double c = det - a - b;
if (c < minD || c > maxD)
return false;
return true;
}
private final double x3, y3;
private final double y23, x32, y31, x13;
private final double det, minD, maxD;
}
The above code will work accurately with integers, assuming no overflows. It will also work with clockwise and anticlockwise triangles. It will not work with collinear triangles (but you can check for that by testing det==0).
The barycentric version is fastest if you are going to test different points with the same triangle.
The barycentric version is not symmetric in the 3 triangle points, so it is likely to be less consistent than Kornel Kisielewicz's edge half-plane version, because of floating point rounding errors.
Credit: I made the above code from Wikipedia's article on barycentric coordinates.
You need to prevent the default behaviour. You can either use e.preventDefault()
or return false;
In this case, the best thing is, you can use return false;
here:
<form onsubmit="completeAndRedirect(); return false;">
Try with Shadow( Like border ) + Border
border-bottom: 5px solid #fff;
box-shadow: 0 5px 0 #ffbf0e;
There are a number of ways to get information on the attributes of your DataFrame or Series.
Create Sample DataFrame and Series
df = pd.DataFrame({'a':[5, 2, np.nan], 'b':[ 9, 2, 4]})
df
a b
0 5.0 9
1 2.0 2
2 NaN 4
s = df['a']
s
0 5.0
1 2.0
2 NaN
Name: a, dtype: float64
shape
AttributeThe shape
attribute returns a two-item tuple of the number of rows and the number of columns in the DataFrame. For a Series, it returns a one-item tuple.
df.shape
(3, 2)
s.shape
(3,)
len
functionTo get the number of rows of a DataFrame or get the length of a Series, use the len
function. An integer will be returned.
len(df)
3
len(s)
3
size
attributeTo get the total number of elements in the DataFrame or Series, use the size
attribute. For DataFrames, this is the product of the number of rows and the number of columns. For a Series, this will be equivalent to the len
function:
df.size
6
s.size
3
ndim
attributeThe ndim
attribute returns the number of dimensions of your DataFrame or Series. It will always be 2 for DataFrames and 1 for Series:
df.ndim
2
s.ndim
1
count
methodThe count
method can be used to return the number of non-missing values for each column/row of the DataFrame. This can be very confusing, because most people normally think of count as just the length of each row, which it is not. When called on a DataFrame, a Series is returned with the column names in the index and the number of non-missing values as the values.
df.count() # by default, get the count of each column
a 2
b 3
dtype: int64
df.count(axis='columns') # change direction to get count of each row
0 2
1 2
2 1
dtype: int64
For a Series, there is only one axis for computation and so it just returns a scalar:
s.count()
2
info
method for retrieving metadataThe info
method returns the number of non-missing values and data types of each column
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
a 2 non-null float64
b 3 non-null int64
dtypes: float64(1), int64(1)
memory usage: 128.0 bytes
Incase of lookup_food_array is array.
match_stage["favoriteFoods"] = {'$elemMatch': {'$in': lookup_food_array}}
Incase of lookup_food_array is string.
match_stage["favoriteFoods"] = {'$elemMatch': lookup_food_string}
The Differences in as easy as much possible: After having a basic understanding, the other comments posted above will be easier to catch.
Shell - "Shell" is a program, which facilitates the interaction between the user and the operating system (kernel). There are many shell implementation available, like sh, bash, csh, zsh...etc.
Using any of the Shell programs, we will be able to execute commands that are supported by that shell program.
Bash - It derived from Bourne-again Shell. Using this program, we will be able to execute all the commands specified by Shell. Also, we will be able to execute some commands that are specifically added to this program. Bash has backward compatibility with sh.
Sh - It derived from Bourne Shell. "sh" supports all the commands specified in the shell. Means, Using this program, we will be able to execute all the commands specified by Shell.
For more information, do: - https://man.cx/sh - https://man.cx/bash
Try using \n
when concatenating strings, as in this example:
var name = "Raihan";
var ID = "1234";
Console.WriteLine(name + "\n" + ID);
I would write the code like this:
def search_book(request):
form = SearchForm(request.POST or None)
if request.method == "POST" and form.is_valid():
stitle = form.cleaned_data['title']
sauthor = form.cleaned_data['author']
scategory = form.cleaned_data['category']
return HttpResponseRedirect('/thanks/')
return render_to_response("books/create.html", {
"form": form,
}, context_instance=RequestContext(request))
Pretty much like the documentation.
The documentation for css() says that setting the style property to the empty string will remove that property if it does not reside in a stylesheet:
Setting the value of a style property to an empty string — e.g.
$('#mydiv').css('color', '')
— removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's.css()
method, or through direct DOM manipulation of the style property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or<style>
element.
Since your styles are inline, you can write:
$(selector).css("-moz-user-select", "");
The following will enable you to quickly remove the duplicate,null values and return only the valid one as list.
CREATE TABLE DuplicateTable (Col1 INT)
INSERT INTO DuplicateTable
SELECT 8
UNION ALL
SELECT 1--duplicate
UNION ALL
SELECT 2 --duplicate
UNION ALL
SELECT 1
UNION ALL
SELECT 3
UNION ALL
SELECT 4
UNION ALL
SELECT 5
UNION
SELECT NULL
GO
WITH CTE (COl1,DuplicateCount)
AS
(
SELECT COl1,
ROW_NUMBER() OVER(PARTITION BY COl1 ORDER BY Col1) AS DuplicateCount
FROM DuplicateTable
WHERE (col1 IS NOT NULL)
)
SELECT COl1
FROM CTE
WHERE DuplicateCount =1
GO
CTE are valid in SQL 2005 , you could then store the values in a temp table and use it with your function.
This is my pure HTML & Javascript solution:
var setHeight = function (element, height) {
if (!element) {;
return false;
}
else {
var elementHeight = parseInt(window.getComputedStyle(element, null).height, 10),
toggleButton = document.createElement('a'),
text = document.createTextNode('...Show more'),
parent = element.parentNode;
toggleButton.src = '#';
toggleButton.className = 'show-more';
toggleButton.style.float = 'right';
toggleButton.style.paddingRight = '15px';
toggleButton.appendChild(text);
parent.insertBefore(toggleButton, element.nextSibling);
element.setAttribute('data-fullheight', elementHeight);
element.style.height = height;
return toggleButton;
}
}
var toggleHeight = function (element, height) {
if (!element) {
return false;
}
else {
var full = element.getAttribute('data-fullheight'),
currentElementHeight = parseInt(element.style.height, 10);
element.style.height = full == currentElementHeight ? height : full + 'px';
}
}
var toggleText = function (element) {
if (!element) {
return false;
}
else {
var text = element.firstChild.nodeValue;
element.firstChild.nodeValue = text == '...Show more' ? '...Show less' : '...Show more';
}
}
var applyToggle = function(elementHeight){
'use strict';
return function(){
toggleHeight(this.previousElementSibling, elementHeight);
toggleText(this);
}
}
var modifyDomElements = function(className, elementHeight){
var elements = document.getElementsByClassName(className);
var toggleButtonsArray = [];
for (var index = 0, arrayLength = elements.length; index < arrayLength; index++) {
var currentElement = elements[index];
var toggleButton = setHeight(currentElement, elementHeight);
toggleButtonsArray.push(toggleButton);
}
for (var index=0, arrayLength=toggleButtonsArray.length; index<arrayLength; index++){
toggleButtonsArray[index].onclick = applyToggle(elementHeight);
}
}
You can then call modifyDomElements function to apply text shortening on all the elements that have shorten-text class name. For that you would need to specify the class name and the height that you would want your elements to be shortened to:
modifyDomElements('shorten-text','50px');
Lastly, in your your html, just set the class name on the element you would want your text to get shorten:
<div class="shorten-text">Your long text goes here...</div>
I don't really understand why you would make this an HTML Helper. I would make it part of the ViewData dictionary in an action method of the controller. Something like this:
ViewData["Age"] = DateTime.Now.Year - birthday.Year;
Given that birthday is passed into an action method and is a DateTime object.
In another case I'm able to use template literal ES6 with backticks, so for yours could be set as:
<img v-bind:src="`${imgPreUrl()}img/logo.png`">
You need to wrap button click handler to match the pattern
public void klik(object sender, EventArgs e)
&
is bitwise.
&&
is logical.
&
evaluates both sides of the operation.
&&
evaluates the left side of the operation, if it's true
, it continues and evaluates the right side.
It is very easy:
On OSX, you need the xcode CLI tools. Just open a terminal and run:
xcode-select --install
One more solution for mysql 8.0.1 and mariadb 10.2.2 using recursive common table expressions:
with recursive dates as (
select '2010-01-20' as date
union all
select date + interval 1 day from dates where date < '2010-01-24'
)
select * from dates;
Simple example :
package test;
public class UpperClass {
public static class StaticInnerClass {}
public class InnerClass {}
public static void main(String[] args) {
// works
StaticInnerClass stat = new StaticInnerClass();
// doesn't compile
InnerClass inner = new InnerClass();
}
}
If non-static the class cannot be instantiated exept in an instance of the upper class (so not in the example where main is a static function)
The sys.maxint constant was removed, since there is no longer a limit to the value of integers. However, sys.maxsize can be used as an integer larger than any practical list or string index. It conforms to the implementation’s “natural” integer size and is typically the same as sys.maxint in previous releases on the same platform (assuming the same build options).
You can use @@trancount
in MSSQL
From the documentation:
Returns the number of BEGIN TRANSACTION statements that have occurred on the current connection.
Just return any kind of list. ArrayList will be fine, its not static.
ArrayList<yourClass> list = new ArrayList<yourClass>();
for (yourClass item : yourArray)
{
list.add(item);
}
Use continue statement instead of return to skip an iteration in JS loops.
The Dr. Memory (http://drmemory.org) tool comes with a system call tracing tool called drstrace that lists all system calls made by a target application along with their arguments: http://drmemory.org/strace_for_windows.html
For programmatically enforcing system call policies, you could use the same underlying engines as drstrace: the DynamoRIO tool platform (http://dynamorio.org) and the DrSyscall system call monitoring library (http://drmemory.org/docs/page_drsyscall.html). These use dynamic binary translation technology, which does incur some overhead (20%-30% in steady state, but much higher when running new code such as launching a big desktop app), which may or may not be suitable for your purposes.
What about the following snippet?
require 'json'
value = '{"val":"test","val1":"test1","val2":"test2"}'
puts JSON.parse(value) # => {"val"=>"test","val1"=>"test1","val2"=>"test2"}
Such is how I have it embedded and outputted to my HTML web page:
<div class="container">
<p class="text-center">Copyright ©
<script>
var CurrentYear = new Date().getFullYear()
document.write(CurrentYear)
</script>
</p>
</div>
Output to HTML page is as follows:
Copyright © 2018
Look for "poi-3.17.jar"!!!
Problem solved and errors disappeared.
It's all a matter of style. It's useful for debugging but otherwise it shouldn't be used in the final version of the program. It really doesn't matter on the memory issue because I'm sure that those guys who invented the system("pause") were anticipating that it'd be used often. In another perspective, computers get throttled on their memory for everything else we use on the computer anyways and it doesn't pose a direct threat like dynamic memory allocation, so I'd recommend it for debugging code, but nothing else.
locals
in Rails 4.2+In Rails 4.2 I had to remove the locals
part and just use size: 30
instead. Otherwise, it wouldn't pass the local variable correctly.
For example, use this:
<%= render @users, size: 30 %>
After your DataBind()
:
lstDepartment.SelectedIndex = 0; //first item
or
lstDepartment.SelectedValue = "Yourvalue"
or
//add error checking, just an example, FindByValue may return null
lstDepartment.Items.FindByValue("Yourvalue").Selected = true;
or
//add error checking, just an example, FindByText may return null
lstDepartment.Items.FindByText("Yourvalue").Selected = true;
There is a way to cleanup workspace in Jenkins. You can clean up the workspace before build or after build.
First, install Workspace Cleanup Plugin.
To clean up the workspace before build: Under Build Environment, check the box that says Delete workspace before build starts.
To clean up the workspace after the build: Under the heading Post-build Actions select Delete workspace when build is done from the Add Post-build Actions drop down menu.
Seems like you expected the query to return running totals, but it must have given you the same values for both partitions of AccountID
.
To obtain running totals with SUM() OVER ()
, you need to add an ORDER BY
sub-clause after PARTITION BY …
, like this:
SUM(Quantity) OVER (PARTITION BY AccountID ORDER BY ID)
But remember, not all database systems support ORDER BY
in the OVER
clause of a window aggregate function. (For instance, SQL Server didn't support it until the latest version, SQL Server 2012.)
The standard way is cin.get()
before your return statement.
int _tmain(int argc, _TCHAR* argv[])
{
cout << "Hello World";
cin.get();
return 0;
}
You shouldn't be using the BinaryFormatter
for this - that's for serializing .Net types to a binary file so they can be read back again as .Net types.
If it's stored in the database, hopefully, as a varbinary
- then all you need to do is get the byte array from that (that will depend on your data access technology - EF and Linq to Sql, for example, will create a mapping that makes it trivial to get a byte array) and then write it to the file as you do in your last line of code.
With any luck - I'm hoping that fileContent
here is the byte array? In which case you can just do
System.IO.File.WriteAllBytes("hello.pdf", fileContent);
To solve a similar problem, I'm using groupby
:
print(f"Distinct entries: {len(df.groupby(['col1', 'col2']))}")
Whether that's appropriate will depend on what you want to do with the result, though (in my case, I just wanted the equivalent of COUNT DISTINCT
as shown).
Use this
public static boolean isNum(String strNum) {
boolean ret = true;
try {
Double.parseDouble(strNum);
}catch (NumberFormatException e) {
ret = false;
}
return ret;
}
These solutions often have issues with the header columns aligning with the body columns, and may not work properly when resizing. I know you didn't want to use an additional library, but if you happen to be using jQuery, this one is really small. It supports fixed header, footer, column spanning (colspan), horizontal scrolling, resizing, and an optional number of rows to display before scrolling starts.
jQuery.scrollTableBody (GitHub)
As long as you have a table with proper <thead>
, <tbody>
, and (optional) <tfoot>
, all you need to do is this:
$('table').scrollTableBody();
Nowadays, it's better to use queues than threads (for those who don't use Laravel there are tons of other implementations out there like this).
The basic idea is, your original PHP script puts tasks or jobs into a queue. Then you have queue job workers running elsewhere, taking jobs out of the queue and starts processing them independently of the original PHP.
The advantages are:
One way to create a quick test query in Windows via an ODBC connection is using the DQY format.
To achieve this, create a DQY file (e.g. test.dqy) containing the magic first two lines (XLODBC and 1) as below, followed by your ODBC connection string on the third line and your query on the fourth line (all on one line), e.g.:
XLODBC
1
Driver={Microsoft ODBC for Oracle};server=DB;uid=scott;pwd=tiger;
SELECT COUNT(1) n FROM emp
Then, if you open the file by double-clicking it, it will open in Excel and populate the worksheet with the results of the query.
For me, it didn't work without enctype: 'multipart/form-data'
field in the Ajax request. I hope it helps someone who is stuck in a similar problem.
Even though the enctype
was already set in the form attribute, for some reason, the Ajax request didn't automatically identify the enctype
without explicit declaration (jQuery 3.3.1).
// Tested, this works for me (jQuery 3.3.1)
fileUploadForm.submit(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: $(this).attr('action'),
enctype: 'multipart/form-data',
data: new FormData(this),
processData: false,
contentType: false,
success: function (data) {
console.log('Thank God it worked!');
}
}
);
});
// enctype field was set in the form but Ajax request didn't set it by default.
<form action="process/file-upload" enctype="multipart/form-data" method="post" >
<input type="file" name="input-file" accept="text/plain" required>
...
</form>
As others mentioned above, please also pay special attention to the contentType
and processData
fields.
UPDATE urls
SET url = REPLACE(url, 'domain1.com/images/', 'domain2.com/otherfolder/')
In AngularJS, we update our models, and our views/templates update the DOM "automatically" (via built-in or custom directives).
$apply and $watch, both being Scope methods, are not related to the DOM.
The Concepts page (section "Runtime") has a pretty good explanation of the $digest loop, $apply, the $evalAsync queue and the $watch list. Here's the picture that accompanies the text:
Whatever code has access to a scope – normally controllers and directives (their link functions and/or their controllers) – can set up a "watchExpression" that AngularJS will evaluate against that scope. This evaluation happens whenever AngularJS enters its $digest loop (in particular, the "$watch list" loop). You can watch individual scope properties, you can define a function to watch two properties together, you can watch the length of an array, etc.
When things happen "inside AngularJS" – e.g., you type into a textbox that has AngularJS two-way databinding enabled (i.e., uses ng-model), an $http callback fires, etc. – $apply has already been called, so we're inside the "AngularJS" rectangle in the figure above. All watchExpressions will be evaluated (possibly more than once – until no further changes are detected).
When things happen "outside AngularJS" – e.g., you used bind() in a directive and then that event fires, resulting in your callback being called, or some jQuery registered callback fires – we're still in the "Native" rectangle. If the callback code modifies anything that any $watch is watching, call $apply to get into the AngularJS rectangle, causing the $digest loop to run, and hence AngularJS will notice the change and do its magic.
val() returns the value of the <select>
element, i.e. the value
attribute of the selected <option>
element.
Since you actually want the inner text of the selected <option>
element, you should match that element and use text() instead:
var nationality = $("#dancerCountry option:selected").text();
This solution uses one function
to split milliseconds into a parts object
, and another function
to format the parts object
.
I created 2 format functions, one as you requested, and another that prints a friendly string and considering singular/plural, and includes an option to show milliseconds.
function parseDuration(duration) {_x000D_
let remain = duration_x000D_
_x000D_
let days = Math.floor(remain / (1000 * 60 * 60 * 24))_x000D_
remain = remain % (1000 * 60 * 60 * 24)_x000D_
_x000D_
let hours = Math.floor(remain / (1000 * 60 * 60))_x000D_
remain = remain % (1000 * 60 * 60)_x000D_
_x000D_
let minutes = Math.floor(remain / (1000 * 60))_x000D_
remain = remain % (1000 * 60)_x000D_
_x000D_
let seconds = Math.floor(remain / (1000))_x000D_
remain = remain % (1000)_x000D_
_x000D_
let milliseconds = remain_x000D_
_x000D_
return {_x000D_
days,_x000D_
hours,_x000D_
minutes,_x000D_
seconds,_x000D_
milliseconds_x000D_
};_x000D_
}_x000D_
_x000D_
function formatTime(o, useMilli = false) {_x000D_
let parts = []_x000D_
if (o.days) {_x000D_
let ret = o.days + ' day'_x000D_
if (o.days !== 1) {_x000D_
ret += 's'_x000D_
}_x000D_
parts.push(ret)_x000D_
}_x000D_
if (o.hours) {_x000D_
let ret = o.hours + ' hour'_x000D_
if (o.hours !== 1) {_x000D_
ret += 's'_x000D_
}_x000D_
parts.push(ret)_x000D_
}_x000D_
if (o.minutes) {_x000D_
let ret = o.minutes + ' minute'_x000D_
if (o.minutes !== 1) {_x000D_
ret += 's'_x000D_
}_x000D_
parts.push(ret)_x000D_
_x000D_
}_x000D_
if (o.seconds) {_x000D_
let ret = o.seconds + ' second'_x000D_
if (o.seconds !== 1) {_x000D_
ret += 's'_x000D_
}_x000D_
parts.push(ret)_x000D_
}_x000D_
if (useMilli && o.milliseconds) {_x000D_
let ret = o.milliseconds + ' millisecond'_x000D_
if (o.milliseconds !== 1) {_x000D_
ret += 's'_x000D_
}_x000D_
parts.push(ret)_x000D_
}_x000D_
if (parts.length === 0) {_x000D_
return 'instantly'_x000D_
} else {_x000D_
return parts.join(' ')_x000D_
}_x000D_
}_x000D_
_x000D_
function formatTimeHMS(o) {_x000D_
let hours = o.hours.toString()_x000D_
if (hours.length === 1) hours = '0' + hours_x000D_
_x000D_
let minutes = o.minutes.toString()_x000D_
if (minutes.length === 1) minutes = '0' + minutes_x000D_
_x000D_
let seconds = o.seconds.toString()_x000D_
if (seconds.length === 1) seconds = '0' + seconds_x000D_
_x000D_
return hours + ":" + minutes + ":" + seconds_x000D_
}_x000D_
_x000D_
function formatDurationHMS(duration) {_x000D_
let time = parseDuration(duration)_x000D_
return formatTimeHMS(time)_x000D_
}_x000D_
_x000D_
function formatDuration(duration, useMilli = false) {_x000D_
let time = parseDuration(duration)_x000D_
return formatTime(time, useMilli)_x000D_
}_x000D_
_x000D_
_x000D_
console.log(formatDurationHMS(57742343234))_x000D_
_x000D_
console.log(formatDuration(57742343234))_x000D_
console.log(formatDuration(5423401000))_x000D_
console.log(formatDuration(500))_x000D_
console.log(formatDuration(500, true))_x000D_
console.log(formatDuration(1000 * 30))_x000D_
console.log(formatDuration(1000 * 60 * 30))_x000D_
console.log(formatDuration(1000 * 60 * 60 * 12))_x000D_
console.log(formatDuration(1000 * 60 * 60 * 1))
_x000D_
IOError: [Errno 13] Permission denied: 'juliodantas2015.json'
tells you everything you need to know: though you successfully made your python program executable with your chmod
, python can't open that juliodantas2015.json'
file for writing. You probably don't have the rights to create new files in the folder you're currently in.
This is slightly tricky as you have to know when the iframe page has loaded, which is difficuly when you're not in control of its content. Its possible to add an onload handler to the iframe, but I've tried this in the past and it has vastly different behaviour across browsers (not guess who's the most annoying...). You'd probably have to add a function to the iframe page that performs the resize and inject some script into the content that either listens to load events or resize events, which then calls the previous function. I'm thinking add a function to the page since you want to make sure its secure, but I have no idea how easy it will be to do.
It depends what is the character and what encoding it is in:
An ASCII character in 8-bit ASCII encoding is 8 bits (1 byte), though it can fit in 7 bits.
An ISO-8895-1 character in ISO-8859-1 encoding is 8 bits (1 byte).
A Unicode character in UTF-8 encoding is between 8 bits (1 byte) and 32 bits (4 bytes).
A Unicode character in UTF-16 encoding is between 16 (2 bytes) and 32 bits (4 bytes), though most of the common characters take 16 bits. This is the encoding used by Windows internally.
A Unicode character in UTF-32 encoding is always 32 bits (4 bytes).
An ASCII character in UTF-8 is 8 bits (1 byte), and in UTF-16 - 16 bits.
The additional (non-ASCII) characters in ISO-8895-1 (0xA0-0xFF) would take 16 bits in UTF-8 and UTF-16.
That would mean that there are between 0.03125 and 0.125 characters in a bit.
If you want a "editable grid" i.e. a table like structure that allows you to make any of the rows a form, use CSS that mimics the TABLE tag's layout: display:table
, display:table-row
, and display:table-cell
.
There is no need to wrap your whole table in a form and no need to create a separate form and table for each apparent row of your table.
Try this instead:
<style>
DIV.table
{
display:table;
}
FORM.tr, DIV.tr
{
display:table-row;
}
SPAN.td
{
display:table-cell;
}
</style>
...
<div class="table">
<form class="tr" method="post" action="blah.html">
<span class="td"><input type="text"/></span>
<span class="td"><input type="text"/></span>
</form>
<div class="tr">
<span class="td">(cell data)</span>
<span class="td">(cell data)</span>
</div>
...
</div>
The problem with wrapping the whole TABLE in a FORM is that any and all form elements will be sent on submit (maybe that is desired but probably not). This method allows you to define a form for each "row" and send only that row of data on submit.
The problem with wrapping a FORM tag around a TR tag (or TR around a FORM) is that it's invalid HTML. The FORM will still allow submit as usual but at this point the DOM is broken. Note: Try getting the child elements of your FORM or TR with JavaScript, it can lead to unexpected results.
Note that IE7 doesn't support these CSS table styles and IE8 will need a doctype declaration to get it into "standards" mode: (try this one or something equivalent)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Any other browser that supports display:table, display:table-row and display:table-cell should display your css data table the same as it would if you were using the TABLE, TR and TD tags. Most of them do.
Note that you can also mimic THEAD, TBODY, TFOOT by wrapping your row groups in another DIV with display: table-header-group
, table-row-group
and table-footer-group
respectively.
NOTE: The only thing you cannot do with this method is colspan.
Check out this illustration: http://jsfiddle.net/ZRQPP/
I'm not 100% sure if this works in all cases (needs at least Java 1.5):
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
public class Main
{
public class A
{
}
public class B extends A
{
}
public Map<A, B> map = new HashMap<Main.A, Main.B>();
public static void main(String[] args)
{
try
{
Field field = Main.class.getField("map");
System.out.println("Field " + field.getName() + " is of type " + field.getType().getSimpleName());
Type genericType = field.getGenericType();
if(genericType instanceof ParameterizedType)
{
ParameterizedType type = (ParameterizedType) genericType;
Type[] typeArguments = type.getActualTypeArguments();
for(Type typeArgument : typeArguments)
{
Class<?> classType = ((Class<?>)typeArgument);
System.out.println("Field " + field.getName() + " has a parameterized type of " + classType.getSimpleName());
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
This will output:
Field map is of type Map
Field map has a parameterized type of A
Field map has a parameterized type of B
There is no such thing as :touch
in the W3C specifications, http://www.w3.org/TR/CSS2/selector.html#pseudo-class-selectors
:active
should work, I would think.
Order on the :active
/:hover
pseudo class is important for it to function correctly.
Here is a quote from that above link
Interactive user agents sometimes change the rendering in response to user actions. CSS provides three pseudo-classes for common cases:
- The :hover pseudo-class applies while the user designates an element (with some pointing device), but does not activate it. For example, a visual user agent could apply this pseudo-class when the cursor (mouse pointer) hovers over a box generated by the element. User agents not supporting interactive media do not have to support this pseudo-class. Some conforming user agents supporting interactive media may not be able to support this pseudo-class (e.g., a pen device).
- The :active pseudo-class applies while an element is being activated by the user. For example, between the times the user presses the mouse button and releases it.
- The :focus pseudo-class applies while an element has the focus (accepts keyboard events or other forms of text input).
Check next lines in you app build.gradle file.
android {
compileSdkVersion 25 <--- Set exist in local machine sdk version.
buildToolsVersion '25.0.3' <--- Set exist build tools version.
}
Thats because DataGridView looks for properties of containing objects. For string there is just one property - length. So, you need a wrapper for a string like this
public class StringValue
{
public StringValue(string s)
{
_value = s;
}
public string Value { get { return _value; } set { _value = value; } }
string _value;
}
Then bind List<StringValue>
object to your grid. It works
Herman's solution works, but it can be simplified because Sqlite allows to store any value type on any field.
Here is a simpler version that uses one Value
field declared as TEXT
to store any value:
CREATE TEMP TABLE IF NOT EXISTS Variables (Name TEXT PRIMARY KEY, Value TEXT);
INSERT OR REPLACE INTO Variables VALUES ('VarStr', 'Val1');
INSERT OR REPLACE INTO Variables VALUES ('VarInt', 123);
INSERT OR REPLACE INTO Variables VALUES ('VarBlob', x'12345678');
SELECT Value
FROM Variables
WHERE Name = 'VarStr'
UNION ALL
SELECT Value
FROM Variables
WHERE Name = 'VarInt'
UNION ALL
SELECT Value
FROM Variables
WHERE Name = 'VarBlob';
PHP 7.4+; with the null coalescing assignment operator
$var ??= '';
PHP 7.0+; with the null coalescing operator
$var = $var ?? '';
PHP 5.3+; with the ternary operator shorthand
isset($var) ?: $var = '';
Or for all/older versions with isset:
$var = isset($var) ? $var : '';
or
!isset($var) && $var = '';