try {
String result = URLDecoder.decode(urlString, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Check out http://www.asciitable.com/
Look at the Hx
, (Hex) column; 2C
maps to ,
Any unusual encoding can be checked this way
+----+-----+----+-----+----+-----+----+-----+
| Hx | Chr | Hx | Chr | Hx | Chr | Hx | Chr |
+----+-----+----+-----+----+-----+----+-----+
| 00 | NUL | 20 | SPC | 40 | @ | 60 | ` |
| 01 | SOH | 21 | ! | 41 | A | 61 | a |
| 02 | STX | 22 | " | 42 | B | 62 | b |
| 03 | ETX | 23 | # | 43 | C | 63 | c |
| 04 | EOT | 24 | $ | 44 | D | 64 | d |
| 05 | ENQ | 25 | % | 45 | E | 65 | e |
| 06 | ACK | 26 | & | 46 | F | 66 | f |
| 07 | BEL | 27 | ' | 47 | G | 67 | g |
| 08 | BS | 28 | ( | 48 | H | 68 | h |
| 09 | TAB | 29 | ) | 49 | I | 69 | i |
| 0A | LF | 2A | * | 4A | J | 6A | j |
| 0B | VT | 2B | + | 4B | K | 6B | k |
| 0C | FF | 2C | , | 4C | L | 6C | l |
| 0D | CR | 2D | - | 4D | M | 6D | m |
| 0E | SO | 2E | . | 4E | N | 6E | n |
| 0F | SI | 2F | / | 4F | O | 6F | o |
| 10 | DLE | 30 | 0 | 50 | P | 70 | p |
| 11 | DC1 | 31 | 1 | 51 | Q | 71 | q |
| 12 | DC2 | 32 | 2 | 52 | R | 72 | r |
| 13 | DC3 | 33 | 3 | 53 | S | 73 | s |
| 14 | DC4 | 34 | 4 | 54 | T | 74 | t |
| 15 | NAK | 35 | 5 | 55 | U | 75 | u |
| 16 | SYN | 36 | 6 | 56 | V | 76 | v |
| 17 | ETB | 37 | 7 | 57 | W | 77 | w |
| 18 | CAN | 38 | 8 | 58 | X | 78 | x |
| 19 | EM | 39 | 9 | 59 | Y | 79 | y |
| 1A | SUB | 3A | : | 5A | Z | 7A | z |
| 1B | ESC | 3B | ; | 5B | [ | 7B | { |
| 1C | FS | 3C | < | 5C | \ | 7C | | |
| 1D | GS | 3D | = | 5D | ] | 7D | } |
| 1E | RS | 3E | > | 5E | ^ | 7E | ~ |
| 1F | US | 3F | ? | 5F | _ | 7F | DEL |
+----+-----+----+-----+----+-----+----+-----+
Replace %2F with %252F after url encoding
PHP
function custom_http_build_query($query=array()){
return str_replace('%2F','%252F', http_build_query($query));
}
Handle the request via htaccess
.htaccess
RewriteCond %{REQUEST_URI} ^(.*?)(%252F)(.*?)$ [NC]
RewriteRule . %1/%3 [R=301,L,NE]
Resources
When you are trying to visit a local filename through firefox browser, you have to force the file:\\\
protocol (http://en.wikipedia.org/wiki/File_URI_scheme) or else firefox will encode your space TWICE. Change the html snippet from this:
<img src="C:\Documents and Settings\screenshots\Image01.png"/>
to this:
<img src="file:\\\C:\Documents and Settings\screenshots\Image01.png"/>
or this:
<img src="file://C:\Documents and Settings\screenshots\Image01.png"/>
Then firefox is notified that this is a local filename, and it renders the image correctly in the browser, correctly encoding the string once.
Helpful link: http://support.mozilla.org/en-US/questions/900466
If you add it manual on html site, just replace:
&
With
&
Standard html code for &
well, the term "url encoded" is a bit vague, perhaps simple regex check will do the trick
$is_encoded = preg_match('~%[0-9A-F]{2}~i', $string);
According to the W3C (and they are the official source on these things), a space character in the query string (and in the query string only) may be encoded as either "%20
" or "+
". From the section "Query strings" under "Recommendations":
Within the query string, the plus sign is reserved as shorthand notation for a space. Therefore, real plus signs must be encoded. This method was used to make query URIs easier to pass in systems which did not allow spaces.
According to section 3.4 of RFC2396 which is the official specification on URIs in general, the "query" component is URL-dependent:
3.4. Query Component The query component is a string of information to be interpreted by the resource.
query = *uric
Within a query component, the characters ";", "/", "?", ":", "@", "&", "=", "+", ",", and "$" are reserved.
It is therefore a bug in the other software if it does not accept URLs with spaces in the query string encoded as "+
" characters.
As for the third part of your question, one way (though slightly ugly) to fix the output from URLEncoder.encode()
is to then call replaceAll("\\+","%20")
on the return value.
I would recommend %20
.
Are you hard-coding them?
This is not very consistent across languages, though.
If I'm not mistaken, in PHP urlencode()
treats spaces as +
whereas Python's urlencode()
treats them as %20
.
EDIT:
It seems I'm mistaken. Python's urlencode()
(at least in 2.7.2) uses quote_plus()
instead of quote()
and thus encodes spaces as "+".
It seems also that the W3C recommendation is the "+" as per here: http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1
And in fact, you can follow this interesting debate on Python's own issue tracker about what to use to encode spaces: http://bugs.python.org/issue13866.
EDIT #2:
I understand that the most common way of encoding " " is as "+", but just a note, it may be just me, but I find this a bit confusing:
import urllib
print(urllib.urlencode({' ' : '+ '})
>>> '+=%2B+'
I also spent quite some time with this issue, so that's my solution:
String urlString2Decode = "http://www.test.com/äüö/path with blanks/";
String decodedURL = URLDecoder.decode(urlString2Decode, "UTF-8");
URL url = new URL(decodedURL);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
String decodedURLAsString = uri.toASCIIString();
I believe spaces must be encoded as:
%20
when used inside URL path component+
when used inside URL query string component or form data (see 17.13.4 Form content types)The following example shows the correct use of rawurlencode
and urlencode
:
echo "http://example.com"
. "/category/" . rawurlencode("latest songs")
. "/search?q=" . urlencode("lady gaga");
Output:
http://example.com/category/latest%20songs/search?q=lady+gaga
What happens if you encode path and query string components the other way round? For the following example:
http://example.com/category/latest+songs/search?q=lady%20gaga
latest+songs
instead of latest songs
q
will contain lady gaga
I tried sudo apt install nginx-full. You will get all the required packages.
A related question has been asked before: What is “above-the-fold content” in Google Pagespeed?
Firstly you have to notice that this is all about 'mobile pages'.
So when I interpreted your question and screenshot correctly, then this is not for your site!
On the contrary - doing some of the things advised by Google in their guidelines will things make worse than better for 'normal' websites.
And not everything that comes from Google is the "holy grail" just because it comes from Google. And they themselves are not a good role model if you have a look at their HTML markup.
The best advice I could give you is:
Additionally why do you use different CSS files, rather than just one?
The additional request is worse than the small amount of data volume. And after the first request the CSS file is cached anyway.
The things one should always take care of are:
And don't puzzle your brain about how to get 100% of Google's PageSpeed Insights tool ...! ;-)
Addition 1: Here is the page on which Google shows us, what they recommend for Optimize CSS Delivery.
As said before, I don't think that this is neither realistic nor that it makes sense for a "normal" website! Because mainly when you have a responsive web design it is most certain that you use media queries and other layout styles. So if you are not gonna load your CSS first and in a blocking manner you'll get a FOUT (Flash Of Unstyled Text). I really do not believe that this is "better" than at least some more milliseconds to render the page!
Imho Google is starting a new "hype" (when I have a look at all the question about it here on Stackoverflow) ...!
We can define maximum pool size in following way:
<pool>
<min-pool-size>5</min-pool-size>
<max-pool-size>200</max-pool-size>
<prefill>true</prefill>
<use-strict-min>true</use-strict-min>
<flush-strategy>IdleConnections</flush-strategy>
</pool>
d = dict()
or
d = {}
or
import types
d = types.DictType.__new__(types.DictType, (), {})
Use --build-arg
with each argument.
If you are passing two argument then add --build-arg
with each argument like:
docker build \
-t essearch/ess-elasticsearch:1.7.6 \
--build-arg number_of_shards=5 \
--build-arg number_of_replicas=2 \
--no-cache .
If you want it one time & let system handle the rest (not dynamic) then do like this in your manifest file:
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name_full" > //This is my custom title name on activity. <- The question is about this one.
<intent-filter android:label="@string/app_launcher_name" > //This is my custom Icon title name (launcher name that you see in android apps/homescreen)
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Use the constructor that allows you to specify the year, month, day, hours, minutes, and seconds:
var dateNow = DateTime.Now;
var date = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day, 4, 5, 6);
This is years later, working on a legacy site... For the life of me I couldn't get the ->andWhere()
or ->expr()->in()
solutions working.
Finally looked in the Doctrine mongodb-odb repo and found some very revealing tests:
public function testQueryWhereIn()
{
$qb = $this->dm->createQueryBuilder('Documents\User');
$choices = array('a', 'b');
$qb->field('username')->in($choices);
$expected = [
'username' => ['$in' => $choices],
];
$this->assertSame($expected, $qb->getQueryArray());
}
It worked for me!
You can find the tests on github here. Useful for clarifying all sorts of nonsense.
Note: My setup is using Doctrine MongoDb ODM v1.0.dev as far as i can make out.
Through Boost you can do it >
std::vector<boost::any> vecobj;
boost::shared_ptr<string> sharedString1(new string("abcdxyz!"));
boost::shared_ptr<int> sharedint1(new int(10));
vecobj.push_back(sharedString1);
vecobj.push_back(sharedint1);
> for inserting different object type in your vector container. while for accessing you have to use any_cast, which works like dynamic_cast, hopes it will work for your need.
public static void main(String[] args) {
try {
File file = new File("test.txt");
System.out.println(file.length());
} catch (Exception e) {
}
}
First off: The variables a and b in the loops refer to numpy.ndarray
objects.
In the first loop, a = a + 1
is evaluated as follows: the __add__(self, other)
function of numpy.ndarray
is called. This creates a new object and hence, A is not modified. Afterwards, the variable a
is set to refer to the result.
In the second loop, no new object is created. The statement b += 1
calls the __iadd__(self, other)
function of numpy.ndarray
which modifies the ndarray
object in place to which b is referring to. Hence, B
is modified.
If the default value of
string
were the empty string, I would not have to test
Wrong! Changing the default value doesn't change the fact that it's a reference type and someone can still explicitly set the reference to be null
.
Additionally
Nullable<String>
would make sense.
True point. It would make more sense to not allow null
for any reference types, instead requiring Nullable<TheRefType>
for that feature.
So why did the designers of C# choose to use
null
as the default value of strings?
Consistency with other reference types. Now, why allow null
in reference types at all? Probably so that it feels like C, even though this is a questionable design decision in a language that also provides Nullable
.
In SQL Management Studio you can expand the columns in Object Explorer, then drag the Columns
tree item into a query window to get a comma separated list of columns.
You can also try this:
for %%a in (*) do echo %%a
Using a for
loop, you can echo
out all the file names of the current directory.
To print them directly from the console:
for %a in (*) do @echo %a
Also, you can use shelljs
plugin.
It's easy and it's cross-platform.
Install command:
npm install [-g] shelljs
What is shellJS
ShellJS is a portable (Windows/Linux/OS X) implementation of Unix shell commands on top of the Node.js API. You can use it to eliminate your shell script's dependency on Unix while still keeping its familiar and powerful commands. You can also install it globally so you can run it from outside Node projects - say goodbye to those gnarly Bash scripts!
An example of how it works:
var shell = require('shelljs');
if (!shell.which('git')) {
shell.echo('Sorry, this script requires git');
shell.exit(1);
}
// Copy files to release dir
shell.rm('-rf', 'out/Release');
shell.cp('-R', 'stuff/', 'out/Release');
// Replace macros in each .js file
shell.cd('lib');
shell.ls('*.js').forEach(function (file) {
shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file);
shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file);
shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file);
});
shell.cd('..');
// Run external tool synchronously
if (shell.exec('git commit -am "Auto-commit"').code !== 0) {
shell.echo('Error: Git commit failed');
shell.exit(1);
}
Also, you can use from the command line:
$ shx mkdir -p foo
$ shx touch foo/bar.txt
$ shx rm -rf foo
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 HikariCPI had this same problem but not necessarily relating to typescript, so I struggled a bit with these different options. I am making a very basic create-react-app using a specific module react-portal-tooltip,
getting similar error:
Could not find a declaration file for module 'react-portal-tooltip'. '/node_modules/react-portal-tooltip/lib/index.js' implicitly has an 'any' type. Try
npm install @types/react-portal-tooltip
if it exists or add a new declaration (.d.ts) file containingdeclare module 'react-portal-tooltip';
ts(7016)
I tried many steps first - adding various .d.ts
files, various npm installs.
But what eventually worked for me was touch src/declare_modules.d.ts
then in src/declare_modules.d.ts
:
declare module "react-portal-tooltip";
and in src/App.js
:
import ToolTip from 'react-portal-tooltip';
// import './declare_modules.d.ts'
I struggled a bit with the different locations to use this general 'declare module' strategy (I am very much a beginner) so I think this will work with different options but I am included paths for what worked work me.
I initially thought import './declare_modules.d.ts'
was necessary. Although now it seems like it isn't! But I am including the step in case it helps someone.
This is my first stackoverflow answer so I apologize for the scattered process here and hope it was still helpful! :)
First :
$ sudo gem install colored2
And,you should input your password
Then :
$ sudo gem update --system
Appear Updating rubygems-update ERROR: While executing gem ... (OpenSSL::SSL::SSLError) hostname "gems.ruby-china.org" does not match the server certificate
Then:
$ rvm -v
$ rvm get head
Last What language do you want to use?? [ Swift / ObjC ]
ObjC
Would you like to include a demo application with your library? [ Yes / No ]
Yes
Which testing frameworks will you use? [ Specta / Kiwi / None ]
None
Would you like to do view based testing? [ Yes / No ]
No
What is your class prefix?
XMG
Running pod install on your new library.
this
inside the step callback isn't the element but the object passed to animate()
$('.Count').each(function (_, self) {
jQuery({
Counter: 0
}).animate({
Counter: $(self).text()
}, {
duration: 1000,
easing: 'swing',
step: function () {
$(self).text(Math.ceil(this.Counter));
}
});
});
Another way to do this and keep the references to this
would be
$('.Count').each(function () {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 1000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
Put breakpoints - double click on the margin. Run > Debug > Yes (if dialog appears), then use commands from Run menu or shortcuts - F5, F6, F7, F8.
You can use jQuery's $.map
.
var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' },
keys = $.map(foo, function(v, i){
return i;
});
I have not tried in Selenium, but for Galen test this is working,
var list = driver.findElementByID("periodID"); // this will return web element
list.click(); // this will open the dropdown list.
list.typeText("14w"); // this will select option "14w".
You can try this in selenium, the galen and selenium working are similar.
To communicate a child component with another child component I've made a method in parent which calls a method in a child with:
this.$refs.childMethod()
And from the another child I've called the root method:
this.$root.theRootMethod()
It worked for me.
Did you try putting all your jars directly in the WEB-INF/lib
dir instead of sub-dirs of that?
No WEB-INF/lib/spring/org.springframework.aop-3.0.0.RELEASE.jar
, just WEB-INF/lib/org.springframework.aop-3.0.0.RELEASE.jar
Same with the rest of the jars.
Hai sridhar, I found an answer for your prob
ClientScript.RegisterClientScriptBlock(GetType(), "sas", "<script> alert('Inserted successfully');</script>", true);
change false to true
or try this
ScriptManager.RegisterClientScriptBlock(ursavebuttonID, typeof(LinkButton or button), "sas", "<script> alert('Inserted successfully');</script>", true);
Don't fear the Exception! Having your program just log and continue is as easy as:
try:
result = simulate(open("myfile"))
except SimulationException as sim_exc:
print "error parsing stream", sim_exc
else:
if result:
print "result pass"
else:
print "result fail"
# execution continues from here, regardless of exception or not
And now you can have a much richer type of notification from the simulate method as to what exactly went wrong, in case you find error/no-error not to be informative enough.
If using AngularJS 1.2 you can use 'track by' to tell Angular how to compare objects.
<select
ng-model="Choice.SelectedOption"
ng-options="choice.Name for choice in Choice.Options track by choice.ID">
</select>
Updated fiddle http://jsfiddle.net/gFCzV/34/
I had the same problem try this:
python manage.py sqlsequencereset table_name
Eg:
python manage.py sqlsequencereset auth
you need to run this in production settings(if you have) and you need Postgres installed to run this on the server
Here's a possible solution.
HTML
<img id="source" src="http://www.byui.edu/images/agriculture-life-sciences/flower.jpg" />
<div id="crop">
<img id="overlay" src="http://www.byui.edu/images/agriculture-life-sciences/flower.jpg" />
</div>
CSS
#crop {
overflow: hidden;
position: absolute;
left: 100px;
top: 100px;
width: 450px;
height: 150px;
}
#overlay {
-webkit-filter:blur(4px);
filter:blur(4px);
width: 450px;
}
#source {
height: 300px;
width: auto;
position: absolute;
left: 100px;
top: 100px;
}
I know the CSS can be simplified and you probably should get rid of the ids. The idea here is to use a div as a cropping container and then apply blur on duplicate of the image. Fiddle
To make this work in Firefox, you would have to use SVG hack.
One liner FTW. I like to keep it simple. Why not use one command that contains ALL the arguments needed? This is how I like it - this creates an x509 certificate and its PEM key:
openssl req -x509 \
-nodes -days 365 -newkey rsa:4096 \
-keyout self.key.pem \
-out self-x509.crt \
-subj "/C=US/ST=WA/L=Seattle/CN=example.com/[email protected]"
That single command contains all the answers you would normally provide for the certificate details. This way you can set the parameters and run the command, get your output - then go for coffee.
This should be a simple solution:
public void correctWidth(TextView textView, int desiredWidth)
{
Paint paint = new Paint();
Rect bounds = new Rect();
paint.setTypeface(textView.getTypeface());
float textSize = textView.getTextSize();
paint.setTextSize(textSize);
String text = textView.getText().toString();
paint.getTextBounds(text, 0, text.length(), bounds);
while (bounds.width() > desiredWidth)
{
textSize--;
paint.setTextSize(textSize);
paint.getTextBounds(text, 0, text.length(), bounds);
}
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
}
You should try this:
df_total = data.frame()
for (i in 1:7){
# vector output
model <- #some processing
# add vector to a dataframe
df <- data.frame(model)
df_total <- rbind(df_total,df)
}
First, if your file contains binary data, then using BufferedReader
would be a big mistake (because you would be converting the data to String, which is unnecessary and could easily corrupt the data); you should use a BufferedInputStream
instead. If it's text data and you need to split it along linebreaks, then using BufferedReader
is OK (assuming the file contains lines of a sensible length).
Regarding memory, there shouldn't be any problem if you use a decently sized buffer (I'd use at least 1MB to make sure the HD is doing mostly sequential reading and writing).
If speed turns out to be a problem, you could have a look at the java.nio
packages - those are supposedly faster than java.io
,
Use the (excellent) JSON-Java library from json.org then
JSONObject json = new JSONObject(str);
String xml = XML.toString(json);
toString
can take a second argument to provide the name of the XML root node.
This library is also able to convert XML to JSON using XML.toJSONObject(java.lang.String string)
Check the Javadoc
Link to the the github repository
POM
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160212</version>
</dependency>
original post updated with new links
Mixed Subtype
The "mixed" subtype of "multipart" is intended for use when the body parts are independent and need to be bundled in a particular order. Any "multipart" subtypes that an implementation does not recognize must be treated as being of subtype "mixed".
Alternative Subtype
The "multipart/alternative" type is syntactically identical to "multipart/mixed", but the semantics are different. In particular, each of the body parts is an "alternative" version of the same information
This is one of the ways:
String toDate = "05/11/2010";
if (new SimpleDateFormat("MM/dd/yyyy").parse(toDate).getTime() / (1000 * 60 * 60 * 24) >= System.currentTimeMillis() / (1000 * 60 * 60 * 24)) {
System.out.println("Display report.");
} else {
System.out.println("Don't display report.");
}
A bit more easy interpretable:
String toDateAsString = "05/11/2010";
Date toDate = new SimpleDateFormat("MM/dd/yyyy").parse(toDateAsString);
long toDateAsTimestamp = toDate.getTime();
long currentTimestamp = System.currentTimeMillis();
long getRidOfTime = 1000 * 60 * 60 * 24;
long toDateAsTimestampWithoutTime = toDateAsTimestamp / getRidOfTime;
long currentTimestampWithoutTime = currentTimestamp / getRidOfTime;
if (toDateAsTimestampWithoutTime >= currentTimestampWithoutTime) {
System.out.println("Display report.");
} else {
System.out.println("Don't display report.");
}
Oh, as a bonus, the JodaTime's variant:
String toDateAsString = "05/11/2010";
DateTime toDate = DateTimeFormat.forPattern("MM/dd/yyyy").parseDateTime(toDateAsString);
DateTime now = new DateTime();
if (!toDate.toLocalDate().isBefore(now.toLocalDate())) {
System.out.println("Display report.");
} else {
System.out.println("Don't display report.");
}
There are obviously several reasons why this might occur, and I thought I'd add the solution to my issue. (I have a java project into which I have imported files with virtual links)
If you have a situation like mine, you will have another folder on the same level as your 'src' folder. If you do, right-click on that other folder, then select 'Build Path' > 'Add to Build Path' (if you see 'Build Path' > 'Remove from Build Path', then it had already been added.)
To further configure the Build Path, right click on your top level project dir, and select 'Build Path' > 'Configure Build Path'. Your folders should show up in the 'Source' tab.
To configure what errors you see, Click on Java Compiler > Errors/Warnings and then click 'Configure Workspace Settings'. That is the same as going to Window > Preferences > Java > Compiler > Errors/Warnings. If you don't want Eclipse to ignore something, then just change it to Warning.
Well you are trying to compare Date with Nvarchar which is wrong. Should be
Where dates between date1 And date2
-- both date1 & date2 should be date/datetime
If date1,date2 strings; server will convert them to date type before filtering.
I would like to run an automation test in different environments.
So I add this to command maven command:
spring-boot:run -Drun.jvmArguments="-Dspring.profiles.active=productionEnv1"
Here is the link where I found the solution: [1]https://github.com/spring-projects/spring-boot/issues/1095
To differentiate between scroll up/down in jQuery, you could use:
var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){
var evt = window.event || e //equalize event object
evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible
var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF
if(delta > 0) {
//scroll up
}
else{
//scroll down
}
});
This method also works in divs that have overflow:hidden
.
I successfully tested it in FireFox, IE and Chrome.
You can use:
$("#tagscloud span").text("Your text here");
The same code will also work for the second case. You could also use:
$("#tagscloud #WebPartCaptionWPQ2").text("Your text here");
Quote from there:
the rules for index usage with LIKE are loosely like this:
If your filter criteria uses equals = and the field is indexed, then most likely it will use an INDEX/CLUSTERED INDEX SEEK
If your filter criteria uses LIKE, with no wildcards (like if you had a parameter in a web report that COULD have a % but you instead use the full string), it is about as likely as #1 to use the index. The increased cost is almost nothing.
If your filter criteria uses LIKE, but with a wildcard at the beginning (as in Name0 LIKE '%UTER') it's much less likely to use the index, but it still may at least perform an INDEX SCAN on a full or partial range of the index.
HOWEVER, if your filter criteria uses LIKE, but starts with a STRING FIRST and has wildcards somewhere AFTER that (as in Name0 LIKE 'COMP%ER'), then SQL may just use an INDEX SEEK to quickly find rows that have the same first starting characters, and then look through those rows for an exact match.
(Also keep in mind, the SQL engine still might not use an index the way you're expecting, depending on what else is going on in your query and what tables you're joining to. The SQL engine reserves the right to rewrite your query a little to get the data in a way that it thinks is most efficient and that may include an INDEX SCAN instead of an INDEX SEEK)
How about
Scanner scanner = new Scanner(result);
String line = scanner.nextLine();//will contain 34.1 -118.33
In SQL Plus:
SQL> create procedure myproc (prc out sys_refcursor)
2 is
3 begin
4 open prc for select * from emp;
5 end;
6 /
Procedure created.
SQL> var rc refcursor
SQL> execute myproc(:rc)
PL/SQL procedure successfully completed.
SQL> print rc
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ---------- --------- ---------- ----------- ---------- ---------- ----------
7839 KING PRESIDENT 17-NOV-1981 4999 10
7698 BLAKE MANAGER 7839 01-MAY-1981 2849 30
7782 CLARKE MANAGER 7839 09-JUN-1981 2449 10
7566 JONES MANAGER 7839 02-APR-1981 2974 20
7788 SCOTT ANALYST 7566 09-DEC-1982 2999 20
7902 FORD ANALYST 7566 03-DEC-1981 2999 20
7369 SMITHY CLERK 7902 17-DEC-1980 9988 11 20
7499 ALLEN SALESMAN 7698 20-FEB-1981 1599 3009 30
7521 WARDS SALESMAN 7698 22-FEB-1981 1249 551 30
7654 MARTIN SALESMAN 7698 28-SEP-1981 1249 1400 30
7844 TURNER SALESMAN 7698 08-SEP-1981 1499 0 30
7876 ADAMS CLERK 7788 12-JAN-1983 1099 20
7900 JAMES CLERK 7698 03-DEC-1981 949 30
7934 MILLER CLERK 7782 23-JAN-1982 1299 10
6668 Umberto CLERK 7566 11-JUN-2009 19999 0 10
9567 ALLBRIGHT ANALYST 7788 02-JUN-2009 76999 24 10
Change your return type to java.lang.Integer . This way you can safely return null
For anaconda installation, first pick a channel which has the latest version of tensorflow binary. Usually, the latest versions are available at the channel conda-forge
. Then simply do:
conda update -f -c conda-forge tensorflow
This will upgrade your existing tensorflow installation to the very latest version available. As of this writing, the latest version is 1.4.0-py36_0
For some reason you don't use jQuery nor ES6? This might help you:
var values = "Test,Prof,Off";_x000D_
var splitValues = values.split(',');_x000D_
var multi = document.getElementById('strings');_x000D_
_x000D_
multi.value = null; // Reset pre-selected options (just in case)_x000D_
var multiLen = multi.options.length;_x000D_
for (var i = 0; i < multiLen; i++) {_x000D_
if (splitValues.indexOf(multi.options[i].value) >= 0) {_x000D_
multi.options[i].selected = true;_x000D_
}_x000D_
}
_x000D_
<select name='strings' id="strings" multiple style="width:100px;">_x000D_
<option value="Test">Test</option>_x000D_
<option value="Prof">Prof</option>_x000D_
<option value="Live">Live</option>_x000D_
<option value="Off">Off</option>_x000D_
<option value="On" selected>On</option>_x000D_
</select>
_x000D_
You're looking for Path.GetFileName
.
Note that this won't work if the path ends in a \
.
This topic is discussed at CProgramming.com:
https://www.cprogramming.com/compilingandlinking.html
Here is what the author there wrote:
Compiling isn't quite the same as creating an executable file! Instead, creating an executable is a multistage process divided into two components: compilation and linking. In reality, even if a program "compiles fine" it might not actually work because of errors during the linking phase. The total process of going from source code files to an executable might better be referred to as a build.
Compilation
Compilation refers to the processing of source code files (.c, .cc, or .cpp) and the creation of an 'object' file. This step doesn't create anything the user can actually run. Instead, the compiler merely produces the machine language instructions that correspond to the source code file that was compiled. For instance, if you compile (but don't link) three separate files, you will have three object files created as output, each with the name .o or .obj (the extension will depend on your compiler). Each of these files contains a translation of your source code file into a machine language file -- but you can't run them yet! You need to turn them into executables your operating system can use. That's where the linker comes in.
Linking
Linking refers to the creation of a single executable file from multiple object files. In this step, it is common that the linker will complain about undefined functions (commonly, main itself). During compilation, if the compiler could not find the definition for a particular function, it would just assume that the function was defined in another file. If this isn't the case, there's no way the compiler would know -- it doesn't look at the contents of more than one file at a time. The linker, on the other hand, may look at multiple files and try to find references for the functions that weren't mentioned.
You might ask why there are separate compilation and linking steps. First, it's probably easier to implement things that way. The compiler does its thing, and the linker does its thing -- by keeping the functions separate, the complexity of the program is reduced. Another (more obvious) advantage is that this allows the creation of large programs without having to redo the compilation step every time a file is changed. Instead, using so called "conditional compilation", it is necessary to compile only those source files that have changed; for the rest, the object files are sufficient input for the linker. Finally, this makes it simple to implement libraries of pre-compiled code: just create object files and link them just like any other object file. (The fact that each file is compiled separately from information contained in other files, incidentally, is called the "separate compilation model".)
To get the full benefits of condition compilation, it's probably easier to get a program to help you than to try and remember which files you've changed since you last compiled. (You could, of course, just recompile every file that has a timestamp greater than the timestamp of the corresponding object file.) If you're working with an integrated development environment (IDE) it may already take care of this for you. If you're using command line tools, there's a nifty utility called make that comes with most *nix distributions. Along with conditional compilation, it has several other nice features for programming, such as allowing different compilations of your program -- for instance, if you have a version producing verbose output for debugging.
Knowing the difference between the compilation phase and the link phase can make it easier to hunt for bugs. Compiler errors are usually syntactic in nature -- a missing semicolon, an extra parenthesis. Linking errors usually have to do with missing or multiple definitions. If you get an error that a function or variable is defined multiple times from the linker, that's a good indication that the error is that two of your source code files have the same function or variable.
If you are on Rails 4 and you get this error, it could happen if you are using enum
on the model if you've defined with symbols like this:
class User
enum preferred_phone: [:home_phone, :mobile_phone, :work_phone]
end
The form will pass say a radio selector as a string param. That's what happened in my case. The simple fix is to change enum
to strings instead of symbols
enum preferred_phone: %w[home_phone mobile_phone work_phone]
# or more verbose
enum preferred_phone: ['home_phone', 'mobile_phone', 'work_phone']
You could decide to make use of a templating engine in your project, such as:
If you don't want to include another library, John Resig offers a jQuery solution, similar to the one below.
Browsers and screen readers ignore unrecognized script types:
<script id="hidden-template" type="text/x-custom-template">
<tr>
<td>Foo</td>
<td>Bar</td>
<tr>
</script>
Using jQuery, adding rows based on the template would resemble:
var template = $('#hidden-template').html();
$('button.addRow').click(function() {
$('#targetTable').append(template);
});
May be will be useful. Just all queries send via ws to node
<VirtualHost *:80>
ServerName www.domain2.com
<Location "/">
ProxyPass "ws://localhost:3001/"
</Location>
</VirtualHost>
With MSSQL you can do something like this:
declare @result varchar(500)
set @result = ''
select @result = @result + ModuleValue + ', '
from TableX where ModuleId = @ModuleId
You can do:
#!/bin/bash
if <command> ; then # TRY
<do-whatever-you-want>
else # CATCH
echo 'Exception'
<do-whatever-you-want>
fi
Add two bindings to your website, one for local access and another for LAN access like so:
Open IIS and select your local website (that you want to access from your local network) from the left panel:
Connections > server (user-pc) > sites > local site
Open Bindings on the right panel under Actions tab add these bindings:
Local:
Type: http Ip Address: All Unassigned Port: 80 Host name: samplesite.local
LAN:
Type: http Ip Address: <Network address of the hosting machine ex. 192.168.0.10> Port: 80 Host name: <Leave it blank>
Voila, you should be able to access the website from any machine on your local network by using the host's LAN IP address (192.168.0.10 in the above example) as the site url.
NOTE:
if you want to access the website from LAN using a host name (like samplesite.local) instead of an ip address, add the host name to the hosts file on the local network machine (The hosts file can be found in "C:\Windows\System32\drivers\etc\hosts" in windows, or "/etc/hosts" in ubuntu):
192.168.0.10 samplesite.local
I'm a lazy programmer. I don't use DOM because it seems like extra typing. To me, the less code the better. Here's how I would add "bar" without replacing "foo":
function start(){
var innermyspan = document.getElementById("myspan").innerHTML;
document.getElementById("myspan").innerHTML=innermyspan+"bar";
}
If you keep grabbing bits from your data, you might want to use a bitfield. You'll just have to set up a struct and load it with only ones and zeroes:
struct bitfield{
unsigned int bit : 1
}
struct bitfield *bitstream;
then later on load it like this (replacing char with int or whatever data you are loading):
long int i;
int j, k;
unsigned char c, d;
bitstream=malloc(sizeof(struct bitfield)*charstreamlength*sizeof(char));
for (i=0; i<charstreamlength; i++){
c=charstream[i];
for(j=0; j < sizeof(char)*8; j++){
d=c;
d=d>>(sizeof(char)*8-j-1);
d=d<<(sizeof(char)*8-1);
k=d;
if(k==0){
bitstream[sizeof(char)*8*i + j].bit=0;
}else{
bitstream[sizeof(char)*8*i + j].bit=1;
}
}
}
Then access elements:
bitstream[bitpointer].bit=...
or
...=bitstream[bitpointer].bit
All of this is assuming are working on i86/64, not arm, since arm can be big or little endian.
"+" instead of "."
Simple, You can see the below template and use it accordingly. Its very common to create a virtual host and very simple. Surely below template will work.
<VirtualHost *:8081>
DocumentRoot "C:/xampp/htdocs/testsite"
ServerName testsite.loc
ServerAlias www.testsite.loc
<Directory "c:/xampp/htdocs/testsite">
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
Also for more reference about virtual host please visit this site. http://www.thegeekstuff.com/2011/07/apache-virtual-host
Thanks,
Cyclic imports terminate, but you need to be careful not to use the cyclically-imported modules during module initialization.
Consider the following files:
a.py:
print "a in"
import sys
print "b imported: %s" % ("b" in sys.modules, )
import b
print "a out"
b.py:
print "b in"
import a
print "b out"
x = 3
If you execute a.py, you'll get the following:
$ python a.py
a in
b imported: False
b in
a in
b imported: True
a out
b out
a out
On the second import of b.py (in the second a in
), the Python interpreter does not import b
again, because it already exists in the module dict.
If you try to access b.x
from a
during module initialization, you will get an AttributeError
.
Append the following line to a.py
:
print b.x
Then, the output is:
$ python a.py
a in
b imported: False
b in
a in
b imported: True
a out
Traceback (most recent call last):
File "a.py", line 4, in <module>
import b
File "/home/shlomme/tmp/x/b.py", line 2, in <module>
import a
File "/home/shlomme/tmp/x/a.py", line 7, in <module>
print b.x
AttributeError: 'module' object has no attribute 'x'
This is because modules are executed on import and at the time b.x
is accessed, the line x = 3
has not be executed yet, which will only happen after b out
.
Solved my problem too when I activated my virtual environment using:
source bin/activate
<?php
$j=1;
?>
<script>
var i = "<?php echo $j; ?>";
//Do something
</script>
<?php
echo $j;
?>
This is the easiest way of passing a php variable to javascript without Ajax.
You can also use something like this:
var i = "<?php echo json_encode($j); ?>";
This said to be safer or more secure. i think
Alternatively, in plain text: (also available as a a screenshot)
Bracket Matching -. .- Line Numbering
Smart Indent -. | | .- UML Editing / Viewing
Source Control Integration -. | | | | .- Code Folding
Error Markup -. | | | | | | .- Code Templates
Integrated Python Debugging -. | | | | | | | | .- Unit Testing
Multi-Language Support -. | | | | | | | | | | .- GUI Designer (Qt, Eric, etc)
Auto Code Completion -. | | | | | | | | | | | | .- Integrated DB Support
Commercial/Free -. | | | | | | | | | | | | | | .- Refactoring
Cross Platform -. | | | | | | | | | | | | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Atom |Y |F |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y | | | | |*many plugins
Editra |Y |F |Y |Y | | |Y |Y |Y |Y | |Y | | | | | |
Emacs |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
Eric Ide |Y |F |Y | |Y |Y | |Y | |Y | |Y | |Y | | | |
Geany |Y |F |Y*|Y | | | |Y |Y |Y | |Y | | | | | |*very limited
Gedit |Y |F |Y¹|Y | | | |Y |Y |Y | | |Y²| | | | |¹with plugin; ²sort of
Idle |Y |F |Y | |Y | | |Y |Y | | | | | | | | |
IntelliJ |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |
JEdit |Y |F | |Y | | | | |Y |Y | |Y | | | | | |
KDevelop |Y |F |Y*|Y | | |Y |Y |Y |Y | |Y | | | | | |*no type inference
Komodo |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | |Y | |
NetBeans* |Y |F |Y |Y |Y | |Y |Y |Y |Y |Y |Y |Y |Y | | |Y |*pre-v7.0
Notepad++ |W |F |Y |Y | |Y*|Y*|Y*|Y |Y | |Y |Y*| | | | |*with plugin
Pfaide |W |C |Y |Y | | | |Y |Y |Y | |Y |Y | | | | |
PIDA |LW|F |Y |Y | | | |Y |Y |Y | |Y | | | | | |VIM based
PTVS |W |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y | | |Y*| |Y |*WPF bsed
PyCharm |Y |CF|Y |Y*|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |*JavaScript
PyDev (Eclipse) |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
PyScripter |W |F |Y | |Y |Y | |Y |Y |Y | |Y |Y |Y | | | |
PythonWin |W |F |Y | |Y | | |Y |Y | | |Y | | | | | |
SciTE |Y |F¹| |Y | |Y | |Y |Y |Y | |Y |Y | | | | |¹Mac version is
ScriptDev |W |C |Y |Y |Y |Y | |Y |Y |Y | |Y |Y | | | | | commercial
Spyder |Y |F |Y | |Y |Y | |Y |Y |Y | | | | | | | |
Sublime Text |Y |CF|Y |Y | |Y |Y |Y |Y |Y | |Y |Y |Y*| | | |extensible w/Python,
TextMate |M |F | |Y | | |Y |Y |Y |Y | |Y |Y | | | | | *PythonTestRunner
UliPad |Y |F |Y |Y |Y | | |Y |Y | | | |Y |Y | | | |
Vim |Y |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |
Visual Studio |W |CF|Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |Y |? |Y |
Visual Studio Code|Y |F |Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |? |? |Y |uses plugins
WingIde |Y |C |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |*support for C
Zeus |W |C | | | | |Y |Y |Y |Y | |Y |Y | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Cross Platform -' | | | | | | | | | | | | | | | |
Commercial/Free -' | | | | | | | | | | | | | | '- Refactoring
Auto Code Completion -' | | | | | | | | | | | | '- Integrated DB Support
Multi-Language Support -' | | | | | | | | | | '- GUI Designer (Qt, Eric, etc)
Integrated Python Debugging -' | | | | | | | | '- Unit Testing
Error Markup -' | | | | | | '- Code Templates
Source Control Integration -' | | | | '- Code Folding
Smart Indent -' | | '- UML Editing / Viewing
Bracket Matching -' '- Line Numbering
Acronyms used:
L - Linux
W - Windows
M - Mac
C - Commercial
F - Free
CF - Commercial with Free limited edition
? - To be confirmed
I don't mention basics like syntax highlighting as I expect these by default.
This is a just dry list reflecting your feedback and comments, I am not advocating any of these tools. I will keep updating this list as you keep posting your answers.
PS. Can you help me to add features of the above editors to the list (like auto-complete, debugging, etc.)?
We have a comprehensive wiki page for this question https://wiki.python.org/moin/IntegratedDevelopmentEnvironments
HTML ... tag can do that itself i.e. no PHP or java.
or see this post for complete detail on the above (with all options..).
You can stash
(save the changes in temporary box) then, back to master
branch HEAD.
$ git add .
$ git stash
$ git checkout master
Jump Over Commits Back and Forth:
Go to a specific commit-sha
.
$ git checkout <commit-sha>
If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.
# checkout a new branch, add, commit, push
$ git checkout -b <branch-name>
$ git add .
$ git commit -m 'Commit message'
$ git push origin HEAD # push the current branch to remote
$ git checkout master # back to master branch now
If you have changes in the specific commit and don't want to keep the changes, you can do stash
or reset
then checkout to master
(or, any other branch).
# stash
$ git add -A
$ git stash
$ git checkout master
# reset
$ git reset --hard HEAD
$ git checkout master
After checking out a specific commit if you have no uncommitted change(s) then, just back to master
or other
branch.
$ git status # see the changes
$ git checkout master
# or, shortcut
$ git checkout - # back to the previous state
just put Wait() to wait until task completed
GetInputReportViaInterruptTransfer().Wait();
import tkinter as tk
...
x = tk.Label(text='Hello', visible=True)
def visiblelabel(lb, visible):
lb.config(visible=visible)
visiblelabel(x, False) # Hide
visiblelabel(x, True) # Show
P.S. config
can change any attribute:
x.config(text='Hello') # Text: Hello
x.config(text='Bye', font=('Arial', 20, 'bold')) # Text: Bye, Font: Arial Bold 20
x.config(bg='red', fg='white') # Background: red, Foreground: white
It's a bypass of StringVar
, IntVar
etc.
Internet Explorer and Edge do not support some MP4 formats that Chrome does. You can use ffprobe
to see the exact MP4 format. In my case I have these two videos:
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'a.mp4':
Metadata:
major_brand : isom
minor_version : 512
compatible_brands: isomiso2avc1mp41
encoder : Lavf56.40.101
Duration: 00:00:12.10, start: 0.000000, bitrate: 287 kb/s
Stream #0:0(und): Video: h264 (High 4:4:4 Predictive) (avc1 / 0x31637661), yuv444p, 1000x1000 [SAR 1:1 DAR 1:1], 281 kb/s, 60 fps, 60 tbr, 15360 tbn, 120 tbc (default)
Metadata:
handler_name : VideoHandler
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'b.mp4':
Metadata:
major_brand : isom
minor_version : 512
compatible_brands: isomiso2avc1mp41
encoder : Lavf57.66.102
Duration: 00:00:33.83, start: 0.000000, bitrate: 505 kb/s
Stream #0:0(und): Video: h264 (Constrained Baseline) (avc1 / 0x31637661), yuv420p, 1280x680, 504 kb/s, 30 fps, 30 tbr, 15360 tbn, 60 tbc (default)
Metadata:
handler_name : VideoHandler
Both play fine in Chrome, but the first one fails in IE and Edge. The problem is that IE and Edge don't support yuv444. You can convert to a shittier colourspace like this:
ffmpeg -i input.mp4 -pix_fmt yuv420p output.mp4
What you suggest is impossible. You will always have collisions.
In order to map two objects to another single set, the mapped set must have a minimum size of the number of combinations expected:
Assuming a 32-bit integer, you have 2147483647 positive integers. Choosing two of these where order doesn't matter and with repetition yields 2305843008139952128 combinations. This does not fit nicely in the set of 32-bit integers.
You can, however fit this mapping in 61 bits. Using a 64-bit integer is probably easiest. Set the high word to the smaller integer and the low word to the larger one.
If you only need to read the file, I can suggest Large Text File Viewer. https://www.portablefreeware.com/?id=693
and also refer this
Text editor to open big (giant, huge, large) text files
else if you would like to make your own tool try this . i presume that you know filestream reader in c#
const int kilobyte = 1024;
const int megabyte = 1024 * kilobyte;
const int gigabyte = 1024 * megabyte;
public void ReadAndProcessLargeFile(string theFilename, long whereToStartReading = 0)
{
FileStream fileStream = new FileStream(theFilename, FileMode.Open, FileAccess.Read);
using (fileStream)
{
byte[] buffer = new byte[gigabyte];
fileStream.Seek(whereToStartReading, SeekOrigin.Begin);
int bytesRead = fileStream.Read(buffer, 0, buffer.Length);
while(bytesRead > 0)
{
ProcessChunk(buffer, bytesRead);
bytesRead = fileStream.Read(buffer, 0, buffer.Length);
}
}
}
private void ProcessChunk(byte[] buffer, int bytesRead)
{
// Do the processing here
}
refer this kindly
http://www.codeproject.com/Questions/543821/ReadplusBytesplusfromplusLargeplusBinaryplusfilepl
I ran into this problem when I simply mistyped my jdbc url in application.properties. Hope this helps someone: before:
spring.datasource.url=jdbc://localhost:3306/test
after:
spring.datasource.url=jdbc:mysql://localhost:3306/test
This already has good answers for most purposes, but I'll add mine which is more specific.
In English, normally when we alphabetise, we ignore the word "the" at the beginning of a phrase. So "The United States" would be ordered under "U" and not "T".
This does that for you.
It would probably be best to put these in categories.
// Sort an array of NSStrings alphabetically, ignoring the word "the" at the beginning of a string.
-(NSArray*) sortArrayAlphabeticallyIgnoringThes:(NSArray*) unsortedArray {
NSArray * sortedArray = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(NSString* a, NSString* b) {
//find the strings that will actually be compared for alphabetical ordering
NSString* firstStringToCompare = [self stringByRemovingPrecedingThe:a];
NSString* secondStringToCompare = [self stringByRemovingPrecedingThe:b];
return [firstStringToCompare compare:secondStringToCompare];
}];
return sortedArray;
}
// Remove "the"s, also removes preceding white spaces that are left as a result. Assumes no preceding whitespaces to start with. nb: Trailing white spaces will be deleted too.
-(NSString*) stringByRemovingPrecedingThe:(NSString*) originalString {
NSString* result;
if ([[originalString substringToIndex:3].lowercaseString isEqualToString:@"the"]) {
result = [[originalString substringFromIndex:3] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}
else {
result = originalString;
}
return result;
}
Here is the notes (from Brian Goetz book) I made, that might be of help to you
AtomicXXX classes
provide Non-blocking Compare-And-Swap implementation
Takes advantage of the support provide by hardware (the CMPXCHG instruction on Intel) When lots of threads are running through your code that uses these atomic concurrency API, they will scale much better than code which uses Object level monitors/synchronization. Since, Java's synchronization mechanisms makes code wait, when there are lots of threads running through your critical sections, a substantial amount of CPU time is spent in managing the synchronization mechanism itself (waiting, notifying, etc). Since the new API uses hardware level constructs (atomic variables) and wait and lock free algorithms to implement thread-safety, a lot more of CPU time is spent "doing stuff" rather than in managing synchronization.
not only offer better throughput, but they also provide greater resistance to liveness problems such as deadlock and priority inversion.
via Jquery filter() method:
http://jsfiddle.net/9n4e1agn/1/
HTML:
<button data-id='1'>One</button>
<button data-id='2'>Two</button>
JavaScript:
$(function() {
$('button').filter(function(){
return $(this).data("id") == 2}).css({background:'red'});
});
Not an answer here and more like a comment, sorry but I can't comment.
In node V10, you can use the flag --experimental-modules
to tell Nodejs you want to use import
. But your entry script should end with .mjs
.
Note this is still an experimental thing and should not be used in production.
// main.mjs
import utils from './utils.js'
utils.print();
// utils.js
module.exports={
print:function(){console.log('print called')}
}
It's very easy if you use Kotlin:
val textFile = File(cacheDir, "/text_file.txt")
val allText = textFile.readText()
println(allText)
From readText()
docs:
Gets the entire content of this file as a String using UTF-8 or specified charset. This method is not recommended on huge files. It has an internal limitation of 2 GB file size.
The difference between joins and include is that using the include statement generates a much larger SQL query loading into memory all the attributes from the other table(s).
For example, if you have a table full of comments and you use a :joins => users to pull in all the user information for sorting purposes, etc it will work fine and take less time than :include, but say you want to display the comment along with the users name, email, etc. To get the information using :joins, it will have to make separate SQL queries for each user it fetches, whereas if you used :include this information is ready for use.
Great example:
The Selenium
client bindings will try to locate the geckodriver
executable from the system PATH
. You will need to add the directory containing the executable to the system path.
On Unix systems you can do the following to append it to your system’s search path, if you’re using a bash-compatible shell:
export PATH=$PATH:/path/to/geckodriver
On Windows you need to update the Path system variable to add the full directory path to the executable. The principle is the same as on Unix.
All below configuration for launching latest firefox using any programming language binding is applicable for Selenium2
to enable Marionette explicitly. With Selenium 3.0 and later, you shouldn't need to do anything to use Marionette, as it's enabled by default.
To use Marionette in your tests you will need to update your desired capabilities to use it.
Java :
As exception is clearly saying you need to download latest geckodriver.exe
from here and set downloaded geckodriver.exe
path where it's exists in your computer as system property with with variable webdriver.gecko.driver
before initiating marionette driver and launching firefox as below :-
//if you didn't update the Path system variable to add the full directory path to the executable as above mentioned then doing this directly through code
System.setProperty("webdriver.gecko.driver", "path/to/geckodriver.exe");
//Now you can Initialize marionette driver to launch firefox
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
WebDriver driver = new MarionetteDriver(capabilities);
And for Selenium3
use as :-
WebDriver driver = new FirefoxDriver();
If you're still in trouble follow this link as well which would help you to solving your problem
.NET :
var driver = new FirefoxDriver(new FirefoxOptions());
Python :
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
caps = DesiredCapabilities.FIREFOX
# Tell the Python bindings to use Marionette.
# This will not be necessary in the future,
# when Selenium will auto-detect what remote end
# it is talking to.
caps["marionette"] = True
# Path to Firefox DevEdition or Nightly.
# Firefox 47 (stable) is currently not supported,
# and may give you a suboptimal experience.
#
# On Mac OS you must point to the binary executable
# inside the application package, such as
# /Applications/FirefoxNightly.app/Contents/MacOS/firefox-bin
caps["binary"] = "/usr/bin/firefox"
driver = webdriver.Firefox(capabilities=caps)
Ruby :
# Selenium 3 uses Marionette by default when firefox is specified
# Set Marionette in Selenium 2 by directly passing marionette: true
# You might need to specify an alternate path for the desired version of Firefox
Selenium::WebDriver::Firefox::Binary.path = "/path/to/firefox"
driver = Selenium::WebDriver.for :firefox, marionette: true
JavaScript (Node.js) :
const webdriver = require('selenium-webdriver');
const Capabilities = require('selenium-webdriver/lib/capabilities').Capabilities;
var capabilities = Capabilities.firefox();
// Tell the Node.js bindings to use Marionette.
// This will not be necessary in the future,
// when Selenium will auto-detect what remote end
// it is talking to.
capabilities.set('marionette', true);
var driver = new webdriver.Builder().withCapabilities(capabilities).build();
Using RemoteWebDriver
If you want to use RemoteWebDriver
in any language, this will allow you to use Marionette
in Selenium
Grid.
Python:
caps = DesiredCapabilities.FIREFOX
# Tell the Python bindings to use Marionette.
# This will not be necessary in the future,
# when Selenium will auto-detect what remote end
# it is talking to.
caps["marionette"] = True
driver = webdriver.Firefox(capabilities=caps)
Ruby :
# Selenium 3 uses Marionette by default when firefox is specified
# Set Marionette in Selenium 2 by using the Capabilities class
# You might need to specify an alternate path for the desired version of Firefox
caps = Selenium::WebDriver::Remote::Capabilities.firefox marionette: true, firefox_binary: "/path/to/firefox"
driver = Selenium::WebDriver.for :remote, desired_capabilities: caps
Java :
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
// Tell the Java bindings to use Marionette.
// This will not be necessary in the future,
// when Selenium will auto-detect what remote end
// it is talking to.
capabilities.setCapability("marionette", true);
WebDriver driver = new RemoteWebDriver(capabilities);
.NET
DesiredCapabilities capabilities = DesiredCapabilities.Firefox();
// Tell the .NET bindings to use Marionette.
// This will not be necessary in the future,
// when Selenium will auto-detect what remote end
// it is talking to.
capabilities.SetCapability("marionette", true);
var driver = new RemoteWebDriver(capabilities);
Note : Just like the other drivers available to Selenium from other browser vendors, Mozilla has released now an executable that will run alongside the browser. Follow this for more details.
You can download latest geckodriver executable to support latest firefox from here
If you want to retrieve POST data:
first_name = request.form.get("firstname")
If you want to retrieve GET (query string) data:
first_name = request.args.get("firstname")
Or if you don't care/know whether the value is in the query string or in the post data:
first_name = request.values.get("firstname")
request.values is a CombinedMultiDict that combines Dicts from request.form and request.args.
I had the same problem... I had to run it as a user.
00 * * * * root /usr/bin/php /var/virtual/hostname.nz/public_html/cronjob.php
UPDATE
`table1` AS `dest`,
(
SELECT
*
FROM
`table2`
WHERE
`id` = x
) AS `src`
SET
`dest`.`col1` = `src`.`col1`
WHERE
`dest`.`id` = x
;
Hope this works for you.
for those who expect a behaviour like the apache StringUtils.isBlank or Guava Strings.isNullOrEmpty :
if mystring and mystring.strip():
print "not blank string"
else:
print "blank string"
In Xcode 5 open the organizer (Window > Organizer) and select "Devices" at the top. Your plugged in device should show up on the left hand side. Drag the IPA file over to that device.
In Xcode 6 and Xcode 7 open Devices (Window > Devices). Again your device should show up in the left hand column. Drag the IPA file to the list of apps underneath "Installed Apps".
For iOS 9 devices, refer to this post on how to get the app running after doing this.
Executing git remote update
works for me.
Personally, I use something close from fubo's solution and it works well:
image.ScaleToFit(document.PageSize);
image.SetAbsolutePosition(0,0);
The answer is surprisingly simple - export the folder to itself! TortoiseSVN detects this special case and asks if you want to make the working copy unversioned. If you answer yes the control directories will be removed and you will have a plain, unversioned directory tree.
Its function depends on the builders that you have in your project (they can choose to interpret clean command however they like) and whether you have auto-build turned on. If auto-build is on, invoking clean is equivalent of a clean build. First artifacts are removed, then a full build is invoked. If auto-build is off, clean will remove the artifacts and stop. You can then invoke build manually later.
In my case I had a similar problem but with c ++ this in windows 10, the problem was solved by adding the environment variables (path) windows, the folder of the c ++ libraries, in my case I used the codeblock libraries:
C:\codeblocks\MinGW\bin
var elems = ['f', 'a','b','f', 'c','d','e','f','c'];
elems.sort();
elems.forEach(function (value, index, arr){
let first_index = arr.indexOf(value);
let last_index = arr.lastIndexOf(value);
if(first_index !== last_index){
console.log('Duplicate item in array ' + value);
}else{
console.log('unique items in array ' + value);
}
});
Just use onChange event of the <select>
object.
Selected value is in e.target.value
then.
By the way, it's a bad practice to use id="..."
. It's better to use ref=">.."
http://facebook.github.io/react/docs/more-about-refs.html
There are several ways. One way is to use save()
to save the exact object. e.g. for data frame foo
:
save(foo,file="data.Rda")
Then load it with:
load("data.Rda")
You could also use write.table()
or something like that to save the table in plain text, or dput()
to obtain R code to reproduce the table.
A bit different opinion instead of storing the Fragments yourself just leave it to the FragmentManager and when you need to do something with the fragments look for them in the FragmentManager:
//make sure you have the right FragmentManager
//getSupportFragmentManager or getChildFragmentManager depending on what you are using to manage this stack of fragments
List<Fragment> fragments = fragmentManager.getFragments();
if(fragments != null) {
int count = fragments.size();
for (int x = 0; x < count; x++) {
Fragment fragment = fragments.get(x);
//check if this is the fragment we want,
//it may be some other inspection, tag etc.
if (fragment instanceof MyFragment) {
//do whatever we need to do with it
}
}
}
If you have a lot of Fragments and the cost of instanceof check may be not what you want, but it is good thing to have in mind that the FragmentManager already keeps account of Fragments.
grep -v
is your friend:
grep --help | grep invert
-v, --invert-match select non-matching lines
Also check out the related -L
(the complement of -l
).
-L, --files-without-match only print FILE names containing no match
That is very odd.
I went through ItemNotFoundException
's base classes and tested the following multiple catch
es to see what would catch it:
try {
remove-item C:\nonexistent\file.txt -erroraction stop
}
catch [System.Management.Automation.ItemNotFoundException] {
write-host 'ItemNotFound'
}
catch [System.Management.Automation.SessionStateException] {
write-host 'SessionState'
}
catch [System.Management.Automation.RuntimeException] {
write-host 'RuntimeException'
}
catch [System.SystemException] {
write-host 'SystemException'
}
catch [System.Exception] {
write-host 'Exception'
}
catch {
write-host 'well, darn'
}
As it turns out, the output was 'RuntimeException'
. I also tried it with a different exception CommandNotFoundException
:
try {
do-nonexistent-command
}
catch [System.Management.Automation.CommandNotFoundException] {
write-host 'CommandNotFoundException'
}
catch {
write-host 'well, darn'
}
That output 'CommandNotFoundException'
correctly.
I vaguely remember reading elsewhere (though I couldn't find it again) of problems with this. In such cases where exception filtering didn't work correctly, they would catch the closest Type
they could and then use a switch
. The following just catches Exception
instead of RuntimeException
, but is the switch
equivalent of my first example that checks all base types of ItemNotFoundException
:
try {
Remove-Item C:\nonexistent\file.txt -ErrorAction Stop
}
catch [System.Exception] {
switch($_.Exception.GetType().FullName) {
'System.Management.Automation.ItemNotFoundException' {
write-host 'ItemNotFound'
}
'System.Management.Automation.SessionStateException' {
write-host 'SessionState'
}
'System.Management.Automation.RuntimeException' {
write-host 'RuntimeException'
}
'System.SystemException' {
write-host 'SystemException'
}
'System.Exception' {
write-host 'Exception'
}
default {'well, darn'}
}
}
This writes 'ItemNotFound'
, as it should.
In Android starting from API level 21, items in the layout file get their Z order both from how they are ordered within the file, as described in correct answer, and from their elevation, a higher elevation value means the item gets a higher Z order.
This can sometimes cause problems, especially with buttons that often appear on top of items that according to the order of the XML should be below them in Z order. To fix this just set the android:elevation
of the the items in your layout XML to match the Z order you want to achieve.
I you set an elevation of an element in the layout it will start to cast a shadow. If you don't want this effect you can remove the shadow with code like so:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
myView.setOutlineProvider(null);
}
I haven't found any way to remove the shadow of a elevated view through the layout xml.
You can try this
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
Or
You can also try following
Add following line at top of your .py file.
# -*- coding: utf-8 -*-
when you use Interface Builder, you can use Connections Inspector to set up the events with event handlers, the event handlers are supposed to be the functions that have the IBAction modifier. A view can be linked with the reference for the same type and with the IBOutlet modifier.
That is not changing due to the default theme set to the screen.
So just change them for the widget you are drawing by wrapping your TextField with new ThemeData()
child: new Theme(
data: new ThemeData(
primaryColor: Colors.redAccent,
primaryColorDark: Colors.red,
),
child: new TextField(
decoration: new InputDecoration(
border: new OutlineInputBorder(
borderSide: new BorderSide(color: Colors.teal)),
hintText: 'Tell us about yourself',
helperText: 'Keep it short, this is just a demo.',
labelText: 'Life story',
prefixIcon: const Icon(
Icons.person,
color: Colors.green,
),
prefixText: ' ',
suffixText: 'USD',
suffixStyle: const TextStyle(color: Colors.green)),
),
));
Change your subplot settings to:
plt.subplot(1, 2, 1)
...
plt.subplot(1, 2, 2)
The parameters for subplot
are: number of rows, number of columns, and which subplot you're currently on. So 1, 2, 1
means "a 1-row, 2-column figure: go to the first subplot." Then 1, 2, 2
means "a 1-row, 2-column figure: go to the second subplot."
You currently are asking for a 2-row, 1-column (that is, one atop the other) layout. You need to ask for a 1-row, 2-column layout instead. When you do, the result will be:
In order to minimize the overlap of subplots, you might want to kick in a:
plt.tight_layout()
before the show. Yielding:
To do it in PHP: You have a couple of parameters to view your page, lets say action
and view-all
. You will (probably) access these already with $action = $_GET['action']
or whatever, maybe setting a default value.
Then you decide depending on that if you want to swich a variable like $viewAll = $viewAll == 'Yes' ? 'No' : 'Yes'
.
And in the end you just build the url with these values again like
$clickUrl = $_SERVER['PHP_SELF'] . '?action=' . $action . '&view-all=' . $viewAll;
And thats it.
So you depend on the page status and not the users url (because maybe you decide later that $viewAll is Yes as default or whatever).
In Android the visual design is stored in XML files and each Activity is associated to a design.
setContentView(R.layout.main)
R
means Resource
layout
means design
main
is the xml you have created under res->layout->main.xml
Whenever you want to change the current look of an Activity or when you move from one Activity to another, the new Activity must have a design to show. We call setContentView
in onCreate with the desired design as argument.
It's possible that you've run out of memory or some space elsewhere and it prompted the system to mount an overflow filesystem, and for whatever reason, it's not going away.
Try unmounting the overflow partition:
umount /tmp
or
umount overflow
The solution i'm using is as follows and allows you to set the active class per php page.
Give each of your menu items a unique class, i use .nav-x
(nav-about, here).
<li class="nav-item nav-about">
<a class="nav-link" href="about.php">About</a>
</li>
At the top of each page (about.php here):
<!-- Navbar Active Class -->
<?php $activeClass = '.nav-about > a'; ?>
Elsewhere (header.php / index.php):
<style>
<?php echo $activeClass; ?> {
color: #fff !important;
}
</style>
Simply change the .nav-about > a
per page, .nav-forum > a
, for example.
If you want different styling (colors etc) for each nav item, just attach the inline styling to that page instead of the index / header page.
There are 2 options to find matching text; string.match
or string.find
.
Both of these perform a regex search on the string to find matches.
string.find()
string.find(subject string, pattern string, optional start position, optional plain flag)
Returns the startIndex
& endIndex
of the substring found.
The plain
flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger)
being interpreted as a regex capture group matching for tiger
, it instead looks for (tiger)
within a string.
Going the other way, if you want to regex match but still want literal special characters (such as .()[]+-
etc.), you can escape them with a percentage; %(tiger%)
.
You will likely use this in combination with string.sub
str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
print ("The word tiger was found.")
else
print ("The word tiger was not found.")
end
string.match()
string.match(s, pattern, optional index)
Returns the capture groups found.
str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
print ("The word tiger was found.")
else
print ("The word tiger was not found.")
end
Just try this code:
start "" "C:\Users\DiPesh\Desktop\vbscript\welcome.vbs"
and save as .bat, it works for me
The (^) XOR operator generates 1 when it is applied on two different bits (0 and 1). It generates 0 when it is applied on two same bits (0 and 0 or 1 and 1).
Maybe a slightly tighter version? My use case is outputting college majors given a json array of majors (data).
var count_data = data.length;
$.each( data, function( index ){
var column = ( index < count_data/2 ) ? 1 : 2;
$("#column"+column).append(this.name+'<br/>');
});
<div id="majors_view" class="span12 pull-left">
<div class="row-fluid">
<div class="span5" id="column1"> </div>
<div class="span5 offset1" id="column2"> </div>
</div>
</div>
Another method utilizing the dplyr package:
library(dplyr)
df <- mtcars %>%
filter(mpg > 25)
Without the chain (%>%) operator:
library(dplyr)
df <- filter(mtcars, mpg > 25)
Presumably no one is forcing you to use a DI container framework. You're already using DI to decouple your classes and improve testability, so you're getting many of the benefits. In short, you're favoring simplicity, which is generally a good thing.
If your system reaches a level of complexity where manual DI becomes a chore (that is, increases maintenance), weigh that against the team learning curve of a DI container framework.
If you need more control over dependency lifetime management (that is, if you feel the need to implement the Singleton pattern), look at DI containers.
If you use a DI container, use only the features you need. Skip the XML configuration file and configure it in code if that is sufficient. Stick to constructor injection. The basics of Unity or StructureMap can be condensed down to a couple of pages.
There's a great blog post by Mark Seemann on this: When to use a DI Container
I struggled a bit with the answers on this question and didn't have much luck with the answers in a similar SO post either. So this is what worked for me - bearing in mind that in my case, the submodule was maintained by a different team, so the conflict came from different submodule versions in master and my local branch of the project I was working on:
git status
- make a note of the submodule folder with conflictsReset the submodule to the version that was last committed in the current branch:
git reset HEAD path/to/submodule
At this point, you have a conflict-free version of your submodule which you can now update to the latest version in the submodule's repository:
cd path/to/submodule git submodule foreach git pull origin SUBMODULE-BRANCH-NAME
And now you can commit
that and get back to work.
const buildSortedQuery = (args) => {_x000D_
return Object.keys(args)_x000D_
.sort()_x000D_
.map(key => {_x000D_
return window.encodeURIComponent(key)_x000D_
+ '='_x000D_
+ window.encodeURIComponent(args[key]);_x000D_
})_x000D_
.join('&');_x000D_
};_x000D_
_x000D_
console.log(buildSortedQuery({_x000D_
foo: "hi there",_x000D_
bar: "100%"_x000D_
}));_x000D_
_x000D_
//bar=100%25&foo=hi%20there
_x000D_
$where = "name='Joe' AND status='boss' OR status='active'";
$this->db->where($where);
Though I am 3/4 of a month late, you still execute the following after your where clauses are defined... $this->db->get("tbl_name");
If all you really care about is the actual query (the last one run) for quick debugging purposes:
DB::enableQueryLog();
# your laravel query builder goes here
$laQuery = DB::getQueryLog();
$lcWhatYouWant = $laQuery[0]['query']; # <-------
# optionally disable the query log:
DB::disableQueryLog();
do a print_r()
on $laQuery[0]
to get the full query, including the bindings. (the $lcWhatYouWant
variable above will have the variables replaced with ??
)
If you're using something other than the main mysql connection, you'll need to use these instead:
DB::connection("mysql2")->enableQueryLog();
DB::connection("mysql2")->getQueryLog();
(with your connection name where "mysql2" is)
In a nutshell, the syntax for Bower version numbers (and NPM's) is called SemVer, which is short for 'Semantic Versioning'. You can find documentation for the detailed syntax of SemVer as used in Bower and NPM on the API for the semver parser within Node/npm. You can learn more about the underlying spec (which does not mention ~
or other syntax details) at semver.org.
There's a super-handy visual semver calculator you can play with, making all of this much easier to grok and test.
SemVer isn't just a syntax! It has some pretty interesting things to say about the right ways to publish API's, which will help to understand what the syntax means. Crucially:
Once you identify your public API, you communicate changes to it with specific increments to your version number. Consider a version format of X.Y.Z (Major.Minor.Patch). Bug fixes not affecting the API increment the patch version, backwards compatible API additions/changes increment the minor version, and backwards incompatible API changes increment the major version.
So, your specific question about ~
relates to that Major.Minor.Patch schema. (As does the related caret operator ^
.) You can use ~
to narrow the range of versions you're willing to accept to either:
For example: to indicate you'll take any subsequent patch-level changes on the 1.2.x tree, starting with 1.2.0, but less than 1.3.0, you could use:
"angular": "~1.2"
or:
"angular": "~1.2.0"
This also gets you the same results as using the .x
syntax:
"angular": "1.2.x"
But, you can use the tilde/~
syntax to be even more specific: if you're only willing to accept patch-level changes starting with 1.2.4, but still less than 1.3.0, you'd use:
"angular": "~1.2.4"
Moving left, towards the major version, if you use...
"angular": "~1"
... it's the same as...
"angular": "1.x"
or:
"angular": "^1.0.0"
...and matches any minor- or patch-level changes above 1.0.0, and less than 2.0:
Note that last variation above: it's called a 'caret range'. The caret looks an awful lot like a >
, so you'd be excused for thinking it means "any version greater than 1.0.0". (I've certainly slipped on that.) Nope!
Caret ranges are basically used to say that you care only about the left-most significant digit - usually the major version - and that you'll permit any minor- or patch-level changes that don't affect that left-most digit. Yet, unlike a tilde range that specifies a major version, caret ranges let you specify a precise minor/patch starting point. So, while ^1.0.0 === ~1
, a caret range such as ^1.2.3
lets you say you'll take any changes >=1.2.3 && <2.0.0
. You couldn't do that with a tilde range.
That all seems confusing at first, when you look at it up-close. But zoom out for a sec, and think about it this way: the caret simply lets you say that you're most concerned about whatever significant digit is left-most. The tilde lets you say you're most concerned about whichever digit is right-most. The rest is detail.
It's the expressive power of the tilde and the caret that explains why people use them much more than the simpler .x
syntax: they simply let you do more. That's why you'll see the tilde used often even where .x
would serve. As an example, see npm itself: its own package.json file includes lots of dependencies in ~2.4.0
format, rather than the 2.4.x
format it could use. By sticking to ~
, the syntax is consistent all the way down a list of 70+ versioned dependencies, regardless of which beginning patch number is acceptable.
Anyway, there's still more to SemVer, but I won't try to detail it all here. Check it out on the node semver package's readme. And be sure to use the semantic versioning calculator while you're practicing and trying to get your head around how SemVer works.
RE: Non-Consecutive Version Numbers: OP's final question seems to be about specifying non-consecutive version numbers/ranges (if I have edited it fairly). Yes, you can do that, using the common double-pipe "or" operator: ||
. Like so:
"angular": "1.2 <= 1.2.9 || >2.0.0"
I ran into the same problem because I set the http_proxy and https_proxy environment variables. But occasionally, I connect to a different network and need to bypass the proxy temporarily. The easiest way to do this (without changing the environment variables) is:
curl --noproxy '*' stackoverflow.com
From the manual: "The only wildcard is a single * character, which matches all hosts, and effectively disables the proxy."
The * character is quoted so that it is not erroneously expanded by the shell.
If you set LD_PRELOAD
to the path of a shared object, that file will be loaded before any other library (including the C runtime, libc.so
). So to run ls
with your special malloc()
implementation, do this:
$ LD_PRELOAD=/path/to/my/malloc.so /bin/ls
This is a FAQ:
//somexpression[$N]
means "Find every node selected by //somexpression
that is the $N
th child of its parent".
What you want is:
(//input[@id="search_query"])[2]
Remember: The []
operator has higher precedence (priority) than the //
abbreviation.
Neither main()
or void main()
are standard C. The former is allowed as it has an implicit int
return value, making it the same as int main()
. The purpose of main
's return value is to return an exit status to the operating system.
In standard C, the only valid signatures for main
are:
int main(void)
and
int main(int argc, char **argv)
The form you're using: int main()
is an old style declaration that indicates main
takes an unspecified number of arguments. Don't use it - choose one of those above.
Here's an alternative custom function approach:
function Test-TernaryOperatorCondition {
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline = $true, Mandatory = $true)]
[bool]$ConditionResult
,
[Parameter(Mandatory = $true, Position = 0)]
[PSObject]$ValueIfTrue
,
[Parameter(Mandatory = $true, Position = 1)]
[ValidateSet(':')]
[char]$Colon
,
[Parameter(Mandatory = $true, Position = 2)]
[PSObject]$ValueIfFalse
)
process {
if ($ConditionResult) {
$ValueIfTrue
}
else {
$ValueIfFalse
}
}
}
set-alias -Name '???' -Value 'Test-TernaryOperatorCondition'
Example
1 -eq 1 |??? 'match' : 'nomatch'
1 -eq 2 |??? 'match' : 'nomatch'
Differences Explained
?
character is already an alias for Where-Object
.??
is used in other languages as a null coalescing operator, and I wanted to avoid confusion.-2..2 |??? 'match' : 'nomatch'
gives: match, match, nomatch, match, match
(i.e. since any non-zero int evaluates to true
; whilst zero evaluates to false
).([bool](-2..2)) |??? 'match' : 'nomatch'
(or simply: [bool](-2..2) |??? 'match' : 'nomatch'
)A handy post explaining several mis-understandings about this:
Don't Call The Destructor explicitly
This covers several misconceptions about how the destructor works. Calling it explicitly will not actually destroy your variable, according to the PHP5 doc:
PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence.
The post above does state that setting the variable to null can work in some cases, as long as nothing else is pointing to the allocated memory.
In my case, the problem was that I was building on a, older virtual machine which was based on Win7.
I found this fix from https://github.com/NuGet/NuGetGallery/issues/8176#issuecomment-683923724 :
nuget.org started enforcing the use of TLS 1.2 (and dropped support for TLS 1.1 and 1.0) earlier this year. Windows 7 has TLS 1.2 disabled by default (check the
DisabledByDefault
value underHKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client
in your registry). To enable the support, please make sure you have an update (*) installed and switch the support on:reg add HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client" /v DisabledByDefault /t REG_DWORD /d 0 /f /reg:32 reg add "HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client" /v DisabledByDefault /t REG_DWORD /d 0 /f /reg:64 reg add "HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client" /v Enabled /t REG_DWORD /d 1 /f /reg:32 reg add "HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client" /v Enabled /t REG_DWORD /d 1 /f /reg:64
The (*) update referred to was Microsoft kb3140245: Update for Windows 7 (KB3140245)
I installed the update, rebooted (as requested by the update), added those registry keys, and then Nuget worked fine.
Use float-right
for block elements, or text-right
for inline elements:
<div class="row">
<div class="col">left</div>
<div class="col text-right">inline content needs to be right aligned</div>
</div>
<div class="row">
<div class="col">left</div>
<div class="col">
<div class="float-right">element needs to be right aligned</div>
</div>
</div>
http://www.codeply.com/go/oPTBdCw1JV
If float-right
is not working, remember that Bootstrap 4 is now flexbox, and many elements are display:flex
which can prevent float-right
from working.
In some cases, the utility classes like align-self-end
or ml-auto
work to right align elements that are inside a flexbox container like the Bootstrap 4 .row, Card or Nav. The ml-auto
(margin-left:auto) is used in a flexbox element to push elements to the right.
I had the same problem. I tried all sorts of things. And I came to know that
Things I did:
Project properties >> Java Build Path >> Source
This solved the error.
Set the max-width:1250px;
that is currently on your body on your #container. This way your header will be 100% of his parent (body) :)
Add the following 2 lines
var regex = new Regex(Regex.Escape(","));
sb_trim = regex.Replace(sb_trim, " ", 1);
If sb_trim= John,Smith,100000,M the above code will return "John Smith,100000,M"
A naive, CPU-intensive method to block execution for a number of milliseconds:
/**
* Delay for a number of milliseconds
*/
function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() < start + delay);
}
Check the unsaved values for your primary key/Object ID in your hbm files. If you have automated ID creation by hibernate framework and you are setting the ID somewhere it will throw this error.By default the unsaved value is 0, so if you set the ID to 0 you will see this error.
Replace the line in htpasswd file:
Go to: http://www.htaccesstools.com/htpasswd-generator-windows/
(If the link is expired, search another generator from google.com.)
Enter your username and password. The site will generate an encrypted line. Copy that line and replace it with the previous line in the file "repo/htpasswd".
You might also need to Clear the 'Authentication data' from TortoiseSVN ? Settings ? Saved Data.
**model.ts**
export class Item {
private key: JSON;
constructor(jsonItem: any) {
this.key = jsonItem;
}
}
**service.ts**
import { Item } from '../model/items';
export class ItemService {
items: Item;
constructor() {
this.items = new Item({
'logo': 'Logo',
'home': 'Home',
'about': 'About',
'contact': 'Contact',
});
}
getItems(): Item {
return this.items;
}
}
you don't, declare an interface that declares the methods you would like to call:
public interface MyInterface
{
void doStuff();
}
public class MyClass implements MyInterface
{
public void doStuff()
{
System.Console.Writeln("done!");
}
}
then you use
MyInterface mobj = (myInterface)obj;
mobj.doStuff();
If MyClass
is not under your control then you can't make it implement some interface, and the other option is to rely on reflection (see this tutorial).
Always keep in mind that 'size' is variable if not explicitly specified so if you declare
int i = 10;
On some systems it may result in 16-bit integer by compiler and on some others it may result in 32-bit integer (or 64-bit integer on newer systems).
In embedded environments this may end up in weird results (especially while handling memory mapped I/O or may be consider a simple array situation), so it is highly recommended to specify fixed size variables. In legacy systems you may come across
typedef short INT16;
typedef int INT32;
typedef long INT64;
Starting from C99, the designers added stdint.h header file that essentially leverages similar typedefs.
On a windows based system, you may see entries in stdin.h header file as
typedef signed char int8_t;
typedef signed short int16_t;
typedef signed int int32_t;
typedef unsigned char uint8_t;
There is quite more to that like minimum width integer or exact width integer types, I think it is not a bad thing to explore stdint.h for a better understanding.
Try this
$('#testID').addClass('nameOfClass');
or
$('#testID').removeClass('nameOfClass');
Sample DF:
In [79]: df = pd.DataFrame(np.random.randint(5, 15, (10, 3)), columns=list('abc'))
In [80]: df
Out[80]:
a b c
0 6 11 11
1 14 7 8
2 13 5 11
3 13 7 11
4 13 5 9
5 5 11 9
6 9 8 6
7 5 11 10
8 8 10 14
9 7 14 13
present only those rows where b > 10
In [81]: df[df.b > 10]
Out[81]:
a b c
0 6 11 11
5 5 11 9
7 5 11 10
9 7 14 13
Minimums (for all columns) for the rows satisfying b > 10
condition
In [82]: df[df.b > 10].min()
Out[82]:
a 5
b 11
c 9
dtype: int32
Minimum (for the b
column) for the rows satisfying b > 10
condition
In [84]: df.loc[df.b > 10, 'b'].min()
Out[84]: 11
UPDATE: starting from Pandas 0.20.1 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.
If it is all a list of lists, you could modify sir @Raymond's answer
L = [ [None], [123], [None], [151] ]
no_none_val = list(filter(None.__ne__, [x[0] for x in L] ) )
for python 2 however
no_none_val = [x[0] for x in L if x[0] is not None]
""" Both returns [123, 151]"""
<< list_indice[0] for variable in List if variable is not None >>
try using ConnectivityManager
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false
Also Add permission to AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
In the context of Ektron, this issue is resolved by installing the "IIS6 Metabase compatibility" feature in Windows:
Check 'Windows features' or 'Role Services' for IIS6 Metabase compatibility, add if missing:
If you have to ask this question then you're probably unfamiliar with what most web applications/services do. You're probably thinking that all software do this:
user do an action
¦
v
application start processing action
+--> loop ...
+--> busy processing
end loop
+--> send result to user
However, this is not how web applications, or indeed any application with a database as the back-end, work. Web apps do this:
user do an action
¦
v
application start processing action
+--> make database request
+--> do nothing until request completes
request complete
+--> send result to user
In this scenario, the software spend most of its running time using 0% CPU time waiting for the database to return.
Multithreaded network apps handle the above workload like this:
request --> spawn thread
+--> wait for database request
+--> answer request
request --> spawn thread
+--> wait for database request
+--> answer request
request --> spawn thread
+--> wait for database request
+--> answer request
So the thread spend most of their time using 0% CPU waiting for the database to return data. While doing so they have had to allocate the memory required for a thread which includes a completely separate program stack for each thread etc. Also, they would have to start a thread which while is not as expensive as starting a full process is still not exactly cheap.
Since we spend most of our time using 0% CPU, why not run some code when we're not using CPU? That way, each request will still get the same amount of CPU time as multithreaded applications but we don't need to start a thread. So we do this:
request --> make database request
request --> make database request
request --> make database request
database request complete --> send response
database request complete --> send response
database request complete --> send response
In practice both approaches return data with roughly the same latency since it's the database response time that dominates the processing.
The main advantage here is that we don't need to spawn a new thread so we don't need to do lots and lots of malloc which would slow us down.
The seemingly mysterious thing is how both the approaches above manage to run workload in "parallel"? The answer is that the database is threaded. So our single-threaded app is actually leveraging the multi-threaded behaviour of another process: the database.
A singlethreaded app fails big if you need to do lots of CPU calculations before returning the data. Now, I don't mean a for loop processing the database result. That's still mostly O(n). What I mean is things like doing Fourier transform (mp3 encoding for example), ray tracing (3D rendering) etc.
Another pitfall of singlethreaded apps is that it will only utilise a single CPU core. So if you have a quad-core server (not uncommon nowdays) you're not using the other 3 cores.
A multithreaded app fails big if you need to allocate lots of RAM per thread. First, the RAM usage itself means you can't handle as many requests as a singlethreaded app. Worse, malloc is slow. Allocating lots and lots of objects (which is common for modern web frameworks) means we can potentially end up being slower than singlethreaded apps. This is where node.js usually win.
One use-case that end up making multithreaded worse is when you need to run another scripting language in your thread. First you usually need to malloc the entire runtime for that language, then you need to malloc the variables used by your script.
So if you're writing network apps in C or go or java then the overhead of threading will usually not be too bad. If you're writing a C web server to serve PHP or Ruby then it's very easy to write a faster server in javascript or Ruby or Python.
Some web servers use a hybrid approach. Nginx and Apache2 for example implement their network processing code as a thread pool of event loops. Each thread runs an event loop simultaneously processing requests single-threaded but requests are load-balanced among multiple threads.
Some single-threaded architectures also use a hybrid approach. Instead of launching multiple threads from a single process you can launch multiple applications - for example, 4 node.js servers on a quad-core machine. Then you use a load balancer to spread the workload amongst the processes.
In effect the two approaches are technically identical mirror-images of each other.
Here is a tutorial about how to do XSL Transformations in C# on MSDN:
http://support.microsoft.com/kb/307322/en-us/
and here how to write files:
http://support.microsoft.com/kb/816149/en-us
just as a side note: if you want to do validation too here is another tutorial (for DTD, XDR, and XSD (=Schema)):
http://support.microsoft.com/kb/307379/en-us/
i added this just to provide some more information.
For this to work, your font also needs to be set to monospace.
If you think about it, lines can't otherwise line up perfectly perfectly.
This answer is detailed at sublime text forum:
http://www.sublimetext.com/forum/viewtopic.php?f=3&p=42052
This answer has links for choosing an appropriate font for your OS,
and gives an answer to an edge case of fonts not lining up.
Another website that lists great monospaced free fonts for programmers. http://hivelogic.com/articles/top-10-programming-fonts
On stackoverflow, see:
Michael Ruth's answer here: How to make ruler always be shown in Sublime text 2?
MattDMo's answer here: What is the default font of Sublime Text?
I have rulers set at the following:
30
50 (git commit message titles should be limited to 50 characters)
72 (git commit message details should be limited to 72 characters)
80 (Windows Command Console Window maxes out at 80 character width)
Other viewing environments that benefit from shorter lines:
github: there is no word wrap when viewing a file online
So, I try to keep .js .md and other files at 70-80 characters.
Windows Console: 80 characters.
Here is example with console.log
instead of alert()
. It is more convenient :)
var parse = function(){
var str = $('textarea').val();
var results = str.split("\n");
$.each(results, function(index, element){
console.log(element);
});
};
$(function(){
$('button').on('click', parse);
});
You can try it here
The other answer (to date) appear to check for substrings rather than words. Major difference.
With the help of this article, I have created this simple method:
static boolean containsWord(String mainString, String word) {
Pattern pattern = Pattern.compile("\\b" + word + "\\b", Pattern.CASE_INSENSITIVE); // "\\b" represents any word boundary.
Matcher matcher = pattern.matcher(mainString);
return matcher.find();
}
You could query an LDAP server from the command line with ldap-utils: ldapsearch, ldapadd, ldapmodify
Have you tried Refinements?
module Nothingness
refine String do
alias_method :nothing?, :empty?
end
refine NilClass do
alias_method :nothing?, :nil?
end
end
using Nothingness
return my_string.nothing?
Short answer: no (easy?) way, but you can do something that serves your purpose.
I've done a similar tool (a small command that, given a description of a project, sets environment, paths, directories, etc.). What I do is set-up everything and then spawn a shell with:
spawn('bash', ['-i'], {
cwd: new_cwd,
env: new_env,
stdio: 'inherit'
});
After execution, you'll be on a shell with the new directory (and, in my case, environment). Of course you can change bash for whatever shell you prefer. The main differences with what you originally asked for are:
However, for me, that differences are desirable.
I know how to generate random number in C++ without using any headers, compiler intrinsics or whatever.
#include <cstdio> // Just for printf
int main() {
auto val = new char[0x10000];
auto num = reinterpret_cast<unsigned long long>(val);
delete[] val;
num = num / 0x1000 % 10;
printf("%llu\n", num);
}
I got the following stats after run for some period of time:
0: 5268
1: 5284
2: 5279
3: 5242
4: 5191
5: 5135
6: 5183
7: 5236
8: 5372
9: 5343
Looks random.
How it works:
The parent component can manage child state passing a prop to child and the child convert this prop in state using componentWillReceiveProps.
class ParentComponent extends Component {
state = { drawerOpen: false }
toggleChildMenu = () => {
this.setState({ drawerOpen: !this.state.drawerOpen })
}
render() {
return (
<div>
<button onClick={this.toggleChildMenu}>Toggle Menu from Parent</button>
<ChildComponent drawerOpen={this.state.drawerOpen} />
</div>
)
}
}
class ChildComponent extends Component {
constructor(props) {
super(props)
this.state = {
open: false
}
}
componentWillReceiveProps(props) {
this.setState({ open: props.drawerOpen })
}
toggleMenu() {
this.setState({
open: !this.state.open
})
}
render() {
return <Drawer open={this.state.open} />
}
}
Without CSS: Use the STYLE property of text input
STYLE="text-align: right;"
This happens to me while working with XCode (I'm using the most current version of XCode in 2019...). I'm using, CMake for build integration. Using the following directive in CMakeLists.txt fixed it for me:
set(CMAKE_CXX_STANDARD 14)
.
Example:
cmake_minimum_required(VERSION 3.14.0)
set(CMAKE_CXX_STANDARD 14)
# Rest of your declarations...
Here's how I did it in Python using csv and the MySQL Connector:
import csv
import mysql.connector
credentials = dict(user='...', password='...', database='...', host='...')
connection = mysql.connector.connect(**credentials)
cursor = connection.cursor(prepared=True)
stream = open('filename.csv', 'rb')
csv_file = csv.DictReader(stream, skipinitialspace=True)
query = 'CREATE TABLE t ('
query += ','.join('`{}` VARCHAR(255)'.format(column) for column in csv_file.fieldnames)
query += ')'
cursor.execute(query)
for row in csv_file:
query = 'INSERT INTO t SET '
query += ','.join('`{}` = ?'.format(column) for column in row.keys())
cursor.execute(query, row.values())
stream.close()
cursor.close()
connection.close()
Key points
'rb'
binaryskipinitialspace
option.255
isn't wide enough you'll get errors on INSERT and have to start over.ALTER TABLE t MODIFY `Amount` DECIMAL(11,2);
ALTER TABLE t ADD `id` INT PRIMARY KEY AUTO_INCREMENT;
I just want to fill only 80% of the screen for that I did like this below
DisplayMetrics metrics = getResources().getDisplayMetrics();
int screenWidth = (int) (metrics.widthPixels * 0.80);
setContentView(R.layout.mylayout);
getWindow().setLayout(screenWidth, LayoutParams.WRAP_CONTENT); //set below the setContentview
it works only when I put the getwindow().setLayout... line below the setContentView(..)
thanks @Matthias
your string is NOT a valid json to start with.
a valid json will be,
{
"area": [
{
"area": "kothrud"
},
{
"area": "katraj"
}
]
}
if you do a json_decode
, it will yield,
stdClass Object
(
[area] => Array
(
[0] => stdClass Object
(
[area] => kothrud
)
[1] => stdClass Object
(
[area] => katraj
)
)
)
Update: to use
$string = '
{
"area": [
{
"area": "kothrud"
},
{
"area": "katraj"
}
]
}
';
$area = json_decode($string, true);
foreach($area['area'] as $i => $v)
{
echo $v['area'].'<br/>';
}
Output:
kothrud
katraj
Update #2:
for that true
:
When TRUE, returned objects will be converted into associative arrays. for more information, click here
Armin's answer + a strict check for object types and non-angular keys such as $resolve
app.filter('orderObjectBy', function(){
return function(input, attribute) {
if (!angular.isObject(input)) return input;
var array = [];
for(var objectKey in input) {
if (typeof(input[objectKey]) === "object" && objectKey.charAt(0) !== "$")
array.push(input[objectKey]);
}
array.sort(function(a, b){
a = parseInt(a[attribute]);
b = parseInt(b[attribute]);
return a - b;
});
return array;
}
})
The best shot:
**
* Integer modifiable fix length list of an int array or many int's.
*
* @author Daniel De Leon.
*/
public class IntegerListWrap extends AbstractList<Integer> {
int[] data;
public IntegerListWrap(int... data) {
this.data = data;
}
@Override
public Integer get(int index) {
return data[index];
}
@Override
public Integer set(int index, Integer element) {
int r = data[index];
data[index] = element;
return r;
}
@Override
public int size() {
return data.length;
}
}
Examples:
int[] intArray = new int[]{1, 2, 3};
List<Integer> integerListWrap = new IntegerListWrap(intArray);
List<Integer> integerListWrap1 = new IntegerListWrap(1, 2, 3);
I solved using as credential built-in accounts as the NetworkService this article point me out in the right direction http://www.sqlcoffee.com/SQLServer2008_0013.htm
In java 8
String lastItem = Stream.of(str.split("-")).reduce((first,last)->last).get();
You could try something like this to test and trim the length:
http://jsfiddle.net/orolo/wJDXL/
var longArray = [1, 2, 3, 4, 5, 6, 7, 8];_x000D_
_x000D_
if (longArray.length >= 6) {_x000D_
longArray.length = 3;_x000D_
}_x000D_
_x000D_
alert(longArray); //1, 2, 3
_x000D_
Here is an extension of @Trasp's answer that has additional logic for handling the corner case of a file that has only one line. It may be useful to handle this case if you repeatedly want to read the last line of a file that is continuously being updated. Without this, if you try to grab the last line of a file that has just been created and has only one line, IOError: [Errno 22] Invalid argument
will be raised.
def tail(filepath):
with open(filepath, "rb") as f:
first = f.readline() # Read the first line.
f.seek(-2, 2) # Jump to the second last byte.
while f.read(1) != b"\n": # Until EOL is found...
try:
f.seek(-2, 1) # ...jump back the read byte plus one more.
except IOError:
f.seek(-1, 1)
if f.tell() == 0:
break
last = f.readline() # Read last line.
return last
^[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)*$
The following approach worked in Angular 5 CLI.
For sake of simplicity, I used similar d3gauge.js demo created and provided by oliverbinns - which you may easily find on Github.
So first, I simply created a new folder named externalJS on same level as the assets folder. I then copied the 2 following .js files.
I then made sure to declare both linked directives in main index.html
<script src="./externalJS/d3.v3.min.js"></script>
<script src="./externalJS/d3gauge.js"></script>
I then added a similar code in a gauge.component.ts component as followed:
import { Component, OnInit } from '@angular/core';
declare var d3gauge:any; <----- !
declare var drawGauge: any; <-----!
@Component({
selector: 'app-gauge',
templateUrl: './gauge.component.html'
})
export class GaugeComponent implements OnInit {
constructor() { }
ngOnInit() {
this.createD3Gauge();
}
createD3Gauge() {
let gauges = []
document.addEventListener("DOMContentLoaded", function (event) {
let opt = {
gaugeRadius: 160,
minVal: 0,
maxVal: 100,
needleVal: Math.round(30),
tickSpaceMinVal: 1,
tickSpaceMajVal: 10,
divID: "gaugeBox",
gaugeUnits: "%"
}
gauges[0] = new drawGauge(opt);
});
}
}
and finally, I simply added a div in corresponding gauge.component.html
<div id="gaugeBox"></div>
et voilà ! :)
This appears to be Microsoft's opinion on the matter:
Adding (and editing) .suo files to source control
I don't know why your project stores the DebuggingWorkingDirectory in the suo file. If that is a user specific setting you should consider storing that in the *.proj.user filename. If that setting is shareable between all users working on the project you should consider storing it in the project file itself.
Don't even think of adding the suo file to source control! The SUO (soluton user options) file is meant to contain user-specific settings, and should not be shared amongst users working on the same solution. If you'd be adding the suo file in the scc database I don't know what other things in the IDE you'd break, but from source control point of view you will break web projects scc integration, the Lan vs Internet plugin used by different users for VSS access, and you could even cause the scc to break completely (VSS database path stored in suo file that may be valid for you may not be valid for another user).
Alin Constantin (MSFT)
In general I use system
, open
, IPC::Open2
, or IPC::Open3
depending on what I want to do. The qx//
operator, while simple, is too constraining in its functionality to be very useful outside of quick hacks. I find open
to much handier.
system
: run a command and wait for it to returnUse system
when you want to run a command, don't care about its output, and don't want the Perl script to do anything until the command finishes.
#doesn't spawn a shell, arguments are passed as they are
system("command", "arg1", "arg2", "arg3");
or
#spawns a shell, arguments are interpreted by the shell, use only if you
#want the shell to do globbing (e.g. *.txt) for you or you want to redirect
#output
system("command arg1 arg2 arg3");
qx//
or ``: run a command and capture its STDOUTUse qx//
when you want to run a command, capture what it writes to STDOUT, and don't want the Perl script to do anything until the command finishes.
#arguments are always processed by the shell
#in list context it returns the output as a list of lines
my @lines = qx/command arg1 arg2 arg3/;
#in scalar context it returns the output as one string
my $output = qx/command arg1 arg2 arg3/;
exec
: replace the current process with another process.Use exec
along with fork
when you want to run a command, don't care about its output, and don't want to wait for it to return. system
is really just
sub my_system {
die "could not fork\n" unless defined(my $pid = fork);
return waitpid $pid, 0 if $pid; #parent waits for child
exec @_; #replace child with new process
}
You may also want to read the waitpid
and perlipc
manuals.
open
: run a process and create a pipe to its STDIN or STDERRUse open
when you want to write data to a process's STDIN or read data from a process's STDOUT (but not both at the same time).
#read from a gzip file as if it were a normal file
open my $read_fh, "-|", "gzip", "-d", $filename
or die "could not open $filename: $!";
#write to a gzip compressed file as if were a normal file
open my $write_fh, "|-", "gzip", $filename
or die "could not open $filename: $!";
Use IPC::Open2
when you need to read from and write to a process's STDIN and STDOUT.
use IPC::Open2;
open2 my $out, my $in, "/usr/bin/bc"
or die "could not run bc";
print $in "5+6\n";
my $answer = <$out>;
use IPC::Open3
when you need to capture all three standard file handles of the process. I would write an example, but it works mostly the same way IPC::Open2 does, but with a slightly different order to the arguments and a third file handle.
Yes - it's possible (though not with your method signature) and yes, with your signature the types must be the same.
With the signature you have given, T
must be associated to a single type (e.g. String
or Integer
) at the call-site. You can, however, declare method signatures which take multiple type parameters
public <S, T> void func(Set<S> s, Set<T> t)
Note in the above signature that I have declared the types S
and T
in the signature itself. These are therefore different to and independent of any generic types associated with the class or interface which contains the function.
public class MyClass<S, T> {
public void foo(Set<S> s, Set<T> t); //same type params as on class
public <U, V> void bar(Set<U> s, Set<V> t); //type params independent of class
}
You might like to take a look at some of the method signatures of the collection classes in the java.util
package. Generics is really rather a complicated subject, especially when wildcards (? extends
and ? super
) are considered. For example, it's often the case that a method which might take a Set<Number>
as a parameter should also accept a Set<Integer>
. In which case you'd see a signature like this:
public void baz(Set<? extends T> s);
There are plenty of questions already on SO for you to look at on the subject!
Not sure what the point of returning an int
from the function is, although you could do that if you want!
var o = {
r: 'some value',
t: 'some other value'
};
is functionally equivalent to
var o = new Object();
o.r = 'some value';
o.t = 'some other value';
You can proceed as follows to check whether a JToken Value is null
JToken token = jObject["key"];
if(token.Type == JTokenType.Null)
{
// Do your logic
}
Instead of using FileWriter
, create a FileOutputStream
. You can then wrap this in an OutputStreamWriter
, which allows you to pass an encoding in the constructor. Then you can write your data to that inside a try-with-resources Statement:
try (OutputStreamWriter writer =
new OutputStreamWriter(new FileOutputStream(PROPERTIES_FILE), StandardCharsets.UTF_8))
// do stuff
}
The very same. A C string is nothing but an array of characters, so a pointer to a string is a pointer to an array of characters. And a pointer to an array is the very same as a pointer to its first element.
You need to be wary of XSS when doing stuff like this:
document.getElementById('<%= Label1.ClientID %>').style.display
The chances are that no-one will be able to tamper with the ClientID of Label1 in this instance, but just to be on the safe side you might want pass it's value through one of the AntiXss library's methods:
document.getElementById('<%= AntiXss.JavaScriptEncode(Label1.ClientID) %>').style.display
Given an Express 4 configuration with endpoints and nested routers
const express = require('express')
const app = express()
const router = express.Router()
app.get(...)
app.post(...)
router.use(...)
router.get(...)
router.post(...)
app.use(router)
Expanding the @caleb answer it is possible to obtain all routes recursively and sorted.
getRoutes(app._router && app._router.stack)
// =>
// [
// [ 'GET', '/'],
// [ 'POST', '/auth'],
// ...
// ]
/**
* Converts Express 4 app routes to an array representation suitable for easy parsing.
* @arg {Array} stack An Express 4 application middleware list.
* @returns {Array} An array representation of the routes in the form [ [ 'GET', '/path' ], ... ].
*/
function getRoutes(stack) {
const routes = (stack || [])
// We are interested only in endpoints and router middleware.
.filter(it => it.route || it.name === 'router')
// The magic recursive conversion.
.reduce((result, it) => {
if (! it.route) {
// We are handling a router middleware.
const stack = it.handle.stack
const routes = getRoutes(stack)
return result.concat(routes)
}
// We are handling an endpoint.
const methods = it.route.methods
const path = it.route.path
const routes = Object
.keys(methods)
.map(m => [ m.toUpperCase(), path ])
return result.concat(routes)
}, [])
// We sort the data structure by route path.
.sort((prev, next) => {
const [ prevMethod, prevPath ] = prev
const [ nextMethod, nextPath ] = next
if (prevPath < nextPath) {
return -1
}
if (prevPath > nextPath) {
return 1
}
return 0
})
return routes
}
For basic string output.
infoAboutRoutes(app)
/**
* Converts Express 4 app routes to a string representation suitable for console output.
* @arg {Object} app An Express 4 application
* @returns {string} A string representation of the routes.
*/
function infoAboutRoutes(app) {
const entryPoint = app._router && app._router.stack
const routes = getRoutes(entryPoint)
const info = routes
.reduce((result, it) => {
const [ method, path ] = it
return result + `${method.padEnd(6)} ${path}\n`
}, '')
return info
}
Due to the internal limitations of Express 4 it is not possible to retrieve mounted app and mounted routers. For example it is not possible to obtain routes from this configuration.
const subApp = express()
app.use('/sub/app', subApp)
const subRouter = express.Router()
app.use('/sub/route', subRouter)
After trying the filter approach without success (it did for some reason not enter the doFilter() function) I changed my setup a bit and found a very simple solution for the root serving problem:
Instead of serving " / * " in my main Servlet, I now only listen to dedicated language prefixes "EN", "EN/ *", "DE", "DE/ *"
Static content gets served by the default Servlet and the empty root requests go to the index.jsp which calls up my main Servlet with the default language:
< jsp:include page="/EN/" /> (no other content on the index page.)
If you want to change the permissions of an existing file, use chmod (change mode):
$itWorked = chmod ("/yourdir/yourfile", 0777);
If you want all new files to have certain permissions, you need to look into setting your umode
. This is a process setting that applies a default modification to standard modes.
It is a subtractive one. By that, I mean a umode
of 022
will give you a default permission of 755
(777 - 022 = 755
).
But you should think very carefully about both these options. Files created with that mode will be totally unprotected from changes.
Verify Google reCapcha is valid or not after form submit
if ($post['g-recaptcha-response']) {
$captcha = $post['g-recaptcha-response'];
$secretKey = 'type here private key';
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=" . $secretKey . "&response=" . $captcha);
$responseKeys = json_decode($response, true);
if (intval($responseKeys["success"]) !== 1) {
return "failed";
} else {
return "success";
}
}
else {
return "failed";
}
You can also use the FileReader class :
var reader = new FileReader();
reader.onload = function (e) {
var data = this.result;
}
reader.readAsDataURL( file );
AFAIK, an Iframe cannot be used that way. You need to point its src attribute to another page.
Here's how to get its body content using plane old javascript. This works with both IE and Firefox.
function getFrameContents(){
var iFrame = document.getElementById('id_description_iframe');
var iFrameBody;
if ( iFrame.contentDocument )
{ // FF
iFrameBody = iFrame.contentDocument.getElementsByTagName('body')[0];
}
else if ( iFrame.contentWindow )
{ // IE
iFrameBody = iFrame.contentWindow.document.getElementsByTagName('body')[0];
}
alert(iFrameBody.innerHTML);
}
Maybe a bit late to answer but i would like to share my way. I found an easy way with threads in the main program for a winform application.
Lets say you have your form "splashscreen" with an animation, and your "main" which has all your application code.
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Thread mythread;
mythread = new Thread(new ThreadStart(ThreadLoop));
mythread.Start();
Application.Run(new MainForm(mythread));
}
public static void ThreadLoop()
{
Application.Run(new SplashScreenForm());
}
In your main form in the constructor:
public MainForm(Thread splashscreenthread)
{
InitializeComponent();
//add your constructor code
splashscreenthread.Abort();
}
This way the splashscreen will last just the time for your main form to load.
Your splashcreen form should have his own way to animate/display information. In my project my splashscreen start a new thread, and every x milliseconds it changes his main picture to another which is a slightly different gear, giving the illusion of a rotation.
example of my splashscreen:
int status = 0;
private bool IsRunning = false;
public Form1()
{
InitializeComponent();
StartAnimation();
}
public void StartAnimation()
{
backgroundWorker1.WorkerReportsProgress = false;
backgroundWorker1.WorkerSupportsCancellation = true;
IsRunning = true;
backgroundWorker1.RunWorkerAsync();
}
public void StopAnimation()
{
backgroundWorker1.CancelAsync();
}
delegate void UpdatingThreadAnimation();
public void UpdateAnimationFromThread()
{
try
{
if (label1.InvokeRequired == false)
{
UpdateAnimation();
}
else
{
UpdatingThreadAnimation d = new UpdatingThreadAnimation(UpdateAnimationFromThread);
this.Invoke(d, new object[] { });
}
}
catch(Exception e)
{
}
}
private void UpdateAnimation()
{
if(status ==0)
{
// mypicture.image = image1
}else if(status ==1)
{
// mypicture.image = image2
}
//doing as much as needed
status++;
if(status>1) //change here if you have more image, the idea is to set a cycle of images
{
status = 0;
}
this.Refresh();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
while (IsRunning == true)
{
System.Threading.Thread.Sleep(100);
UpdateAnimationFromThread();
}
}
Hope this will help some people. Sorry if i have made some mistakes. English is not my first language.
Easy way
from IPython.display import Image
Image(filename ="Covid.jpg" size )
The answer to your problem is easy: replace the current Fragment
with the new Fragment
and push transaction onto the backstack. This preserves back button behaviour...
Creating a new Activity
really defeats the whole purpose to use fragments anyway...very counter productive.
@Override
public void onClick(View v) {
// Create new fragment and transaction
Fragment newFragment = new chartsFragment();
// consider using Java coding conventions (upper first char class names!!!)
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
http://developer.android.com/guide/components/fragments.html#Transactions
You should capitalize names of your classes. After doing that do this in your school class,
Classroom cls = new Classroom();
cls.setTeacherName(newTeacherName);
Also I'd recommend you use some kind of IDE such as eclipse, which can help you with your code for instance generate getters and setters for you. Ex: right click Source -> Generate getters and setters
Swift 3 / 4 / 5.1
Here is a simple String
extension, allowing for preserving optionals in the event of an error when decoding.
extension String {
/// Encode a String to Base64
func toBase64() -> String {
return Data(self.utf8).base64EncodedString()
}
/// Decode a String from Base64. Returns nil if unsuccessful.
func fromBase64() -> String? {
guard let data = Data(base64Encoded: self) else { return nil }
return String(data: data, encoding: .utf8)
}
}
Example:
let testString = "A test string."
let encoded = testString.toBase64() // "QSB0ZXN0IHN0cmluZy4="
guard let decoded = encoded.fromBase64() // "A test string."
else { return }
Your server configuration settings allows users to upload files upto 16MB (because you have set upload_max_filesize = 16Mb) but the post_max_size accepts post data upto 8MB only. This is why it throws an error.
Quoted from the official PHP site:
To upload large files, post_max_size value must be larger than upload_max_filesize.
memory_limit should be larger than post_max_size
You should always set your post_max_size value greater than the upload_max_filesize value.
1) With C# on .Net Core 3.0 and beyond, there is now a third boolean parameter:
see https://docs.microsoft.com/en-us/dotnet/api/system.io.file.move?view=netcore-3.1
In .NET Core 3.0 and later versions, you can call Move(String, String, Boolean) setting the parameter overwrite to true, which will replace the file if it exists.
2) For all other versions of .Net, https://stackoverflow.com/a/42224803/887092 is the best answer. Copy with Overwrite, then delete the source file. This is better because it makes it an atomic operation. (I have attempted to update the MS Docs with this)
I'm searched many answers that suggest me to type in cmd:
set path = "%path%;c:program files\java\jdk1.7.0\bin"
but this is WRONG!
the right solution is that you leave "set" and just type
path = %path%;c:program files\java\jdk1.7.0\bin
P/s: of course you have to replace "jdk1.7.0" folder by your current java version folder. This works well on win 7 32bit, but I think it also works on win 8 - try it!
I would use a duplex stream instead. like documented here nodejs doc duplex streams
A Transform stream is a Duplex stream where the output is computed in some way from the input.
In react/redux/webpack/babel build fixed this error by removing script tag type text/babel
got error:
<script type="text/babel" src="/js/bundle.js"></script>
no error:
<script src="/js/bundle.js"></script>
This question was linked from this blog post and an alternative solution was proposed for the newer versions of Git:
git branch -m master old_master
git checkout --orphan master
git branch -D old_master
This solution assumes that:
master
branchold_master
so I'm free to use that nameIt will rename the existing branch to old_master
and create a new, orphaned, branch master
(like it is created for new repositories) after which you can freely delete old_master
... or not. Up to you.
Note: Moving or copying a git branch preserves its reflog (see this code) while deleting and then creating a new branch destroys it. Since you want to get back to the original state with no history you probably want to delete the branch, but others may want to consider this small note.
If you are running in Android 29 then you have to use scoped storage or for now, you can bypass this issue by using:
android:requestLegacyExternalStorage="true"
in manifest in the application tag.
I had the same issue in gradle
when creating a fat Jar, updating the build.gradle
file with an exclude line corrected the issue.
jar {
from {
configurations.compile.collect {
it.isDirectory() ? it : zipTree(it)
}
}
exclude 'META-INF/*.RSA', 'META-INF/*.SF','META-INF/*.DSA'
manifest {
attributes 'Main-Class': 'com.test.Main'
}
}
On OS X (10.9.4), cat
works, and is easier if your email is already in a file:
cat email_template.html | mail -s "$(echo -e "Test\nContent-Type: text/html")" [email protected]
You can easily add a View with the height of 1dp aligning start and the end of TextView, right below it. You can also use marginTop with negative value to make the underline closer to TextView. If you use your TextView and the under inside a relative layout, it would be much easier for alignments. here is the example:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<View
android:id="@+id/viewForgotPasswordUnderline"
android:layout_width="wrap_content"
android:layout_height="1dp"
android:layout_below="@id/txtForgotPassword"
android:layout_alignStart="@id/txtForgotPassword"
android:layout_alignEnd="@id/txtForgotPassword"
android:layout_marginTop="-2dp"
android:background="@color/lightGray" />
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/txtForgotPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:paddingTop="8dp"
android:text="@string/userLoginForgotPassword"
android:textColor="@color/lightGray"
android:textSize="16dp" />
</RelativeLayout>
If you simply want to trash all your local changes/commits and make your local branch look like the origin branch you started from...
git reset --hard origin/branch-name
There are a number of things wrong with your code:
char *readFile(char *fileName)
{
FILE *file;
char *code = malloc(1000 * sizeof(char));
file = fopen(fileName, "r");
do
{
*code++ = (char)fgetc(file);
} while(*code != EOF);
return code;
}
code
each time you read a character, and you return code
back to the caller (even though it is no longer pointing at the first byte of the memory block as it was returned by malloc
).fgetc(file)
to char
. You need to check for EOF
before casting the result to char
.It is important to maintain the original pointer returned by malloc
so that you can free it later. If we disregard the file size, we can achieve this still with the following:
char *readFile(char *fileName)
{
FILE *file = fopen(fileName, "r");
char *code;
size_t n = 0;
int c;
if (file == NULL)
return NULL; //could not open file
code = malloc(1000);
while ((c = fgetc(file)) != EOF)
{
code[n++] = (char) c;
}
// don't forget to terminate with the null character
code[n] = '\0';
return code;
}
There are various system calls that will give you the size of a file; a common one is stat
.
select convert_tz(now(),@@session.time_zone,'+05:30')
replace '+05:30' with desired timezone. see here - https://stackoverflow.com/a/3984412/2359994
to format into desired time format, eg:
select DATE_FORMAT(convert_tz(now(),@@session.time_zone,'+05:30') ,'%b %d %Y %h:%i:%s %p')
you will get similar to this -> Dec 17 2014 10:39:56 AM
use inline-block
instead of inline
. Read more information here about the difference between inline and inline-block.
.inline {
display: inline-block;
border: 1px solid red;
margin:10px;
}
Or second solution
you can try to connect using Direct not TNS by providing host and port in the connect screen of Toad
Since Ruby 2.5.0, Array ships with the prepend
method (which is just an alias for the unshift
method).