You should consider ConfigGen. It was developed for this purpose. It produces a config file for each deployment machine, based on a template file and a settings file. I know that this doesn't answer your question specifically, but it might well answer your problem.
So rather than Debug, Release etc, you might have Test, UAT, Production etc. You can also have different settings for each developer machine, so that you can generate a config specific to your dev machine and change it without affecting any one else's deployment.
An example of usage might be...
<Target Name="BeforeBuild">
<Exec Command="C:\Tools\cfg -s $(ProjectDir)App.Config.Settings.xls -t
$(ProjectDir)App.config.template.xml -o $(SolutionDir)ConfigGen" />
<Exec Command="C:\Tools\cfg -s $(ProjectDir)App.Config.Settings.xls -t
$(ProjectDir)App.config.template.xml -l -n $(ProjectDir)App.config" />
</Target>
If you place this in your .csproj file, and you have the following files...
$(ProjectDir)App.Config.Settings.xls
MachineName ConfigFilePath SQLServer
default App.config DEVSQL005
Test App.config TESTSQL005
UAT App.config UATSQL005
Production App.config PRODSQL005
YourLocalMachine App.config ./SQLEXPRESS
$(ProjectDir)App.config.template.xml
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<configuration>
<appSettings>
<add key="ConnectionString" value="Data Source=[%SQLServer%];
Database=DatabaseName; Trusted_Connection=True"/>
</appSettings>
</configuration>
... then this will be the result...
From the first command, a config file generated for each environment specified in the xls file, placed in the output directory $(SolutionDir)ConfigGen
.../solutiondir/ConfigGen/Production/App.config
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<configuration>
<appSettings>
<add key="ConnectionString" value="Data Source=PRODSQL005;
Database=DatabaseName; Trusted_Connection=True"/>
</appSettings>
</configuration>
From the second command, the local App.config used on your dev machine will be replaced with the generated config specified by the local (-l) switch and the filename (-n) switch.
The maven dependency plugin saved me a lot of time fondling with ant tasks:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>install-jar</id>
<phase>install</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>...</groupId>
<artifactId>...</artifactId>
<version>...</version>
</artifactItem>
</artifactItems>
<outputDirectory>...</outputDirectory>
<stripVersion>true</stripVersion>
</configuration>
</execution>
</executions>
</plugin>
The dependency:copy is documentend, and has more useful goals like unpack.
PySimpleGUI wraps tkinter and works on Python 3 and 2.7. It also runs on Qt, WxPython and in a web browser, using the same source code for all platforms.
You can make custom GUIs that utilize all of the same widgets that you find in tkinter (sliders, checkboxes, radio buttons, ...). The code tends to be very compact and readable.
#!/usr/bin/env python
import sys
if sys.version_info[0] >= 3:
import PySimpleGUI as sg
else:
import PySimpleGUI27 as sg
layout = [[ sg.Text('My Window') ],
[ sg.Button('OK')]]
window = sg.Window('My window').Layout(layout)
button, value = window.Read()
As explained in the PySimpleGUI Documentation, to build the .EXE file you run:
pyinstaller -wF MyGUIProgram.py
Replace your implementation
with classpath
. That should work.
Imagine that you are a boss and you have an assistant and a maid, and you give them a list of tasks to do, the assistant (compile time) will grab this list and make a checkup to see if the tasks are understandable and that you didn't write in any awkward language or syntax, so he understands that you want to assign someone for a Job so he assign him for you and he understand that you want some coffee, so his role is over and the maid (run time)starts to run those tasks so she goes to make you some coffee but in sudden she doesn’t find any coffee to make so she stops making it or she acts differently and make you some tea (when the program acts differently because he found an error).
To lock whole workbook from opening, Thisworkbook.password
option can be used in VBA.
If you want to Protect Worksheets, then you have to first Lock the cells with option Thisworkbook.sheets.cells.locked = True
and then use the option Thisworkbook.sheets.protect password:="pwd"
.
Primarily search for these keywords: Thisworkbook.password
or Thisworkbook.Sheets.Cells.Locked
Few too many answers on this one, but I feel it's worth adding this solution. It combines a few different answers.
Key points for me were
Use .onload() to wait until the script has finished loading before using it
mounted() {
// First check if the script already exists on the dom
// by searching for an id
let id = 'googleMaps'
if(document.getElementById(id) === null) {
let script = document.createElement('script')
script.setAttribute('src', 'https://maps.googleapis.com/maps/api/js?key=' + apiKey)
script.setAttribute('id', id)
document.body.appendChild(script)
// now wait for it to load...
script.onload = () => {
// script has loaded, you can now use it safely
alert('thank me later')
// ... do something with the newly loaded script
}
}
}
var helper = {};
for(var i = 0; i < data.length; i++){
helper[data[i]] = 1; // Fill object
}
var result = Object.keys(helper); // Unique items
I had the same problem with .c files that contained functions (not main()
of my program). For example, my header files were "fact.h" and "fact.c", and my main program was "main.c" so my commands were like this:
E:\proj> gcc -c fact.c
Now I had an object file of fact.c (fact.o). after that:
E:\proj>gcc -o prog.exe fact.o main.c
Then my program (prog.exe) was ready to use and worked properly. I think that -c
after gcc
was important, because it makes object files that can attach to make the program we need. Without using -c
, gcc ties to find main in your program and when it doesn't find it, it gives you this error.
I have been a big fan of a filter with lambda. However, it is not best option if you consider time complexity.
sorted_list = sorted(list_to_sort, key= lambda x: x['name'])
# Returns list of values
list_to_sort.sort(key=operator.itemgetter('name'))
# Edits the list, and does not return a new list
# First option
python3.6 -m timeit -s "list_to_sort = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}, {'name':'Faaa', 'age':57}, {'name':'Errr', 'age':20}]" -s "sorted_l=[]" "sorted_l = sorted(list_to_sort, key=lambda e: e['name'])"
1000000 loops, best of 3: 0.736 µsec per loop
# Second option
python3.6 -m timeit -s "list_to_sort = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}, {'name':'Faaa', 'age':57}, {'name':'Errr', 'age':20}]" -s "sorted_l=[]" -s "import operator" "list_to_sort.sort(key=operator.itemgetter('name'))"
1000000 loops, best of 3: 0.438 µsec per loop
You can use String.Format:
DateTime d = DateTime.Now;
string str = String.Format("{0:00}/{1:00}/{2:0000} {3:00}:{4:00}:{5:00}.{6:000}", d.Month, d.Day, d.Year, d.Hour, d.Minute, d.Second, d.Millisecond);
// I got this result: "02/23/2015 16:42:38.234"
IMO some of the previous answers are incorrect! (It's possible to sort the answers to start from oldest to newest).
array_merge()
actually merges the arrays, meaning, if the arrays have a common item one of the copies will be omitted. Same goes for +
(union).
I didn't find a "work-around" for this issue, but to do it manually...
Here it goes:
<?php
$part1 = array(1,2,3);
echo "array 1 = \n";
print_r($part1);
$part2 = array(4,5,6);
echo "array 2 = \n";
print_r($part2);
$ans = NULL;
for ($i = 0; $i < count($part1); $i++) {
$ans[] = $part1[$i];
}
for ($i = 0; $i < count($part2); $i++) {
$ans[] = $part2[$i];
}
echo "after arrays concatenation:\n";
print_r($ans);
?>
FWIW I created a JavaScript class that can be used at run-time.
It's over on GitHub, here.
There is a readme there with a more in-depth explanation, but I'll do a quick example below:
var ba = new BootstrapAlert();
ba.addP("Some content here");
$("body").append(ba.render());
The above would create a simple primary alert with a paragraph element inside containing the text "Some content here".
There are also options that can be set on initialisation.
For your requirement you'd do:
var ba = new BootstrapAlert({
dismissible: true,
background: 'warning'
});
ba.addP("Invalid Credentials");
$("body").append(ba.render());
The render
method will return an HTML element, which can then be inserted into the DOM. In this case, we append it to the bottom of the body tag.
This is a work in progress library, but it still is in a very good working order.
You can check in the system 'table column mapping' table
SELECT count(*)
FROM Sys.Columns c
JOIN Sys.Tables t ON c.Object_Id = t.Object_Id
WHERE upper(t.Name) = 'TAGS'
AND upper(c.NAME) = 'MODIFIEDBYUSER'
There are a couple ways to do this.
First, instead of going into openssl command prompt mode, just enter everything on one command line from the Windows prompt:
E:\> openssl x509 -pubkey -noout -in cert.pem > pubkey.pem
If for some reason, you have to use the openssl command prompt, just enter everything up to the ">". Then OpenSSL will print out the public key info to the screen. You can then copy this and paste it into a file called pubkey.pem.
openssl> x509 -pubkey -noout -in cert.pem
Output will look something like this:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAryQICCl6NZ5gDKrnSztO
3Hy8PEUcuyvg/ikC+VcIo2SFFSf18a3IMYldIugqqqZCs4/4uVW3sbdLs/6PfgdX
7O9D22ZiFWHPYA2k2N744MNiCD1UE+tJyllUhSblK48bn+v1oZHCM0nYQ2NqUkvS
j+hwUU3RiWl7x3D2s9wSdNt7XUtW05a/FXehsPSiJfKvHJJnGOX0BgTvkLnkAOTd
OrUZ/wK69Dzu4IvrN4vs9Nes8vbwPa/ddZEzGR0cQMt0JBkhk9kU/qwqUseP1QRJ
5I1jR4g8aYPL/ke9K35PxZWuDp3U0UPAZ3PjFAh+5T+fc7gzCs9dPzSHloruU+gl
FQIDAQAB
-----END PUBLIC KEY-----
Approach I followed to solve this problem is by created a Global Secondary Index as below. Not sure if this is the best approach but hopefully if it is useful to someone.
Hash Key | Range Key
------------------------------------
Date value of CreatedAt | CreatedAt
Limitation imposed on the HTTP API user to specify the number of days to retrieve data, defaulted to 24 hr.
This way, I can always specify the HashKey as Current date's day and RangeKey can use > and < operators while retrieving. This way the data is also spread across multiple shards.
Because lock is expensive, when you are using synchronized block you lock only if _instance == null
, and after _instance
finally initialized you'll never lock. But when you synchronize on method you lock unconditionally, even after the _instance
is initialized. This is the idea behind double-checked locking optimization pattern http://en.wikipedia.org/wiki/Double-checked_locking.
Got to the question but could not figure out how to print it from externally-loaded mongo. So:
This works is for console: and is prefered in console, but does not work in external mongo-loaded javascript:
db.quizes.find().pretty()
This works in external mongo-loaded javscript:
db.quizes.find().forEach(printjson)
Remove the max-width
from the body
, and put it to the #container
.
So, instead of:
body {
max-width:1250px;
}
You should have:
#container {
max-width:1250px;
}
$("a.directions-link").attr("href", $("a.directions-link").attr("href")+"...your additions...");
In Eclipse Kepler,
JST Server Adapters
and JST Server Adapters Extensions
and install itAfter Eclipse restart, go to Window / Preferences / Server / Runtime Environments
LinearLayout layout = (LinearLayout)findViewById(R.id.layout);
View child = getLayoutInflater().inflate(R.layout.child, null);
layout.addView(child);
I prefer Google Collections over Apache StringUtils for this particular problem:
Joiner.on(separator).join(array)
Compared to StringUtils, the Joiner API has a fluent design and is a bit more flexible, e.g. null
elements may be skipped or replaced by a placeholder. Also, Joiner
has a feature for joining maps with a separator between key and value.
Search for LISTEN directive in the apache config files (httpd.conf, apache2.conf, listen.conf,...) and if you see localhost, or 127.0.0.1, then you need to overwrite with your public ip.
Use SELECT or an output parameter. More can be found here: http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=100201
No, inside the views folder is not good.
Look: You must have 3 basic folders on your project:
system // This is CI framework there are not much reasons to touch this files
application //this is where your logic goes, the files that makes the application,
public // this must be your documentroot
For security reasons its better to keep your framework and the application outside your documentroot,(public_html, htdocs, public, www... etc)
Inside your public folder, you should put your public info, what the browsers can see, its common to find the folders: images, js, css; so your structure will be:
|- system/
|- application/
|---- models/
|---- views/
|---- controllers/
|- public/
|---- images/
|---- js/
|---- css/
|---- index.php
|---- .htaccess
inspect.stack()
returns the current stack rather than the exception traceback:
import inspect
print inspect.stack()
See https://gist.github.com/FredLoney/5454553 for a log_stack utility function.
In Chrome, For "Selenium IDE", I was also struggling that it doesn't pause. It will pause, if you give as below:
This will pause for 10 seconds.
I couldn't get the form suggested by @thoredge to work in Gradle 1.11, but this works for me:
home = System.getenv('HOME')
It helps to keep in mind that anything that works in pure Java will work in Gradle too.
Thanks for all the different suggestions, but I finally figured it out. The custom class was set up correctly. All I needed to do, was in the storyboard where I choose the custom class: remove it, and select it again. It doesn't make much sense, but that ended up working for me.
Getting an ECONNREFUSED errno means that your kernel was refused a connection at the other end, so if it's a bug, it's either in your kernel or in the other end. What you can do is to trap the error in a very specific way and try again in a little while, since this seems to work:
# This is Python > 2.5 code
import errno, time
for attempt in range(MAXIMUM_NUMBER_OF_ATTEMPTS):
try:
# your urllib call here
except EnvironmentError as exc: # replace " as " with ", " for Python<2.6
if exc.errno == errno.ECONNREFUSED:
time.sleep(A_COUPLE_OF_SECONDS)
else:
raise # re-raise otherwise
else: # we tried, and we had no failure, so
break
else: # we never broke out of the for loop
raise RuntimeError("maximum number of unsuccessful attempts reached")
Replace the two all-caps constants with your favourite numbers.
Remove the date()
part
SELECT name, datum
FROM tasks
WHERE datum >= NOW()
and if you use a specific date, don't forget the quotes around it and use the proper format with :
SELECT name, datum
FROM tasks
WHERE datum >= '2014-05-18 15:00:00'
With Recent Symfony 2.6+ versions as a best practice Request is passed as an argument with action in that case you won't need to explicitly call $this->getRequest(), but rather call $request->request->all()
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException;
use Symfony\Component\HttpFoundation\RedirectResponse;
class SampleController extends Controller
{
public function indexAction(Request $request) {
var_dump($request->request->all());
}
}
If you're looking for short answer:
In the case of using java.util.Date, Java doesn't really know how to directly relate to SQL types. This is when @Temporal
comes into play. It's used to specify the desired SQL type.
Source: Baeldung
After many hours troubleshooting this stuff... Here are some quick highlights that helped us from the X-UA-Compatible
docs: http://msdn.microsoft.com/en-us/library/cc288325(VS.85).aspx#ctl00_contentContainer_ctl16
Using <meta http-equiv="X-UA-Compatible" content=" _______ " />
The Standard User Agent modes (the non-emulate ones) ignore <!DOCTYPE>
directives in your page and render based on the standards supported by that version of IE (e.g., IE=8
will better obey table border spacing and some pseudo selectors than IE=7
).
Whereas, the Emulate modes tell IE to follow any <!DOCTYPE>
directives in your page, rendering standards mode based the version you choose and quirks mode based on IE=5
Possible values for the content
attribute are:
content="IE=5"
content="IE=7"
content="IE=EmulateIE7"
content="IE=8"
content="IE=EmulateIE8"
content="IE=9"
content="IE=EmulateIE9"
content="IE=edge"
Step 1
public class TopAttractions extends Fragment implements OnMapReadyCallback,
GoogleMap.OnMarkerClickListener
Step 2
gMap.setOnMarkerClickListener(this);
Step 3
@Override
public boolean onMarkerClick(Marker marker) {
if(marker.getTitle().equals("sharm el-shek"))
Toast.makeText(getActivity().getApplicationContext(), "Hamdy", Toast.LENGTH_SHORT).show();
return false;
}
window.location is an object in javascript. it returns following data
window.location.host #returns host
window.location.hostname #returns hostname
window.location.path #return path
window.location.href #returns full current url
window.location.port #returns the port
window.location.protocol #returns the protocol
in jquery you can use
$(location).attr('host'); #returns host
$(location).attr('hostname'); #returns hostname
$(location).attr('path'); #returns path
$(location).attr('href'); #returns href
$(location).attr('port'); #returns port
$(location).attr('protocol'); #returns protocol
With the support of ES6
, the best way to this is to use let
and const
keywords for this exact circumstance. So var
variable get hoisted
and with the end of loop the value of i
gets updated for all the closures
..., we can just use let
to set a loop scope variable like this:
var funcs = [];
for (let i = 0; i < 3; i++) {
funcs[i] = function() {
console.log("My value: " + i);
};
}
Modern BASH has support for regular expressions:
while read -r line; do
if [[ $line =~ ^potato:\ ([0-9]+) ]]; then
echo "${BASH_REMATCH[1]}"
fi
done
In ST2 there's a package you can install called Default FileType which does just that.
More info here.
Please check whether you have provided js references correctly. JQuery files first and then your custom files. Since you are using '$' in your js methods.
That depends. If said file is publicly available via your HTTP server or servlet container you can simply redirect to via response.sendRedirect()
.
If it's not, you'll need to manually copy it to response output stream:
OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(my_file);
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.flush();
You'll need to handle the appropriate exceptions, of course.
I looked around for a solution to this for a while. It appears that the JDK doesn't have the Mozilla plugins (which is what Chrome uses) in it's installation. It is only in the JRE installation. There are a couple of DLLs that make up the plugin and they all start with np*
I have tried everything, but only this helped:
php artisan route:clear
php artisan cache:clear
Answered the same question here:
To repost:
After searching through many solutions I decided to blog about how to sort in jquery. In summary, steps to sort jquery "array-like" objects by data attribute...
Html
<div class="item" data-order="2">2</div> <div class="item" data-order="1">1</div> <div class="item" data-order="4">4</div> <div class="item" data-order="3">3</div>
Plain jquery selector
$('.item');
[<div class="item" data-order="2">2</div>, <div class="item" data-order="1">1</div>, <div class="item" data-order="4">4</div>, <div class="item" data-order="3">3</div> ]
Lets sort this by data-order
function getSorted(selector, attrName) { return $($(selector).toArray().sort(function(a, b){ var aVal = parseInt(a.getAttribute(attrName)), bVal = parseInt(b.getAttribute(attrName)); return aVal - bVal; })); }
> getSorted('.item', 'data-order')
[<div class="item" data-order="1">1</div>, <div class="item" data-order="2">2</div>, <div class="item" data-order="3">3</div>, <div class="item" data-order="4">4</div> ]
Hope this helps!
There is a subtle issue here that is a bit of a gotcha.
The toString()
method has a base implementation in Object
. CharSequence
is an interface; and although the toString()
method appears as part of that interface, there is nothing at compile-time that will force you to override it and honor the additional constraints that the CharSequence
toString()
method's javadoc puts on the toString()
method; ie that it should return a string containing the characters in the order returned by charAt()
.
Your IDE won't even help you out by reminding that you that you probably should override toString()
. For example, in intellij, this is what you'll see if you create a new CharSequence
implementation: http://puu.sh/2w1RJ. Note the absence of toString()
.
If you rely on toString()
on an arbitrary CharSequence
, it should work provided the CharSequence
implementer did their job properly. But if you want to avoid any uncertainty altogether, you should use a StringBuilder
and append()
, like so:
final StringBuilder sb = new StringBuilder(charSequence.length());
sb.append(charSequence);
return sb.toString();
The only option I have found to do this is find some exact wording and put that under the "Has the words" option. Its not the best option, but it works.
Both keywords can be used in the declaration of objects as well as functions. The basic difference when applied to objects is this:
const
declares an object as constant. This implies a guarantee that once initialized, the value of that object won't change, and the compiler can make use of this fact for optimizations. It also helps prevent the programmer from writing code that modifies objects that were not meant to be modified after initialization.
constexpr
declares an object as fit for use in what the Standard calls constant expressions. But note that constexpr
is not the only way to do this.
When applied to functions the basic difference is this:
const
can only be used for non-static member functions, not functions in general. It gives a guarantee that the member function does not modify any of the non-static data members (except for mutable data members, which can be modified anyway).
constexpr
can be used with both member and non-member functions, as well as constructors. It declares the function fit for use in constant expressions. The compiler will only accept it if the function meets certain criteria (7.1.5/3,4), most importantly (†):
return
statement is allowed. In the case of a constructor, only an initialization list, typedefs, and static assert are allowed. (= default
and = delete
are allowed, too, though.)asm
declaration, a goto
statement, a statement with a label other than case
and default
, try-block, the definition of a variable of non-literal type, definition of a variable of static or thread storage duration, the definition of a variable for which no initialization is performed.As said above, constexpr
declares both objects as well as functions as fit for use in constant expressions. A constant expression is more than merely constant:
It can be used in places that require compile-time evaluation, for example, template parameters and array-size specifiers:
template<int N>
class fixed_size_list
{ /*...*/ };
fixed_size_list<X> mylist; // X must be an integer constant expression
int numbers[X]; // X must be an integer constant expression
But note:
Declaring something as constexpr
does not necessarily guarantee that it will be evaluated at compile time. It can be used for such, but it can be used in other places that are evaluated at run-time, as well.
An object may be fit for use in constant expressions without being declared constexpr
. Example:
int main()
{
const int N = 3;
int numbers[N] = {1, 2, 3}; // N is constant expression
}
This is possible because N
, being constant and initialized at declaration time with a literal, satisfies the criteria for a constant expression, even if it isn't declared constexpr
.
So when do I actually have to use constexpr
?
N
above can be used as constant expression without being declared constexpr
. This is true for all objects that are:const
[This is due to §5.19/2: A constant expression must not include a subexpression that involves "an lvalue-to-rvalue modification unless […] a glvalue of integral or enumeration type […]" Thanks to Richard Smith for correcting my earlier claim that this was true for all literal types.]
For a function to be fit for use in constant expressions, it must be explicitly declared constexpr
; it is not sufficient for it merely to satisfy the criteria for constant-expression functions. Example:
template<int N>
class list
{ };
constexpr int sqr1(int arg)
{ return arg * arg; }
int sqr2(int arg)
{ return arg * arg; }
int main()
{
const int X = 2;
list<sqr1(X)> mylist1; // OK: sqr1 is constexpr
list<sqr2(X)> mylist2; // wrong: sqr2 is not constexpr
}
When can I / should I use both, const
and constexpr
together?
A. In object declarations. This is never necessary when both keywords refer to the same object to be declared. constexpr
implies const
.
constexpr const int N = 5;
is the same as
constexpr int N = 5;
However, note that there may be situations when the keywords each refer to different parts of the declaration:
static constexpr int N = 3;
int main()
{
constexpr const int *NP = &N;
}
Here, NP
is declared as an address constant-expression, i.e. a pointer that is itself a constant expression. (This is possible when the address is generated by applying the address operator to a static/global constant expression.) Here, both constexpr
and const
are required: constexpr
always refers to the expression being declared (here NP
), while const
refers to int
(it declares a pointer-to-const). Removing the const
would render the expression illegal (because (a) a pointer to a non-const object cannot be a constant expression, and (b) &N
is in-fact a pointer-to-constant).
B. In member function declarations. In C++11, constexpr
implies const
, while in C++14 and C++17 that is not the case. A member function declared under C++11 as
constexpr void f();
needs to be declared as
constexpr void f() const;
under C++14 in order to still be usable as a const
function.
Position your <div>
absolutely at the bottom and don't forget to give div.A
a position: relative
- http://jsfiddle.net/TTaMx/
.A {
position: relative;
margin: 40px 0;
height: 40px;
width: 200px;
background: #eee;
}
.A:after {
content: " ";
display: block;
background: #c00;
height: 29px;
width: 100%;
position: absolute;
bottom: -29px;
}?
While it is not possible to write a switch statement, it is possible to branch out to specific processing for each given type. One way of doing this is to use standard double dispatch mechanism. An example where we want to "switch" based on type is Jersey Exception mapper where we need to map multitude of exceptions to error responses. While for this specific case there is probably a better way (i.e. using a polymorphic method that translates each exception to an error response), using double dispatch mechanism is still useful and practical.
interface Processable {
<R> R process(final Processor<R> processor);
}
interface Processor<R> {
R process(final A a);
R process(final B b);
R process(final C c);
// for each type of Processable
...
}
class A implements Processable {
// other class logic here
<R> R process(final Processor<R> processor){
return processor.process(this);
}
}
class B implements Processable {
// other class logic here
<R> R process(final Processor<R> processor){
return processor.process(this);
}
}
class C implements Processable {
// other class logic here
<R> R process(final Processor<R> processor){
return processor.process(this);
}
}
Then where ever the "switch" is needed, you can do it as follows:
public class LogProcessor implements Processor<String> {
private static final Logger log = Logger.for(LogProcessor.class);
public void logIt(final Processable base) {
log.info("Logging for type {}", process(base));
}
// Processor methods, these are basically the effective "case" statements
String process(final A a) {
return "Stringifying A";
}
String process(final B b) {
return "Stringifying B";
}
String process(final C c) {
return "Stringifying C";
}
}
Use this code in onCreate()
method:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
Every public folder makes the permission to 755. Problem solved.
ADD it in the lowermost part og your View:
@section Scripts { @Scripts.Render("~/bundles/jqueryval") }
Looks like you are using maven (src/main/java)
. In this case put the applicationContext.xml
file in the src/main/resources
directory. It will be copied in the classpath directory and you should be able to access it with
@ContextConfiguration("/applicationContext.xml")
From the Spring-Documentation: A plain path, for example "context.xml", will be treated as a classpath resource from the same package in which the test class is defined. A path starting with a slash is treated as a fully qualified classpath location, for example "/org/example/config.xml".
So it's important that you add the slash when referencing the file in the root directory of the classpath.
If you work with the absolute file path you have to use 'file:C:...' (if I understand the documentation correctly).
DISCLAIMER: This solution is not 100% accurate in terms of determining the minimal width.
I was also figuring out how to measure text on a canvas. After reading the great post from mice i had some problems on how to measure multiline text. There is no obvious way from these contributions but after some research i cam across the StaticLayout class. It allows you to measure multiline text (text with "\n") and configure much more properties of your text via the associated Paint.
Here is a snippet showing how to measure multiline text:
private StaticLayout measure( TextPaint textPaint, String text, Integer wrapWidth ) {
int boundedWidth = Integer.MAX_VALUE;
if (wrapWidth != null && wrapWidth > 0 ) {
boundedWidth = wrapWidth;
}
StaticLayout layout = new StaticLayout( text, textPaint, boundedWidth, Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false );
return layout;
}
The wrapwitdh is able to determin if you want to limit your multiline text to a certain width.
Since the StaticLayout.getWidth() only returns this boundedWidth you have to take another step to get the maximum width required by your multiline text. You are able to determine each lines width and the max width is the highest line width of course:
private float getMaxLineWidth( StaticLayout layout ) {
float maxLine = 0.0f;
int lineCount = layout.getLineCount();
for( int i = 0; i < lineCount; i++ ) {
if( layout.getLineWidth( i ) > maxLine ) {
maxLine = layout.getLineWidth( i );
}
}
return maxLine;
}
Yes, you can do it. you can either use css or javascript to hide the reCaptcha v3 badge.
display: none
or visibility: hidden
to hide the reCaptcha batch. It's easy and quick..grecaptcha-badge {
display:none !important;
}
var el = document.querySelector('.grecaptcha-badge');
el.style.display = 'none';
Hiding the badge is valid, according to the google policy and answered in faq here. It is recommended to show up the privacy policy and terms of use from google as shown below.
Use a parameterized query to prevent Sql injections (secutity problem)
Use the using statement so the connection will be closed and resources will be disposed.
using(var connection = new SqlConnection("connectionString"))
{
connection.Open();
var sql = "INSERT INTO Main(FirstName, SecondName) VALUES(@FirstName, @SecondName)";
using(var cmd = new SqlCommand(sql, connection))
{
cmd.Parameters.AddWithValue("@FirstName", txFirstName.Text);
cmd.Parameters.AddWithValue("@SecondName", txSecondName.Text);
cmd.ExecuteNonQuery();
}
}
I came here from google so it might be relevant to others:
for yarn
you could use:
yarn --cwd /path/to/your/app run start
Please read this: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
You should set indicies for your html elements "name" attributes like planCompareViewModel[0].PlanId
, planCompareViewModel[1].PlanId
to make binder able to parse them into IEnumerable.
Instead of @foreach (var planVM in Model)
use for
loop and render names with indexes.
To get an object from a xib file programatically you can use: [[NSBundle mainBundle] loadNibNamed:@"MyXibName" owner:self options:nil]
which returns an array of the top level objects in the xib.
So, you could do something like this:
UIView *rootView = [[[NSBundle mainBundle] loadNibNamed:@"MyRootView" owner:self options:nil] objectAtIndex:0];
UIView *containerView = [[[NSBundle mainBundle] loadNibNamed:@"MyContainerView" owner:self options:nil] lastObject];
[rootView addSubview:containerView];
[self.view addSubview:rootView];
Ref :Youtube Video Download (Android/Java)
Edit 3
You can use the Lib : https://github.com/HaarigerHarald/android-youtubeExtractor
Ex :
String youtubeLink = "http://youtube.com/watch?v=xxxx";
new YouTubeExtractor(this) {
@Override
public void onExtractionComplete(SparseArray<YtFile> ytFiles, VideoMeta vMeta) {
if (ytFiles != null) {
int itag = 22;
String downloadUrl = ytFiles.get(itag).getUrl();
}
}
}.extract(youtubeLink, true, true);
They decipherSignature using :
private boolean decipherSignature(final SparseArray<String> encSignatures) throws IOException {
// Assume the functions don't change that much
if (decipherFunctionName == null || decipherFunctions == null) {
String decipherFunctUrl = "https://s.ytimg.com/yts/jsbin/" + decipherJsFileName;
BufferedReader reader = null;
String javascriptFile;
URL url = new URL(decipherFunctUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("User-Agent", USER_AGENT);
try {
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder sb = new StringBuilder("");
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append(" ");
}
javascriptFile = sb.toString();
} finally {
if (reader != null)
reader.close();
urlConnection.disconnect();
}
if (LOGGING)
Log.d(LOG_TAG, "Decipher FunctURL: " + decipherFunctUrl);
Matcher mat = patSignatureDecFunction.matcher(javascriptFile);
if (mat.find()) {
decipherFunctionName = mat.group(1);
if (LOGGING)
Log.d(LOG_TAG, "Decipher Functname: " + decipherFunctionName);
Pattern patMainVariable = Pattern.compile("(var |\\s|,|;)" + decipherFunctionName.replace("$", "\\$") +
"(=function\\((.{1,3})\\)\\{)");
String mainDecipherFunct;
mat = patMainVariable.matcher(javascriptFile);
if (mat.find()) {
mainDecipherFunct = "var " + decipherFunctionName + mat.group(2);
} else {
Pattern patMainFunction = Pattern.compile("function " + decipherFunctionName.replace("$", "\\$") +
"(\\((.{1,3})\\)\\{)");
mat = patMainFunction.matcher(javascriptFile);
if (!mat.find())
return false;
mainDecipherFunct = "function " + decipherFunctionName + mat.group(2);
}
int startIndex = mat.end();
for (int braces = 1, i = startIndex; i < javascriptFile.length(); i++) {
if (braces == 0 && startIndex + 5 < i) {
mainDecipherFunct += javascriptFile.substring(startIndex, i) + ";";
break;
}
if (javascriptFile.charAt(i) == '{')
braces++;
else if (javascriptFile.charAt(i) == '}')
braces--;
}
decipherFunctions = mainDecipherFunct;
// Search the main function for extra functions and variables
// needed for deciphering
// Search for variables
mat = patVariableFunction.matcher(mainDecipherFunct);
while (mat.find()) {
String variableDef = "var " + mat.group(2) + "={";
if (decipherFunctions.contains(variableDef)) {
continue;
}
startIndex = javascriptFile.indexOf(variableDef) + variableDef.length();
for (int braces = 1, i = startIndex; i < javascriptFile.length(); i++) {
if (braces == 0) {
decipherFunctions += variableDef + javascriptFile.substring(startIndex, i) + ";";
break;
}
if (javascriptFile.charAt(i) == '{')
braces++;
else if (javascriptFile.charAt(i) == '}')
braces--;
}
}
// Search for functions
mat = patFunction.matcher(mainDecipherFunct);
while (mat.find()) {
String functionDef = "function " + mat.group(2) + "(";
if (decipherFunctions.contains(functionDef)) {
continue;
}
startIndex = javascriptFile.indexOf(functionDef) + functionDef.length();
for (int braces = 0, i = startIndex; i < javascriptFile.length(); i++) {
if (braces == 0 && startIndex + 5 < i) {
decipherFunctions += functionDef + javascriptFile.substring(startIndex, i) + ";";
break;
}
if (javascriptFile.charAt(i) == '{')
braces++;
else if (javascriptFile.charAt(i) == '}')
braces--;
}
}
if (LOGGING)
Log.d(LOG_TAG, "Decipher Function: " + decipherFunctions);
decipherViaWebView(encSignatures);
if (CACHING) {
writeDeciperFunctToChache();
}
} else {
return false;
}
} else {
decipherViaWebView(encSignatures);
}
return true;
}
Now with use of this library High Quality Videos Lossing Audio so i use the MediaMuxer for Murging Audio
and Video for Final Output
Edit 1
https://stackoverflow.com/a/15240012/9909365
Why the previous answer not worked
Pattern p2 = Pattern.compile("sig=(.*?)[&]");
Matcher m2 = p2.matcher(url);
String sig = null;
if (m2.find()) {
sig = m2.group(1);
}
As of November 2016, this is a little rough around the edges, but displays the basic principle. The url_encoded_fmt_stream_map today does not have a space after the colon (better make this optional) and "
sig
" has been changed to "signature
"and while i am debuging the code i found the new keyword its
signature&s
in many video's URL
here edited answer
private static final HashMap<String, Meta> typeMap = new HashMap<String, Meta>();
initTypeMap(); call first
class Meta {
public String num;
public String type;
public String ext;
Meta(String num, String ext, String type) {
this.num = num;
this.ext = ext;
this.type = type;
}
}
class Video {
public String ext = "";
public String type = "";
public String url = "";
Video(String ext, String type, String url) {
this.ext = ext;
this.type = type;
this.url = url;
}
}
public ArrayList<Video> getStreamingUrisFromYouTubePage(String ytUrl)
throws IOException {
if (ytUrl == null) {
return null;
}
// Remove any query params in query string after the watch?v=<vid> in
// e.g.
// http://www.youtube.com/watch?v=0RUPACpf8Vs&feature=youtube_gdata_player
int andIdx = ytUrl.indexOf('&');
if (andIdx >= 0) {
ytUrl = ytUrl.substring(0, andIdx);
}
// Get the HTML response
/* String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0.1)";*/
/* HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
userAgent);
HttpGet request = new HttpGet(ytUrl);
HttpResponse response = client.execute(request);*/
String html = "";
HttpsURLConnection c = (HttpsURLConnection) new URL(ytUrl).openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
InputStream in = c.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line.replace("\\u0026", "&"));
}
in.close();
html = str.toString();
// Parse the HTML response and extract the streaming URIs
if (html.contains("verify-age-thumb")) {
Log.e("Downloader", "YouTube is asking for age verification. We can't handle that sorry.");
return null;
}
if (html.contains("das_captcha")) {
Log.e("Downloader", "Captcha found, please try with different IP address.");
return null;
}
Pattern p = Pattern.compile("stream_map\":\"(.*?)?\"");
// Pattern p = Pattern.compile("/stream_map=(.[^&]*?)\"/");
Matcher m = p.matcher(html);
List<String> matches = new ArrayList<String>();
while (m.find()) {
matches.add(m.group());
}
if (matches.size() != 1) {
Log.e("Downloader", "Found zero or too many stream maps.");
return null;
}
String urls[] = matches.get(0).split(",");
HashMap<String, String> foundArray = new HashMap<String, String>();
for (String ppUrl : urls) {
String url = URLDecoder.decode(ppUrl, "UTF-8");
Log.e("URL","URL : "+url);
Pattern p1 = Pattern.compile("itag=([0-9]+?)[&]");
Matcher m1 = p1.matcher(url);
String itag = null;
if (m1.find()) {
itag = m1.group(1);
}
Pattern p2 = Pattern.compile("signature=(.*?)[&]");
Matcher m2 = p2.matcher(url);
String sig = null;
if (m2.find()) {
sig = m2.group(1);
} else {
Pattern p23 = Pattern.compile("signature&s=(.*?)[&]");
Matcher m23 = p23.matcher(url);
if (m23.find()) {
sig = m23.group(1);
}
}
Pattern p3 = Pattern.compile("url=(.*?)[&]");
Matcher m3 = p3.matcher(ppUrl);
String um = null;
if (m3.find()) {
um = m3.group(1);
}
if (itag != null && sig != null && um != null) {
Log.e("foundArray","Adding Value");
foundArray.put(itag, URLDecoder.decode(um, "UTF-8") + "&"
+ "signature=" + sig);
}
}
Log.e("foundArray","Size : "+foundArray.size());
if (foundArray.size() == 0) {
Log.e("Downloader", "Couldn't find any URLs and corresponding signatures");
return null;
}
ArrayList<Video> videos = new ArrayList<Video>();
for (String format : typeMap.keySet()) {
Meta meta = typeMap.get(format);
if (foundArray.containsKey(format)) {
Video newVideo = new Video(meta.ext, meta.type,
foundArray.get(format));
videos.add(newVideo);
Log.d("Downloader", "YouTube Video streaming details: ext:" + newVideo.ext
+ ", type:" + newVideo.type + ", url:" + newVideo.url);
}
}
return videos;
}
private class YouTubePageStreamUriGetter extends AsyncTask<String, String, ArrayList<Video>> {
ProgressDialog progressDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(webViewActivity.this, "",
"Connecting to YouTube...", true);
}
@Override
protected ArrayList<Video> doInBackground(String... params) {
ArrayList<Video> fVideos = new ArrayList<>();
String url = params[0];
try {
ArrayList<Video> videos = getStreamingUrisFromYouTubePage(url);
/* Log.e("Downloader","Size of Video : "+videos.size());*/
if (videos != null && !videos.isEmpty()) {
for (Video video : videos)
{
Log.e("Downloader", "ext : " + video.ext);
if (video.ext.toLowerCase().contains("mp4") || video.ext.toLowerCase().contains("3gp") || video.ext.toLowerCase().contains("flv") || video.ext.toLowerCase().contains("webm")) {
ext = video.ext.toLowerCase();
fVideos.add(new Video(video.ext,video.type,video.url));
}
}
return fVideos;
}
} catch (Exception e) {
e.printStackTrace();
Log.e("Downloader", "Couldn't get YouTube streaming URL", e);
}
Log.e("Downloader", "Couldn't get stream URI for " + url);
return null;
}
@Override
protected void onPostExecute(ArrayList<Video> streamingUrl) {
super.onPostExecute(streamingUrl);
progressDialog.dismiss();
if (streamingUrl != null) {
if (!streamingUrl.isEmpty()) {
//Log.e("Steaming Url", "Value : " + streamingUrl);
for (int i = 0; i < streamingUrl.size(); i++) {
Video fX = streamingUrl.get(i);
Log.e("Founded Video", "URL : " + fX.url);
Log.e("Founded Video", "TYPE : " + fX.type);
Log.e("Founded Video", "EXT : " + fX.ext);
}
//new ProgressBack().execute(new String[]{streamingUrl, filename + "." + ext});
}
}
}
}
public void initTypeMap()
{
typeMap.put("13", new Meta("13", "3GP", "Low Quality - 176x144"));
typeMap.put("17", new Meta("17", "3GP", "Medium Quality - 176x144"));
typeMap.put("36", new Meta("36", "3GP", "High Quality - 320x240"));
typeMap.put("5", new Meta("5", "FLV", "Low Quality - 400x226"));
typeMap.put("6", new Meta("6", "FLV", "Medium Quality - 640x360"));
typeMap.put("34", new Meta("34", "FLV", "Medium Quality - 640x360"));
typeMap.put("35", new Meta("35", "FLV", "High Quality - 854x480"));
typeMap.put("43", new Meta("43", "WEBM", "Low Quality - 640x360"));
typeMap.put("44", new Meta("44", "WEBM", "Medium Quality - 854x480"));
typeMap.put("45", new Meta("45", "WEBM", "High Quality - 1280x720"));
typeMap.put("18", new Meta("18", "MP4", "Medium Quality - 480x360"));
typeMap.put("22", new Meta("22", "MP4", "High Quality - 1280x720"));
typeMap.put("37", new Meta("37", "MP4", "High Quality - 1920x1080"));
typeMap.put("33", new Meta("38", "MP4", "High Quality - 4096x230"));
}
Edit 2:
Some time This Code Not worked proper
Same-origin policy
https://en.wikipedia.org/wiki/Same-origin_policy
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing
problem of Same-origin policy. Essentially, you cannot download this file from www.youtube.com because they are different domains. A workaround of this problem is [CORS][1].
url_encoded_fmt_stream_map // traditional: contains video and audio stream
adaptive_fmts // DASH: contains video or audio stream
Each of these is a comma separated array of what I would call "stream objects". Each "stream object" will contain values like this
url // direct HTTP link to a video
itag // code specifying the quality
s // signature, security measure to counter downloading
Each URL will be encoded so you will need to decode them. Now the tricky part.
YouTube has at least 3 security levels for their videos
unsecured // as expected, you can download these with just the unencoded URL
s // see below
RTMPE // uses "rtmpe://" protocol, no known method for these
The RTMPE videos are typically used on official full length movies, and are protected with SWF Verification Type 2. This has been around since 2011 and has yet to be reverse engineered.
The type "s" videos are the most difficult that can actually be downloaded. You will typcially see these on VEVO videos and the like. They start with a signature such as
AA5D05FA7771AD4868BA4C977C3DEAAC620DE020E.0F421820F42978A1F8EAFCDAC4EF507DB5 Then the signature is scrambled with a function like this
function mo(a) {
a = a.split("");
a = lo.rw(a, 1);
a = lo.rw(a, 32);
a = lo.IC(a, 1);
a = lo.wS(a, 77);
a = lo.IC(a, 3);
a = lo.wS(a, 77);
a = lo.IC(a, 3);
a = lo.wS(a, 44);
return a.join("")
}
This function is dynamic, it typically changes every day. To make it more difficult the function is hosted at a URL such as
http://s.ytimg.com/yts/jsbin/html5player-en_US-vflycBCEX.js
this introduces the problem of Same-origin policy. Essentially, you cannot download this file from www.youtube.com because they are different domains. A workaround of this problem is CORS. With CORS, s.ytimg.com could add this header
Access-Control-Allow-Origin: http://www.youtube.com
and it would allow the JavaScript to download from www.youtube.com. Of course they do not do this. A workaround for this workaround is to use a CORS proxy. This is a proxy that responds with the following header to all requests
Access-Control-Allow-Origin: *
So, now that you have proxied your JS file, and used the function to scramble the signature, you can use that in the querystring to download a video.
Based on the above answer I've written a small extension class to work with CSS and JS files:
public static class TimestampedContentExtensions
{
public static string VersionedContent(this UrlHelper helper, string contentPath)
{
var context = helper.RequestContext.HttpContext;
if (context.Cache[contentPath] == null)
{
var physicalPath = context.Server.MapPath(contentPath);
var version = @"v=" + new FileInfo(physicalPath).LastWriteTime.ToString(@"yyyyMMddHHmmss");
var translatedContentPath = helper.Content(contentPath);
var versionedContentPath =
contentPath.Contains(@"?")
? translatedContentPath + @"&" + version
: translatedContentPath + @"?" + version;
context.Cache.Add(physicalPath, version, null, DateTime.Now.AddMinutes(1), TimeSpan.Zero,
CacheItemPriority.Normal, null);
context.Cache[contentPath] = versionedContentPath;
return versionedContentPath;
}
else
{
return context.Cache[contentPath] as string;
}
}
}
Instead of writing something like:
<link href="@Url.Content(@"~/Content/bootstrap.min.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content(@"~/Scripts/bootstrap.min.js")"></script>
You can now write:
<link href="@Url.VersionedContent(@"~/Content/bootstrap.min.css")" rel="stylesheet" type="text/css" />
<script src="@Url.VersionedContent(@"~/Scripts/bootstrap.min.js")"></script>
I.e. simply replace Url.Content
with Url.VersionedContent
.
Generated URLs look something like:
<link href="/Content/bootstrap.min.css?v=20151104105858" rel="stylesheet" type="text/css" />
<script src="/Scripts/bootstrap.min.js?v=20151029213517"></script>
If you use the extension class you might want to add error handling in case the MapPath
call doesn't work, since contentPath
isn't a physical file.
The correct format for IE8 is:
$("#ActionBox").css({ 'margin-top': '10px' });
with this work.
Promises
Observables
One operator retry can be used to retry whenever needed, also if we need to retry the observable based on some conditions retryWhen can be used.
Note: A list of operators along with their interactive diagrams is available here at RxMarbles.com
Java simple code to generate encoded(HMAC-x) signatures. (Tried using Java-8 and Eclipse)
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import com.sun.org.apache.xml.internal.security.utils.Base64;
/**
* Encryption class to show how to generate encoded(HMAC-x) signatures.
*
*/
public class Encryption {
public static void main(String args[]) {
String message = "This is my message.";
String key = "your_key";
String algorithm = "HmacMD5"; // OPTIONS= HmacSHA512, HmacSHA256, HmacSHA1, HmacMD5
try {
// 1. Get an algorithm instance.
Mac sha256_hmac = Mac.getInstance(algorithm);
// 2. Create secret key.
SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), algorithm);
// 3. Assign secret key algorithm.
sha256_hmac.init(secret_key);
// 4. Generate Base64 encoded cipher string.
String hash = Base64.encode(sha256_hmac.doFinal(message.getBytes("UTF-8")));
// You can use any other encoding format to get hash text in that encoding.
System.out.println(hash);
/**
* Here are the outputs for given algorithms:-
*
* HmacMD5 = hpytHW6XebJ/hNyJeX/A2w==
* HmacSHA1 = CZbtauhnzKs+UkBmdC1ssoEqdOw=
* HmacSHA256 =gCZJBUrp45o+Z5REzMwyJrdbRj8Rvfoy33ULZ1bySXM=
* HmacSHA512 = OAqi5yEbt2lkwDuFlO6/4UU6XmU2JEDuZn6+1pY4xLAq/JJGSNfSy1if499coG1K2Nqz/yyAMKPIx9C91uLj+w==
*/
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
}
}
NOTE: You can use any other Algorithms and can try generating
HmacMD5
,HmacSHA1
,HmacSHA256
,HmacSHA512
signatures.
You could use something like this:
(function($) {
$.fn.parentNth = function(n) {
var el = $(this);
for(var i = 0; i < n; i++)
el = el.parent();
return el;
};
})(jQuery);
alert($("#foo").parentNth(2).attr("id"));
A picture is worth a thousand words !
The concept of Angular is very simple. It propose to "build" an app with "bricks" -> modules.
This concept makes it possible to better structure the code and to facilitate reuse and sharing.
Be careful not to confuse the Angular modules with the ES2015 / TypeScript modules.
Regarding the Angular module, it is a mechanism for:
1- group components (but also services, directives, pipes etc ...)
2- define their dependencies
3- define their visibility.
An Angular module is simply defined with a class (usually empty) and the NgModule decorator.
Use the below command to get hive version
hive --service version
my_hash.each { |k, v| my_hash[k] = v.upcase }
or, if you'd prefer to do it non-destructively, and return a new hash instead of modifying my_hash
:
a_new_hash = my_hash.inject({}) { |h, (k, v)| h[k] = v.upcase; h }
This last version has the added benefit that you could transform the keys too.
To create list and list of lists use below syntax
x = [[] for i in range(10)]
this will create 1-d list and to initialize it put number in [[number] and set length of list put length in range(length)
x = [[[0] for i in range(3)] for i in range(10)]
this will initialize list of lists with 10*3 dimension and with value 0
x[1][5]=value
In short, Idempotent operations means that the operation will not result in different results no matter how many times you operate the idempotent operations.
For example, according to the definition of the spec of HTTP, GET, HEAD, PUT, and DELETE
are idempotent operations; however POST and PATCH
are not. That's why sometimes POST
is replaced by PUT
.
Invalidating caches/Restart didn't worked for me. But simply deleting the caches folder in \Users\user.AndroidStudio(version)\system worked like a charm
If you need only Parameter info then:
On Mac, it's assigned to Command+P
On Windows, it's assigned to Ctrl+P
If you need document info then:
On Mac, it's assigned to Command+Q
On Windows, it's assigned to Ctrl+Q
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mywebsite</groupId>
<artifactId>emusicstore</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.9</source>
<target>1.9</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- ... -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
MyWebAppContextListener.java
package com.emusicstore.utils;
import com.mysql.cj.jdbc.AbandonedConnectionCleanupThread;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;
public class MyWebAppContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
System.out.println("************** Starting up! **************");
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("************** Shutting down! **************");
System.out.println("Destroying Context...");
System.out.println("Calling MySQL AbandonedConnectionCleanupThread checkedShutdown");
AbandonedConnectionCleanupThread.checkedShutdown();
ClassLoader cl = Thread.currentThread().getContextClassLoader();
Enumeration<Driver> drivers = DriverManager.getDrivers();
while (drivers.hasMoreElements()) {
Driver driver = drivers.nextElement();
if (driver.getClass().getClassLoader() == cl) {
try {
System.out.println("Deregistering JDBC driver {}");
DriverManager.deregisterDriver(driver);
} catch (SQLException ex) {
System.out.println("Error deregistering JDBC driver {}");
ex.printStackTrace();
}
} else {
System.out.println("Not deregistering JDBC driver {} as it does not belong to this webapp's ClassLoader");
}
}
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<listener>
<listener-class>com.emusicstore.utils.MyWebAppContextListener</listener-class>
</listener>
<!-- ... -->
</web-app>
Source that inspired me for this bug fix.
As Ollie C mentioned, there is an active bug for the support library using returned values to onActivityResult when you are using nested fragments. I just hit it :-(.
See Fragment.onActivityResult not called when requestCode != 0.
Save:
public boolean saveFile(Context context, String mytext){
Log.i("TESTE", "SAVE");
try {
FileOutputStream fos = context.openFileOutput("file_name"+".txt",Context.MODE_PRIVATE);
Writer out = new OutputStreamWriter(fos);
out.write(mytext);
out.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
Load:
public String load(Context context){
Log.i("TESTE", "FILE");
try {
FileInputStream fis = context.openFileInput("file_name"+".txt");
BufferedReader r = new BufferedReader(new InputStreamReader(fis));
String line= r.readLine();
r.close();
return line;
} catch (IOException e) {
e.printStackTrace();
Log.i("TESTE", "FILE - false");
return null;
}
}
If you want to "uncommit", erase the last commit message, and put the modified files back in staging, you would use the command:
git reset --soft HEAD~1
--soft
indicates that the uncommitted files should be retained as working files opposed to --hard
which would discard them.HEAD~1
is the last commit. If you want to rollback 3 commits you could use HEAD~3
. If you want to rollback to a specific revision number, you could also do that using its SHA hash.This is an extremely useful command in situations where you committed the wrong thing and you want to undo that last commit.
Source: http://nakkaya.com/2009/09/24/git-delete-last-commit/
this is pretty simple:
HttpUtility.HtmlDecode(Model.Content)
Another Solution, you could also return a HTMLString, Razor will output the correct formatting:
in the view itself:
@Html.GetSomeHtml()
in controller:
public static HtmlString GetSomeHtml()
{
var Data = "abc<br/>123";
return new HtmlString(Data);
}
This method seems to do what you want:
$('#email-field-only').valid();
I would suggest
sapply(foo, typeof)
if you need the actual types of the vectors in the data frame. class()
is somewhat of a different beast.
If you don't need to get this information as a vector (i.e. you don't need it to do something else programmatically later), just use str(foo)
.
In both cases foo
would be replaced with the name of your data frame.
we need to create package.json by entering npm init
and enter package name as package.json and optionally fill other requirements else press enter and at last
enter yes to confirm.
Great!!
Now install any npm package without any error.
npm install <package_name>
Windows10
Use the after
method on the Tk
object:
from tkinter import *
root = Tk()
def task():
print("hello")
root.after(2000, task) # reschedule event in 2 seconds
root.after(2000, task)
root.mainloop()
Here's the declaration and documentation for the after
method:
def after(self, ms, func=None, *args):
"""Call function once after given time.
MS specifies the time in milliseconds. FUNC gives the
function which shall be called. Additional parameters
are given as parameters to the function call. Return
identifier to cancel scheduling with after_cancel."""
You can create a .timer
systemd unit file to control the execution of your .service
unit file.
So for example, to wait for 1 minute after boot-up before starting your foo.service
, create a foo.timer
file in the same directory with the contents:
[Timer]
OnBootSec=1min
It is important that the service is disabled (so it doesn't start at boot), and the timer enabled, for all this to work (thanks to user tride for this):
systemctl disable foo.service
systemctl enable foo.timer
You can find quite a few more options and all information needed here: https://wiki.archlinux.org/index.php/Systemd/Timers
There is an api in Express.
res.sendFile
app.get('/report/:chart_id/:user_id', function (req, res) {
// res.sendFile(filepath);
});
As with many questions, the answer is - It depends.
You should be very careful when handling large amounts of data on the front end. On top of making your front end feel sluggish, Firestore also charges you $0.60 per million reads you make.
Use with care - Frontend user experience may take a hit
Handling this on the front end should be fine as long as you are not doing too much logic with this returned array.
db.collection('...').get().then(snap => {
size = snap.size // will return the collection size
});
Use with care - Firestore read invocations may cost a lot
Handling this on the front end is not feasible as it has too much potential to slow down the users system. We should handle this logic server side and only return the size.
The drawback to this method is you are still invoking firestore reads (equal to the size of your collection), which in the long run may end up costing you more than expected.
Cloud Function:
...
db.collection('...').get().then(snap => {
res.status(200).send({length: snap.size});
});
Front End:
yourHttpClient.post(yourCloudFunctionUrl).toPromise().then(snap => {
size = snap.length // will return the collection size
})
Most scalable solution
FieldValue.increment()
As of April 2019 Firestore now allows incrementing counters, completely atomically, and without reading the data prior. This ensures we have correct counter values even when updating from multiple sources simultaneously (previously solved using transactions), while also reducing the number of database reads we perform.
By listening to any document deletes or creates we can add to or remove from a count field that is sitting in the database.
See the firestore docs - Distributed Counters Or have a look at Data Aggregation by Jeff Delaney. His guides are truly fantastic for anyone using AngularFire but his lessons should carry over to other frameworks as well.
Cloud Function:
export const documentWriteListener =
functions.firestore.document('collection/{documentUid}')
.onWrite((change, context) => {
if (!change.before.exists) {
// New document Created : add one to count
db.doc(docRef).update({numberOfDocs: FieldValue.increment(1)});
} else if (change.before.exists && change.after.exists) {
// Updating existing document : Do nothing
} else if (!change.after.exists) {
// Deleting document : subtract one from count
db.doc(docRef).update({numberOfDocs: FieldValue.increment(-1)});
}
return;
});
Now on the frontend you can just query this numberOfDocs field to get the size of the collection.
Description and examples can be found in IEEE Std 1800-2017 § 11.5.1 "Vector bit-select and part-select addressing". First IEEE appearance is IEEE 1364-2001 (Verilog) § 4.2.1 "Vector bit-select and part-select addressing". Here is an direct example from the LRM:
logic [31: 0] a_vect; logic [0 :31] b_vect; logic [63: 0] dword; integer sel; a_vect[ 0 +: 8] // == a_vect[ 7 : 0] a_vect[15 -: 8] // == a_vect[15 : 8] b_vect[ 0 +: 8] // == b_vect[0 : 7] b_vect[15 -: 8] // == b_vect[8 :15] dword[8*sel +: 8] // variable part-select with fixed width
If sel
is 0 then dword[8*(0) +: 8] == dword[7:0]
If sel
is 7 then dword[8*(7) +: 8] == dword[63:56]
The value to the left always the starting index. The number to the right is the width and must be a positive constant. the +
and -
indicates to select the bits of a higher or lower index value then the starting index.
Assuming address
is in little endian ([msb:lsb]) format, then if(address[2*pointer+:2])
is the equivalent of if({address[2*pointer+1],address[2*pointer]})
.pdflink:after {
background-image: url('/images/pdf.png');
background-size: 10px 20px;
width: 10px;
height: 20px;
padding-left: 10px;// equal to width of image.
margin-left:5px;// to add some space for better look
content:"";
}
To answer one of the questions, it is necessary to have both a global and local install for the tools to work.
If you try to run ng serve
on an application without the local install of the CLI (global install only), you will get the following error.
You have to be inside an Angular CLI project in order to use the serve command.
It will also print this message:
Please take the following steps to avoid issues:
"npm install --save-dev @angular/cli@latest"
Run that npm
command to update the CLI locally, and avoid the warning that you are getting.
Other question: It looks like they do not have to be in sync, but it's probably best that they are in order to avoid any unusual behavior with the tool, or any inconsistencies with the code the tool generates.
Why do we need both the global install, and a local install?
The global install is needed to start a new application. The ng new <app-name>
command is run using the global installation of the CLI. In fact, if you try to run ng new
while inside the folder structure of an existing CLI application, you get this lovely error:
You cannot use the
new
command inside an Angular CLI project.
Other commands that can be run from the global install are ng help
, ng get/set
with the --global
option, ng version
, ng doc
, and ng completion
.
The local install of the CLI is used after an application has been built. This way, when new versions of the CLI are available, you can update your global install, and not affect the local install. This is good for the stability of a project. Most ng
commands only make sense with the local version, like lint
, build
and serve
, etc.
According to the CLI GitHub readme, to update the CLI you must update the global and local package. However, I have used the CLI where the global and local version vary without any trouble so far. If I ever run across an error related to having the global and local CLI versions out of sync, I will post that here.
I like the answer of Patrick Cuff. What I like to add is the distinction between a test level and a test type which was for me an eye opener.
Test level is easy to explain using V-model, an example: Each test level has its corresponding development level. It has a typical time characteristic, they're executed at certain phase in the development life cycle.
A test type is a characteristics, it focuses on a specific test objective. Test types emphasize your quality aspects, also known as technical or non-functional aspects. Test types can be executed at any test level. I like to use as test types the quality characteristics mentioned in ISO/IEC 25010:2011.
To make it complete. There's also something called regression testing. This an extra classification next to test level and test type. A regression test is a test you want to repeat because it touches something critical in your product. It's in fact a subset of tests you defined for each test level. If a there's a small bug fix in your product, one doesn't always have the time to repeat all tests. Regression testing is an answer to that.
In case of JBoss... right click on project ? Build Java path ? add external JAR files.
Then browse to jboss-folder ? Common ? lib ? servlet-api.jar
. . Click OK, refresh the project, and run it...
You can use "dd/MM/yyyy"
format for using it in DateTime.ParseExact
.
Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.
DateTime date = DateTime.ParseExact("24/01/2013", "dd/MM/yyyy", CultureInfo.InvariantCulture);
Here is a DEMO
.
For more informations, check out Custom Date and Time Format Strings
Something like this.
num1 = num2 = 5
I've experienced the same problem. One of the responds to your question led me to the following idea (which worked eventually). I use Python 3.7.
# just an example
def func(): # define a function
func.y = 4 # here y is a local variable, which I want to access; func.y defines
# a method for my example function which will allow me to access
# function's local variable y
x = func.y + 8 # this is the main task for the function: what it should do
return x
func() # now I'm calling the function
a = func.y # I put it's local variable into my new variable
print(a) # and print my new variable
Then I launch this program in Windows PowerShell and get the answer 4. Conclusion: to be able to access a local function's variable one might add the name of the function and a dot before the name of the local variable (and then, of course, use this construction for calling the variable both in the function's body and outside of it). I hope this will help.
Currently, Firefox honors the language of the HTML element in which the input resides. For example, try this fiddle in Firefox:
http://jsfiddle.net/ashraf_sabry_m/yzzhop75/1/
You will see that the numerals are in Arabic, and the comma is used as the decimal separator, which is the case with Arabic. This is because the BODY
tag is given the attribute lang="ar-EG"
.
Next, try this one:
http://jsfiddle.net/ashraf_sabry_m/yzzhop75/2/
This one is displayed with a dot as the decimal separator because the input is wrapped in a DIV
given the attribute lang="en-US"
.
So, a solution you may resort to is to wrap your numeric inputs with a container element that is set to use a culture that uses dots as the decimal separator.
You have to specify what encoding the data is. Either in meta or in headers
header('Content-Type: text/plain; charset=utf-8');
I tried clearing the chrome cookies to get rid of postman cookies, as one of the answers given here. But it didn't work for me. I checked my postman version, found that it's an old version 5.5.4. So I just tried a Postman update to its latest version 7.3.4. Cool, the issue fixed !!
As you see in an error UseCalls.java:27: error: cannot find symbol
return String.parseString(input);
there is no method parseString
in String
class. There is no need to parse it as long as JOptionPane.showInputDialog(prompt);
already returns a string.
but layer 02, will cover all drawings in layer 01. I used this to show drawing in both layers. use (background-color: transparent;) in style.
<div style="position: relative;"> _x000D_
<canvas id="lay01" width="500" height="500" style="position: absolute; left: 0; top: 0; z-index: 0; background-color: transparent;">_x000D_
</canvas> _x000D_
<canvas id="lay02" width="500" height="500" style="position: absolute; left: 0; top: 0; z-index: 1; background-color: transparent;">_x000D_
</canvas>_x000D_
</div>
_x000D_
Just drop the option v
.
-v
is for verbose. If you don't use it then it won't display:
tar -zxf tmp.tar.gz -C ~/tmp1
I apologize if this is too late to reply, but since I've been doing something similar I thought I could contribute somehow.
Maybe with OpenCV you could use template matching. Assuming you're using a webcam as you said:
Tip: max_val (or min_val depending on the method used) will give you numbers, large numbers. To get the difference in percentage, use template matching with the same image -- the result will be your 100%.
Pseudo code to exemplify:
previous_screenshot = ...
current_screenshot = ...
# simplify both images somehow
# get the 100% corresponding value
res = matchTemplate(previous_screenshot, previous_screenshot, TM_CCOEFF)
_, hundred_p_val, _, _ = minMaxLoc(res)
# hundred_p_val is now the 100%
res = matchTemplate(previous_screenshot, current_screenshot, TM_CCOEFF)
_, max_val, _, _ = minMaxLoc(res)
difference_percentage = max_val / hundred_p_val
# the tolerance is now up to you
Hope it helps.
first you have to set an id for your audio element
in your js :
var ply = document.getElementById('player');
var oldSrc = ply.src;
// just to remember the old source
ply.src = "";
// to stop the player you have to replace the source with nothing
Working with a dictionary ->level2 above comes from a dictionary in my case (just in case anybody will find it useful) Trying the first example I stumbled over this error: "This document already has a 'DocumentElement' node." I was inspired by the answer here
and edited my code: (xmlDoc.DocumentElement.AppendChild(body))
//a dictionary:
Dictionary<string, string> Level2Data
{
{"level2", "text"},
{"level2", "other text"},
{"same_level2", "more text"}
}
//xml Decalration:
XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = xmlDoc.DocumentElement;
xmlDoc.InsertBefore(xmlDeclaration, root);
// add body
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.AppendChild(body);
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.DocumentElement.AppendChild(body); //without DocumentElement ->ERR
foreach (KeyValuePair<string, string> entry in Level2Data)
{
//write to xml: - it works version 1.
XmlNode keyNode = xmlDoc.CreateElement(entry.Key); //open TAB
keyNode.InnerText = entry.Value;
body.AppendChild(keyNode); //close TAB
//Write to xmml verdion 2: (uncomment the next 4 lines and comment the above 3 - version 1
//XmlElement key = xmlDoc.CreateElement(string.Empty, entry.Key, string.Empty);
//XmlText value = xmlDoc.CreateTextNode(entry.Value);
//key.AppendChild(value);
//body.AppendChild(key);
}
Both versions (1 and 2 inside foreach loop) give the output:
<?xml version="1.0" encoding="UTF-8"?>
<body>
<level1>
<level2>text</level2>
<level2>ther text</level2>
<same_level2>more text</same_level2>
</level1>
</body>
(Note: third line "same level2" in dictionary can be also level2 as the others but I wanted to ilustrate the advantage of the dictionary - in my case I needed level2 with different names.
The m2e plugin uses it's own distribution of Maven, packaged with the plugin.
In order to use Maven from command line, you need to have it installed as a standalone application. Here is an instruction explaining how to do it in Windows
Once Maven is properly installed (i.e. be sure that MAVEN_HOME
, JAVA_HOME
and PATH
variables are set correctly): you must run mvn eclipse:eclipse
from the directory containing the pom.xml
.
Whilst the above answers are correct its worth noting that MSBuild has changed and it no longer ships with the .net framework, it comes either stand alone or with visual studio. As a result it's binaries have moved... so the one you get under the 4.0.303619 directory is actually the old one!
I've just been caught out by this - I found automatic binding redirects were only working when running from VisualStudio but not when running msbuild from the command line... the clue was that binding redirects were added in VS 2013 (for that read .net framework 4.5). If you open up a vs command prompt you'll see it now gets it from program files as the other article mentions. Whereas I was using a batch file on my path which linked to the old version.
Version numbers
Under framework:
PS C:\Windows\Microsoft.NET\Framework\v4.0.30319> .\msbuild.exe -version
Microsoft (R) Build Engine version 4.0.30319.33440
[Microsoft .NET Framework, version 4.0.30319.34014]
Copyright (C) Microsoft Corporation. All rights reserved.
4.0.30319.33440PS C:\Windows\Microsoft.NET\Framework\v4.0.30319>
Under program files:
PS C:\Program Files (x86)\MSBuild\12.0\Bin> .\MSBuild.exe -version
Microsoft (R) Build Engine version 12.0.21005.1
[Microsoft .NET Framework, version 4.0.30319.34014]
Copyright (C) Microsoft Corporation. All rights reserved.
12.0.21005.1PS C:\Program Files (x86)\MSBuild\12.0\Bin>
If you are doing this in Java then why are you doing it? Just call .hashCode()
on the string
You can also use string.match().
var string1 = "aBc";
var match = string1.match(/AbC/i);
if(match) {
}
here is the code
import React, { Component } from 'react';
import logo from './logo.svg';
import './image.css';
import Dropdown from 'react-dropdown';
import axios from 'axios';
let obj = {};
class App extends Component {
constructor(){
super();
this.state = {
selectedFiles: []
}
this.fileUploadHandler = this.fileUploadHandler.bind(this);
}
fileUploadHandler(file){
let selectedFiles_ = this.state.selectedFiles;
selectedFiles_.push(file);
this.setState({selectedFiles: selectedFiles_});
}
render() {
let Images = this.state.selectedFiles.map(image => {
<div className = "image_parent">
<img src={require(image.src)}
/>
</div>
});
return (
<div className="image-upload images_main">
<input type="file" onClick={this.fileUploadHandler}/>
{Images}
</div>
);
}
}
export default App;
Check existing row with Any.
public static void insertOrUpdateCustomer(Customer customer)
{
using (var db = getDb())
{
db.Entry(customer).State = !db.Customer.Any(f => f.CustomerId == customer.CustomerId) ? EntityState.Added : EntityState.Modified;
db.SaveChanges();
}
}
This works for PL/SQL:
select count(*), id,address from table group by id,address having count(*)<2
(a[n:]+[default])[0]
This is probably better as a
gets larger
(a[n:n+1]+[default])[0]
This works because if a[n:]
is an empty list if n => len(a)
Here is an example of how this works with range(5)
>>> range(5)[3:4]
[3]
>>> range(5)[4:5]
[4]
>>> range(5)[5:6]
[]
>>> range(5)[6:7]
[]
And the full expression
>>> (range(5)[3:4]+[999])[0]
3
>>> (range(5)[4:5]+[999])[0]
4
>>> (range(5)[5:6]+[999])[0]
999
>>> (range(5)[6:7]+[999])[0]
999
I had a terrible time getting global modules to work. Eventually, I explicitly added C:\Users\yourusername\AppData\Roaming\npm
to the PATH variable under System Variables. I also needed to have this variable come before the nodejs path variable in the list.
I am running Windows 10.
A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.
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
I went to system
preferences -> mysql -> initialize database -> use legacy password encryption(instead of strong) -> entered same password
as my config.inc.php
file, restarted the apache server and it worked. I was still suspicious about it so I stopped the apache and mysql server and started them again and now it's working.
You can only stringify the array and append it. Sends the array as an actual Array even if it has only one item.
const array = [ 1, 2 ];
let formData = new FormData();
formData.append("numbers", JSON.stringify(array));
Using ints.sum()
has two problems:
customerssalary
, not ints
Sum()
, not sum()
.Additionally, you'll need a using directive of
using System.Linq;
Once you've got the sum, you can just divide by the length of the array to get the average - you don't need to use Average()
which will iterate over the array again.
int sum = customerssalary.Sum();
int average = sum / customerssalary.Length;
or as a double
:
double average = ((double) sum) / customerssalary.Length;
You may use an iterator over each byte in the output of the subprocess. This allows inline update (lines ending with '\r' overwrite previous output line) from the subprocess:
from subprocess import PIPE, Popen
command = ["my_command", "-my_arg"]
# Open pipe to subprocess
subprocess = Popen(command, stdout=PIPE, stderr=PIPE)
# read each byte of subprocess
while subprocess.poll() is None:
for c in iter(lambda: subprocess.stdout.read(1) if subprocess.poll() is None else {}, b''):
c = c.decode('ascii')
sys.stdout.write(c)
sys.stdout.flush()
if subprocess.returncode != 0:
raise Exception("The subprocess did not terminate correctly.")
You can avoid the unpleasant looking try/catch or regex by using the Scanner class:
String input = "123";
Scanner sc = new Scanner(input);
if (sc.hasNextInt())
System.out.println("an int: " + sc.nextInt());
else {
//handle the bad input
}
In Bootstrap 3 'dropdown.js' provides us with the various events that are triggered.
click.bs.dropdown
show.bs.dropdown
shown.bs.dropdown
etc
Instead of
Object.values(myObject);
use
Object["values"](myObject);
In your example case:
const values = Object["values"](data).map(x => x.substr(0, x.length - 4));
This will hide the ts compiler error.
I had some problems with the other solutions on this page, so thought I'd drop this in.
@Html.TextBoxFor(m => m.EndDate, "{0:d}", new { @class = "form-control datepicker" })
So you only need to add "{0:d}" in the second parameter and you should be good to go.
I am adding another answer for other solution I am using now because Android Query is so big and unmaintained to stay healthy. So i moved to this https://github.com/amitshekhariitbhu/Fast-Android-Networking.
AndroidNetworking.download(url,dirPath,fileName).build()
.setDownloadProgressListener(new DownloadProgressListener() {
public void onProgress(long bytesDownloaded, long totalBytes) {
bar.setMax((int) totalBytes);
bar.setProgress((int) bytesDownloaded);
}
}).startDownload(new DownloadListener() {
public void onDownloadComplete() {
...
}
public void onError(ANError error) {
...
}
});
The emulator included in your (old) version of Eclipse is very slow.
Recent emulators are faster than they use to be in 2010. Update your SDK/IDE.
Personally, I use a real phone to do my tests. It is faster and tests are more realistic. But if you want to test your application on a lot of different Android versions and don't want to buy several phones, you will have to use the emulator from time to time.
Here are some examples for insert ... on conflict ...
(pg 9.5+) :
insert into dummy(id, name, size) values(1, 'new_name', 3)
on conflict do nothing;`
insert into dummy(id, name, size) values(1, 'new_name', 3)
on conflict(id)
do update set name = 'new_name', size = 3;
insert into dummy(id, name, size) values(1, 'new_name', 3)
on conflict on constraint dummy_pkey
do update set name = 'new_name', size = 4;
The closest you can get to that kind of behavior with switch
statements is
switch (num) {
case 1:
case 2:
case 3:
case 4:
case 5:
System.out.println("1 through 5");
break;
case 6:
case 7:
case 8:
case 9:
case 10:
System.out.println("6 through 10");
break;
}
Use if
statements.
You could use a literal eval:
>>> ast.literal_eval('0xdeadbeef')
3735928559
Or just specify the base as argument to int
:
>>> int('deadbeef', 16)
3735928559
A trick that is not well known, if you specify the base 0
to int
, then Python will attempt to determine the base from the string prefix:
>>> int("0xff", 0)
255
>>> int("0o644", 0)
420
>>> int("0b100", 0)
4
>>> int("100", 0)
100
Unfortunately the xkcd comic isn't completely up to date anymore.
Since Python 3.0 you have to write:
print("Hello world!")
And someone still has to write that antigravity
library :(
C++ sorting using sort function
#include <bits/stdc++.h>
using namespace std;
vector <int> v[100];
int main()
{
sort(v.begin(), v.end());
}
add to your code:
"#include < stdlib.h>"
return EXIT_SUCCESS;
at the end of main()
Where do these values come from? The documentation for android:fontFamily does not list this information in any place
These are indeed not listed in the documentation. But they are mentioned here under the section 'Font families'. The document lists every new public API for Android Jelly Bean 4.1.
In the styles.xml file in the application I'm working on somebody listed this as the font family, and I'm pretty sure it's wrong:
Yes, that's wrong. You don't reference the font file, you have to use the font name mentioned in the linked document above. In this case it should have been this:
<item name="android:fontFamily">sans-serif</item>
Like the linked answer already stated, 12 variants are possible:
Regular (default):
<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">normal</item>
Italic:
<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">italic</item>
Bold:
<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold</item>
Bold-italic:
<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold|italic</item>
Light:
<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">normal</item>
Light-italic:
<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">italic</item>
Thin :
<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">normal</item>
Thin-italic :
<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">italic</item>
Condensed regular:
<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">normal</item>
Condensed italic:
<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">italic</item>
Condensed bold:
<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold</item>
Condensed bold-italic:
<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold|italic</item>
Medium:
<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">normal</item>
Medium-italic:
<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">italic</item>
Black:
<item name="android:fontFamily">sans-serif-black</item>
<item name="android:textStyle">italic</item>
For quick reference, this is how they all look like:
Dump the row you want to sql and then use the generated SQL, less the ID column to import it back in.
If you just want to show different texts or images, keep the tag empty and write your content in multiple data attributes like that <span data-text1="Hello" data-text2="Bye"></span>
.
Display them with one of the pseudo classes :before {content: attr(data-text1)}
Now you have a bunch of different ways to switch between them. I used them in combination with media queries for a responsive design approach to change the names of my navigation to icons.
jsfiddle demonstration and examples
It may not perfectly answer the question, but it satisfied my needs and maybe others too.
From the kubernetes docs:
https://kubernetes.io/docs/concepts/containers/images/#updating-images
The default pull policy is IfNotPresent which causes the Kubelet to skip pulling an image if it already exists. If you would like to always force a pull, you can do one of the following:
- set the imagePullPolicy of the container to Always;
- use :latest as the tag for the image to use;
- enable the AlwaysPullImages admission controller.
Or read the other way: Using the :latest tag forces images to always be pulled. If you use the eval $(minikube docker-env)
as mentioned above, then either don't use any tag, or assign a tag to your local image you can avoid Kubernetes trying to forcibly pull it.
One more way- By using java.lang.Integer you can get string representation of the first argument i
in the radix (Octal - 8, Hex - 16, Binary - 2)
specified by the second argument.
Integer.toString(i, radix)
Example_
private void getStrtingRadix() {
// TODO Auto-generated method stub
/* returns the string representation of the
unsigned integer in concern radix*/
System.out.println("Binary eqivalent of 100 = " + Integer.toString(100, 2));
System.out.println("Octal eqivalent of 100 = " + Integer.toString(100, 8));
System.out.println("Decimal eqivalent of 100 = " + Integer.toString(100, 10));
System.out.println("Hexadecimal eqivalent of 100 = " + Integer.toString(100, 16));
}
OutPut_
Binary eqivalent of 100 = 1100100
Octal eqivalent of 100 = 144
Decimal eqivalent of 100 = 100
Hexadecimal eqivalent of 100 = 64
All browsers, including Safari (+ mobile):
input[type=text] {
/* Remove */
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
/* Optional */
border: solid;
box-shadow: none;
/*etc.*/
}
Use scp priv_key.pem source user@host:target
if you need to connect using a private key.
or if using pscp then use pscp -i priv_key.ppk source user@host:target
a solution i came up with... probably pretty inefficient in comparison tho Fosco's solution:
protected function getFirstPosition(array$array, $content, $key = true) {
$index = 0;
if ($key) {
foreach ($array as $key => $value) {
if ($key == $content) {
return $index;
}
$index++;
}
} else {
foreach ($array as $key => $value) {
if ($value == $content) {
return $index;
}
$index++;
}
}
}
In my case (I'm using VS 2017) works fine the following simple code:
#include "pch.h"
#include <iostream>
#include <stdlib.h>
#include <time.h>
int main()
{
srand(time(NULL));
for (int i = 1000; i > 0; i--) //try it thousand times
{
int randnum = (double)rand() / ((double)RAND_MAX + 1);
std::cout << " rnum: " << rand()%2 ;
}
}
If this error occurs with the jdk use this :
progra~1 instead of program files in the path example :
c:/progra~1/java instead of c:/program files/java
It will be ok always avoid space in java code.....
it can be used for every thing in program files, otherwise put quotes at the beginning and the en of path
"c:/..../"
For debugging purposes this might help you:
function print_form_data(form) {
const form_data = new FormData(form);
for (const item of form_data.entries()) {
console.log(item);
}
return false;
}
It works very nice and simple.
xaml
<ComboBox ItemsSource="{Binding MyEnumArray}">
.cs
public Array MyEnumArray
{
get { return Enum.GetValues(typeof(MyEnum)); }
}
In your link function, do this:
// link function
function (scope, element, attrs) {
var myEl = angular.element(element[0].querySelector('.list-scrollable'));
}
Also, in your link function, don't name your scope
variable using a $
. That is an angular convention that is specific to built in angular services, and is not something that you want to use for your own variables.
Plus, you should make sure the MySQL server's config (/etc/mysql/my.cnf, /etc/default/mysql on Debian) doesn't have "skip-networking" activated and is not binded exclusively to the loopback interface (127.0.0.1) but also to the interface/IP address you want connect to.
One solution to this is to use Maven. From the project root folder do mvn eclipse:clean followed by mvn eclipse:eclipse. This will generate the .project and .classpath files required by eclipse.
You have not appended your li
as a child to your ul
element
Try this
function function1() {
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode("Four"));
ul.appendChild(li);
}
If you need to set the id , you can do so by
li.setAttribute("id", "element4");
Which turns the function into
function function1() {
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode("Four"));
li.setAttribute("id", "element4"); // added line
ul.appendChild(li);
alert(li.id);
}
In [95]: import scipy
In [96]: scipy.__version__
Out[96]: '0.12.0'
In [104]: scipy.version.*version?
scipy.version.full_version
scipy.version.short_version
scipy.version.version
In [105]: scipy.version.full_version
Out[105]: '0.12.0'
In [106]: scipy.version.git_revision
Out[106]: 'cdd6b32233bbecc3e8cbc82531905b74f3ea66eb'
In [107]: scipy.version.release
Out[107]: True
In [108]: scipy.version.short_version
Out[108]: '0.12.0'
In [109]: scipy.version.version
Out[109]: '0.12.0'
See SciPy doveloper documentation for reference.
Listing Keys Using the AWS SDK for Java
http://docs.aws.amazon.com/AmazonS3/latest/dev/ListingObjectKeysUsingJava.html
import java.io.IOException;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.ListObjectsRequest;
import com.amazonaws.services.s3.model.ListObjectsV2Request;
import com.amazonaws.services.s3.model.ListObjectsV2Result;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.S3ObjectSummary;
public class ListKeys {
private static String bucketName = "***bucket name***";
public static void main(String[] args) throws IOException {
AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider());
try {
System.out.println("Listing objects");
final ListObjectsV2Request req = new ListObjectsV2Request().withBucketName(bucketName);
ListObjectsV2Result result;
do {
result = s3client.listObjectsV2(req);
for (S3ObjectSummary objectSummary :
result.getObjectSummaries()) {
System.out.println(" - " + objectSummary.getKey() + " " +
"(size = " + objectSummary.getSize() +
")");
}
System.out.println("Next Continuation Token : " + result.getNextContinuationToken());
req.setContinuationToken(result.getNextContinuationToken());
} while(result.isTruncated() == true );
} catch (AmazonServiceException ase) {
System.out.println("Caught an AmazonServiceException, " +
"which means your request made it " +
"to Amazon S3, but was rejected with an error response " +
"for some reason.");
System.out.println("Error Message: " + ase.getMessage());
System.out.println("HTTP Status Code: " + ase.getStatusCode());
System.out.println("AWS Error Code: " + ase.getErrorCode());
System.out.println("Error Type: " + ase.getErrorType());
System.out.println("Request ID: " + ase.getRequestId());
} catch (AmazonClientException ace) {
System.out.println("Caught an AmazonClientException, " +
"which means the client encountered " +
"an internal error while trying to communicate" +
" with S3, " +
"such as not being able to access the network.");
System.out.println("Error Message: " + ace.getMessage());
}
}
}
HTTP request POST in java does not dump the answer?
public class HttpClientExample
{
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception
{
HttpClientExample http = new HttpClientExample();
System.out.println("\nTesting 1 - Send Http POST request");
http.sendPost();
}
// HTTP POST request
private void sendPost() throws Exception {
String url = "http://www.wmtechnology.org/Consultar-RUC/index.jsp";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", USER_AGENT);
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("accion", "busqueda"));
urlParameters.add(new BasicNameValuePair("modo", "1"));
urlParameters.add(new BasicNameValuePair("nruc", "10469415177"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " +response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
StringBuilder result = new StringBuilder();
String line = "";
while ((line = rd.readLine()) != null)
{
result.append(line);
System.out.println(line);
}
}
}
This is the web: http://www.wmtechnology.org/Consultar-RUC/index.jsp,from you can consult Ruc without captcha. Your opinions are welcome!
Upon hours of debugging, it was just an c# error in my html view. Check your view and track down any error
Don't comment c# code using html style ie
This also works like a charm
<form>_x000D_
<label class="radio-inline">_x000D_
<input type="radio" name="optradio" checked>Option 1_x000D_
</label>_x000D_
<label class="radio-inline">_x000D_
<input type="radio" name="optradio">Option 2_x000D_
</label>_x000D_
<label class="radio-inline">_x000D_
<input type="radio" name="optradio">Option 3_x000D_
</label>_x000D_
</form>
_x000D_
Assigning promises-for-later-needed-values to variables and then getting their value via synchronous inspection. The example uses bluebird's .value()
method but many libraries provide similar method.
function getExample() {
var a = promiseA(…);
return a.then(function() {
// some processing
return promiseB(…);
}).then(function(resultB) {
// a is guaranteed to be fulfilled here so we can just retrieve its
// value synchronously
var aValue = a.value();
});
}
This can be used for as many values as you like:
function getExample() {
var a = promiseA(…);
var b = a.then(function() {
return promiseB(…)
});
var c = b.then(function() {
return promiseC(…);
});
var d = c.then(function() {
return promiseD(…);
});
return d.then(function() {
return a.value() + b.value() + c.value() + d.value();
});
}
I asume you have connected to your database already.
$sql = "SELECT * FROM my_table";
$result = mysql_query($sql);
$row = 1; // 1-based index
while($row_data = mysql_fetch_assoc($result)) {
$col = 0;
foreach($row_data as $key=>$value) {
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
$col++;
}
$row++;
}
Probably the most definitive is Figure B.1(d) of the ggplot2 book, the appendices of which are available at http://ggplot2.org/book/appendices.pdf.
However, it is not quite that simple. hjust
and vjust
as described there are how it works in geom_text
and theme_text
(sometimes). One way to think of it is to think of a box around the text, and where the reference point is in relation to that box, in units relative to the size of the box (and thus different for texts of different size). An hjust
of 0.5 and a vjust
of 0.5 center the box on the reference point. Reducing hjust
moves the box right by an amount of the box width times 0.5-hjust
. Thus when hjust=0
, the left edge of the box is at the reference point. Increasing hjust
moves the box left by an amount of the box width times hjust-0.5
. When hjust=1
, the box is moved half a box width left from centered, which puts the right edge on the reference point. If hjust=2
, the right edge of the box is a box width left of the reference point (center is 2-0.5=1.5
box widths left of the reference point. For vertical, less is up and more is down. This is effectively what that Figure B.1(d) says, but it extrapolates beyond [0,1].
But, sometimes this doesn't work. For example
DF <- data.frame(x=c("a","b","cdefghijk","l"),y=1:4)
p <- ggplot(DF, aes(x,y)) + geom_point()
p + opts(axis.text.x=theme_text(vjust=0))
p + opts(axis.text.x=theme_text(vjust=1))
p + opts(axis.text.x=theme_text(vjust=2))
The three latter plots are identical. I don't know why that is. Also, if text is rotated, then it is more complicated. Consider
p + opts(axis.text.x=theme_text(hjust=0, angle=90))
p + opts(axis.text.x=theme_text(hjust=0.5 angle=90))
p + opts(axis.text.x=theme_text(hjust=1, angle=90))
p + opts(axis.text.x=theme_text(hjust=2, angle=90))
The first has the labels left justified (against the bottom), the second has them centered in some box so their centers line up, and the third has them right justified (so their right sides line up next to the axis). The last one, well, I can't explain in a coherent way. It has something to do with the size of the text, the size of the widest text, and I'm not sure what else.
You have an extra '{' before return type. You may also want to put '==' instead of '=' in if and else condition.
As you mentioned in a comment, you're using log4j. I discovered (inadvertently) a place where I had written
LOG.error(exc);
instead of the typical
LOG.error("Some informative message", e);
through laziness or perhaps just not thinking about it. The unfortunate part of this is that it doesn't behave as you expect. The logger API actually takes Object as the first argument, not a string - and then it calls toString() on the argument. So instead of getting the nice pretty stack trace, it just prints out the toString - which in the case of NPE is pretty useless.
Perhaps this is what you're experiencing?
const Minutes = ((123456/60000).toFixed(2)).replace('.',':');
//Result = 2:06
We divide the number in milliseconds (123456) by 60000 to give us the same number in minutes, which here would be 2.0576.
toFixed(2) - Rounds the number to nearest two decimal places, which in this example gives an answer of 2.06.
You then use replace to swap the period for a colon.
i had a similar problem when i removed VS 2013 community Update 5 and switched over to VS 2015 community edition
and the problem acquired in windows phone 8.1 projects where it complained about not having the right msbuild toolset and about the emulators not installed even if they are.
i know that the source of the problem was the VS 2013 community settings that has been left by that last uninstall which messed everything for me even though the uninstall process went smooth with no problems from the control panel.
i did my best to remove any files left but there was always some thing left.
and what only fixed it for me is a fresh windows 10 x64 installation then after it i installed VS 2015 community edition and that's it!! no more errors for me and the wp8.1 emulator worked fine too!!
in my case now am completely sure that the previous visual studio install settings has messed everything for me and because there wasn't any way i found and tried to completely erase VS 2013 community files and settings i had to pay the price for it and reinstall my OS.
you might be able to avoid OS reinstall if you can find a way to completely erase last visual studio install files.
P.S:only attempt this solution(OS reinstall) after you tried every possible way first then if nothing works and only then ... make this solution as a last resort.
You can add below code in Global.asax.cs file
protected void Application_PreSendRequestHeaders()
{
Response.Headers.Remove("Server");
}
This is asking for your MySQL username and password.
You should enter these details, which will default to "root" and "" (i.e.: nothing) if you've not specified a password.
Ralph's answer is fabulous. I would rather use StringBuilder class to build/decorate the String because the usage of it is more look like Builder pattern.
public String decorateTheString(String orgStr){
StringBuilder builder = new StringBuilder();
builder.append(orgStr);
builder.deleteCharAt(orgStr.length()-1);
builder.insert(0,builder.hashCode());
return builder.toString();
}
It can be use as a helper/builder to build the String, not the String itself.
You have a typo in your xml; it should be:
android:textColor="@color/text_color"
that's "@color" without the 's'.
Here's how I do file upload in react using axios
import React from 'react'
import axios, { post } from 'axios';
class SimpleReactFileUpload extends React.Component {
constructor(props) {
super(props);
this.state ={
file:null
}
this.onFormSubmit = this.onFormSubmit.bind(this)
this.onChange = this.onChange.bind(this)
this.fileUpload = this.fileUpload.bind(this)
}
onFormSubmit(e){
e.preventDefault() // Stop form submit
this.fileUpload(this.state.file).then((response)=>{
console.log(response.data);
})
}
onChange(e) {
this.setState({file:e.target.files[0]})
}
fileUpload(file){
const url = 'http://example.com/file-upload';
const formData = new FormData();
formData.append('file',file)
const config = {
headers: {
'content-type': 'multipart/form-data'
}
}
return post(url, formData,config)
}
render() {
return (
<form onSubmit={this.onFormSubmit}>
<h1>File Upload</h1>
<input type="file" onChange={this.onChange} />
<button type="submit">Upload</button>
</form>
)
}
}
export default SimpleReactFileUpload
In addition to the answers already given it will be quicker if you use OrElse
instead of Or
because the second test is short circuited. This is especially true if you know that one string is more likely than the other in which case place this first:
If strMyString.Contains("Most Likely To Find") OrElse strMyString.Contains("Less Likely to Find") Then
'Code
End if
You need to set AutoPostBack
to true for the Country DropDownList
.
protected override void OnLoad(EventArgs e)
{
// base stuff
ddlCountries.AutoPostBack = true;
// other stuff
}
Edit
I missed that you had done this. In that case you need to check that ViewState is enabled.
For those interested in removing extension from filename, you can use https://nodejs.org/api/path.html#path_path_basename_path_ext
path.basename('/foo/bar/baz/asdf/quux.html', '.html');
Are you using .NET 3.5? You could use the ZipPackage
class and related classes. Its more than just zipping up a file list because it wants a MIME type for each file you add. It might do what you want.
I'm currently using these classes for a similar problem to archive several related files into a single file for download. We use a file extension to associate the download file with our desktop app. One small problem we ran into was that its not possible to just use a third-party tool like 7-zip to create the zip files because the client side code can't open it -- ZipPackage adds a hidden file describing the content type of each component file and cannot open a zip file if that content type file is missing.
If the user exists you can get the user in user_object
else user_object
will be None
.
try:
user_object = User.objects.get(email = cleaned_info['username'])
except User.DoesNotExist:
user_object = None
if user_object:
# user exist
pass
else:
# user does not exist
pass
If you are starting out with a ListView, do yourself a huge favour and use an ObjectListView instead. ObjectListView is an open source wrapper around .NET WinForms ListView, which makes the ListView much easier to use and solves lots of common problems for you. Sorting by column click is one of the many things it handles for you automatically.
Seriously, you will never regret using an ObjectListView instead of a normal ListView.
<?php
$thumbs_dir = 'E:/xampp/htdocs/uploads/thumbs/';
$videos = array();
if (isset($_POST["name"])) {
if (!preg_match('/data:([^;]*);base64,(.*)/', $_POST['data'], $matches)) {
die("error");
}
$data = $matches[2];
$data = str_replace(' ', '+', $data);
$data = base64_decode($data);
$file = 'text.jpg';
$dataname = file_put_contents($thumbs_dir . $file, $data);
}
?>
//jscode
<script type="text/javascript">
var videos = <?= json_encode($videos); ?>;
var video = document.getElementById('video');
video.addEventListener('canplay', function () {
this.currentTime = this.duration / 2;
}, false);
var seek = true;
video.addEventListener('seeked', function () {
if (seek) {
getThumb();
}
}, false);
function getThumb() {
seek = false;
var filename = video.src;
var w = video.videoWidth;//video.videoWidth * scaleFactor;
var h = video.videoHeight;//video.videoHeight * scaleFactor;
var canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
var ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0, w, h);
var data = canvas.toDataURL("image/jpg");
var xmlhttp = new XMLHttpRequest;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
}
}
xmlhttp.open("POST", location.href, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send('name=' + encodeURIComponent(filename) + '&data=' + data);
}
function failed(e) {
// video playback failed - show a message saying why
switch (e.target.error.code) {
case e.target.error.MEDIA_ERR_ABORTED:
console.log('You aborted the video playback.');
break;
case e.target.error.MEDIA_ERR_NETWORK:
console.log('A network error caused the video download to fail part-way.');
break;
case e.target.error.MEDIA_ERR_DECODE:
console.log('The video playback was aborted due to a corruption problem or because the video used features your browser did not support.');
break;
case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:
console.log('The video could not be loaded, either because the server or network failed or because the format is not supported.');
break;
default:
console.log('An unknown error occurred.');
break;
}
}
</script>
//Html
<div>
<video id="video" src="1499752288.mp4" autoplay="true" onerror="failed(event)" controls="controls" preload="none"></video>
</div>
I had a similar problem and after going over a lot on stack overflow and spending time on the jar dependencies, I figured out that in my case, I had two sets of asm.jar. I removed one of them and it worked fine...
Just to expand a little on Dirk's example:
It helps to think of a data frame as a list with equal length vectors. That's probably why names
works with a data frame but not a matrix.
The other useful function is dimnames
which returns the names for every dimension. You will notice that the rownames
function actually just returns the first element from dimnames
.
Regarding rownames
and row.names
: I can't tell the difference, although rownames
uses dimnames
while row.names
was written outside of R. They both also seem to work with higher dimensional arrays:
>a <- array(1:5, 1:4)
> a[1,,,]
> rownames(a) <- "a"
> row.names(a)
[1] "a"
> a
, , 1, 1
[,1] [,2]
a 1 2
> dimnames(a)
[[1]]
[1] "a"
[[2]]
NULL
[[3]]
NULL
[[4]]
NULL
My error was define the view like this:
view = inflater.inflate(R.layout.qr_fragment, container);
It was missing:
view = inflater.inflate(R.layout.qr_fragment, container, false);
function getCaretPosition() {
var x = 0;
var y = 0;
var sel = window.getSelection();
if(sel.rangeCount) {
var range = sel.getRangeAt(0).cloneRange();
if(range.getClientRects()) {
range.collapse(true);
var rect = range.getClientRects()[0];
if(rect) {
y = rect.top;
x = rect.left;
}
}
}
return {
x: x,
y: y
};
}
It looks like you might have inserted an extra +
at the beginning of each line, which R is interpreting as a unary operator (like -
interpreted as negation, rather than subtraction). I think what will work is
ggplot(combined.data, aes(x = region, y = expression, fill = species)) +
geom_boxplot() +
scale_fill_manual(values = c("yellow", "orange")) +
ggtitle("Expression comparisons for ACTB") +
theme(axis.text.x = element_text(angle=90, face="bold", colour="black"))
Perhaps you copy and pasted from the output of an R console? The console uses +
at the start of the line when the input is incomplete.
Just Need to Start MySQL Service after installation:
For Ubuntu:
sudo service mysql start;
For CentOS or RHEL:
sudo service mysqld start;
As this is the first result on google and there's no C++20 answer yet, here's how to use std::chrono to do this:
#include <chrono>
//...
using namespace std::chrono;
int64_t timestamp = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
In versions of C++ before 20, system_clock's epoch being Unix epoch is a de-facto convention, but it's not standardized. If you're not on C++20, use at your own risk.
On the File menu, choose Advanced Save Options, you can control it there.
Edit: Here's the documentation, you should have a file open first.
binascii methodes are easier by the way
>>> import binascii
>>> x=b'test'
>>> x=binascii.hexlify(x)
>>> x
b'74657374'
>>> y=str(x,'ascii')
>>> y
'74657374'
>>> x=binascii.unhexlify(x)
>>> x
b'test'
>>> y=str(x,'ascii')
>>> y
'test'
Hope it helps. :)
For a pointer, we could just use
*pointervariable.foo
But the .
operator has greater precedence than the *
operator, so .
is evaluated first. So we need to force this with parenthesis:
(*pointervariable).foo
But typing the ()'s all the time is hard, so they developed ->
as a shortcut to say the same thing. If you are accessing a property of an object or object reference, use .
If you are accessing a property of an object through a pointer, use ->
System call fork() is used to create processes. It takes no arguments and returns a process ID. The purpose of fork() is to create a new process, which becomes the child process of the caller. After a new child process is created, both processes will execute the next instruction following the fork() system call. Therefore, we have to distinguish the parent from the child. This can be done by testing the returned value of fork()
Fork is a system call and you shouldnt think of it as a normal C function. When a fork() occurs you effectively create two new processes with their own address space.Variable that are initialized before the fork() call store the same values in both the address space. However values modified within the address space of either of the process remain unaffected in other process one of which is parent and the other is child. So if,
pid=fork();
If in the subsequent blocks of code you check the value of pid.Both processes run for the entire length of your code. So how do we distinguish them. Again Fork is a system call and here is difference.Inside the newly created child process pid will store 0 while in the parent process it would store a positive value.A negative value inside pid indicates a fork error.
When we test the value of pid to find whether it is equal to zero or greater than it we are effectively finding out whether we are in the child process or the parent process.
I think you've created your project like this:
vue init webpack myproject
Well, now you can run
npm run build
Copy index.html and /dist/ folder into your website root directory. Done.
I believe this is the Debian package 'bible'.
Well, it's the Debian new maintainer's guide, so a lot of it won't be applicable, but they do cover what goes where.
To add a class to a div that is generated via the HtmlGenericControl
way you can use:
div1.Attributes.Add("class", "classname");
If you are using the Panel
option, it would be:
panel1.CssClass = "classname";
As this was already answered, I just wanted to point out the differences in approaches on getting the constructor of an object in JavaScript.
There is a difference between the constructor and the actual object/class name. If the following adds to the complexity of your decision then maybe you're looking for instanceof
. Or maybe you should ask yourself "Why am I doing this? Is this really what I am trying to solve?"
Notes:
The obj.constructor.name
is not available on older browsers.
Matching (\w+)
should satisfy ES6 style classes.
Code:
var what = function(obj) {
return obj.toString().match(/ (\w+)/)[1];
};
var p;
// Normal obj with constructor.
function Entity() {}
p = new Entity();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name , "class:", what(p));
// Obj with prototype overriden.
function Player() { console.warn('Player constructor called.'); }
Player.prototype = new Entity();
p = new Player();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));
// Obj with constructor property overriden.
function OtherPlayer() { console.warn('OtherPlayer constructor called.'); }
OtherPlayer.constructor = new Player();
p = new OtherPlayer();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));
// Anonymous function obj.
p = new Function("");
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));
// No constructor here.
p = {};
console.log("constructor:", what(p.constructor), "name:", p.constructor.name, "class:", what(p));
// ES6 class.
class NPC {
constructor() {
}
}
p = new NPC();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name , "class:", what(p));
// ES6 class extended
class Boss extends NPC {
constructor() {
super();
}
}
p = new Boss();
console.log("constructor:", what(p.constructor), "name:", p.constructor.name , "class:", what(p));
Result:
Following Code work for me.
Update:
As I am calling a free API request (json base ) IpStack.
public static string CityStateCountByIp(string IP)
{
//var url = "http://freegeoip.net/json/" + IP;
//var url = "http://freegeoip.net/json/" + IP;
string url = "http://api.ipstack.com/" + IP + "?access_key=[KEY]";
var request = System.Net.WebRequest.Create(url);
using (WebResponse wrs = request.GetResponse())
using (Stream stream = wrs.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
string json = reader.ReadToEnd();
var obj = JObject.Parse(json);
string City = (string)obj["city"];
string Country = (string)obj["region_name"];
string CountryCode = (string)obj["country_code"];
return (CountryCode + " - " + Country +"," + City);
}
return "";
}
Edit : First, it was http://freegeoip.net/ now it's https://ipstack.com/ (and maybe now it's a paid service- Free Up to 10,000 request/month)
FFTW is the 'fastest fourier transform in the west', and has some Java wrappers:
Hope that helps!
I implemented Joseph Johnson solution and it worked well, I noticed after using this solution sometimes the drawer on the application will not close properly. I added a functionality to remove the listener removeOnGlobalLayoutListener when the user closes the fragment where are edittexts located.
//when the application uses full screen theme and the keyboard is shown the content not scrollable!
//with this util it will be scrollable once again
//http://stackoverflow.com/questions/7417123/android-how-to-adjust-layout-in-full-screen-mode-when-softkeyboard-is-visible
public class AndroidBug5497Workaround {
private static AndroidBug5497Workaround mInstance = null;
private View mChildOfContent;
private int usableHeightPrevious;
private FrameLayout.LayoutParams frameLayoutParams;
private ViewTreeObserver.OnGlobalLayoutListener _globalListener;
// For more information, see https://code.google.com/p/android/issues/detail?id=5497
// To use this class, simply invoke assistActivity() on an Activity that already has its content view set.
public static AndroidBug5497Workaround getInstance (Activity activity) {
if(mInstance==null)
{
synchronized (AndroidBug5497Workaround.class)
{
mInstance = new AndroidBug5497Workaround(activity);
}
}
return mInstance;
}
private AndroidBug5497Workaround(Activity activity) {
FrameLayout content = (FrameLayout) activity.findViewById(android.R.id.content);
mChildOfContent = content.getChildAt(0);
frameLayoutParams = (FrameLayout.LayoutParams) mChildOfContent.getLayoutParams();
_globalListener = new ViewTreeObserver.OnGlobalLayoutListener()
{
@Override
public void onGlobalLayout()
{
possiblyResizeChildOfContent();
}
};
}
public void setListener()
{
mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(_globalListener);
}
public void removeListener()
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
mChildOfContent.getViewTreeObserver().removeOnGlobalLayoutListener(_globalListener);
} else {
mChildOfContent.getViewTreeObserver().removeGlobalOnLayoutListener(_globalListener);
}
}
private void possiblyResizeChildOfContent() {
int usableHeightNow = computeUsableHeight();
if (usableHeightNow != usableHeightPrevious) {
int usableHeightSansKeyboard = mChildOfContent.getRootView().getHeight();
int heightDifference = usableHeightSansKeyboard - usableHeightNow;
if (heightDifference > (usableHeightSansKeyboard/4)) {
// keyboard probably just became visible
frameLayoutParams.height = usableHeightSansKeyboard - heightDifference;
} else {
// keyboard probably just became hidden
frameLayoutParams.height = usableHeightSansKeyboard;
}
mChildOfContent.requestLayout();
usableHeightPrevious = usableHeightNow;
}
}
private int computeUsableHeight() {
Rect r = new Rect();
mChildOfContent.getWindowVisibleDisplayFrame(r);
return (r.bottom - r.top);
}
}
uses the class where is my edittexts located
@Override
public void onStart()
{
super.onStart();
AndroidBug5497Workaround.getInstance(getActivity()).setListener();
}
@Override
public void onStop()
{
super.onStop();
AndroidBug5497Workaround.getInstance(getActivity()).removeListener();
}
All the changes to the NSMutableURLRequest
must be made before calling NSURLConnection
.
I see this problem as I copy and paste the code above and run TCPMon
and see the request is GET
instead of the expected POST
.
NSURL *aUrl = [NSURL URLWithString:@"http://www.apple.com/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
NSString *postString = @"company=Locassa&quality=AWESOME!";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request
delegate:self];
If you are like me just want to print a sequence within a lambda, without get the return value (list of None).
x = range(3)
from __future__ import print_function # if not python 3
pra = lambda seq=x: map(print,seq) and None # pra for 'print all'
pra()
pra('abc')
I accidentally ended up writing almost the same as provided by git-extras. So if you prefer a single custom command instead of installing a bunch of other extra commands, just place this git-pr
file somewhere in your $PATH
and then you can just write:
git pr 42
// or
git pr upstream 42
// or
git pr https://github.com/peerigon/phridge/pull/1
The difference between the commands is that one provides you with a tag message while the other doesn't. An annotated tag has a message that can be displayed with git-show(1), while a tag without annotations is just a named pointer to a commit.
According to the documentation: "To create a lightweight tag, don’t supply any of the -a, -s, or -m options, just provide a tag name". There are also some different options to write a message on annotated tags:
git tag <tagname>
, Git will create a tag at the current revision but will not prompt you for an annotation. It will be tagged without a message (this is a lightweight tag).git tag -a <tagname>
, Git will prompt you for an annotation unless you have also used the -m flag to provide a message.git tag -a -m <msg> <tagname>
, Git will tag the commit and annotate it with the provided message.git tag -m <msg> <tagname>
, Git will behave as if you passed the -a flag for annotation and use the provided message.Basically, it just amounts to whether you want the tag to have an annotation and some other information associated with it or not.
Here is what worked for me:
telnet
It will confirm whether the port is opened.
Easy way:
str = "[12,23,987,43"
removed = str[1..str.length]
Awesome way:
class String
def reverse_chop()
self[1..self.length]
end
end
"[12,23,987,43".reverse_chop()
(Note: prefer the easy way :) )
Create new instances in your fragments and do like so in your Activity
private class SlidePagerAdapter extends FragmentStatePagerAdapter {
public SlidePagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch(position){
case 0:
return Fragment1.newInstance();
case 1:
return Fragment2.newInstance();
case 2:
return Fragment3.newInstance();
case 3:
return Fragment4.newInstance();
default: break;
}
return null;
}
Better than all options, you can set your signingConfig
to be equals your debug.signingConfig
.
To do that you just need to do the following:
android {
...
buildTypes {
...
wantedBuildType {
signingConfig debug.signingConfig
}
}
}
With that you will not need to know where the debug.keystore
is, the app will work for all team, even if someone use a different environment.
As other users said, the best way for Windows users is to set the global environment variable.
I install the Miniconda3 for MXNet.
Before I do something, only Anaconda Prompt works for conda
.
After setting the global environment variable, The CMD and Git Bash work. But in some IDEs like RStudio, the nested Git Bash doesn't work.
After restarting my computer, the Git Bash in the RStudio works for conda
.
I hope these tests helps for you.
Main issue is that you first need to set the location of your x and y ticks. Also, it helps to use the more object-oriented interface to matplotlib. Namely, interact with the axes
object directly.
import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
data = np.random.rand(4,4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data)
# put the major ticks at the middle of each cell, notice "reverse" use of dimension
ax.set_yticks(np.arange(data.shape[0])+0.5, minor=False)
ax.set_xticks(np.arange(data.shape[1])+0.5, minor=False)
ax.set_xticklabels(row_labels, minor=False)
ax.set_yticklabels(column_labels, minor=False)
plt.show()
Hope that helps.
I have used JTextArea for multiline JLabels.
JTextArea textarea = new JTextArea ("1\n2\n3\n"+"4\n");
http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextArea.html
Probably to guarantee that public webservices will be unique.
It always makes me think of delicious deep fried treats...
I ended up using a variation of Shawn's solution:
Create a custom UITableView class with a delegate:
protocol CustomTableViewDelegate {
func CustomTableViewDidLayoutSubviews()
}
class CustomTableView: UITableView {
var customDelegate: CustomTableViewDelegate?
override func layoutSubviews() {
super.layoutSubviews()
self.customDelegate?.CustomTableViewDidLayoutSubviews()
}
}
Then in my code, I use
class SomeClass: UIViewController, CustomTableViewDelegate {
@IBOutlet weak var myTableView: CustomTableView!
override func viewDidLoad() {
super.viewDidLoad()
self.myTableView.customDelegate = self
}
func CustomTableViewDidLayoutSubviews() {
print("didlayoutsubviews")
// DO other cool things here!!
}
}
Also make sure you set your table view to CustomTableView in the interface builder:
If You want the Path After successful installation then first open you CMD and type python or python -i
It Will Open interactive shell for You and Then type
import sys
sys.executable
Hit enter and you will get path where your python is installed ...