The following is function would work for async
wrap or promise then
chains
const readFileAsync = async (path) => fs.readFileSync(path, 'utf8');
Use 10.0.2.2 for default AVD and 10.0.3.2 for Genymotion
Besides CMAKE_GENERATOR_PLATFORM
variable, there is also the -A
switch
cmake -G "Visual Studio 16 2019" -A Win32
cmake -G "Visual Studio 16 2019" -A x64
https://cmake.org/cmake/help/v3.16/generator/Visual%20Studio%2016%202019.html#platform-selection
-A <platform-name> = Specify platform name if supported by
generator.
The question:
Does one unknown equal another unknown?
(NULL = NULL)
That question is something no one can answer so it defaults to true or false depending on your ansi_nulls setting.
However the question:
Is this unknown variable unknown?
This question is quite different and can be answered with true.
nullVariable = null is comparing the values
nullVariable is null is comparing the state of the variable
If you are using JDK 7 you can use the following code..
import java.nio.file.Files;
import java.io.File;
File fi = new File("myfile.jpg");
byte[] fileContent = Files.readAllBytes(fi.toPath())
If you don't want to map the JSON by yourself, you can do it as follows:
RestTemplate restTemplate = new RestTemplate();
restTemplate.setMessageConverters(Arrays.asList(new MappingJackson2HttpMessageConverter()));
ResponseEntity<String> result = restTemplate.postForEntity(uri, yourObject, String.class);
The most important thing is to avoid creating a problem
, so I believe that you should use a direct relation to avoid having a cycle.
As @markmywords said, #include "fritzl.h".
Finally I have to say recheck your data structure
. Maybe something is going wrong over there (maybe a bidirectional linked list solves your problem).
Use the "has attribute" selector:
$('p[MyTag]')
Or to select one where that attribute has a specific value:
$('p[MyTag="Sara"]')
There are other selectors for "attribute value starts with", "attribute value contains", etc.
First of all, install the prerequisite libraries:
sudo apt-get update
sudo apt-get install git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev libcurl4-openssl-dev python-software-properties libffi-dev
Then install rbenv, which is used to install Ruby:
cd
git clone https://github.com/rbenv/rbenv.git ~/.rbenv
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(rbenv init -)"' >> ~/.bashrc
exec $SHELL
git clone https://github.com/rbenv/ruby-build.git ~/.rbenv/plugins/ruby-build
echo 'export PATH="$HOME/.rbenv/plugins/ruby-build/bin:$PATH"' >> ~/.bashrc
exec $SHELL
rbenv install 2.3.1
rbenv global 2.3.1
ruby -v
Then (optional) tell Rubygems to not install local documentation:
echo "gem: --no-ri --no-rdoc" > ~/.gemrc
Credits: https://gorails.com/setup/ubuntu/14.10
Warning!!!
There are issues with Gnome-Shell
. See comment below.
I have design google map infowindow with image & some content as per below.
map_script (Just for infowindow html reference)
for (i = 0; i < locations.length; i++) {
var latlng = new google.maps.LatLng(locations[i][1], locations[i][2]);
marker = new google.maps.Marker({
position: latlng,
map: map,
icon: "<?php echo plugins_url( 'assets/img/map-pin.png', ELEMENTOR_ES__FILE__ ); ?>"
});
var property_img = locations[i][6],
title = locations[i][0],
price = locations[i][3],
bedrooms = locations[i][4],
type = locations[i][5],
listed_on = locations[i][7],
prop_url = locations[i][8];
content = "<div class='map_info_wrapper'><a href="+prop_url+"><div class='img_wrapper'><img src="+property_img+"></div>"+
"<div class='property_content_wrap'>"+
"<div class='property_title'>"+
"<span>"+title+"</span>"+
"</div>"+
"<div class='property_price'>"+
"<span>"+price+"</span>"+
"</div>"+
"<div class='property_bed_type'>"+
"<span>"+bedrooms+"</span>"+
"<ul><li>"+type+"</li></ul>"+
"</div>"+
"<div class='property_listed_date'>"+
"<span>Listed on "+listed_on+"</span>"+
"</div>"+
"</div></a></div>";
google.maps.event.addListener(marker, 'click', (function(marker, content, i) {
return function() {
infowindow.setContent(content);
infowindow.open(map, marker);
}
})(marker, content, i));
}
Most important thing is CSS
#propertymap .gm-style-iw{
box-shadow:none;
color:#515151;
font-family: "Georgia", "Open Sans", Sans-serif;
text-align: center;
width: 100% !important;
border-radius: 0;
left: 0 !important;
top: 20px !important;
}
#propertymap .gm-style > div > div > div > div > div > div > div {
background: none!important;
}
.gm-style > div > div > div > div > div > div > div:nth-child(2) {
box-shadow: none!important;
}
#propertymap .gm-style-iw > div > div{
background: #FFF!important;
}
#propertymap .gm-style-iw a{
text-decoration: none;
}
#propertymap .gm-style-iw > div{
width: 245px !important
}
#propertymap .gm-style-iw .img_wrapper {
height: 150px;
overflow: hidden;
width: 100%;
text-align: center;
margin: 0px auto;
}
#propertymap .gm-style-iw .img_wrapper > img {
width: 100%;
height:auto;
}
#propertymap .gm-style-iw .property_content_wrap {
padding: 0px 20px;
}
#propertymap .gm-style-iw .property_title{
min-height: auto;
}
Read this thread R - boolean operators && and ||.
Basically, the &
is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. &&
is not, returning a single logical.
Currently (July 2015), HTML escape sequences (• •
) do not work in browser version of Play Store, they're displayed as text. Though, Play Store app handles them as expected.
So, if you're after the unicode bullet point in your app/update description [that's what's got you here, most likely], just copy-paste the bullet character
PS You can also use unicode input combo to get the character
Linux: CtrlShiftu 2022
Enter or Space
Mac: Hold ? 2022
release ?
Windows: Hold Alt 2022
release Alt
Mac and Windows require some setup, read on Wikipedia
PPS If you're feeling creative, here's a good link with more copypastable symbols, but don't go too crazy, nobody likes clutter in what they read.
I got the same error when importing a .csv file using phpMyAdmin.
Solution to my problem was that my computer saved the .csv file with ; (semi-colon) as delimiter instead of , (commas).
In the Format-Specific Options you can however chose "columns separated:" and select ; instead of , (comma).
In order to see what your computer stores the file in, open the .csv file in an text editor.
To reference an element by id, you need to use the #
qualifier.
Try:
alert($("#link1").text());
To replace it, you could use:
$("#link1").text('New text');
The .html()
function would work in this case too.
From What's this "serialization" thing all about?:
It lets you take an object or group of objects, put them on a disk or send them through a wire or wireless transport mechanism, then later, perhaps on another computer, reverse the process: resurrect the original object(s). The basic mechanisms are to flatten object(s) into a one-dimensional stream of bits, and to turn that stream of bits back into the original object(s).
Like the Transporter on Star Trek, it's all about taking something complicated and turning it into a flat sequence of 1s and 0s, then taking that sequence of 1s and 0s (possibly at another place, possibly at another time) and reconstructing the original complicated "something."
So, implement the Serializable
interface when you need to store a copy of the object, send them to another process which runs on the same system or over the network.
Because you want to store or send an object.
It makes storing and sending objects easy. It has nothing to do with security.
Using Math.Round()
:
int percentComplete = (int)Math.Round((double)(100 * complete) / total);
or manually rounding:
int percentComplete = (int)(0.5f + ((100f * complete) / total));
For java 11+ you can use Objects.nonNull(Object obj)
if(nonNull(foo)){
//
}
:%s/$/\*/g
should work and so should :%s/$/*/g
.
Dick.Guertin's answer [1] suggested that one could escape the spaces in a filename is a valuable alternative to other solutions suggested here (such as using a null character as a separator rather than whitespace). But it could be simpler - you don't really need a unique character. You can just have sed add the escaped spaces directly:
ls | grep ' ' | sed 's| |\\ |g' | xargs ...
Furthermore, the grep is only necessary if you only want files with spaces in the names. More generically (e.g., when processing a batch of files some of which have spaces, some not), just skip the grep:
ls | sed 's| |\\ |g' | xargs ...
Then, of course, the filename may have other whitespace than blanks (e.g., a tab):
ls | sed -r 's|[[:blank:]]|\\\1|g' | xargs ...
That assumes you have a sed that supports -r (extended regex) such as GNU sed or recent versions of bsd sed (e.g., FreeBSD which originally spelled the option "-E" before FreeBSD 8 and supports both -r & -E for compatibility through FreeBSD 11 at least). Otherwise you can use a basic regex character class bracket expression and manually enter the space and tab characters in the []
delimiters.
[1] This is perhaps more appropriate as a comment or an edit to that answer, but at the moment I do not have enough reputation to comment and can only suggest edits. Since the latter forms above (without the grep) alters the behavior of Dick.Guertin's original answer, a direct edit is perhaps not appropriate anyway.
While installing lombok in ubuntu machine with java -jar lombok.jar
you may find following error:
java.awt.AWTError: Assistive Technology not found: org.GNOME.Accessibility.AtkWrapper
You can overcome this by simply doing following steps:
Step 1: This can be done by editing the accessibility.properties file of JDK:
sudo gedit /etc/java-8-openjdk/accessibility.properties
Step 2: Comment (#) the following line:
assistive_technologies=org.GNOME.Accessibility.AtkWrapper
If you are using NUnit one simple but effective demo is to run NUnit's own test suite(s) in front of them. Seeing a real test suite giving a codebase a workout is worth a thousand words...
The fastest way that I came up is using EnumerateFiles with SearchOption.AllDirectories. This method also allows updating the UI while going through the files and counting the size. Long path names don't cause any problems since FileInfo or DirectoryInfo are not tried to be created for the long path name. While enumerating files even though the filename is long the FileInfo returned by the EnumerateFiles don't cause problems as long as the starting directory name is not too long. There is still a problem with UnauthorizedAccess.
private void DirectoryCountEnumTest(string sourceDirName)
{
// Get the subdirectories for the specified directory.
long dataSize = 0;
long fileCount = 0;
string prevText = richTextBox1.Text;
if (Directory.Exists(sourceDirName))
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
foreach (FileInfo file in dir.EnumerateFiles("*", SearchOption.AllDirectories))
{
fileCount++;
try
{
dataSize += file.Length;
richTextBox1.Text = prevText + ("\nCounting size: " + dataSize.ToString());
}
catch (Exception e)
{
richTextBox1.AppendText("\n" + e.Message);
}
}
richTextBox1.AppendText("\n files:" + fileCount.ToString());
}
}
I usually just use RAND()
http://php.net/manual/en/function.rand.php
e.g.
rand ( 10000 , 99999 );
for your 5 digit random number
I believe the previous answer is the correct answer to this problem but I was getting this error when I tried installing npm package (see below) :
The fix for me was : npm init --yes
import sys, os
try:
raise NotImplementedError("No error")
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
public static class StringEscape
{
static char[] toEscape = "\0\x1\x2\x3\x4\x5\x6\a\b\t\n\v\f\r\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\"\\".ToCharArray();
static string[] literals = @"\0,\x0001,\x0002,\x0003,\x0004,\x0005,\x0006,\a,\b,\t,\n,\v,\f,\r,\x000e,\x000f,\x0010,\x0011,\x0012,\x0013,\x0014,\x0015,\x0016,\x0017,\x0018,\x0019,\x001a,\x001b,\x001c,\x001d,\x001e,\x001f".Split(new char[] { ',' });
public static string Escape(this string input)
{
int i = input.IndexOfAny(toEscape);
if (i < 0) return input;
var sb = new System.Text.StringBuilder(input.Length + 5);
int j = 0;
do
{
sb.Append(input, j, i - j);
var c = input[i];
if (c < 0x20) sb.Append(literals[c]); else sb.Append(@"\").Append(c);
} while ((i = input.IndexOfAny(toEscape, j = ++i)) > 0);
return sb.Append(input, j, input.Length - j).ToString();
}
}
Here's a UIButton
subclass that supports the highlighted state animation without using images. It also updates the border color when the view's tint mode changes.
class BorderedButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
layer.borderColor = tintColor.CGColor
layer.borderWidth = 1
layer.cornerRadius = 5
contentEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
}
required init?(coder aDecoder: NSCoder) {
fatalError("NSCoding not supported")
}
override func tintColorDidChange() {
super.tintColorDidChange()
layer.borderColor = tintColor.CGColor
}
override var highlighted: Bool {
didSet {
let fadedColor = tintColor.colorWithAlphaComponent(0.2).CGColor
if highlighted {
layer.borderColor = fadedColor
} else {
layer.borderColor = tintColor.CGColor
let animation = CABasicAnimation(keyPath: "borderColor")
animation.fromValue = fadedColor
animation.toValue = tintColor.CGColor
animation.duration = 0.4
layer.addAnimation(animation, forKey: "")
}
}
}
}
Usage:
let button = BorderedButton(style: .System) //style .System is important
Appearance:
To update this for Python-3 you can do this
"{} {}".format(True, False)
However if you want to actually format the string (e.g. add white space), you encounter Python casting the boolean into the underlying C value (i.e. an int), e.g.
>>> "{:<8} {}".format(True, False)
'1 False'
To get around this you can cast True
as a string, e.g.
>>> "{:<8} {}".format(str(True), False)
'True False'
This work for me it is showing the objects and type of event which has occurred.
var foo = $._data( $('body').get(0), 'events' );
$.each( foo, function(i,o) {
console.log(i); // guide of the event
console.log(o); // the function definition of the event handler
});
You just want to get the name of the function here is a simple code for that. let say you have these functions defined
def function1():
print "function1"
def function2():
print "function2"
def function3():
print "function3"
print function1.__name__
the output will be function1
Now let say you have these functions in a list
a = [function1 , function2 , funciton3]
to get the name of the functions
for i in a:
print i.__name__
the output will be
function1
function2
function3
If the file share is not open to everybody you will need to serve it up in the background from the file system via the web server.
You can use something like this "ASP.Net Serve File For Download" example (archived copy of 2).
Check out eval:
x = 1
print eval('x+1')
->2
for D in `find . -type d`
do
//Do whatever you need with D
done
In the latest version of Android studio, "\n" is going to be printed like it was meant to be there unless the whole string it's in apostrophes
For Example:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="title">"Hello\nWorld!"</string>
</resources>
If you get the context via the parameter list of Configure in Startup.cs, You can instead do this:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, LoggerFactory loggerFactory,
ApplicationDbContext context)
{
context.Database.Migrate();
...
This data is JSON! You can deserialize it using the built-in json
module if you're on Python 2.6+, otherwise you can use the excellent third-party simplejson
module.
import json # or `import simplejson as json` if on Python < 2.6
json_string = u'{ "id":"123456789", ... }'
obj = json.loads(json_string) # obj now contains a dict of the data
De-structuring Assignment in ES6 would help here.For Ex:
let [arg1, arg2] = new Promise((resolve, reject) => {
resolve([argument1, argument2]);
});
I think the best answer I've come up with is here: https://codepen.io/sentrathis96/pen/yJPZGx
I can't take credit for this, I forked this from another codepen user to fix the google maps dependency to actually load
Make note of the call to:
InfoWindow() // constructor
Use the SingleOrDefault() instead of FirstOrDefault().
Writing this middleware might help !
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
for details visit http://enable-cors.org/server_expressjs.html
If you have user specific credentials ( i.e each developer might have different username/password ) then I would recommend using the gradle-properties-plugin.
gradle.properties
gradle-local.properties
( this should be git ignored ).This is better than overriding using $USER_HOME/.gradle/gradle.properties
because different projects might have same property names.
As it was mentioned by Davos you can use the IDLEX
It happens that I'm using Linux version and from all extensions I needed only LineNumbers. So I've downloaded IDLEX archive, took LineNumbers.py from it, copied it to Python's lib folder ( in my case its /usr/lib/python3.5/idlelib ) and added following lines to configuration file in my home folder which is ~/.idlerc/config-extensions.cfg:
[LineNumbers]
enable = 1
enable_shell = 0
visible = True
[LineNumbers_cfgBindings]
linenumbers-show =
To add to svick's answer, the -m
option simply adds a message to your stash, and is entirely optional. Thus, the command
git stash push [paths you wish to stash]
is perfectly valid. So for instance, if I want to only stash changes in the src/
directory, I can just run
git stash push src/
This works in all browsers. jsfiddle here http://jsfiddle.net/zvhysct7/1/
<iframe src="http://buythecity.com" scrolling="no" style=" width: 550px; height: 500px; overflow: hidden;" ></iframe>
Heap dumps anytime you wish to see what is being held in memory Out-of-memory errors Heap dumps - picture of in memory objects - used for memory analysis Java cores - also known as thread dumps or java dumps, used for viewing the thread activity inside the JVM at a given time. IBM javacores should a lot of additional information besides just the threads and stacks -- used to determine hangs, deadlocks, and reasons for performance degredation System cores
After many years of success with the answers above, I have found this not to work again - but I did find a working solution for subplots at
https://jdhao.github.io/2017/06/03/change-aspect-ratio-in-mpl
With full credit of course to the author above (who can perhaps rather post here), the relevant lines are:
ratio = 1.0
xleft, xright = ax.get_xlim()
ybottom, ytop = ax.get_ylim()
ax.set_aspect(abs((xright-xleft)/(ybottom-ytop))*ratio)
The link also has a crystal clear explanation of the different coordinate systems used by matplotlib.
Thanks for all great answers received - especially @Yann's which will remain the winner.
There is much simpler way:
using System;
using System.Collections.Generic;
....
var caseInsensitiveDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
You can raise a notice in Postgres
as follows:
raise notice 'Value: %', deletedContactId;
Read here
The simple fix to your example is :
handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
tv.append("Hello World");
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(r, 1000);
Or we can use normal thread for example (with original Runner) :
Thread thread = new Thread() {
@Override
public void run() {
try {
while(true) {
sleep(1000);
handler.post(this);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
You may consider your runnable object just as a command that can be sent to the message queue for execution, and handler as just a helper object used to send that command.
More details are here http://developer.android.com/reference/android/os/Handler.html
Foreword: Well, that escalated quickly. But decided to pull it through. May this answer be helpful to you and other readers.
While JSLint and JSHint are good tools to use, over the years I've come to appreciate what my friend @ugly_syntax calls:
smaller design space.
This is a general principle, much like a "zen monk", limiting the choices one has to make, one can be more productive and creative.
Therefore my current favourite zero-config JS code style:
UPDATE:
Flow has improved a lot. With it, you can add types to your JS with will help you prevent a lot of bugs. But it can also stay out of your way, for instance when interfacing untyped JS. Give it a try!
Add standard
as a dependency to you project
npm install --save standard
Then in package.json
, add the following test script:
"scripts": {
"test": "node_modules/.bin/standard && echo put further tests here"
},
For snazzier output while developing, npm install --global snazzy
and run it instead of npm test
.
My friend when mentioning design space referred to Elm and I encourage you to give that language a try.
Why? JS is in fact inspired by LISP, which is a special class of languages, which happens to be untyped. Language such as Elm or Purescript are typed functional programming languages.
Type restrict your freedom in order for the compiler to be able to check and guide you when you end up violation the language or your own program's rules; regardless of the size (LOC) of your program.
We recently had a junior colleague implement a reactive interface twice: once in Elm, once in React; have a look to get some idea of what I'm talking about.
(ps. note that the React code is not idiomatic and could be improved)
the reality is that JS is untyped. Who am I to suggest typed programming to you?
See, with JS we are in a different domain: freed from types, we can easily express things that are hard or impossible to give a proper type (which can certainly be an advantage).
But without types there is little to keep our programs in check, so we are forced to introduce tests and (to a lesser extend) code styles.
I recommend you look at LISP (e.g. ClojureScript) for inspiration and invest in testing your codes. Read The way of the substack to get an idea.
Peace.
The official API is:
This was introduced in 2.0 where larger memory devices appeared. You can assume that devices running prior versions of the OS are using the original memory class (16).
In my case after spending many days on this issues a gentleman help on this issue below is the solution and it worked for me. Issue: While trying to connect SqlServer DB with Service account authentication using spring boot it throws below exception.
com.microsoft.sqlserver.jdbc.SQLServerException: This driver is not configured for integrated authentication. ClientConnectionId:ab942951-31f6-44bf-90aa-7ac4cec2e206 at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:2392) ~[mssql-jdbc-6.1.0.jre8.jar!/:na] Caused by: java.lang.UnsatisfiedLinkError: sqljdbc_auth (Not found in java.library.path) at java.lang.ClassLoader.loadLibraryWithPath(ClassLoader.java:1462) ~[na:2.9 (04-02-2020)] Solution: Use JTDS driver with the following steps
Use JTDS driver insteadof sqlserver driver.
datasource.dedicatedpicup.url=jdbc:jtds:sqlserver://YourSqlServer:PortNo/DatabaseName;instance=InstanceName;domain=DomainName
datasource.dedicatedpicup.jdbcUrl=${datasource.dedicatedpicup.url}
datasource.dedicatedpicup.username=$da-XYZ
datasource.dedicatedpicup.password=ENC(XYZ)
datasource.dedicatedpicup.driver-class-name=net.sourceforge.jtds.jdbc.Driver
Remove Hikari in configuration properties.
#datasource.dedicatedpicup.hikari.connection-timeout=60000 #datasource.dedicatedpicup.hikari.maximum-pool-size=5
Add sqljdbc4 dependency.
com.microsoft.sqlserver sqljdbc4 4.0Add Tomcatjdbc dependency.
org.apache.tomcat tomcat-jdbcExclude HikariCP from spring-boot-starter-jdbc dependency.
org.springframework.boot spring-boot-starter-jdbc com.zaxxer HikariCPPush annotated tags, keep lightweight local
man git-tag
says:
Annotated tags are meant for release while lightweight tags are meant for private or temporary object labels.
And certain behaviors do differentiate between them in ways that this recommendation is useful e.g.:
annotated tags can contain a message, creator, and date different than the commit they point to. So you could use them to describe a release without making a release commit.
Lightweight tags don't have that extra information, and don't need it, since you are only going to use it yourself to develop.
git describe
without command line options only sees annotated tagsInternals differences
both lightweight and annotated tags are a file under .git/refs/tags
that contains a SHA-1
for lightweight tags, the SHA-1 points directly to a commit:
git tag light
cat .git/refs/tags/light
prints the same as the HEAD's SHA-1.
So no wonder they cannot contain any other metadata.
annotated tags point to a tag object in the object database.
git tag -as -m msg annot
cat .git/refs/tags/annot
contains the SHA of the annotated tag object:
c1d7720e99f9dd1d1c8aee625fd6ce09b3a81fef
and then we can get its content with:
git cat-file -p c1d7720e99f9dd1d1c8aee625fd6ce09b3a81fef
sample output:
object 4284c41353e51a07e4ed4192ad2e9eaada9c059f
type commit
tag annot
tagger Ciro Santilli <[email protected]> 1411478848 +0200
msg
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.11 (GNU/Linux)
<YOUR PGP SIGNATURE>
-----END PGP SIGNAT
And this is how it contains extra metadata. As we can see from the output, the metadata fields are:
A more detailed analysis of the format is present at: What is the format of a git tag object and how to calculate its SHA?
Bonuses
Determine if a tag is annotated:
git cat-file -t tag
Outputs
commit
for lightweight, since there is no tag object, it points directly to the committag
for annotated, since there is a tag object in that caseList only lightweight tags: How can I list all lightweight tags?
First I needed to remote into my server with ssh. If someone has a non ssh way of doing this please post.
I found my bare repositories at
cd /var/opt/gitlab/git-data/repositories/group-name/project-name.git
used
git branch
to see the wrong active branch
git symbolic-ref HEAD refs/heads/master
to change the master to to be the branch called master then use the web interface and "git branch" to confirm.
Table structure...very basic:
create table tabla(ID int, Stuff varchar (50));
insert into tabla values(1, '32.43');
insert into tabla values(2, '43.33');
insert into tabla values(3, '23.22');
Query:
SELECT SUM(cast(Stuff as decimal(4,2))) as result FROM tabla
Or, try this:
SELECT SUM(cast(isnull(Stuff,0) as decimal(12,2))) as result FROM tabla
Working on SQLServer 2008
Another Simple way i found in Netbeans right click on your project>libraris click add jar/folder add your comm.jar and you done.
if you dont have comm.jar download it from >>> http://llk.media.mit.edu/projects/picdev/software/javaxcomm.zip
If you get the IP address from a DHCP server, you can also set the server to send a DNS server. Or add the nameserver 8.8.8.8
into /etc/resolvconf/resolv.conf.d/base file. The information in this file is included in the resolver configuration file even when no interfaces are configured.
No need for mysqladmin:
just use mysql command line
mysql -u [username] -p[password] -e 'drop database db-name;'
This will send the drop command although I wouldn't pass the password this way as it'll be exposed to other users of the system via ps aux
If the string is empty, comboBox.getSelectedItem().toString()
will give a NullPointerException
. So better to typecast by (String)
.
$(Split-Path "D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv" -leaf)
The newline character is actually '\n'
.
Video with fall back:
try {
video.srcObject = mediaSource;
} catch (error) {
video.src = URL.createObjectURL(mediaSource);
}
video.play();
From: https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/srcObject
To be short, use:
write-output "your text" | out-file -append -encoding utf8 "filename"
sudo gem install -n /usr/local/bin cocoapods
This worked for me, -n helps you fix the permission error.
Actually the best answer is
SELECT CONVERT(VARCHAR(1000), varbinary_value, 1);
using "2
" cuts off the "0x
" at the start of the varbinary
.
This code is working fine for me in a loop
$remove = array(
"market_value",
"sector_id"
);
foreach($remove as $key){
unset($obj_name->$key);
}
Try this
var url = "http://www.exmple.com/234234234"
var res = url.split("/").pop();
alert(res);
This worked for me in Bitbucket Cloud.
Entering this:
* item a
* item b
** item b1
** item b2
* item3
I've got this:
Another option which doesn't have the need to create a custom Model is to use a Tuple<>.
@model Tuple<Person,Order>
It's not as clean as creating a new class which contains both, as per Andi's answer, but it is viable.
json_decode will return the same array that was originally encoded. For instanse, if you
$array = json_decode($json, true);
echo $array['countryId'];
OR
$obj= json_decode($json);
echo $obj->countryId;
These both will echo 84. I think json_encode and json_decode function names are self-explanatory...
You have successfully removed the row names. The print.data.frame
method just shows the row numbers if no row names are present.
df1 <- data.frame(values = rnorm(3), group = letters[1:3],
row.names = paste0("RowName", 1:3))
print(df1)
# values group
#RowName1 -1.469809 a
#RowName2 -1.164943 b
#RowName3 0.899430 c
rownames(df1) <- NULL
print(df1)
# values group
#1 -1.469809 a
#2 -1.164943 b
#3 0.899430 c
You can suppress printing the row names and numbers in print.data.frame
with the argument row.names
as FALSE
.
print(df1, row.names = FALSE)
# values group
# -1.4345829 d
# 0.2182768 e
# -0.2855440 f
Edit: As written in the comments, you want to convert this to HTML. From the xtable
and print.xtable
documentation, you can see that the argument include.rownames
will do the trick.
library("xtable")
print(xtable(df1), type="html", include.rownames = FALSE)
#<!-- html table generated in R 3.1.0 by xtable 1.7-3 package -->
#<!-- Thu Jun 26 12:50:17 2014 -->
#<TABLE border=1>
#<TR> <TH> values </TH> <TH> group </TH> </TR>
#<TR> <TD align="right"> -0.34 </TD> <TD> a </TD> </TR>
#<TR> <TD align="right"> -1.04 </TD> <TD> b </TD> </TR>
#<TR> <TD align="right"> -0.48 </TD> <TD> c </TD> </TR>
#</TABLE>
Recursion means a function calls repeatedly
It uses system stack to accomplish it's task. As stack uses LIFO approach and when a function is called the controlled is moved to where function is defined which has it is stored in memory with some address, this address is stored in stack
Secondly, it reduces a time complexity of a program.
Though bit off-topic,a bit related. Must read. : Recursion vs Iteration
Spring started off as a fairly simple dependency injection system. Now it is huge and has everything in it (except for the proverbial kitchen sink).
But fear not, it is quite modular so you can use just the pieces you want.
To see where it all began try:
It might be old but it is an excellent book.
For another good book this time exclusively devoted to Spring see:
It also references older versions of Spring but is definitely worth looking at.
if a device has an SD card, you use:
Environment.getExternalStorageState()
if you don't have an SD card, you use:
Environment.getDataDirectory()
if there is no SD card, you can create your own directory on the device locally.
//if there is no SD card, create new directory objects to make directory on device
if (Environment.getExternalStorageState() == null) {
//create new file directory object
directory = new File(Environment.getDataDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(Environment.getDataDirectory()
+ "/Robotium-Screenshots/");
/*
* this checks to see if there are any previous test photo files
* if there are any photos, they are deleted for the sake of
* memory
*/
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length != 0) {
for (int ii = 0; ii <= dirFiles.length; ii++) {
dirFiles[ii].delete();
}
}
}
// if no directory exists, create new directory
if (!directory.exists()) {
directory.mkdir();
}
// if phone DOES have sd card
} else if (Environment.getExternalStorageState() != null) {
// search for directory on SD card
directory = new File(Environment.getExternalStorageDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(
Environment.getExternalStorageDirectory()
+ "/Robotium-Screenshots/");
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length > 0) {
for (int ii = 0; ii < dirFiles.length; ii++) {
dirFiles[ii].delete();
}
dirFiles = null;
}
}
// if no directory exists, create new directory to store test
// results
if (!directory.exists()) {
directory.mkdir();
}
}// end of SD card checking
add permissions on your manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Happy coding..
You can easily test the difference between HTTP and HTTPS performance in your own browser using the HTTP vs HTTPS Test website by AnthumChris: “This page measures its load time over unsecure HTTP and encrypted HTTPS connections. Both pages load 360 unique, non-cached images (2.04 MB total).”
The results may surprise you.
It's important to have an up to date knowledge about the HTTPS performance because the Let’s Encrypt Certificate Authority will start issuing free, automated, and open SSL certificates in Summer 2015, thanks to Mozilla, Akamai, Cisco, Electronic Frontier Foundation and IdenTrust.
Updates on Let’s Encrypt - Arriving September 2015:
More info on Twitter: @letsencrypt
For more info on HTTPS and SSL/TLS performance see:
For more info on the importance of using HTTPS see:
To sum it up, let me quote Ilya Grigorik: "TLS has exactly one performance problem: it is not used widely enough. Everything else can be optimized."
Thanks to Chris - author of the HTTP vs HTTPS Test benchmark - for his comments below.
All string data must be UTF-8 encoded.
$out = array(
'render' => utf8_encode($renderOutput),
'text' => utf8_encode($textOutput)
);
$out = json_encode($out);
die($out);
I don't believe search and replace will do it for you (doesn't work for me in Excel 2010 Home). Are you sure you want to put "null" in EVERY cell in the sheet? That is millions of cells, in which case there is no way a search and replace would be able to handle it memory-wise (correct me if I am wrong).
In the case I am right and you don't want millions of "null" cells, then here is a macro. It asks you to select the range then put "null" inside every cell that was blank.
Sub FillWithNull()
Dim cell As range
Dim myRange As range
Set myRange = Application.InputBox("Select the range", Type:=8)
Application.ScreenUpdating = False
For Each cell In myRange
If Len(cell) = 0 Then
cell.Value = "Null"
End If
Next
Application.ScreenUpdating = True
End Sub
The fact that the first digit has to be in the range 5-9
only applies in case of two digits. So, check for that in the case of 2 digits, and allow any more digits directly:
^([5-9]\d|\d{3,})$
This regexp has beginning/ending anchors to make sure you're checking all digits, and the string actually represents a number. The |
means "or", so either [5-9]\d
or any number with 3 or more digits. \d
is simply a shortcut for [0-9]
.
Edit: To disallow numbers like 001
:
^([5-9]\d|[1-9]\d{2,})$
This forces the first digit to be not a zero in the case of 3 or more digits.
I sometimes encounter the same issue. I can only answer your second bullet, because I am not as expert in R as I am with other languages. I have found that the standard for
loop has some unexpected results. Say x = 0
for (i in 1:x) {
print(i)
}
The output is
[1] 1
[1] 0
Whereas with python, for example
for i in range(x):
print i
does nothing. The loop is not entered.
I expected that if x = 0
that in R, the loop would not be entered. However, 1:0
is a valid range of numbers. I have not yet found a good workaround besides having an if
statement wrapping the for
loop
Update for Python 3.4+ pathlib
that actually answers the question:
from pathlib import Path
relative = Path("mydir/myfile.txt")
absolute = relative.absolute() # absolute is a Path object
If you only need a temporary string, keep in mind that you can use Path
objects with all the relevant functions in os.path
, including of course abspath
:
from os.path import abspath
absolute = abspath(relative) # absolute is a str object
A secondary option would be to check otherwise, with not space (\S
), using an expression similar to:
^\S+$
function has_any_spaces(regex, str) {_x000D_
if (regex.test(str) || str === '') {_x000D_
return false;_x000D_
}_x000D_
return true;_x000D_
}_x000D_
_x000D_
const expression = /^\S+$/g;_x000D_
const string = 'foo baz bar';_x000D_
_x000D_
console.log(has_any_spaces(expression, string));
_x000D_
Here, we can for instance push
strings without spaces into an array:
const regex = /^\S+$/gm;_x000D_
const str = `_x000D_
foo_x000D_
foo baz_x000D_
bar_x000D_
foo baz bar_x000D_
abc_x000D_
abc abc_x000D_
abc abc abc_x000D_
`;_x000D_
let m, arr = [];_x000D_
_x000D_
while ((m = regex.exec(str)) !== null) {_x000D_
// This is necessary to avoid infinite loops with zero-width matches_x000D_
if (m.index === regex.lastIndex) {_x000D_
regex.lastIndex++;_x000D_
}_x000D_
_x000D_
// Here, we push those strings without spaces in an array_x000D_
m.forEach((match, groupIndex) => {_x000D_
arr.push(match);_x000D_
});_x000D_
}_x000D_
console.log(arr);
_x000D_
If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.
jex.im visualizes regular expressions:
Use the lsof command "lsof -i tcp:port #", here is an example.
$ lsof -i tcp:1555
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
java 27330 john 121u IPv4 36028819 0t0 TCP 10.10.10.1:58615->10.10.10.10:livelan (ESTABLISHED)
java 27330 john 201u IPv4 36018833 0t0 TCP 10.10.10.1:58586->10.10.10.10:livelan (ESTABLISHED)
java 27330 john 264u IPv4 36020018 0t0 TCP 10.10.10.1:58598->10.10.10.10:livelan (ESTABLISHED)
java 27330 john 312u IPv4 36058194 0t0 TCP 10.10.10.1:58826->10.10.10.10:livelan (ESTABLISHED)
You can achieve this with the background-size property, which is now supported by most browsers.
To scale the background image to fit inside the div:
background-size: contain;
To scale the background image to cover the whole div:
background-size: cover;
Note Slipstream's response, that base64.b64encode
and base64.b64decode
need bytes-like object, not string.
>>> import base64
>>> a = '{"name": "John", "age": 42}'
>>> base64.b64encode(a)
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/usr/lib/python3.6/base64.py", line 58, in b64encode
encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not 'str'
You can run the pipenv
command with the --rm
option as in:
pipenv --rm
This will remove the virtualenv created for you under ~/.virtualenvs
See https://pipenv.kennethreitz.org/en/latest/cli/#cmdoption-pipenv-rm
I think we do not accept long structure programming we will add everytime shot code see below answer.
<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" >
_x000D_
You can use the IPython.display.clear_output to clear the output as mentioned in cel's answer. I would add that for me the best solution was to use this combination of parameters to print without any "shakiness" of the notebook:
from IPython.display import clear_output
for i in range(10):
clear_output(wait=True)
print(i, flush=True)
try this angular.isUndefined(value);
https://docs.angularjs.org/api/ng/function/angular.isUndefined
.then
function of promiseB receives what is returned from .then
function of promiseA.
here promiseA is returning is a number, which will be available as number
parameter in success function of promiseB. which will then be incremented by 1
You can use AOP and Java annotations from jcabi-aspects (I'm a developer):
@RetryOnFailure(attempts = 3, delay = 5)
public String load(URL url) {
return url.openConnection().getContent();
}
You could also use @Loggable
and @LogException
annotations.
Use CreateDirectory (char *DirName, SECURITY_ATTRIBUTES Attribs);
If the function succeeds it returns non-zero otherwise NULL
.
I got my solution
var claim = HttpContext.User.CurrentUserID();
public static class XYZ
{
public static int CurrentUserID(this ClaimsPrincipal claim)
{
var userID = claimsPrincipal.Claims.ToList().Find(r => r.Type ==
"UserID").Value;
return Convert.ToInt32(userID);
}
public static string CurrentUserRole(this ClaimsPrincipal claim)
{
var role = claimsPrincipal.Claims.ToList().Find(r => r.Type ==
"Role").Value;
return role;
}
}
In response to @A.M.K's question about how to do transitions without jQuery. A very simple example I threw together. If I had time to think this through some more, I might be able to eliminate the JavaScript code altogether:
<style>
body {
background-color: red;
transition: background-color 2s ease-in;
}
</style>
<script>
window.onload = function() {
document.body.style.backgroundColor = '#00f';
}
</script>
<body>
<p>test</p>
</body>
I thinks this is the best example for using randomUUID :
Hoisted from the comments
2020 comment: rather than using regex, we now have
URLSearchParams
, which does all of this for us, so no custom code, let alone regex, are necessary anymore.
Browser support is listed here https://caniuse.com/#feat=urlsearchparams
I would suggest an alternative regex, using sub-groups to capture name and value of the parameters individually and re.exec()
:
function getUrlParams(url) {
var re = /(?:\?|&(?:amp;)?)([^=&#]+)(?:=?([^&#]*))/g,
match, params = {},
decode = function (s) {return decodeURIComponent(s.replace(/\+/g, " "));};
if (typeof url == "undefined") url = document.location.href;
while (match = re.exec(url)) {
params[decode(match[1])] = decode(match[2]);
}
return params;
}
var result = getUrlParams("http://maps.google.de/maps?f=q&source=s_q&hl=de&geocode=&q=Frankfurt+am+Main&sll=50.106047,8.679886&sspn=0.370369,0.833588&ie=UTF8&ll=50.116616,8.680573&spn=0.35972,0.833588&z=11&iwloc=addr");
result
is an object:
{ f: "q" geocode: "" hl: "de" ie: "UTF8" iwloc: "addr" ll: "50.116616,8.680573" q: "Frankfurt am Main" sll: "50.106047,8.679886" source: "s_q" spn: "0.35972,0.833588" sspn: "0.370369,0.833588" z: "11" }
The regex breaks down as follows:
(?: # non-capturing group \?|& # "?" or "&" (?:amp;)? # (allow "&", for wrongly HTML-encoded URLs) ) # end non-capturing group ( # group 1 [^=]+ # any character except "=", "&" or "#"; at least once ) # end group 1 - this will be the parameter's name (?: # non-capturing group =? # an "=", optional ( # group 2 [^]* # any character except "&" or "#"; any number of times ) # end group 2 - this will be the parameter's value ) # end non-capturing group
All fields in JavaScript (and in TypeScript) can have the value null
or undefined
.
You can make the field optional which is different from nullable.
interface Employee1 {
name: string;
salary: number;
}
var a: Employee1 = { name: 'Bob', salary: 40000 }; // OK
var b: Employee1 = { name: 'Bob' }; // Not OK, you must have 'salary'
var c: Employee1 = { name: 'Bob', salary: undefined }; // OK
var d: Employee1 = { name: null, salary: undefined }; // OK
// OK
class SomeEmployeeA implements Employee1 {
public name = 'Bob';
public salary = 40000;
}
// Not OK: Must have 'salary'
class SomeEmployeeB implements Employee1 {
public name: string;
}
Compare with:
interface Employee2 {
name: string;
salary?: number;
}
var a: Employee2 = { name: 'Bob', salary: 40000 }; // OK
var b: Employee2 = { name: 'Bob' }; // OK
var c: Employee2 = { name: 'Bob', salary: undefined }; // OK
var d: Employee2 = { name: null, salary: 'bob' }; // Not OK, salary must be a number
// OK, but doesn't make too much sense
class SomeEmployeeA implements Employee2 {
public name = 'Bob';
}
Vector and list aren't conceptually tied to C++. Similar structures can be implemented in C, just the syntax (and error handling) would look different. For example LodePNG implements a dynamic array with functionality very similar to that of std::vector. A sample usage looks like:
uivector v = {};
uivector_push_back(&v, 1);
uivector_push_back(&v, 42);
for(size_t i = 0; i < v.size; ++i)
printf("%d\n", v.data[i]);
uivector_cleanup(&v);
As can be seen the usage is somewhat verbose and the code needs to be duplicated to support different types.
nothings/stb gives a simpler implementation that works with any types, but compiles only in C:
double *v = 0;
sb_push(v, 1.0);
sb_push(v, 42.0);
for(int i = 0; i < sb_count(v); ++i)
printf("%g\n", v[i]);
sb_free(v);
A lot of C code, however, resorts to managing the memory directly with realloc:
void* newMem = realloc(oldMem, newSize);
if(!newMem) {
// handle error
}
oldMem = newMem;
Note that realloc
returns null in case of failure, yet the old memory is still valid. In such situation this common (and incorrect) usage leaks memory:
oldMem = realloc(oldMem, newSize);
if(!oldMem) {
// handle error
}
Compared to std::vector
and the C equivalents from above, the simple realloc
method does not provide O(1) amortized guarantee, even though realloc
may sometimes be more efficient if it happens to avoid moving the memory around.
This worked for my purposes. Pretty basic and simple, but it did what I needed (which was to get a personal photo of mine onto the internet so I could use its URL).
Go to photos.google.com and open any image that you wish to embed in your website.
Tap the Share Icon and then choose "Get Link" to generate a shareable link for that image.
Go to j.mp/EmbedGooglePhotos, paste that link and it will instantly generate the embed code for that picture.
Open your website template, paste the generated code and save. The image will now serve directly from your Google Photos account.
Check this video tutorial out if you have trouble.
Don't declare the variable in the userform. Declare it as Public
in the module.
Public pass As String
In the Userform
Private Sub CommandButton1_Click()
pass = UserForm1.TextBox1
Unload UserForm1
End Sub
In the Module
Public pass As String
Public Sub Login()
'
'~~> Rest of the code
'
UserForm1.Show
driver.findElementByName("PASSWORD").SendKeys pass
'
'~~> Rest of the code
'
End Sub
You might want to also add an additional check just before calling the driver.find...
line?
If Len(Trim(pass)) <> 0 Then
This will ensure that a blank string is not passed.
On the CREATE TABLE,
The AUTO_INCREMENT of abuse_id is set to 2. MySQL now thinks 1 already exists.
With the INSERT statement you are trying to insert abuse_id with record 1. Please set AUTO_INCREMENT on CREATE_TABLE to 1 and try again.
Otherwise set the abuse_id in the INSERT statement to 'NULL'.
How can i resolve this?
If you want to replace the entire Fragment1
with Fragment2
, you need to do it inside MainActivity
, by using:
Fragment2 fragment2 = new Fragment2();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(android.R.id.content, fragment2);
fragmentTransaction.commit();
Just put this code inside a method in MainActivity
, then call that method from Fragment1
.
Color
has a getRGB() method that returns the color as an int
.
const keys = Array(n).keys();
[...Array.from(keys)].forEach(callback);
in Typescript
Try to add RecyclerView.ItemDecoration
To know how to do that: How to add dividers and spaces between items in RecyclerView?
You could use rails d model/controller/migration ...
to destroy or remove the changes generated by using the rails generate
command.
For example:
rails g model Home name:string
creates a model named home
with attribute name
. To remove the files and code generated from that command we can use
rails d model Home
MongoDB is not magically faster. If you store the same data, organised in basically the same fashion, and access it exactly the same way, then you really shouldn't expect your results to be wildly different. After all, MySQL and MongoDB are both GPL, so if Mongo had some magically better IO code in it, then the MySQL team could just incorporate it into their codebase.
People are seeing real world MongoDB performance largely because MongoDB allows you to query in a different manner that is more sensible to your workload.
For example, consider a design that persisted a lot of information about a complicated entity in a normalised fashion. This could easily use dozens of tables in MySQL (or any relational db) to store the data in normal form, with many indexes needed to ensure relational integrity between tables.
Now consider the same design with a document store. If all of those related tables are subordinate to the main table (and they often are), then you might be able to model the data such that the entire entity is stored in a single document. In MongoDB you can store this as a single document, in a single collection. This is where MongoDB starts enabling superior performance.
In MongoDB, to retrieve the whole entity, you have to perform:
So a b-tree lookup, and a binary page read. Log(n) + 1 IOs. If the indexes can reside entirely in memory, then 1 IO.
In MySQL with 20 tables, you have to perform:
So the total for mysql, even assuming that all indexes are in memory (which is harder since there are 20 times more of them) is about 20 range lookups.
These range lookups are likely comprised of random IO — different tables will definitely reside in different spots on disk, and it's possible that different rows in the same range in the same table for an entity might not be contiguous (depending on how the entity has been updated, etc).
So for this example, the final tally is about 20 times more IO with MySQL per logical access, compared to MongoDB.
This is how MongoDB can boost performance in some use cases.
Here's another option for those not using heatmap.2
(aheatmap
is good!)
Make a sequential vector of 100 values from min to max of your input matrix, find value closest to 0 in that, make two vector of colours to and from desired midpoint, combine and use them:
breaks <- seq(from=min(range(inputMatrix)), to=max(range(inputMatrix)), length.out=100)
midpoint <- which.min(abs(breaks - 0))
rampCol1 <- colorRampPalette(c("forestgreen", "darkgreen", "black"))(midpoint)
rampCol2 <- colorRampPalette(c("black", "darkred", "red"))(100-(midpoint+1))
rampCols <- c(rampCol1,rampCol2)
if type(a)==type(1.1)
if type(a)==type(1)
I see examples with both DOM and SimpleXML, but none with the XMLWriter.
Please keep in mind that from the tests I've done, both DOM and SimpleXML are almost twice slower then the XMLWriter and for larger files you should consider using the later one.
Here's a full working example, clear and simple that meets the requirements, written with XMLWriter (I'm sure it will help other users):
// array with the key / value pairs of the information to be added (can be an array with the data fetched from db as well)
$songs = [
'song1.mp3' => 'Track 1 - Track Title',
'song2.mp3' => 'Track 2 - Track Title',
'song3.mp3' => 'Track 3 - Track Title',
'song4.mp3' => 'Track 4 - Track Title',
'song5.mp3' => 'Track 5 - Track Title',
'song6.mp3' => 'Track 6 - Track Title',
'song7.mp3' => 'Track 7 - Track Title',
'song8.mp3' => 'Track 8 - Track Title',
];
$xml = new XMLWriter();
$xml->openURI('songs.xml');
$xml->setIndent(true);
$xml->setIndentString(' ');
$xml->startDocument('1.0', 'UTF-8');
$xml->startElement('xml');
foreach($songs as $song => $track){
$xml->startElement('track');
$xml->writeElement('path', $song);
$xml->writeElement('title', $track);
$xml->endElement();
}
$xml->endElement();
$xml->endDocument();
$xml->flush();
unset($xml);
str.replace(/^.+?\"|^.|\".+/, '');
This is sometimes bad to use when you wanna select what else to remove between "" and you cannot use it more than twice in one string. All it does is select whatever is not in between "" and replace it with nothing.
Even for me it is a bit confusing, but ill try to explain it. ^.+?
(not anything OPTIONAL) till first "
then |
Or/stop (still researching what it really means) till/at ^.
has selected nothing until before the 2nd "
using (|
stop/at). And select all that comes after with .+.
Update the create
action as below:
def create
...
respond_to do |format|
if @reservation.save
format.html do
redirect_to '/'
end
format.json { render json: @reservation.to_json }
else
format.html { render 'new'} ## Specify the format in which you are rendering "new" page
format.json { render json: @reservation.errors } ## You might want to specify a json format as well
end
end
end
You are using respond_to
method but anot specifying the format in which a new
page is rendered. Hence, the error ActionController::UnknownFormat
.
Some decent answers, but just thought I'd expand a bit to explain more clearly when PHP determines if an array is empty.
Main Notes:
An array with a key (or keys) will be determined as NOT empty by PHP.
As array values need keys to exist, having values or not in an array doesn't determine if it's empty, only if there are no keys (AND therefore no values).
So checking an array with empty()
doesn't simply tell you if you have values or not, it tells you if the array is empty, and keys are part of an array.
So consider how you are producing your array before deciding which checking method to use.
EG An array will have keys when a user submits your HTML form when each form field has an array name (ie name="array[]"
).
A non empty array will be produced for each field as there will be auto incremented key values for each form field's array.
Take these arrays for example:
/* Assigning some arrays */
// Array with user defined key and value
$ArrayOne = array("UserKeyA" => "UserValueA", "UserKeyB" => "UserValueB");
// Array with auto increment key and user defined value
// as a form field would return with user input
$ArrayTwo[] = "UserValue01";
$ArrayTwo[] = "UserValue02";
// Array with auto incremented key and no value
// as a form field would return without user input
$ArrayThree[] = '';
$ArrayThree[] = '';
If you echo out the array keys and values for the above arrays, you get the following:
ARRAY ONE:
[UserKeyA] => [UserValueA]
[UserKeyB] => [UserValueB]ARRAY TWO:
[0] => [UserValue01]
[1] => [UserValue02]ARRAY THREE:
[0] => []
[1] => []
And testing the above arrays with empty()
returns the following results:
ARRAY ONE:
$ArrayOne is not emptyARRAY TWO:
$ArrayTwo is not emptyARRAY THREE:
$ArrayThree is not empty
An array will always be empty when you assign an array but don't use it thereafter, such as:
$ArrayFour = array();
This will be empty, ie PHP will return TRUE when using if empty()
on the above.
So if your array has keys - either by eg a form's input names or if you assign them manually (ie create an array with database column names as the keys but no values/data from the database), then the array will NOT be empty()
.
In this case, you can loop the array in a foreach, testing if each key has a value. This is a good method if you need to run through the array anyway, perhaps checking the keys or sanitising data.
However it is not the best method if you simply need to know "if values exist" returns TRUE or FALSE. There are various methods to determine if an array has any values when it's know it will have keys. A function or class might be the best approach, but as always it depends on your environment and exact requirements, as well as other things such as what you currently do with the array (if anything).
Here's an approach which uses very little code to check if an array has values:
Using array_filter()
:
Iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from array is returned into the result array. Array keys are preserved.
$EmptyTestArray = array_filter($ArrayOne);
if (!empty($EmptyTestArray))
{
// do some tests on the values in $ArrayOne
}
else
{
// Likely not to need an else,
// but could return message to user "you entered nothing" etc etc
}
Running array_filter()
on all three example arrays (created in the first code block in this answer) results in the following:
ARRAY ONE:
$arrayone is not emptyARRAY TWO:
$arraytwo is not emptyARRAY THREE:
$arraythree is empty
So when there are no values, whether there are keys or not, using array_filter()
to create a new array and then check if the new array is empty shows if there were any values in the original array.
It is not ideal and a bit messy, but if you have a huge array and don't need to loop through it for any other reason, then this is the simplest in terms of code needed.
I'm not experienced in checking overheads, but it would be good to know the differences between using array_filter()
and foreach
checking if a value is found.
Obviously benchmark would need to be on various parameters, on small and large arrays and when there are values and not etc.
This is what I got working- set UIButton in xCode's IB to transparent/clear, and no bg image.
UIColor *pinkDarkOp = [UIColor colorWithRed:0.9f green:0.53f blue:0.69f alpha:1.0];
UIColor *pinkLightOp = [UIColor colorWithRed:0.79f green:0.45f blue:0.57f alpha:1.0];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = [[shareWordButton layer] bounds];
gradient.cornerRadius = 7;
gradient.colors = [NSArray arrayWithObjects:
(id)pinkDarkOp.CGColor,
(id)pinkLightOp.CGColor,
nil];
gradient.locations = [NSArray arrayWithObjects:
[NSNumber numberWithFloat:0.0f],
[NSNumber numberWithFloat:0.7],
nil];
[[recordButton layer] insertSublayer:gradient atIndex:0];
You could simply get the character length of the current directory, and remove them from your absolute list
setlocal EnableDelayedExpansion
for /L %%n in (1 1 500) do if "!__cd__:~%%n,1!" neq "" set /a "len=%%n+1"
setlocal DisableDelayedExpansion
for /r . %%g in (*.log) do (
set "absPath=%%g"
setlocal EnableDelayedExpansion
set "relPath=!absPath:~%len%!"
echo(!relPath!
endlocal
)
I have a stored proc that allows the customer to extend validation, if it exists I do not want to change it, if it doesn't I want to create it, the best way I have found:
IF OBJECT_ID('ValidateRequestPost') IS NULL
BEGIN
EXEC ('CREATE PROCEDURE ValidateRequestPost
@RequestNo VARCHAR(30),
@ErrorStates VARCHAR(255) OUTPUT
AS
BEGIN
SELECT @ErrorStates = @ErrorStates
END')
END
From your SQL Server Management Studio, you open Object Explorer, go to your database where you want to load the data into, right click, then pick Tasks > Import Data.
This opens the Import Data Wizard, which typically works pretty well for importing from Excel. You can pick an Excel file, pick what worksheet to import data from, you can choose what table to store it into, and what the columns are going to be. Pretty flexible indeed.
You can run this as a one-off, or you can store it as a SQL Server Integration Services (SSIS) package into your file system, or into SQL Server itself, and execute it over and over again (even scheduled to run at a given time, using SQL Agent).
Update: yes, yes, yes, you can do all those things you keep asking - have you even tried at least once to run that wizard??
OK, here it comes - step by step:
Step 1: pick your Excel source
Step 2: pick your SQL Server target database
Step 3: pick your source worksheet (from Excel) and your target table in your SQL Server database; see the "Edit Mappings" button!
Step 4: check (and change, if needed) your mappings of Excel columns to SQL Server columns in the table:
Step 5: if you want to use it later on, save your SSIS package to SQL Server:
Step 6: - success! This is on a 64-bit machine, works like a charm - just do it!!
Pretty much what others have put before, but as a one liner that can be put at the beginning of a batch command. (Well, usually after @echo off.)
net.exe session 1>NUL 2>NUL || (Echo This script requires elevated rights. & Exit /b 1)
How about putting WebDriverWait in While loop and catching the exceptions.
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
browser = webdriver.Firefox()
browser.get("url")
delay = 3 # seconds
while True:
try:
WebDriverWait(browser, delay).until(EC.presence_of_element_located(browser.find_element_by_id('IdOfMyElement')))
print "Page is ready!"
break # it will break from the loop once the specific element will be present.
except TimeoutException:
print "Loading took too much time!-Try again"
If you're repeating single characters like the OP, and the maximum number of repeats is not too high, then you could use a simple substring operation like this:
int i = 3;
String someNum = "123";
someNum += "00000000000000000000".substring(0, i);
Use pdfMake.js and this Gist.
(I found the Gist here along with a link to the package html-to-pdfmake, which I end up not using for now.)
After npm install pdfmake
and saving the Gist in htmlToPdf.js
I use it like this:
const pdfMakeX = require('pdfmake/build/pdfmake.js');
const pdfFontsX = require('pdfmake-unicode/dist/pdfmake-unicode.js');
pdfMakeX.vfs = pdfFontsX.pdfMake.vfs;
import * as pdfMake from 'pdfmake/build/pdfmake';
import htmlToPdf from './htmlToPdf.js';
var docDef = htmlToPdf(`<b>Sample</b>`);
pdfMake.createPdf({content:docDef}).download('sample.pdf');
Remarks:
pdfMake
's getBuffer()
function), all from the browser. The generated pdf turns out to be nicer for this kind of html than with other solutions I have tried.jsPDF.fromHTML()
suggested in the accepted answer, as that solution gets easily confused by special characters in my HTML that apparently are interpreted as a sort of markup and totally mess up the resulting PDF.jsPDF.from_html()
function, not to be confused with the one from the accepted answer) is not an option for me since I want the text in the generated PDF to be pasteable, whereas canvas based solutions generate bitmap based PDFs.StringUtils.isBlank
also returns true
for just whitespace:
isBlank(String str)
Checks if a String is whitespace, empty ("") or null.
I am assuming that you have enough permissions to create this directory.
To fix your problem, you can either ssh to some other location:
ssh [email protected]
and accept new key - it will create directory ~/.ssh
and known_hosts
underneath, or simply create it manually using
mkdir ~/.ssh
chmod 700 ~/.ssh
Note that chmod 700
is an important step!
After that, ssh-keygen should work without complaints.
width: 80vmin; height: 80vmin;
CSS does 80% of the smallest view, height or width
I had a similar scenario, and I thought that something like
str.replaceAll("\[|\]", "");
looked cleaner. Of course, if your token might have brackets in it, that wouldn't work.
You can configure your log4j
file with the category tag like this (with a console appender for the example):
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yy-MM-dd HH:mm:ss} %p %c - %m%n" />
</layout>
</appender>
<category name="org.hibernate">
<priority value="WARN" />
</category>
<root>
<priority value="INFO" />
<appender-ref ref="console" />
</root>
So every warning, error or fatal message from hibernate will be displayed, nothing more. Also, your code and library code will be in info level (so info, warn, error and fatal)
To change log level of a library, just add a category, for example, to desactive spring info log:
<category name="org.springframework">
<priority value="WARN" />
</category>
Or with another appender, break the additivity (additivity default value is true)
<category name="org.springframework" additivity="false">
<priority value="WARN" />
<appender-ref ref="anotherAppender" />
</category>
And if you don't want that hibernate log every query, set the hibernate property show_sql
to false
.
Using the ternary :?
operator [spec].
var hasName = (name === 'true') ? 'Y' :'N';
The ternary operator lets us write shorthand if..else
statements exactly like you want.
It looks like:
(name === 'true')
- our condition
?
- the ternary operator itself
'Y'
- the result if the condition evaluates to true
'N'
- the result if the condition evaluates to false
So in short (question)?(result if true):(result is false)
, as you can see - it returns the value of the expression so we can simply assign it to a variable just like in the example above.
This is straightforward if you have control over the client that is sending the communications. All you need to do is set the HttpProxy on the client-side service class.
I did this, for example, to trace a web service client running on a smartphone. I set the proxy on that client-side connection to the IP/port of Fiddler, which was running on a PC on the network. The smartphone app then sent all of its outgoing communication to the web service, through Fiddler.
This worked perfectly.
If your client is a WCF client, then see this Q&A for how to set the proxy.
Even if you don't have the ability to modify the code of the client-side app, you may be able to set the proxy administratively, depending on the webservices stack your client uses.
You can use CAST
function:
SELECT CAST(your_column_name AS varchar(10)) FROM your_table_name
Maybe you should try it with -quality 100 -size "1024x1024", because resize often gives results that are ugly to view.
Does your cacerts.pem file hold a single certificate? Since it is a PEM, have a look at it (with a text editor), it should start with
-----BEGIN CERTIFICATE-----
and end with
-----END CERTIFICATE-----
Finally, to check it is not corrupted, get hold of openssl and print its details using
openssl x509 -in cacerts.pem -text
Type the following statement in the javascript console:
debugger
Now you can inspect the global scope using the normal debug tools.
To be fair, you'll get everything in the window
scope, including browser built-ins, so it might be sort of a needle-in-a-haystack experience. :/
This error is usually encountered when inserting a record in a table where one of the columns is a VARCHAR or CHAR data type and the length of the value being inserted is longer than the length of the column.
I am not satisfied how Microsoft decided to inform with this "dry" response message, without any point of where to look for the answer.
It's also possible by using rsync
, for example:
rsync -va --delete-after src/ dst/
where:
-v
, --verbose
: increase verbosity-a
, --archive
: archive mode; equals -rlptgoD
(no -H,-A,-X
)--delete-after
: delete files on the receiving side be done after the transfer has completedIf you've root privileges, prefix with sudo
to override potential permission issues.
In case you have composite primary key, do like this- ALTER TABLE table_name DROP PRIMARY KEY,ADD PRIMARY KEY (col_name1, col_name2);
Well one way to do it is set the height of your body to the height
that you want your page
to be. In this example I did 600px
.
Then set your wrapper
height to a percentage of the body here I did 70%
This will adjust your table so that it does not fill up the whole screen but in stead just takes up a percentage of the specified page height.
body {
padding-top: 70px;
border:1px solid black;
height:600px;
}
.mygrid-wrapper-div {
border: solid red 5px;
overflow: scroll;
height: 70%;
}
Update How about a jQuery approach.
$(function() {
var window_height = $(window).height(),
content_height = window_height - 200;
$('.mygrid-wrapper-div').height(content_height);
});
$( window ).resize(function() {
var window_height = $(window).height(),
content_height = window_height - 200;
$('.mygrid-wrapper-div').height(content_height);
});
I will just link to my other answer: How do YOU reduce compile time, and linking time for Visual C++ projects (native C++)?. Another point I want to add, but which causes often problems is to use precompiled headers. But please, only use them for parts which hardly ever change (like GUI toolkit headers). Otherwise, they will cost you more time than they save you in the end.
Another option is, when you work with GNU make, to turn on -j<N>
option:
-j [N], --jobs[=N] Allow N jobs at once; infinite jobs with no arg.
I usually have it at 3
since I've got a dual core here. It will then run compilers in parallel for different translation units, provided there are no dependencies between them. Linking cannot be done in parallel, since there is only one linker process linking together all object files.
But the linker itself can be threaded, and this is what the GNU gold
ELF linker does. It's optimized threaded C++ code which is said to link ELF object files a magnitude faster than the old ld
(and was actually included into binutils).
This is the right way to clear this error.
export ORACLE_HOME=/u01/app/oracle/product/10.2.0/db_1 sqlplus / as sysdba
I found using jQuery was my best solution.
$( "#my_number_field" ).blur(function() {
this.value = parseFloat(this.value).toFixed(2);
});
For anyone running SQL Server on RDS (AWS), there's a built-in procedure callable in the msdb
database which provides comprehensive information for all backup and restore tasks:
exec msdb.dbo.rds_task_status;
This will give a full rundown of each task, its configuration, details about execution (such as completed percentage and total duration), and a task_info
column which is immensely helpful when trying to figure out what's wrong with a backup or restore.
Alternative solution for rows of NA
s using janitor
package
myData %>% remove_empty("rows")
For those who are having the same issue with Swagger or Postman like I did, if you are passing a simple attribute as string in a post, even with the "ContentType" specified, you still going to get a null value.
Passing just:
MyValue
Will get in the controller as null.
But if you pass:
"MyValue"
The value will get right.
The quotes made the difference here. Of course, this is only for Swagger and Postman. For instance, in a Frontend app using Angular this should be resolved by the framework automaticly.
Clearing metadata helped me or change the workspace.
df.iloc[0].head(1)
- First data set only from entire first row.df.iloc[0]
- Entire First row in column.I have great news: this will be in Compose 1.3!
I'm using it in the current RC (RC1) like this:
rng:
build: rng
extra_hosts:
seed: 1.2.3.4
tree: 4.3.2.1
OK, here's the solution I settled on.
First you create a seed value using the "newseed()" function. Then you pass the seed value to the "srandom()" function. Lastly, the "srandom()" function returns a pseudo random value between 0 and 1.
The crucial bit is that the seed value is stored inside an array. If it were simply an integer or float, the value would get overwritten each time the function were called, since the values of integers, floats, strings and so forth are stored directly in the stack versus just the pointers as in the case of arrays and other objects. Thus, it's possible for the value of the seed to remain persistent.
Finally, it is possible to define the "srandom()" function such that it is a method of the "Math" object, but I'll leave that up to you to figure out. ;)
Good luck!
JavaScript:
// Global variables used for the seeded random functions, below.
var seedobja = 1103515245
var seedobjc = 12345
var seedobjm = 4294967295 //0x100000000
// Creates a new seed for seeded functions such as srandom().
function newseed(seednum)
{
return [seednum]
}
// Works like Math.random(), except you provide your own seed as the first argument.
function srandom(seedobj)
{
seedobj[0] = (seedobj[0] * seedobja + seedobjc) % seedobjm
return seedobj[0] / (seedobjm - 1)
}
// Store some test values in variables.
var my_seed_value = newseed(230951)
var my_random_value_1 = srandom(my_seed_value)
var my_random_value_2 = srandom(my_seed_value)
var my_random_value_3 = srandom(my_seed_value)
// Print the values to console. Replace "WScript.Echo()" with "alert()" if inside a Web browser.
WScript.Echo(my_random_value_1)
WScript.Echo(my_random_value_2)
WScript.Echo(my_random_value_3)
Lua 4 (my personal target environment):
-- Global variables used for the seeded random functions, below.
seedobja = 1103515.245
seedobjc = 12345
seedobjm = 4294967.295 --0x100000000
-- Creates a new seed for seeded functions such as srandom().
function newseed(seednum)
return {seednum}
end
-- Works like random(), except you provide your own seed as the first argument.
function srandom(seedobj)
seedobj[1] = mod(seedobj[1] * seedobja + seedobjc, seedobjm)
return seedobj[1] / (seedobjm - 1)
end
-- Store some test values in variables.
my_seed_value = newseed(230951)
my_random_value_1 = srandom(my_seed_value)
my_random_value_2 = srandom(my_seed_value)
my_random_value_3 = srandom(my_seed_value)
-- Print the values to console.
print(my_random_value_1)
print(my_random_value_2)
print(my_random_value_3)
Be careful. For this you need @GET (not @PUT).
while you should show how your code looks like that gives the problem, i think this scenario is very common. See copy/deepcopy
Are there any libraries to do this in numpy/SciPy
Sure. You can do this without OpenCV, scikit-image or PIL.
Image resizing is basically mapping the coordinates of each pixel from the original image to its resized position.
Since the coordinates of an image must be integers (think of it as a matrix), if the mapped coordinate has decimal values, you should interpolate the pixel value to approximate it to the integer position (e.g. getting the nearest pixel to that position is known as Nearest neighbor interpolation).
All you need is a function that does this interpolation for you. SciPy has interpolate.interp2d
.
You can use it to resize an image in numpy array, say arr
, as follows:
W, H = arr.shape[:2]
new_W, new_H = (600,300)
xrange = lambda x: np.linspace(0, 1, x)
f = interp2d(xrange(W), xrange(H), arr, kind="linear")
new_arr = f(xrange(new_W), xrange(new_H))
Of course, if your image is RGB, you have to perform the interpolation for each channel.
If you would like to understand more, I suggest watching Resizing Images - Computerphile.
Use second process. Declare at AndroidManifest
new Service
with
android:process=":second"
Exchange between first and second process over BroadcastReceiver
Open the IDLE and use below commands.
import sys print(sys.path)
It will give you the path where the python.exe is installed. For eg: C:\Users\\...\python.exe
Add the same path to system environment variable.
The shortest way (will print "not same" because String comparison is case sensitive):
def compareString = {
it == "india" ? "same" : "not same"
}
compareString("India")
Although Reed Copsey and Marc Gravell already described about IQueryable
(and also IEnumerable
) enough,mI want to add little more here by providing a small example on IQueryable
and IEnumerable
as many users asked for it
Example: I have created two table in database
CREATE TABLE [dbo].[Employee]([PersonId] [int] NOT NULL PRIMARY KEY,[Gender] [nchar](1) NOT NULL)
CREATE TABLE [dbo].[Person]([PersonId] [int] NOT NULL PRIMARY KEY,[FirstName] [nvarchar](50) NOT NULL,[LastName] [nvarchar](50) NOT NULL)
The Primary key(PersonId
) of table Employee
is also a forgein key(personid
) of table Person
Next i added ado.net entity model in my application and create below service class on that
public class SomeServiceClass
{
public IQueryable<Employee> GetEmployeeAndPersonDetailIQueryable(IEnumerable<int> employeesToCollect)
{
DemoIQueryableEntities db = new DemoIQueryableEntities();
var allDetails = from Employee e in db.Employees
join Person p in db.People on e.PersonId equals p.PersonId
where employeesToCollect.Contains(e.PersonId)
select e;
return allDetails;
}
public IEnumerable<Employee> GetEmployeeAndPersonDetailIEnumerable(IEnumerable<int> employeesToCollect)
{
DemoIQueryableEntities db = new DemoIQueryableEntities();
var allDetails = from Employee e in db.Employees
join Person p in db.People on e.PersonId equals p.PersonId
where employeesToCollect.Contains(e.PersonId)
select e;
return allDetails;
}
}
they contains same linq. It called in program.cs
as defined below
class Program
{
static void Main(string[] args)
{
SomeServiceClass s= new SomeServiceClass();
var employeesToCollect= new []{0,1,2,3};
//IQueryable execution part
var IQueryableList = s.GetEmployeeAndPersonDetailIQueryable(employeesToCollect).Where(i => i.Gender=="M");
foreach (var emp in IQueryableList)
{
System.Console.WriteLine("ID:{0}, EName:{1},Gender:{2}", emp.PersonId, emp.Person.FirstName, emp.Gender);
}
System.Console.WriteLine("IQueryable contain {0} row in result set", IQueryableList.Count());
//IEnumerable execution part
var IEnumerableList = s.GetEmployeeAndPersonDetailIEnumerable(employeesToCollect).Where(i => i.Gender == "M");
foreach (var emp in IEnumerableList)
{
System.Console.WriteLine("ID:{0}, EName:{1},Gender:{2}", emp.PersonId, emp.Person.FirstName, emp.Gender);
}
System.Console.WriteLine("IEnumerable contain {0} row in result set", IEnumerableList.Count());
Console.ReadKey();
}
}
The output is same for both obviously
ID:1, EName:Ken,Gender:M
ID:3, EName:Roberto,Gender:M
IQueryable contain 2 row in result set
ID:1, EName:Ken,Gender:M
ID:3, EName:Roberto,Gender:M
IEnumerable contain 2 row in result set
So the question is what/where is the difference? It does not seem to have any difference right? Really!!
Let's have a look on sql queries generated and executed by entity framwork 5 during these period
IQueryable execution part
--IQueryableQuery1
SELECT
[Extent1].[PersonId] AS [PersonId],
[Extent1].[Gender] AS [Gender]
FROM [dbo].[Employee] AS [Extent1]
WHERE ([Extent1].[PersonId] IN (0,1,2,3)) AND (N'M' = [Extent1].[Gender])
--IQueryableQuery2
SELECT
[GroupBy1].[A1] AS [C1]
FROM ( SELECT
COUNT(1) AS [A1]
FROM [dbo].[Employee] AS [Extent1]
WHERE ([Extent1].[PersonId] IN (0,1,2,3)) AND (N'M' = [Extent1].[Gender])
) AS [GroupBy1]
IEnumerable execution part
--IEnumerableQuery1
SELECT
[Extent1].[PersonId] AS [PersonId],
[Extent1].[Gender] AS [Gender]
FROM [dbo].[Employee] AS [Extent1]
WHERE [Extent1].[PersonId] IN (0,1,2,3)
--IEnumerableQuery2
SELECT
[Extent1].[PersonId] AS [PersonId],
[Extent1].[Gender] AS [Gender]
FROM [dbo].[Employee] AS [Extent1]
WHERE [Extent1].[PersonId] IN (0,1,2,3)
Common script for both execution part
/* these two query will execute for both IQueryable or IEnumerable to get details from Person table
Ignore these two queries here because it has nothing to do with IQueryable vs IEnumerable
--ICommonQuery1
exec sp_executesql N'SELECT
[Extent1].[PersonId] AS [PersonId],
[Extent1].[FirstName] AS [FirstName],
[Extent1].[LastName] AS [LastName]
FROM [dbo].[Person] AS [Extent1]
WHERE [Extent1].[PersonId] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=1
--ICommonQuery2
exec sp_executesql N'SELECT
[Extent1].[PersonId] AS [PersonId],
[Extent1].[FirstName] AS [FirstName],
[Extent1].[LastName] AS [LastName]
FROM [dbo].[Person] AS [Extent1]
WHERE [Extent1].[PersonId] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=3
*/
So you have few questions now, let me guess those and try to answer them
Why are different scripts generated for same result?
Lets find out some points here,
all queries has one common part
WHERE [Extent1].[PersonId] IN (0,1,2,3)
why? Because both function IQueryable<Employee> GetEmployeeAndPersonDetailIQueryable
and
IEnumerable<Employee> GetEmployeeAndPersonDetailIEnumerable
of SomeServiceClass
contains one common line in linq queries
where employeesToCollect.Contains(e.PersonId)
Than why is the
AND (N'M' = [Extent1].[Gender])
part is missing in IEnumerable
execution part, while in both function calling we used Where(i => i.Gender == "M") in
program.cs`
Now we are in the point where difference came between
IQueryable
andIEnumerable
What entity framwork does when an IQueryable
method called, it tooks linq statement written inside the method and try to find out if more linq expressions are defined on the resultset, it then gathers all linq queries defined until the result need to fetch and constructs more appropriate sql query to execute.
It provide a lots of benefits like,
like here in example sql server returned to application only two rows after IQueryable execution` but returned THREE rows for IEnumerable query why?
In case of IEnumerable
method, entity framework took linq statement written inside the method and constructs sql query when result need to fetch. it does not include rest linq part to constructs the sql query. Like here no filtering is done in sql server on column gender
.
But the outputs are same? Because 'IEnumerable filters the result further in application level after retrieving result from sql server
SO, what should someone choose?
I personally prefer to define function result as IQueryable<T>
because there are lots of benefit it has over IEnumerable
like, you could join two or more IQueryable functions, which generate more specific script to sql server.
Here in example you can see an IQueryable Query(IQueryableQuery2)
generates a more specific script than IEnumerable query(IEnumerableQuery2)
which is much more acceptable in my point of view.
In c++, compiler always ensure that functions in object hierarchy are called successfully. These functions are constructors and destructors and object hierarchy means inheritance tree.
According to this rule we can guess compiler will call constructors and destructors for each object in inheritance hierarchy even if we don't implement it. To perform this operation compiler will synthesize the undefined constructors and destructors for us and we name them as a default constructors and destructors.Then, compiler will call default constructor of base class and then calls constructor of derived class.
In your case you don't call base class constructor but compiler does that for you by calling default constructor of base class because if compiler didn't do it your derived class which is Rectangle in your example will not be complete and it might cause disaster because maybe you will use some member function of base class in your derived class. So for the sake of safety compiler always need all constructor calls.
CODE WILL BE GENERATED AUTOMATICALLY
<configuration> <configSections> <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup ..." ... > <section name="XX....Properties.Settings" type="System.Configuration.ClientSettingsSection ..." ... /> </sectionGroup> </configSections> <applicationSettings> <XX....Properties.Settings> <setting name="name" serializeAs="String"> <value>value</value> </setting> <setting name="name2" serializeAs="String"> <value>value2</value> </setting> </XX....Properties.Settings> </applicationSettings> </configuration>
To get a value
Properties.Settings.Default.Name
OR
Properties.Settings.Default["name"]
In file - \vendor\autoload.php, define your gobals variable as follows, should be in the topmost line.
$global_variable = "Some value";//the global variable
Access that global variable anywhere as :-
$GLOBALS['global_variable'];
Enjoy :)
You seem to have used some [Authorize]
attribute on your Web API controller action and I don't see how this is relevant to your question.
So, let's get into practice. Here's a how a trivial Web API controller might look like:
public class TestController : ApiController
{
public string Post([FromBody] string value)
{
return value;
}
}
and a consumer for that matter:
class Program
{
static void Main()
{
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
var data = "=Short test...";
var result = client.UploadString("http://localhost:52996/api/test", "POST", data);
Console.WriteLine(result);
}
}
}
You will undoubtedly notice the [FromBody]
decoration of the Web API controller attribute as well as the =
prefix of the POST data om the client side. I would recommend you reading about how does the Web API does parameter binding to better understand the concepts.
As far as the [Authorize]
attribute is concerned, this could be used to protect some actions on your server from being accessible only to authenticated users. Actually it is pretty unclear what you are trying to achieve here.You should have made this more clear in your question by the way. Are you are trying to understand how parameter bind works in ASP.NET Web API (please read the article I've linked to if this is your goal) or are attempting to do some authentication and/or authorization? If the second is your case you might find the following post
that I wrote on this topic interesting to get you started.
And if after reading the materials I've linked to, you are like me and say to yourself, WTF man, all I need to do is POST a string to a server side endpoint and I need to do all of this? No way. Then checkout ServiceStack. You will have a good base for comparison with Web API. I don't know what the dudes at Microsoft were thinking about when designing the Web API, but come on, seriously, we should have separate base controllers for our HTML (think Razor) and REST stuff? This cannot be serious.
If you're using React.FC
, add the HTMLDivElement
interface:
const myRef = React.useRef<HTMLDivElement>(null);
And use it like the following:
return <div ref={myRef} />;
The URL should be a string:
import urllib
link = "http://www.somesite.com/details.pl?urn=2344"
f = urllib.urlopen(link)
myfile = f.readline()
print myfile
I think this is a much simpler version. Bundle
is a built-in type which implements Parcelable
public class CustomView extends View
{
private int stuff; // stuff
@Override
public Parcelable onSaveInstanceState()
{
Bundle bundle = new Bundle();
bundle.putParcelable("superState", super.onSaveInstanceState());
bundle.putInt("stuff", this.stuff); // ... save stuff
return bundle;
}
@Override
public void onRestoreInstanceState(Parcelable state)
{
if (state instanceof Bundle) // implicit null check
{
Bundle bundle = (Bundle) state;
this.stuff = bundle.getInt("stuff"); // ... load stuff
state = bundle.getParcelable("superState");
}
super.onRestoreInstanceState(state);
}
}
Flexboxes can accomplish this by using align-items: flex-end;
with display: flex;
or display: inline-flex;
div#imageContainer {
height: 160px;
align-items: flex-end;
display: flex;
/* This is the default value, so you only need to explicitly set it if it's already being set to something else elsewhere. */
/*flex-direction: row;*/
}
It is important to see if the element is visible or not as the Driver.FindElement
will only check the HTML source. But popup code could be in the page html, and not be visible. Therefore, Driver.FindElement
function returns a false positive (and your test will fail)
Using @property
and @dynamic
could also work. If you declare a dynamic property and don't give a matching method implementation, everything will still compile without warnings, and you'll get an unrecognized selector
error at runtime if you try to access it. This essentially the same thing as calling [self doesNotRecognizeSelector:_cmd]
, but with far less typing.
A two line intuitive solution to round to a given time unit, here seconds, for a datetime
object t
:
format_str = '%Y-%m-%d %H:%M:%S'
t_rounded = datetime.strptime(datetime.strftime(t, format_str), format_str)
If you wish to round to a different unit simply alter format_str
.
This approach does not round to arbitrary time amounts as above methods, but is a nicely Pythonic way to round to a given hour, minute or second.
You cannot redeclare any functions in PHP. You can, however, override them. Check out overriding functions as well as renaming functions in order to save the function you're overriding if you want.
So, keep in mind that when you override a function, you lose it. You may want to consider keeping it, but in a different name. Just saying.
Also, if these are functions in classes that you're wanting to override, you would just need to create a subclass and redeclare the function in your class without having to do rename_function and override_function.
Example:
rename_function('mysql_connect', 'original_mysql_connect' );
override_function('mysql_connect', '$a,$b', 'echo "DOING MY FUNCTION INSTEAD"; return $a * $b;');
keep everything as clean as possible when working with huge classes, or when working on a team, you can edit without overriding (or always commiting changes)
I checked all the answers around the web and the best one seemed to be: (actually it isn't)
<img src="image.png?cache=none">
at first.
However, if you add cache=none parameter (which is static "none" word), it doesn't effect anything, browser still loads from cache.
Solution to this problem was:
<img src="image.png?nocache=<?php echo time(); ?>">
where you basically add unix timestamp to make the parameter dynamic and no cache, it worked.
However, my problem was a little different: I was loading on the fly generated php chart image, and controlling the page with $_GET parameters. I wanted the image to be read from cache when the URL GET parameter stays the same, and do not cache when the GET parameters change.
To solve this problem, I needed to hash $_GET but since it is array here is the solution:
$chart_hash = md5(implode('-', $_GET));
echo "<img src='/images/mychart.png?hash=$chart_hash'>";
Edit:
Although the above solution works just fine, sometimes you want to serve the cached version UNTIL the file is changed. (with the above solution, it disables the cache for that image completely) So, to serve cached image from browser UNTIL there is a change in the image file use:
echo "<img src='/images/mychart.png?hash=" . filemtime('mychart.png') . "'>";
filemtime() gets file modification time.
A dozen pages is not a big deal when using OFFSET
. But when you have hundreds of pages, you will find that OFFSET
is bad for performance. This is because all the skipped rows need to be read each time.
It is better to remember where you left off.
I like to have a control over the root view so I added the includeSelf
flag to deepForEach
fun ViewGroup.deepForEach(includeSelf: Boolean = true, function: View.() -> Unit) {
if (includeSelf) function()
forEach {
it.apply {
function()
(this as? ViewGroup)?.apply { deepForEach(includeSelf, function) }
}
}
}
Your CA file must have been in a binary X.509 format instead of Base64 encoding; it needs to be a regular DER or PEM in order for it to be added successfully to the list of trusted CAs on your server.
To proceed, do place your CA file inside your /usr/share/pki/ca-trust-source/anchors/
directory, then run the command line below (you might need sudo privileges based on your settings);
# CentOS 7, Red Hat 7, Oracle Linux 7
update-ca-trust
Please note that all trust settings available in the /usr/share/pki/ca-trust-source/anchors/
directory are interpreted with a lower priority compared to the ones placed under the /etc/pki/ca-trust/source/anchors/
directory which may be in the extended BEGIN TRUSTED file format.
For Ubuntu and Debian systems, /usr/local/share/ca-certificates/
is the preferred directory for that purpose.
As such, you need to place your CA file within the /usr/local/share/ca-certificates/
directory, then update the of trusted CAs by running, with sudo privileges where required, the command line below;
update-ca-certificates
For readability purposes i use query scope, makes my code more declarative.
namespace App\Models;
use Illuminate\Support\Carbon;
use Illuminate\Database\Eloquent\Model;
class MyModel extends Model
{
// ...
/**
* Scope a query to only include today's entries.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeCreatedToday($query)
{
return $query->where('created_at', '>=', Carbon::today());
}
// ...
}
MyModel::createdToday()->get()
Sql : select * from "my_models" where "created_at" >= ?
Bindings : ["2019-10-22T00:00:00.000000Z"]
According to Steve McConnell in Code Complete, you should
Limit the number of a routine's parameters to about seven
If you can use Java NIO (JDK 1.4 or greater), then I think you're looking for java.nio.channels.FileChannel.lock()
org.apache.jasper.JasperException: Unable to compile class for JSP:
I've seen this occur in our 7-8 docker production system. Another solution that worked for me in production was to run
docker-compose down
docker-compose up -d
this removes the containers and seems to make 'up' create new ones from the latest image.
This doesn't yet solve my dream of down+up per EACH changed container (serially, less down time), but it works to force 'up' to update the containers.
Note: Recent npm
versions do this automatically when package-locks are enabled, so this is not necessary except for removing development packages with the --production
flag.
Run npm prune
to remove modules not listed in package.json
.
From npm help prune
:
This command removes "extraneous" packages. If a package name is provided, then only packages matching one of the supplied names are removed.
Extraneous packages are packages that are not listed on the parent package's dependencies list.
If the
--production
flag is specified, this command will remove the packages specified in your devDependencies.
Git creates a master branch once you've done your first commit. There's nothing to have a branch for if there's no code in the repository.
It's worth noting, since it's confusing for people new to XML, that the root (or document node) of an XML document is not the top-level element. It's the parent of the top-level element. This is confusing because it doesn't seem like the top-level element can have a parent. Isn't it the top level?
But look at this, a well-formed XML document:
<?xml-stylesheet href="my_transform.xsl" type="text/xsl"?>
<!-- Comments and processing instructions are XML nodes too, remember. -->
<TopLevelElement/>
The root of this document has three children: a processing instruction, a comment, and an element.
So, for example, if you wanted to write a transform that got rid of that comment, but left in any comments appearing anywhere else in the document, you'd add this to the identity transform:
<xsl:template match="/comment()"/>
Even simpler (and more commonly useful), here's an XPath pattern that matches the document's top-level element irrespective of its name: /*
.
If you want to see queries that are already executed there is no supported default way to do this. There are some workarounds you can try but don’t expect to find all.
You won’t be able to see SELECT statements for sure but there is a way to see other DML and DDL commands by reading transaction log (assuming database is in full recovery mode).
You can do this using DBCC LOG or fn_dblog commands or third party log reader like ApexSQL Log (note that tool comes with a price)
Now, if you plan on auditing statements that are going to be executed in the future then you can use SQL Profiler to catch everything.
Reference article: Show red color border for invalid input fields angualrjs
I used ng-class on all input fields.like below
<input type="text" ng-class="{submitted:newEmployee.submitted}" placeholder="First Name" data-ng-model="model.firstName" id="FirstName" name="FirstName" required/>
when I click on save button I am changing newEmployee.submitted value to true(you can check it in my question). So when I click on save, a class named submitted gets added to all input fields(there are some other classes initially added by angularjs).
So now my input field contains classes like this
class="ng-pristine ng-invalid submitted"
now I am using below css code to show red border on all invalid input fields(after submitting the form)
input.submitted.ng-invalid
{
border:1px solid #f00;
}
Thank you !!
Update:
We can add the ng-class at the form element instead of applying it to all input elements. So if the form is submitted, a new class(submitted) gets added to the form element. Then we can select all the invalid input fields using the below selector
form.submitted .ng-invalid
{
border:1px solid #f00;
}
You can use following query to delete rows from multiple tables,
DELETE table1, table2, table3 FROM table1 INNER JOIN table2 INNER JOIN table3 WHERE table1.userid = table2.userid AND table2.userid = table3.userid AND table1.userid=3
django_template_filter filter name get_value_from_dict
{{ your_dict|get_value_from_dict:your_key }}
It's caused by NetBeans retaining some of the old source and/or compiled code in its cache and not noticing that e.g. some of the code's dependencies (i.e. referenced packages) have changed, and that a proper refresh/recompile of the file would be in order.
The solution is to force that refresh by either:
a) locating & editing the offending source file to force its recompilation (e.g. add a dummy line, save, remove it, save again),
b) doing a clean build (sometimes will work, sometimes won't),
c) disabling "Compile on save" (not recommended, since it can make using the IDE a royal PITA), or
d) simply remove NetBeans cache by hand, forcing the recompilation.
As to how to remove the cache:
If you're using an old version of NetBeans:
.netbeans/6.9/var/cache/index/
(replace 6.9 with your version).If you're using a newer one:
AppData/Local/NetBeans/Cache/8.1/index/
(replace 8.1 with your version).The paths may vary a little e.g. on different platforms, but the idea is still the same.
I'd like to add my Python3 answer for completeness:
from io import BytesIO
from zipfile import ZipFile
import requests
def get_zip(file_url):
url = requests.get(file_url)
zipfile = ZipFile(BytesIO(url.content))
zip_names = zipfile.namelist()
if len(zip_names) == 1:
file_name = zip_names.pop()
extracted_file = zipfile.open(file_name)
return extracted_file
return [zipfile.open(file_name) for file_name in zip_names]
As TASKKILL might be unavailable on some Home/basic editions of windows here some alternatives:
TSKILL processName
or
TSKILL PID
Have on mind that processName
should not have the .exe
suffix and is limited to 18 characters.
Another option is WMIC
:
wmic Path win32_process Where "Caption Like 'MyProcess.exe'" Call Terminate
wmic offer even more flexibility than taskkill .With wmic Path win32_process get
you can see the available fileds you can filter.
This worked for me, the key is you need a separate thread to analyze the socket state with polling. doing it in the same thread as the socket fails detection.
//open or receive a server socket - TODO your code here
socket = new Socket(....);
//enable the keep alive so we can detect closure
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
//create a thread that checks every 5 seconds if the socket is still connected. TODO add your thread starting code
void MonitorSocketsForClosureWorker() {
DateTime nextCheckTime = DateTime.Now.AddSeconds(5);
while (!exitSystem) {
if (nextCheckTime < DateTime.Now) {
try {
if (socket!=null) {
if(socket.Poll(5000, SelectMode.SelectRead) && socket.Available == 0) {
//socket not connected, close it if it's still running
socket.Close();
socket = null;
} else {
//socket still connected
}
}
} catch {
socket.Close();
} finally {
nextCheckTime = DateTime.Now.AddSeconds(5);
}
}
Thread.Sleep(1000);
}
}
You could try using Linq to project the list:
var output = lst.Select(x => x % 2 == 0).ToList();
This will return a new list of bools such that {1, 2, 3, 4, 5}
will map to {false, true, false, true, false}
.
Solution for Webflux (Reactive) Spring Boot, since Google shows this as one of the top results when searching with 'Reactive' for this same problem. Using Spring boot version 2.2.2
@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
return http.cors().and().build();
}
@Bean
public CorsWebFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.applyPermitDefaultValues();
config.addAllowedHeader("Authorization");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
}
For a full example, with the setup that works with a custom authentication manager (in my case JWT authentication). See here https://gist.github.com/FiredLight/d973968cbd837048987ab2385ba6b38f
jQuery Plugin
I created a jQuery plugin so I can use it easily anywhere I need it:
jQuery.fn.clear = function()
{
var $form = $(this);
$form.find('input:text, input:password, input:file, textarea').val('');
$form.find('select option:selected').removeAttr('selected');
$form.find('input:checkbox, input:radio').removeAttr('checked');
return this;
};
So now I can use it by calling:
$('#my-form').clear();
From here:
-Xmn : the size of the heap for the young generation
Young generation represents all the objects which have a short life of time. Young generation objects are in a specific location into the heap, where the garbage collector will pass often. All new objects are created into the young generation region (called "eden"). When an object survive is still "alive" after more than 2-3 gc cleaning, then it will be swap has an "old generation" : they are "survivor".
And a more "official" source from IBM:
-Xmn
Sets the initial and maximum size of the new (nursery) heap to the specified value when using -Xgcpolicy:gencon. Equivalent to setting both -Xmns and -Xmnx. If you set either -Xmns or -Xmnx, you cannot set -Xmn. If you attempt to set -Xmn with either -Xmns or -Xmnx, the VM will not start, returning an error. By default, -Xmn is selected internally according to your system's capability. You can use the -verbose:sizes option to find out the values that the VM is currently using.
I modified indgar's solution to handle negative numbers and small numbers (including zero).
from math import log10, floor
def round_sig(x, sig=6, small_value=1.0e-9):
return round(x, sig - int(floor(log10(max(abs(x), abs(small_value))))) - 1)
maybe you can try using
SELECT user_name
FROM user_master
WHERE upper(user_name) LIKE '%ME%'
Note the plural in this method:
document.getElementsByName()
That returns an array of elements, so use [0] to get the first occurence, e.g.
document.getElementsByName()[0]
try using the after()
method:
$('#bla').after('<div id="space"></div>');
If downgrading from pip version 10 because of PyCharm manage.py or other python errors:
python -m pip install pip==9.0.1
You first have to tell Gnuplot to use a style that uses points, e.g. with points
or with linespoints
. Try for example:
plot sin(x) with points
Output:
Now try:
plot sin(x) with points pointtype 5
Output:
You may also want to look at the output from the test
command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:
The problem is the Python module requests
. It can be fixed by
$ sudo apt-get purge python-requests
[now requests and pip gets deinstalled]
$ sudo apt-get install python-requests python-pip
If you have this problem with Python 3, you have to write python3
instead of python
.
I have done something like this and it's working for me
$('#fileInput').val(null);
You need to define propTypes
as a static getter if you want it inside the class declaration:
static get propTypes() {
return {
children: PropTypes.any,
onClickOut: PropTypes.func
};
}
If you want to define it as an object, you need to define it outside the class, like this:
IxClickOut.propTypes = {
children: PropTypes.any,
onClickOut: PropTypes.func,
};
Also it's better if you import prop types from prop-types
, not react
, otherwise you'll see warnings in console (as preparation for React 16):
import PropTypes from 'prop-types';